From 814a0322b21ed0a4cbb5da398c4989dcb0101675 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:53:42 +0800 Subject: [PATCH 01/41] docs(sessionmethods): add the SessionMethods owner contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Session's method table behind `sessionMethods`: `register`, `call` and `methods` replace the `MethodTable` readers, the provider object and the `ForeignMethods` wrapper. The contract defines the method-table call data once — `MethodCall`, `MethodReply`, the handler's error and the table's error kinds — so A.1 and the process table stop carrying copies, and the Session boundary's rows point at it (#2026). --- .../rust-agent/plugins/SessionMethods.md | 2 +- docs/design/contracts/session-boundary.md | 20 +- docs/design/plugins/README.md | 3 +- docs/design/plugins/SessionMethods.md | 316 ++++++++++++++++++ docs/zh/design/contracts/session-boundary.md | 20 +- docs/zh/design/plugins/README.md | 3 +- 6 files changed, 335 insertions(+), 29 deletions(-) create mode 100644 docs/design/plugins/SessionMethods.md diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 0c3d4a4523..4f3f8c3a72 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -4,7 +4,7 @@ Owner: [methods.rs](../../../../crates/dim-agent-capabilities/src/methods.rs). Keeps the Session's method table, `sessionMethods`: the method namespaces the Session's parts register with it, which Rpc reads on each call to dispatch a Session method through the Session. Contract: -[methods contract A.1](../../../design/contracts/session-boundary.md#a1-method-contributions). +[SessionMethods](../../../design/plugins/SessionMethods.md). ## Dependencies diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 0bbd6f4f3c..e37d8de69b 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -138,7 +138,7 @@ Methods have no model-visible effect. A method that changes model context does s | Service and method | Mode | Purpose | | --- | --- | --- | -| `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads | +| `sessionMethods.register(caller, namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; shape in [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | @@ -202,12 +202,14 @@ Shapes are JSON with camelCase fields; a `?` after a field name marks it optiona ### A.1 Method contributions +The call data of both tables — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; this appendix keeps the client error, interruption and routing behavior that the redesign does not change. + `sessionMethods` (Session) and `managementMethods` (process) are method tables with the same method, `register`. A part registers each namespace it serves with the table of its scope, and the table calls back the part's own `call`. Parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)) and reach the native call admission of Appendix F. | Method | Mode | Request | Reply | | --- | --- | --- | --- | -| `register` (the table's) | async | `namespace`, `MethodDecl[]`, `call` | Nothing once registered; an error when refused | -| `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply`, or `MethodError` | +| `register` (the table's) | async | `caller`, `namespace`, `MethodDecl[]`, `call` | Nothing once registered; an error when refused | +| `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply` data: the handler's value, or its own `{code, message}` error | ```text // MethodDecl @@ -217,18 +219,10 @@ Shapes are JSON with camelCase fields; a `?` after a field name marks it optiona "progress": false, "notifications?": ["session.goal.changed"], // inside the namespace "reply": "direct" | "handoff" } // handoff: daemon.shutdown -// MethodCall -{ "callId": "string", "method": "session.goal.set", - "params": {}, // as sent; Session methods keep sessionId (and branchId) here - "origin": { "entry?": { "name": "string", "deviceId?": "string" }, // the connection's ConnectionEntry - "connectionId?": "string", "peer?": "string" } } // peer: rutis link; diagnostics only -// MethodReply -{ "kind": "value", "value": {} } | { "kind": "handedOff" } -// MethodError -{ "code": -32000, "appError": "string", "message": "string" } +// MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (`origin.connectionId` on the wire); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, `handedOff`, `origin.entry` and `origin.peer` are not implemented. +Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (`origin.connectionId` on the wire); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, reply handoff, `origin.entry` and `origin.peer` are not implemented. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..598d645c37 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [SessionMethods](SessionMethods.md) (owner contract) | — | `sessionMethods`: the Session's method namespaces, their admission and the method list | — | [#2026](https://github.com/arcships/dim/issues/2026) | | [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 | @@ -52,5 +53,5 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | | 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) | +| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, SessionMethods, 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) | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md new file mode 100644 index 0000000000..58391134c5 --- /dev/null +++ b/docs/design/plugins/SessionMethods.md @@ -0,0 +1,316 @@ +# SessionMethods + +Scope: session. Issue: #2026. + +SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The table's call data — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is defined here once for both method tables. ManagementMethods (#2021) is the process table; Rpc, the registering parts and `session.methods` are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). + +## Use and scope: responsibility split + +SessionMethods owns: + +- **Registrations.** One namespace per registering row, its declarations and its call callback; a registration ends when its row unloads. +- **Admission.** One call: the name's owner, the interruption kind its declaration names, the caller identity, and the settlement of the calls a registration accepted. +- **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers `reloading` or `unavailable` instead of falling through to a parent namespace. +- **Reserved names.** The host's own roots, built-ins and management namespaces are refused at registration; the host supplies the check as a process face. +- **The method list.** The declarations of the namespaces registered now, each under its owning namespace. + +Callers keep: + +- What a method means: the registering part declares and implements its namespace. +- Routing: Rpc decides which table a wire name reaches and reads `sessionId` from the params. +- Client methods: Rpc serves `session.methods` and the built-ins; this table answers its own registrations. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the reserved-name check are the owner's | `register` | +| Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | +| `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | +| The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `reserved`; a pre-check races the next registration | Business | +| Rpc routes a name between management and Session | Yes: management answers its own `call` and whether it holds a name; Rpc reads `sessionId` | Business | +| A provider notifies its caller | Yes: the handler has the caller identity and uses `callChannel` (#2021) | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +A part registers from its `apply`; the registration belongs to that part's row: + +```rust +methods.register( + ctx, + "session.input".into(), + declarations, + |call, cancelled, _progress| Box::pin(withdraw(call, cancelled)), +).await?; +``` + +Rpc dispatches one wire call; the caller identity is data, and the reply is `MethodReply` data: + +```rust +let reply = match methods.call( + method.into(), + params, + Some(CallerRef { connection_id, call_id }), + cancelled.clone(), +).await { + Ok(reply) => reply, + Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), + Err(MethodError::Reloading) => return Err(RpcError::reloading()), + Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), + Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), + Err(MethodError::Invalid { .. }) => return Err(RpcError::invalid("Invalid request parameters")), + Err(MethodError::Closed) => return Err(RpcError::closed()), + Err(MethodError::Reserved { .. }) | Err(MethodError::Duplicate { .. }) => unreachable!("dispatch cannot register"), +}; +``` + +`session.methods` composes the value with the management table: + +```rust +let listed = methods.methods()?.into_iter().filter(|decl| !management.holds(&decl.name)).collect::>(); +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:reservedMethods` | The host's reserved names, consulted at registration; a host that names none reserves only the name grammar. | +| `P:callChannel` | The calling connection's per-call progress, addressed by the caller's `{connectionId, callId}`; the table builds the handler's `Progress` from it, and an in-process call has none. | +| The loader's row status (`rutis/loader`) | The row that registered a withdrawn namespace and its copy in this Session, read when a call answers `reloading` or `unavailable`. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | The calling connection closing ends the call as interrupted; the provider's unload ends it by its declaration (`report` or `drain`) | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `invalid`, `closed` | +| `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | + +`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses; absent for an in-process call. The table passes the caller identity to the handler unchanged and writes no socket. The handler receives a `Progress` for its call through `callChannel`, addressed by the same ids; an in-process call has none. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; its future is dropped when the call is interrupted. + +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. An error reply reaches the client as an error whose `appError` is the handler's `code`, with the JSON-RPC code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). + +### Errors + +| Kind | Client `appError` | What the caller does next | +| --- | --- | --- | +| `reserved` | — | The namespace or a name is the host's; pick another name | +| `duplicate` | — | The namespace is registered already; the row must not register twice | +| `invalid` | `invalid_params` | The namespace or a declaration is outside the grammar, or the request is malformed | +| `unknown_method` | `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | +| `reloading` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | +| `unavailable` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | +| `interrupted` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | +| `closed` | `session_closed` | This Session is closing; a later generation serves the next Session | + +`reserved` and `duplicate` answer a registration only, so no client sees them. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Check the grammar, the reserved names and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | +| `call` | Find the owner, admit the call, run the callback, return the reply; on unload interrupt `report` and wait for `drain` | The connection's close ends the call as interrupted; the handler's own work settles by its own rule | The call ends; the registration's accepted calls settle | A withdrawn namespace answers from its row's status; a table reload ends in-flight calls | The table for admission and settlement; the handler for its effects | +| `methods` | Read the registered namespaces' declarations | — | Nothing to release | Pending reads answer from the state they observed | SessionMethods | + +## Exceptions with reasons + +- The table reads the loader's row status for a withdrawn namespace: the status is the mechanism's record of the registering row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. +- A handler's progress and notifications are not written here: the caller identity is data and `callChannel` (#2021) addresses the connection by call id, so no connection, `Caller` or caller index crosses this owner. +- The table remembers the registering row per namespace: a withdrawn namespace must answer from that row rather than fall through to a parent namespace. + +## Verification + +Flow tests on the owner: + +- A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are refused; a refused registration fails the registering part. +- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held is `unknown_method`. +- A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result. +- The caller identity reaches the handler unchanged for a wire call and is absent for an in-process call; the handler's notification with the same call id is written by `callChannel`. +- A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. +- `methods` lists the registered declarations; Rpc's filter removes management-held names. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and the call channel, and reads the loader's row status. | +| §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | +| §3 orthogonality | No other business owner's state is read or changed; the reserved names, the call channel and the loader are the mechanism's faces. | +| §4 rule 1 | No command event: a registration is the calling row's effect. | +| §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | Core and assembly carry no method-specific meaning; a namespace's contents are its part's. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | +| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. | +| §4 rule 8 | No infrastructure change; the withdrawn-row answer is the loader's existing record. | +| §4 rule 9 | No Timeline fact. | +| §7 values, ids and callbacks | The caller identity is data; the call callback crosses by reference; a registration lives with its row; no object, channel or provider crosses. | +| §7 no proxy | The table answers its own registrations; the loader answers the row status. | +| §7 one interface | One name, `sessionMethods`, on the owner type; the Rust binding and the wire call the same methods; the call data is defined here once; `SessionMethods` no longer derefs to a shared table type. | +| §7 cross-language | `register` crosses as data plus the caller's callback, `methods` as data, and `call` is Rpc's in-process call with the protocol's cancellation; no operation is a Rust-only convenience. | +| §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | +| ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | +| ADR 002 D3 | No dependency on providers; a failed row affects only its namespaces. | +| ADR 002 D4 | The namespace set is structural: parts bring their namespaces. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. [#2021](https://github.com/arcships/dim/issues/2021): the process table serves the same `call {method, params, caller?}` request and `{reply}` shape, so Rpc has one call path for both tables. +2. [#2021](https://github.com/arcships/dim/issues/2021): the process table answers whether a registered or withdrawn namespace holds a name (today `MethodTable::holds`); Rpc routes a name by it and `session.methods` removes the names it holds. +3. [#2021](https://github.com/arcships/dim/issues/2021): `reservedMethods` stays a process face; the Session table consults `check {namespace, declarations}` at registration. +4. [#2021](https://github.com/arcships/dim/issues/2021): `callChannel` answers a progress write addressed by `{connectionId, callId}`; the table builds each call's `Progress` from it, because `call` takes the caller rather than a sink. +5. [#2021](https://github.com/arcships/dim/issues/2021): reply handoff (`handedOff`, `daemon.shutdown`) is not implemented; when it lands it is a variant of this shared `MethodReply`, and the process table's contract states it. + +## Supersedes + +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted`/`Caller`/`CallSite`/`Callers` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined here and A.1 links to them. + +No client wire protocol or user-visible behavior changes: `register` keeps its wire form `register(namespace, declarations, call)` for a part of another language, and every client error keeps its application code. + +## Binding appendix + +The owner type `SessionMethods` carries the catalog name `sessionMethods` and serves other languages at its Session dispatcher key. `#[rutis::service]` cannot bind the face: `register` takes a callback and `call` a cancellation, so the dispatch is written by hand and calls the same operations. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `MethodDecl`, `Interruption` and `Progress` are the capabilities crate's types; `RpcError` is its wire error, and the caller example above uses it. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. The process table ([ManagementMethods](https://github.com/arcships/dim/issues/2021)) uses the same `MethodDecl`, `MethodCall`, `MethodReply`, `MethodCallbackError`, `MethodError`, `CallerRef` and `Interruption`. + +```rust +use crate::host::CancelledFn; +use crate::methods::{MethodDecl, Progress}; +use rutis::host::{BoxFuture, CallError}; +use rutis::Ctx; +use rutis_bridge::session::{HostDispatch, Reply, Value as BridgeValue}; +use tokio_util::sync::CancellationToken; + +/// Who called: the connection the call arrived on and the call id the reply +/// ordering uses; absent for an in-process call. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallerRef { + pub connection_id: String, + pub call_id: String, +} + +/// One admitted call as its handler receives it: the declared name, the raw +/// params and who called. +#[derive(Debug, Clone)] +pub struct MethodCall { + pub method: String, + pub params: serde_json::Value, + pub origin: Origin, +} + +#[derive(Debug, Clone)] +pub struct Origin { + pub caller: Option, +} + +/// A handler's own failure, carried to the client as its `code` and `message`. +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{code}: {message}")] +pub struct MethodCallbackError { + pub code: String, + pub message: String, +} + +impl From for MethodCallbackError { + fn from(error: CallError) -> Self { + match error.raw().and_then(|raw| raw.downcast_ref::()) { + Some(rutis_bridge::session::Error::Remote { name, message, .. }) => Self { code: name.clone(), message: message.clone() }, + Some(other) => Self { code: other.code().unwrap_or("failed").into(), message: other.to_string() }, + None => Self { code: "failed".into(), message: error.message().into() }, + } + } +} + +/// The dispatch reply: the handler's value, or its own error as data. The +/// bridge writes a value as `{kind: "value", value}` and an error as +/// `{code, message}`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum MethodReply { + Value(ValueReply), + Error(MethodCallbackError), +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum ValueReply { + Value { + #[serde(default)] + value: serde_json::Value, + }, +} + +impl From for MethodReply { + fn from(error: MethodCallbackError) -> Self { + Self::Error(error) + } +} + +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum MethodError { + #[error("{message}")] + Reserved { message: String }, + #[error("{message}")] + Duplicate { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("no namespace holds {method}")] + UnknownMethod { method: String }, + #[error("the registering row is reloading")] + Reloading, + #[error("the registering row is unavailable")] + Unavailable, + #[error("the provider unloaded during the call")] + Interrupted, + #[error("the Session is closing")] + Closed, +} + +/// The owner type; the namespaces, their declarations and their last rows +/// stay private. +pub struct SessionMethods { /* ... */ } + +impl SessionMethods { + /// Publishes `namespace` for the lifetime of the row that owns `caller`. + pub async fn register( + &self, + caller: &Ctx, + namespace: String, + declarations: Vec, + call: impl Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> + Send + Sync + 'static, + ) -> Result<(), MethodError> { /* ... */ } + + pub async fn call( + &self, + method: String, + params: serde_json::Value, + caller: Option, + cancelled: CancelledFn, + ) -> Result { /* ... */ } // builds MethodCall { method, params, origin } + + pub fn methods(&self) -> Result, MethodError> { /* ... */ } +} + +/// The catalog name `sessionMethods` in the Session group, served to other +/// languages at its dispatcher key. `#[rutis::service]` cannot bind this face: +/// `register` carries a callback and `call` a cancellation, and neither is +/// data. The dispatch decodes the wire form and calls the same operations. +impl HostDispatch for SessionMethods { + fn methods(&self) -> Option { + Some(serde_json::json!({ "register": "async" })) + } + + /// `register {namespace, declarations, call}`, registered for the bridge's + /// calling row. + fn invoke(&self, method: &str, args: BridgeValue) -> Reply { /* ... */ } +} +``` + +`MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name. `SessionMethods` derives the catalog name `sessionMethods` from the owner type, as it does today; `ForeignMethods` no longer exists and the dispatch above is the owner's own entry. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 4b4af3095b..6c556854d6 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -138,7 +138,7 @@ sequenceDiagram | 服务与方法 | 模式 | 用途 | | --- | --- | --- | -| `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载 | +| `sessionMethods.register(caller, namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | @@ -202,12 +202,14 @@ sequenceDiagram ### A.1 方法贡献 +两张表的调用数据——`MethodCall`、`MethodReply`、处理函数自己的错误与方法表的错误种类——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约定义;本附录保留重构不改的客户端错误、中断与路由行为。 + `sessionMethods`(Session)与 `managementMethods`(进程)是方法表,具有同一个方法 `register`。部件把它提供的每个命名空间注册到其作用域的方法表,方法表回调该部件自己的 `call`。其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md)),并进入附录 F 的原生调用受理。 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | -| `register`(方法表的) | async | `namespace`、`MethodDecl[]`、`call` | 注册完成时无返回值;被拒绝时返回错误 | -| `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply`,或 `MethodError` | +| `register`(方法表的) | async | `caller`、`namespace`、`MethodDecl[]`、`call` | 注册完成时无返回值;被拒绝时返回错误 | +| `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply` 数据:处理函数的值,或它自己的 `{code, message}` 错误 | ```text // MethodDecl @@ -217,18 +219,10 @@ sequenceDiagram "progress": false, "notifications?": ["session.goal.changed"], // 位于命名空间内 "reply": "direct" | "handoff" } // handoff:daemon.shutdown -// MethodCall -{ "callId": "string", "method": "session.goal.set", - "params": {}, // 原样传入;Session 方法的 sessionId(以及 branchId)留在这里 - "origin": { "entry?": { "name": "string", "deviceId?": "string" }, // 连接的 ConnectionEntry - "connectionId?": "string", "peer?": "string" } } // peer:rutis 链接;仅用于诊断 -// MethodReply -{ "kind": "value", "value": {} } | { "kind": "handedOff" } -// MethodError -{ "code": -32000, "appError": "string", "message": "string" } +// MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(线上为 `origin.connectionId`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、`handedOff`、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(线上为 `origin.connectionId`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、回复交接、`origin.entry` 与 `origin.peer` 未实现。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 diff --git a/docs/zh/design/plugins/README.md b/docs/zh/design/plugins/README.md index 266a344e16..652aef431f 100644 --- a/docs/zh/design/plugins/README.md +++ b/docs/zh/design/plugins/README.md @@ -8,6 +8,7 @@ | 插件 | 进程部件 | Session 部件 | 分支部件 | 阶段 / issue | | --- | --- | --- | --- | --- | +| [SessionMethods](../../../design/plugins/SessionMethods.md)(所有者契约) | — | `sessionMethods`:本 Session 的方法命名空间、调用准入与方法清单 | — | [#2026](https://github.com/arcships/dim/issues/2026) | | [Migration](../../../design/plugins/Migration.md) | 按需加载的导入任务、来源映射、进度与重试记录;结算后卸载 | — | — | [实施计划](../../../plan/analysis/legacy-migration.md) | | [Provider 管理](../appserver/provider-management.md) | 现有 Provider:配置、目录、客户端偏好与管理方法 | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` 工具、`session.question.respond`、运行中 `ask_user` 调用的等待者;没有事件 | — | M2;#262 | @@ -45,5 +46,5 @@ | 作用域 | 部分 | | --- | --- | | 进程部件 | daemon 内的 Provider(管理补充提案)、Scheduler、Workflow、ExternalAgent、Modality、PluginManager、RuntimeManager、RemoteGateway、Skills(安装)、PromptSuggestion(Settings 来源)、`CodeMode`(安装时)、light-ocr、EventHub;接入方宿主进程内的 AcpGateway | -| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、Prompt(条目表)、Code Mode(启用时) | +| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、SessionMethods、Prompt(条目表)、Code Mode(启用时) | | 分支部件 | Goal(含 Pursuit)、ModelRecovery(拟议)、Hooks、Prompt、Code Mode(启用时) | From 1f5c891594808b7c5e396f9d2ab4079268450be9 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:58:43 +0800 Subject: [PATCH 02/41] docs(sessionmethods): read the registering row through a host port The table answers `reloading` and `unavailable` from the registering row's status, so the dependency states a host port rather than the public loader name. Both READMEs keep only this owner's index row; the catalog's By-scope line and the batch's names stay with the organizer. --- docs/design/plugins/README.md | 2 +- docs/design/plugins/SessionMethods.md | 12 ++++++------ docs/zh/design/plugins/README.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 598d645c37..7e4cf2baec 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -53,5 +53,5 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | | 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, SessionMethods, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | +| 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) | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 58391134c5..068ff66a10 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -78,7 +78,7 @@ let listed = methods.methods()?.into_iter().filter(|decl| !management.holds(&dec | --- | --- | | `P:reservedMethods` | The host's reserved names, consulted at registration; a host that names none reserves only the name grammar. | | `P:callChannel` | The calling connection's per-call progress, addressed by the caller's `{connectionId, callId}`; the table builds the handler's `Progress` from it, and an in-process call has none. | -| The loader's row status (`rutis/loader`) | The row that registered a withdrawn namespace and its copy in this Session, read when a call answers `reloading` or `unavailable`. | +| Host port: the registering row's status | The row that registered a withdrawn namespace and its copy in this Session, read when a call answers `reloading` or `unavailable`. The host supplies the port, so the table names no public service for the read. | ### Operations @@ -117,7 +117,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- The table reads the loader's row status for a withdrawn namespace: the status is the mechanism's record of the registering row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. +- The table reads the registering row's status through a host port: the status is the mechanism's record of the row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. - A handler's progress and notifications are not written here: the caller identity is data and `callChannel` (#2021) addresses the connection by call id, so no connection, `Caller` or caller index crosses this owner. - The table remembers the registering row per namespace: a withdrawn namespace must answer from that row rather than fall through to a parent namespace. @@ -136,9 +136,9 @@ Flow tests on the owner: | Rule | Application | | --- | --- | -| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and the call channel, and reads the loader's row status. | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and the call channel, and reads the registering row's status through a host port. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | -| §3 orthogonality | No other business owner's state is read or changed; the reserved names, the call channel and the loader are the mechanism's faces. | +| §3 orthogonality | No other business owner's state is read or changed; the reserved names, the call channel and the row-status port are the mechanism's faces. | | §4 rule 1 | No command event: a registration is the calling row's effect. | | §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | | §4 rule 3 | No before callback. | @@ -146,10 +146,10 @@ Flow tests on the owner: | §4 rule 5 | No batches. | | §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. | -| §4 rule 8 | No infrastructure change; the withdrawn-row answer is the loader's existing record. | +| §4 rule 8 | No infrastructure change; the withdrawn-row answer reads the mechanism's existing record through the port. | | §4 rule 9 | No Timeline fact. | | §7 values, ids and callbacks | The caller identity is data; the call callback crosses by reference; a registration lives with its row; no object, channel or provider crosses. | -| §7 no proxy | The table answers its own registrations; the loader answers the row status. | +| §7 no proxy | The table answers its own registrations; the host port answers the row status. | | §7 one interface | One name, `sessionMethods`, on the owner type; the Rust binding and the wire call the same methods; the call data is defined here once; `SessionMethods` no longer derefs to a shared table type. | | §7 cross-language | `register` crosses as data plus the caller's callback, `methods` as data, and `call` is Rpc's in-process call with the protocol's cancellation; no operation is a Rust-only convenience. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | diff --git a/docs/zh/design/plugins/README.md b/docs/zh/design/plugins/README.md index 652aef431f..259484f5e4 100644 --- a/docs/zh/design/plugins/README.md +++ b/docs/zh/design/plugins/README.md @@ -46,5 +46,5 @@ | 作用域 | 部分 | | --- | --- | | 进程部件 | daemon 内的 Provider(管理补充提案)、Scheduler、Workflow、ExternalAgent、Modality、PluginManager、RuntimeManager、RemoteGateway、Skills(安装)、PromptSuggestion(Settings 来源)、`CodeMode`(安装时)、light-ocr、EventHub;接入方宿主进程内的 AcpGateway | -| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、SessionMethods、Prompt(条目表)、Code Mode(启用时) | +| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、Prompt(条目表)、Code Mode(启用时) | | 分支部件 | Goal(含 Pursuit)、ModelRecovery(拟议)、Hooks、Prompt、Code Mode(启用时) | From 3a0bb969ba9ab66a819d4582631c7837a41c6f40 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:18:07 +0800 Subject: [PATCH 03/41] docs(sessionmethods): answer the first pre-review The table answers a disconnect by nothing: only the provider generation or the admitting Rpc load interrupts an admitted call. `call` takes the progress sink and the cancellation so `callChannel` is no longer a dependency, and the row status is read through `rutis/loader`, whose missing public read is raised to the mechanism owner. The appendix binds `register` and `methods` as the face with `#[service(skip)]` for the registration callback, and Appendix F and A.1 now link the call data here instead of defining it a second time. --- docs/design/contracts/session-boundary.md | 71 ++------- docs/design/plugins/SessionMethods.md | 155 +++++++++++-------- docs/zh/design/contracts/session-boundary.md | 71 ++------- 3 files changed, 116 insertions(+), 181 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index e37d8de69b..2b4cac3b35 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -198,7 +198,7 @@ The implemented foreign Session subset is [C4](../session-typescript.md); genera ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). Every error is `MethodError` data. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; a handler answers its own `{code, message}` failure, and the client receives every error in the Rpc envelope `{code, appError, message}`. ### A.1 Method contributions @@ -234,9 +234,9 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | -| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then reads the name's owner in that Session's `sessionMethods`: a registered namespace → its provider; a withdrawn namespace → the status of the registering row's copy in this Session (§9.4), read with the management table (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | +| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§9.4, §3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `Handler`, `Progress`, `RpcError` and `MethodTable`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. They sit beside the Session table `SessionMethods` (Appendix F), as `ToolContribution` and `ToolHandler`, which also takes a `CancellationToken`, live beside ToolRegistry. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `CallerRef`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -551,68 +551,23 @@ existing wire shape. ## Appendix F. Rust binding -The neutral services map to the native owners below. Tools register with ToolRegistry (A.5). Each method table also serves other languages through its own dispatcher: the `SessionMethods` part at `host_key_in("sessionMethods", session_instance)` and App Server's `ManagementMethods` row at `host_key("managementMethods")`. A Session part of another language ([C4](../session-typescript.md)) or a process row ([TypeScript process binding](../process-typescript.md)) injects the table and calls `register(namespace, declarations, call)`, which returns a Promise. The registration belongs to its caller (the bridge's caller row), and `call` is called back through the bridge with C1 admission, progress and `report`/`drain`; admitted calls drain before the caller's cleanup runs. No service lookup by name is added to the Session facade, and entry admission is unchanged. Session parts read Session identity, configuration and closing from the `sessionIdentity`, `sessionConfig` and `sessionLifecycle` services; each listens to its Session's `session/{sessionId}` channel itself. It adds no public facade lookup or critical branch input path. Connection notifications (`notify` and `closed`) are implemented for both bindings; handoff (`takeFinalReply`) remains outside the implemented subset. +The neutral services map to the native owners below. Tools register with ToolRegistry (A.5). Each method table's Rust binding and wire form are its owner's contract: [SessionMethods](../plugins/SessionMethods.md#binding-appendix) for `sessionMethods`, and the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) for `managementMethods`. No service lookup by name is added to the Session facade, and entry admission is unchanged. Session parts read Session identity, configuration and closing from the `sessionIdentity`, `sessionConfig` and `sessionLifecycle` services; each listens to its Session's `session/{sessionId}` channel itself. It adds no public facade lookup or critical branch input path. Connection notifications (`notify` and `closed`) are implemented for both bindings; handoff (`takeFinalReply`) remains outside the implemented subset. | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`, a process service holding a `MethodTable`, provided by App Server's `ManagementMethodsPlugin` row | A process part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Rpc depends on the table and reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382) | -| `sessionMethods` | `SessionMethods`, a Session service holding a `MethodTable`, provided by the `SessionMethodsPlugin` Session part; its check is the process value `ReservedMethods` App Server provides | A Session part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Per call: `Session::session_service::()` on the Session `sessionId` names, after `index.acquire`, then `session_provider` (A.1); no provider is in Rpc's `Deps` | Implemented (C1, #382) | +| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382) | +| `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | -| `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel` | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | +| `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -```rust -// crates/dim-agent-capabilities/src/methods.rs (C1), shared by both services -pub type Handler = Arc< - dyn Fn(MethodCall, CancellationToken, Progress) - -> BoxFuture<'static, Result> + Send + Sync, ->; // (call, cancellation token, progress) -impl Progress { - pub fn send(&self, data: Value); // best effort; dropped unless declared, or once the reply is handed over -} -pub enum Interruption { Report, Drain } -pub struct MethodDecl { - pub name: String, - pub mutating: bool, - #[serde(skip_serializing)] - pub interruption: Interruption, // required in foreign declarations - #[serde(skip_serializing)] - pub progress: bool, // required in foreign declarations - #[serde(default, skip_serializing)] - pub notifications: Vec, // inside the namespace, unique across the set -} -impl MethodProvider { // one provider generation: declarations, handler, admitted calls - pub fn new(ctx: &Ctx, namespace: &str, declarations: Vec, handler: Handler, - foreign: bool) // a part of another language: its calls are recorded until the reply - -> Result, CordisError>; - pub fn accept(self: &Arc, method: String, params: Value, site: Option, - entry_stopping: CancellationToken, progress: impl Fn(Value) + Send + Sync + 'static) - -> Result; -} -// A table's check of a namespace and its declarations before they register. -pub type Check = Arc Result<(), CordisError> + Send + Sync>; -pub enum Owner { Active(Arc), Left { row: Option }, None } -impl MethodTable { // the namespaces registered, and those withdrawn with their last row - pub fn new(check: Check) -> Self; - pub fn register(&self, ctx: &Ctx, namespace: &str, declarations: Vec, - handler: Handler) -> Result<(), CordisError>; // until the part that owns ctx unloads - pub fn owner(&self, name: &str) -> Owner; // the longest namespace holding name - pub fn listed(&self) -> Vec; // the registered namespaces' methods -} -pub struct SessionMethods(pub Arc); // Deref -pub struct ReservedMethods(Check); // process value: the Session table's check -// and the data face `reservedMethods`; `check {namespace, declarations}` asks it -// crates/dim-app-server/src/methods.rs -pub struct ManagementMethods(pub Arc); // Deref -``` +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `CallerRef`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. -`MethodProvider::new` rejects invalid declarations (the A.1 grammar; at least one method, each unique and inside the namespace; and each declared notification: grammar, inside the namespace, unique across the declaration set and never a method's name) and ties the provider to the generation of the part that registers it: when that generation is cancelled, the first step of its unload and before any of its effects runs, the provider stops admitting and interrupts its admitted `Report` calls, and its unload effect waits for every admitted call, so the two tables cannot diverge. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls are told to settle while the plugin still runs. `MethodTable::register` runs the table's `Check`, builds the provider and registers the namespace on behalf of the part that owns `ctx`; a namespace registered already fails. When that part unloads, the table records its row with the namespace, so a later call answers from that row (`Owner::Left`). The `ManagementMethods` check is the management rule of A.1 Reserved names; the Session table's is App Server's `ReservedMethods`, which the table depends on when the assembly names it; a host that names none reserves nothing, and only the grammar applies. `ReservedMethods` is a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and a Rust table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)). The handler receives the `MethodCall` -- the name, the raw params and its `Origin` -- a cancellation token that fires on either unload (A.1) and the call's `Progress`. `origin.caller` is present when a client connection made the call, through either table, and absent otherwise. `RpcError`, with its `From`, lives in the same module (A.1 Shared types); dim-app-server keeps `ManagementMethods`, the reserved-name checks and Rpc's lookups (`management_provider`, `session_provider`). +A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). -`Progress` binds A.2 `progress` per call rather than through a `callChannel` process service: Rpc passes each admitted call a sink that writes `management.progress {id, method, data}` to the calling connection, and the admission hands it to the handler only when the method declares `progress` and closes it before it hands over the reply. The sink queues progress under its own allowance on the connection, so progress never takes room from the reply or durable notifications. Management methods use the same path; `runtime.watch` and `schedule.watch` declare `progress` ([RuntimeManager §10](../plugins/RuntimeManager.md#10-client-change-notices); [Scheduler §11.2](../plugins/Scheduler.md#112-jobs-and-runs)). +`Progress` binds A.2 `progress` per call rather than through a `callChannel` process service: Rpc passes each admitted call a sink that writes `management.progress {id, method, data}` to the calling connection, and the table's `call` hands it to the handler only when the method declares `progress` and closes it before the reply is written. The sink queues progress under its own allowance on the connection, so progress never takes room from the reply or durable notifications. Management methods use the same path; `runtime.watch` and `schedule.watch` declare `progress` ([RuntimeManager §10](../plugins/RuntimeManager.md#10-client-change-notices); [Scheduler §11.2](../plugins/Scheduler.md#112-jobs-and-runs)). ```rust // crates/dim-agent-capabilities/src/methods.rs, shared by both services -pub struct MethodCall { pub method: String, pub params: Value, pub origin: Origin } -pub struct Origin { pub caller: Option } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NotifyError { Undeclared, Gone, TooLarge } // code(): "undeclared", "gone", "too_large" impl Caller { @@ -622,10 +577,10 @@ impl Caller { } ``` -`Caller` binds A.2 `notify` and `closed` per call, like `Progress`: `MethodProvider::accept` builds it only when the call arrived on a client connection, bound to the notifications its declaration set declared, so a name outside that set is `Undeclared` before anything is written, and a generation that has unloaded is `Gone` first. It holds the connection through a trait object (`CallerConnection`) that keeps no strong reference to it, so a provider that keeps a `Caller` does not keep a closed connection alive. Rpc writes each notification after the reply of the call that produced the caller: one sent while the call runs is encoded once, admitted under the connection's held allowance, held in order and flushed right after the reply; one over the frame limit is `TooLarge` and the connection stays open, and one the held allowance cannot take closes the connection as a slow consumer. The caller resolves `closed` when the connection closes or the admitting Rpc load unloads. +`Caller` binds A.2 `notify` and `closed` per call, like `Progress`: the table's `call` builds it only when the call arrived on a client connection, bound to the notifications its declaration set declared, so a name outside that set is `Undeclared` before anything is written, and a generation that has unloaded is `Gone` first. It holds the connection through a trait object (`CallerConnection`) that keeps no strong reference to it, so a provider that keeps a `Caller` does not keep a closed connection alive. Rpc writes each notification after the reply of the call that produced the caller: one sent while the call runs is encoded once, admitted under the connection's held allowance, held in order and flushed right after the reply; one over the frame limit is `TooLarge` and the connection stays open, and one the held allowance cannot take closes the connection as a slow consumer. The caller resolves `closed` when the connection closes or the admitting Rpc load unloads. -`Callers` is private transport wiring shared by the CallChannel and Rpc rows at its Rust type key; it has no service catalog name. The public operation surface remains `callChannel`. `Callers` is the process's only caller index: per row instance it holds the notification names its generation declared, kept after a connection of that instance closes so `Undeclared` is decided before `Gone`, and per row instance and connection the connection's direct writer and the row's unfinished calls by `callId`. `MethodProvider::accept` mints a foreign call's `callId` where the call's sink, the instance and the provider's declarations meet, and records the call; `Connection::answer` removes it after the reply is written. The entries of a connection are removed when it closes, when the admitting Rpc load unloads and when the row's generation unloads; the declared names go with the instance's generation. A native provider keeps its own `Caller` and records nothing. App Server provides A.2 `callChannel` for other languages as the process service `callChannel` (`ForeignCallChannel`, at `host_key("callChannel")`, from the `CallChannel` row that has no dependencies): its `notify` and `closed` read the calling row's instance with `rutis_bridge::session::caller_row()` and end in the same call's sink the Rust binding uses, so both bindings share one delivery path. +`Callers` is private transport wiring shared by the CallChannel and Rpc rows at its Rust type key; it has no service catalog name. The public operation surface remains `callChannel`. `Callers` is the process's only caller index: per row instance it holds the notification names its generation declared, kept after a connection of that instance closes so `Undeclared` is decided before `Gone`, and per row instance and connection the connection's direct writer and the row's unfinished calls by `callId`. The table's admission mints a foreign call's `callId` where the call's sink, the instance and the provider's declarations meet, and records the call; `Connection::answer` removes it after the reply is written. The entries of a connection are removed when it closes, when the admitting Rpc load unloads and when the row's generation unloads; the declared names go with the instance's generation. A native provider keeps its own `Caller` and records nothing. App Server provides A.2 `callChannel` for other languages as the process service `callChannel` (`ForeignCallChannel`, at `host_key("callChannel")`, from the `CallChannel` row that has no dependencies): its `notify` and `closed` read the calling row's instance with `rutis_bridge::session::caller_row()` and end in the same call's sink the Rust binding uses, so both bindings share one delivery path. -The foreign `register` (`ForeignMethods`, shared by both tables) decodes the declarations once, with the required fields above. It calls `call` with `{callId, method, params}` and, when the call came from a connection, `origin: {connectionId}`, a cancellation Promise and a per-call progress callback, and decodes `{kind:"value", value}` or a `{code, message}` error, whose `code` is the `appError`; an omitted `value`, including JavaScript `undefined` omitted by JSON serialization, becomes JSON `null`. A method may instead rethrow a service error it received. Unsupported declaration/reply fields and malformed data fail at this boundary. Not implemented: final-reply handoff, `origin.entry` and `origin.peer`, and the `reply` declaration field. +Another language registers through the owning table's dispatch: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), the process table's is its own contract ([#2021](https://github.com/arcships/dim/issues/2021)). Each decodes the declarations once and calls the same `register` with the caller's function; `ForeignMethods` leaves. Not implemented in either binding: final-reply handoff, `origin.entry`, `origin.peer` and the `reply` declaration field. `ToolContribution` and `ToolHandler` are the native types in `dim-agent-capabilities/src/tool_registry.rs`. `ToolRegistry::register(ctx, ToolContribution)` registers on behalf of the part that owns `ctx`, until that part unloads; it refuses a name outside `[A-Za-z0-9_-]{1,64}`, a host tool's name and a name registered already. Other languages reach `toolRegistry` through ToolRegistry's dispatcher: `register(declaration, execute, options?)` decodes the declaration as `ToolDefinition` once, requires a nonempty `risk`, and registers, on behalf of the calling row (the bridge's `caller_row`), a `ToolHandler` that calls `execute` back through the bridge. `options.concurrency` is `'concurrent'` or absent; it is not part of the declaration, because the class is an execution property of the bound handler, so the persisted `ToolDefinition` keeps its shape. Absent means the tool's calls run alone, in call order. That handler holds the calling row's generation token: once the row starts unloading, a call through a retained handler is not made, and a call in flight ends with an error warning that it may already have taken effect, without rebinding to a replacement generation; the foreign owner still settles its JavaScript work. Each execution derives a child cancellation token so completing one call cannot cancel other tools in the same batch. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 068ff66a10..0358538718 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -2,7 +2,7 @@ Scope: session. Issue: #2026. -SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The table's call data — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is defined here once for both method tables. ManagementMethods (#2021) is the process table; Rpc, the registering parts and `session.methods` are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). +SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The call data both method tables serve — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — has one definition, in the `methods` module of `dim-agent-capabilities`; this contract states it. ManagementMethods (#2021) is the process table; Rpc, the registering parts and `session.methods` are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). ## Use and scope: responsibility split @@ -26,7 +26,7 @@ Callers keep: | Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | | `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | | The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `reserved`; a pre-check races the next registration | Business | -| Rpc routes a name between management and Session | Yes: management answers its own `call` and whether it holds a name; Rpc reads `sessionId` | Business | +| Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: the handler has the caller identity and uses `callChannel` (#2021) | Business | An operation or parameter exists only where the row says No. @@ -44,30 +44,36 @@ methods.register( ).await?; ``` -Rpc dispatches one wire call; the caller identity is data, and the reply is `MethodReply` data: +Rpc dispatches one wire call; the caller identity is data, the call's sink is the connection's, and the reply is `MethodReply` data: ```rust let reply = match methods.call( method.into(), params, - Some(CallerRef { connection_id, call_id }), + Some(CallerRef { connection_id, call_id: call_id.clone() }), cancelled.clone(), + move |data| connection.progress(call_id.clone(), data), ).await { Ok(reply) => reply, Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), Err(MethodError::Reloading) => return Err(RpcError::reloading()), Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), - Err(MethodError::Invalid { .. }) => return Err(RpcError::invalid("Invalid request parameters")), Err(MethodError::Closed) => return Err(RpcError::closed()), - Err(MethodError::Reserved { .. }) | Err(MethodError::Duplicate { .. }) => unreachable!("dispatch cannot register"), + Err(MethodError::Reserved { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Invalid { .. }) => unreachable!("dispatch cannot register"), }; ``` -`session.methods` composes the value with the management table: +`session.methods` composes the value with the process table's held namespaces: ```rust -let listed = methods.methods()?.into_iter().filter(|decl| !management.holds(&decl.name)).collect::>(); +// A.1's longest-namespace rule: a name a held management namespace equals or +// prefixes is routed to management and is never listed for the Session. +let held = management.held_namespaces(); +let listed = methods.methods()?.into_iter().filter(|decl| { + let covered = |ns: &str| decl.name == ns || decl.name.strip_prefix(ns).is_some_and(|rest| rest.starts_with('.')); + !held.iter().any(|namespace| covered(&namespace.namespace)) +}).collect::>(); ``` ## Own contract @@ -77,48 +83,49 @@ let listed = methods.methods()?.into_iter().filter(|decl| !management.holds(&dec | Service | Purpose | | --- | --- | | `P:reservedMethods` | The host's reserved names, consulted at registration; a host that names none reserves only the name grammar. | -| `P:callChannel` | The calling connection's per-call progress, addressed by the caller's `{connectionId, callId}`; the table builds the handler's `Progress` from it, and an in-process call has none. | -| Host port: the registering row's status | The row that registered a withdrawn namespace and its copy in this Session, read when a call answers `reloading` or `unavailable`. The host supplies the port, so the table names no public service for the read. | +| `P:loader` (`rutis_loader::Loader`, App Server's loader row) | The row that registered a withdrawn namespace and its copy in this Session: `get(row)` answers the row's `EntryStatus`, and `entries()` lists its copies with their instances. Read when a call answers `reloading` or `unavailable`; the name is `internal(owner-api)` today, so the read is raised to the mechanism owner (§4 rule 8). | + +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data, and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule; its contract states both. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | The calling connection closing ends the call as interrupted; the provider's unload ends it by its declaration (`report` or `drain`) | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `invalid`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` and the call's progress sink are binding parameters, not request fields. The admitting Rpc load's unload and the provider's generation unload interrupt the call: `report` answers `interrupted` and settles, `drain` replies with its own result. A caller disconnect cancels nothing | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | -`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses; absent for an in-process call. The table passes the caller identity to the handler unchanged and writes no socket. The handler receives a `Progress` for its call through `callChannel`, addressed by the same ids; an in-process call has none. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; its future is dropped when the call is interrupted. +`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses; absent for an in-process call. The table passes the caller identity to the handler unchanged and writes no socket. The table hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's unload and on the admitting Rpc load's. -A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. An error reply reaches the client as an error whose `appError` is the handler's `code`, with the JSON-RPC code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, its message the handler's `message`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). ### Errors -| Kind | Client `appError` | What the caller does next | -| --- | --- | --- | -| `reserved` | — | The namespace or a name is the host's; pick another name | -| `duplicate` | — | The namespace is registered already; the row must not register twice | -| `invalid` | `invalid_params` | The namespace or a declaration is outside the grammar, or the request is malformed | -| `unknown_method` | `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | -| `reloading` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | -| `unavailable` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | -| `interrupted` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | -| `closed` | `session_closed` | This Session is closing; a later generation serves the next Session | +| Kind | Operation | Client `appError` | What the caller does next | +| --- | --- | --- | --- | +| `reserved` | `register` | — | The namespace or a name is the host's; pick another name | +| `duplicate` | `register` | — | The namespace is registered already; the row must not register twice | +| `invalid` | `register` | `invalid_params` | The namespace or a declaration is outside the grammar | +| `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | +| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | +| `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | +| `interrupted` | `call` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | +| `closed` | all | `session_closed` | This Session is closing; a later generation serves the next Session | -`reserved` and `duplicate` answer a registration only, so no client sees them. +`reserved`, `duplicate` and `invalid` answer a registration only, so no client sees them. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the grammar, the reserved names and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | -| `call` | Find the owner, admit the call, run the callback, return the reply; on unload interrupt `report` and wait for `drain` | The connection's close ends the call as interrupted; the handler's own work settles by its own rule | The call ends; the registration's accepted calls settle | A withdrawn namespace answers from its row's status; a table reload ends in-flight calls | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | A disconnect cancels nothing; the accepted call settles by its declaration | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations | — | Nothing to release | Pending reads answer from the state they observed | SessionMethods | ## Exceptions with reasons -- The table reads the registering row's status through a host port: the status is the mechanism's record of the row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. -- A handler's progress and notifications are not written here: the caller identity is data and `callChannel` (#2021) addresses the connection by call id, so no connection, `Caller` or caller index crosses this owner. +- The table reads the registering row's status through `rutis/loader`: the status is the mechanism's record of the row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. The name is `internal(owner-api)` today; §4 rule 8 records the read. +- A handler's notifications are not written here: the caller identity is data and `callChannel` (#2021) addresses the connection by call id, so no connection, `Caller` or caller index crosses this owner. - The table remembers the registering row per namespace: a withdrawn namespace must answer from that row rather than fall through to a parent namespace. ## Verification @@ -126,19 +133,19 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are refused; a refused registration fails the registering part. -- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held is `unknown_method`. -- A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result. +- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. +- A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. - The caller identity reaches the handler unchanged for a wire call and is absent for an in-process call; the handler's notification with the same call id is written by `callChannel`. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. -- `methods` lists the registered declarations; Rpc's filter removes management-held names. +- `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. ## Rule check | Rule | Application | | --- | --- | -| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and the call channel, and reads the registering row's status through a host port. | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and reads the loader's row status. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | -| §3 orthogonality | No other business owner's state is read or changed; the reserved names, the call channel and the row-status port are the mechanism's faces. | +| §3 orthogonality | No other business owner's state is read or changed; the reserved names and the loader's row status are the mechanism's faces. | | §4 rule 1 | No command event: a registration is the calling row's effect. | | §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | | §4 rule 3 | No before callback. | @@ -146,12 +153,15 @@ Flow tests on the owner: | §4 rule 5 | No batches. | | §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. | -| §4 rule 8 | No infrastructure change; the withdrawn-row answer reads the mechanism's existing record through the port. | +| §4 rule 8 | No infrastructure change in this contract: the withdrawn-row answer uses the loader's existing row status, whose read is raised to the mechanism owner (see below). | | §4 rule 9 | No Timeline fact. | -| §7 values, ids and callbacks | The caller identity is data; the call callback crosses by reference; a registration lives with its row; no object, channel or provider crosses. | -| §7 no proxy | The table answers its own registrations; the host port answers the row status. | -| §7 one interface | One name, `sessionMethods`, on the owner type; the Rust binding and the wire call the same methods; the call data is defined here once; `SessionMethods` no longer derefs to a shared table type. | -| §7 cross-language | `register` crosses as data plus the caller's callback, `methods` as data, and `call` is Rpc's in-process call with the protocol's cancellation; no operation is a Rust-only convenience. | +| §7 values, ids and callbacks | The caller identity is data; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row; no object, channel or provider crosses. | +| §7 no proxy | The table answers its own registrations; the loader answers the row status. | +| §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | +| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the progress sink and the cancellation, neither of which is data. | +| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | +| §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | +| §7.2 review checks | No cross-owner call is left unmapped; no object or handle crosses; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | | ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | | ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | @@ -161,29 +171,28 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -1. [#2021](https://github.com/arcships/dim/issues/2021): the process table serves the same `call {method, params, caller?}` request and `{reply}` shape, so Rpc has one call path for both tables. -2. [#2021](https://github.com/arcships/dim/issues/2021): the process table answers whether a registered or withdrawn namespace holds a name (today `MethodTable::holds`); Rpc routes a name by it and `session.methods` removes the names it holds. -3. [#2021](https://github.com/arcships/dim/issues/2021): `reservedMethods` stays a process face; the Session table consults `check {namespace, declarations}` at registration. -4. [#2021](https://github.com/arcships/dim/issues/2021): `callChannel` answers a progress write addressed by `{connectionId, callId}`; the table builds each call's `Progress` from it, because `call` takes the caller rather than a sink. -5. [#2021](https://github.com/arcships/dim/issues/2021): reply handoff (`handedOff`, `daemon.shutdown`) is not implemented; when it lands it is a variant of this shared `MethodReply`, and the process table's contract states it. +| Field | Value | +| --- | --- | +| Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and `loader` is `internal(owner-api)` in the catalog, so the table has no readable face for it. | +| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on the public `loader` name: blocked, it is `internal(owner-api)` and `dim-agent-capabilities` does not depend on `rutis-loader`. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | +| Generic capability needed | A data face over one loader row: `{row, instance}` → the row's `EntryStatus` and the status of its copy in that instance. No business meaning. | +| Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | +| Who implements it, which issue | The mechanism owner: App Server's loader row and rutis-loader (`loader`, `crates/dim-app-server/src/lib.rs:1626`; the read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`), tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted`/`Caller`/`CallSite`/`Callers` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined here and A.1 links to them. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted`/`Caller`/`CallSite`/`Callers` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. No client wire protocol or user-visible behavior changes: `register` keeps its wire form `register(namespace, declarations, call)` for a part of another language, and every client error keeps its application code. ## Binding appendix -The owner type `SessionMethods` carries the catalog name `sessionMethods` and serves other languages at its Session dispatcher key. `#[rutis::service]` cannot bind the face: `register` takes a callback and `call` a cancellation, so the dispatch is written by hand and calls the same operations. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `MethodDecl`, `Interruption` and `Progress` are the capabilities crate's types; `RpcError` is its wire error, and the caller example above uses it. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. The process table ([ManagementMethods](https://github.com/arcships/dim/issues/2021)) uses the same `MethodDecl`, `MethodCall`, `MethodReply`, `MethodCallbackError`, `MethodError`, `CallerRef` and `Interruption`. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below, beside `MethodDecl`, `Interruption` and `Progress`. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust -use crate::host::CancelledFn; -use crate::methods::{MethodDecl, Progress}; -use rutis::host::{BoxFuture, CallError}; -use rutis::Ctx; -use rutis_bridge::session::{HostDispatch, Reply, Value as BridgeValue}; -use tokio_util::sync::CancellationToken; +// crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. +use rutis::host::CallError; /// Who called: the connection the call arrived on and the call id the reply /// ordering uses; absent for an in-process call. @@ -208,7 +217,8 @@ pub struct Origin { pub caller: Option, } -/// A handler's own failure, carried to the client as its `code` and `message`. +/// A handler's own failure: its application code and message, which the client +/// sees as the Rpc envelope's `appError` and message. #[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[error("{code}: {message}")] @@ -227,9 +237,8 @@ impl From for MethodCallbackError { } } -/// The dispatch reply: the handler's value, or its own error as data. The -/// bridge writes a value as `{kind: "value", value}` and an error as -/// `{code, message}`. +/// The handler's reply: its value, or its own failure as data. The bridge +/// writes a value as `{kind: "value", value}` and a failure as `{code, message}`. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum MethodReply { @@ -252,6 +261,7 @@ impl From for MethodReply { } } +/// The table's own failures, by kind. #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum MethodError { @@ -272,13 +282,27 @@ pub enum MethodError { #[error("the Session is closing")] Closed, } +``` + +```rust +// crates/dim-agent-capabilities/src/methods.rs: the owner, in the same module. +use crate::host::CancelledFn; +use crate::methods::{MethodDecl, Progress}; +use rutis::host::BoxFuture; +use rutis::Ctx; +use rutis_bridge::session::{HostDispatch, Reply, Value as BridgeValue}; +use tokio_util::sync::CancellationToken; /// The owner type; the namespaces, their declarations and their last rows /// stay private. pub struct SessionMethods { /* ... */ } +#[rutis::service(name = "sessionMethods")] impl SessionMethods { /// Publishes `namespace` for the lifetime of the row that owns `caller`. + /// The macro leaves it to the dispatch below: the callback's arguments are + /// not data. + #[service(skip)] pub async fn register( &self, caller: &Ctx, @@ -287,30 +311,31 @@ impl SessionMethods { call: impl Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> + Send + Sync + 'static, ) -> Result<(), MethodError> { /* ... */ } + /// The declarations registered now. + pub fn methods(&self) -> Result, MethodError> { /* ... */ } + + /// One call, in process: the cancellation and the progress sink are + /// parameters, and the reply is data. + #[service(skip)] pub async fn call( &self, method: String, params: serde_json::Value, caller: Option, cancelled: CancelledFn, - ) -> Result { /* ... */ } // builds MethodCall { method, params, origin } - - pub fn methods(&self) -> Result, MethodError> { /* ... */ } + progress: impl Fn(serde_json::Value) + Send + Sync + 'static, + ) -> Result { /* ... */ } } -/// The catalog name `sessionMethods` in the Session group, served to other -/// languages at its dispatcher key. `#[rutis::service]` cannot bind this face: -/// `register` carries a callback and `call` a cancellation, and neither is -/// data. The dispatch decodes the wire form and calls the same operations. +/// Another language reaches the table at its Session dispatcher key: +/// `register {namespace, declarations, call}` and `methods {}`. impl HostDispatch for SessionMethods { fn methods(&self) -> Option { - Some(serde_json::json!({ "register": "async" })) + Some(serde_json::json!({ "register": "async", "methods": "sync" })) } - /// `register {namespace, declarations, call}`, registered for the bridge's - /// calling row. fn invoke(&self, method: &str, args: BridgeValue) -> Reply { /* ... */ } } ``` -`MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name. `SessionMethods` derives the catalog name `sessionMethods` from the owner type, as it does today; `ForeignMethods` no longer exists and the dispatch above is the owner's own entry. +`register` and `methods` are the wire face: `register` through the dispatch above, which decodes the declarations and the caller's function for the bridge's calling row, and `methods` through the marked service and that dispatch. `call` is the owner's in-process operation, so its cancellation and progress sink never cross a wire. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant, never carried in the data. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 6c556854d6..27647afead 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -198,7 +198,7 @@ sequenceDiagram ## 附录 A. 接口细节 -结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。每个错误都是 `MethodError` 数据。 +结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约;处理函数以自己的 `{code, message}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, appError, message}`。 ### A.1 方法贡献 @@ -234,9 +234,9 @@ sequenceDiagram | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | -| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 在该 Session 的 `sessionMethods` 中读取该名称的所有者:已注册的命名空间 → 其提供方;已撤回的命名空间 → 读取注册它的行在本 Session 中的副本状态(§9.4),按管理方法的对照表作答(§3.2):该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | +| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§9.4、§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`Handler`、`Progress`、`RpcError` 与 `MethodTable`,连同两张方法表共用的调用受理逻辑,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session Capability 不能依赖 dim-app-server。它们与 Session 方法表 `SessionMethods` 放在一起(附录 F),如同 `ToolContribution` 与同样接收 `CancellationToken` 的 `ToolHandler` 和 ToolRegistry 放在一起。不放在 dim-agent-types:它只允许依赖 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不依赖 Tokio 或 rutis),而 `Handler` 接收 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 放在那里时,`From for RpcError` 只能在 dim-agent-runtime 中实现(孤儿规则)。放在 dim-agent-capabilities 时,这个转换与 `RpcError` 放在一起,Rpc 与 Session 提供方仍可对运行时错误使用 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`CallerRef`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | | `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | @@ -514,68 +514,23 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 ## 附录 F. Rust 绑定 -上述服务映射到下列原生所有者。工具注册到 ToolRegistry(A.5)。每张方法表也经自己的分发器服务其他语言:`SessionMethods` 部件在 `host_key_in("sessionMethods", session_instance)`,App Server 的 `ManagementMethods` 行在 `host_key("managementMethods")`。其他语言的 Session 部件([C4](../../../design/session-typescript.md))或进程行([TypeScript 进程绑定](../../../design/process-typescript.md))注入方法表并调用 `register(namespace, declarations, call)`,它返回一个 Promise。注册属于调用方(桥的调用方行),`call` 经桥回调,并使用 C1 的受理、进度与 `report`/`drain`;已受理的调用在调用方清理之前结束。不向 Session facade 增加按名称的服务查找,入口准入不变。Session 部件从 `sessionIdentity`、`sessionConfig` 与 `sessionLifecycle` 服务读取 Session 标识、配置与 closing;每个部件自己监听其 Session 的 `session/{sessionId}` 通道。它不增加公开 facade 查找或关键分支输入路径。连接通知(`notify` 与 `closed`)在两种绑定中均已实现;交接(`takeFinalReply`)不在已实现的子集内。 +上述服务映射到下列原生所有者。工具注册到 ToolRegistry(A.5)。每张方法表的 Rust 绑定与线上形状归其所有者契约:`sessionMethods` 见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),`managementMethods` 见进程表的契约([#2021](https://github.com/arcships/dim/issues/2021))。不向 Session facade 增加按名称的服务查找,入口准入不变。Session 部件从 `sessionIdentity`、`sessionConfig` 与 `sessionLifecycle` 服务读取 Session 标识、配置与 closing;每个部件自己监听其 Session 的 `session/{sessionId}` 通道。它不增加公开 facade 查找或关键分支输入路径。连接通知(`notify` 与 `closed`)在两种绑定中均已实现;交接(`takeFinalReply`)不在已实现的子集内。 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | -| `sessionMethods` | `SessionMethods`,持有一个 `MethodTable` 的 Session 服务,由 `SessionMethodsPlugin` Session 部件提供;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | 每次调用:在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `Session::session_service::()`,再经 `session_provider`(A.1);没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382) | +| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | +| `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | -| `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel` | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | +| `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -```rust -// crates/dim-agent-capabilities/src/methods.rs(C1),两个服务共用 -pub type Handler = Arc< - dyn Fn(MethodCall, CancellationToken, Progress) - -> BoxFuture<'static, Result> + Send + Sync, ->; // (call, 取消令牌, 进度) -impl Progress { - pub fn send(&self, data: Value); // 尽力送达;未声明时、或回复交出之后丢弃 -} -pub enum Interruption { Report, Drain } -pub struct MethodDecl { - pub name: String, - pub mutating: bool, - #[serde(skip_serializing)] - pub interruption: Interruption, // 外来声明必填 - #[serde(skip_serializing)] - pub progress: bool, // 外来声明必填 - #[serde(default, skip_serializing)] - pub notifications: Vec, // 位于命名空间内,整个声明集内唯一 -} -impl MethodProvider { // 一代提供方:声明、处理函数、已受理的调用 - pub fn new(ctx: &Ctx, namespace: &str, declarations: Vec, handler: Handler, - foreign: bool) // 其他语言的部件:其调用被记录到回复写出 - -> Result, CordisError>; - pub fn accept(self: &Arc, method: String, params: Value, site: Option, - entry_stopping: CancellationToken, progress: impl Fn(Value) + Send + Sync + 'static) - -> Result; -} -// 方法表在命名空间及其声明注册之前对它们的检查。 -pub type Check = Arc Result<(), CordisError> + Send + Sync>; -pub enum Owner { Active(Arc), Left { row: Option }, None } -impl MethodTable { // 已注册的命名空间,以及已撤回的命名空间与其最后的行 - pub fn new(check: Check) -> Self; - pub fn register(&self, ctx: &Ctx, namespace: &str, declarations: Vec, - handler: Handler) -> Result<(), CordisError>; // 直到拥有 ctx 的部件卸载 - pub fn owner(&self, name: &str) -> Owner; // 持有 name 的最长命名空间 - pub fn listed(&self) -> Vec; // 已注册命名空间的方法 -} -pub struct SessionMethods(pub Arc); // Deref -pub struct ReservedMethods(Check); // 进程值:Session 方法表的检查, -// 也是数据面 `reservedMethods`;`check {namespace, declarations}` 就是这个问题 -// crates/dim-app-server/src/methods.rs -pub struct ManagementMethods(pub Arc); // Deref -``` +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`CallerRef`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 -`MethodProvider::new` 拒绝无效的声明(A.1 的语法;至少一个方法,每个方法唯一且位于命名空间内;以及每个声明的通知:符合语法、位于命名空间内、整个声明集内不重复,且不等于任何方法名),并把提供方绑定到注册它的部件的这一代:这一代被取消时(这是卸载的第一步,早于它的任何 effect),提供方停止受理,并中断已受理的 `Report` 调用;它的卸载 effect 等待每个已受理调用,因此两张方法表不会分叉。其他语言的行在其 apply 返回的 effect 里卸载插件,这个 effect 先于 apply 期间注册的 effect 运行,所以它已受理的调用在插件仍在运行时就收到结束信号。`MethodTable::register` 先运行方法表的 `Check`,再构造提供方,并代表拥有 `ctx` 的部件注册该命名空间;已被注册的命名空间会失败。该部件卸载时,方法表把它的行与命名空间一起记下,之后的调用按该行作答(`Owner::Left`)。`ManagementMethods` 的检查是 A.1 保留名中的管理规则;Session 方法表的检查是 App Server 的 `ReservedMethods`,装配登记了这个名字时方法表依赖它;宿主不登记它时不保留任何名字,只检查语法。`ReservedMethods` 是数据面:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个))。处理函数接收 `MethodCall`——方法名、原始 params 与其 `Origin`——在任一卸载时触发的取消令牌(A.1),以及该调用的 `Progress`。调用由客户端连接发出时(无论经哪张表)`origin.caller` 存在,否则不存在。`RpcError`(连同它的 `From`)位于同一模块(A.1 共享类型);`ManagementMethods`、保留名检查与 Rpc 的查找(`management_provider`、`session_provider`)留在 dim-app-server。 +注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 -`Progress` 按调用绑定 A.2 的 `progress`,而不是通过 `callChannel` 进程服务:Rpc 给每个已受理调用一个 sink,把 `management.progress {id, method, data}` 写到发起调用的连接;受理逻辑只在方法声明了 `progress` 时把它交给处理函数,并在交出回复之前关闭它。sink 在连接上按进度自己的额度排队,所以进度不会占用回复和持久通知的空间。管理方法走同一路径;`runtime.watch` 与 `schedule.watch` 声明了 `progress`([RuntimeManager §10](../plugins/RuntimeManager.md#10-客户端变更通知);[Scheduler §11.2](../plugins/Scheduler.md#112-任务与运行))。 +`Progress` 按调用绑定 A.2 的 `progress`,而不是通过 `callChannel` 进程服务:Rpc 给每个已受理调用一个 sink,把 `management.progress {id, method, data}` 写到发起调用的连接;方法表的 `call` 只在方法声明了 `progress` 时把它交给处理函数,并在回复写出之前关闭它。sink 在连接上按进度自己的额度排队,所以进度不会占用回复和持久通知的空间。管理方法走同一路径;`runtime.watch` 与 `schedule.watch` 声明了 `progress`([RuntimeManager §10](../plugins/RuntimeManager.md#10-客户端变更通知);[Scheduler §11.2](../plugins/Scheduler.md#112-任务与运行))。 ```rust // crates/dim-agent-capabilities/src/methods.rs,两个服务共用 -pub struct MethodCall { pub method: String, pub params: Value, pub origin: Origin } -pub struct Origin { pub caller: Option } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NotifyError { Undeclared, Gone, TooLarge } // code():"undeclared"、"gone"、"too_large" impl Caller { @@ -585,10 +540,10 @@ impl Caller { } ``` -`Caller` 与 `Progress` 一样按调用绑定 A.2 的 `notify` 与 `closed`:只有调用来自客户端连接时 `MethodProvider::accept` 才构造它,并绑定到该声明集声明的通知,因此集合外的名称在写入任何内容之前就是 `Undeclared`,已卸载的代际则先返回 `Gone`。它通过 `CallerConnection` 这个 trait 对象持有连接,而该对象不强引用连接,所以保留 `Caller` 的提供方不会让已关闭的连接存活。Rpc 在产生该 `Caller` 的调用回复之后写出每条通知:调用进行中发出的通知只编码一次,经连接的暂存额度受理,按序暂存,紧接回复之后写出;超过帧上限的通知是 `TooLarge`,连接保持;暂存额度收不下的通知作为慢消费者关闭连接。连接关闭或受理该调用的 Rpc 代际卸载时,`closed` 完成。 +`Caller` 与 `Progress` 一样按调用绑定 A.2 的 `notify` 与 `closed`:只有调用来自客户端连接时方法表的 `call` 才构造它,并绑定到该声明集声明的通知,因此集合外的名称在写入任何内容之前就是 `Undeclared`,已卸载的代际则先返回 `Gone`。它通过 `CallerConnection` 这个 trait 对象持有连接,而该对象不强引用连接,所以保留 `Caller` 的提供方不会让已关闭的连接存活。Rpc 在产生该 `Caller` 的调用回复之后写出每条通知:调用进行中发出的通知只编码一次,经连接的暂存额度受理,按序暂存,紧接回复之后写出;超过帧上限的通知是 `TooLarge`,连接保持;暂存额度收不下的通知作为慢消费者关闭连接。连接关闭或受理该调用的 Rpc 代际卸载时,`closed` 完成。 -`Callers` 是 CallChannel 和 Rpc 行通过 Rust 类型键共享的私有传输装配,不登记服务目录名称;公开操作面仍是 `callChannel`。`Callers` 是进程内唯一的调用方索引:按行实例保存该代际声明的通知名称,该实例的连接关闭后仍保留,因此先判定 `Undeclared` 再看连接状态;并按行实例与连接保存该连接的直接写入端与该行按 `callId` 记录的未完成调用。`MethodProvider::accept` 在调用的 sink、实例与提供方声明都可用的位置生成其他语言调用的 `callId` 并记录该调用;`Connection::answer` 在回复写出后移除它。连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除该连接的条目;声明的名称随该实例的代际一起删除。原生提供方保留自己的 `Caller`,不记录任何内容。App Server 以进程服务 `callChannel`(`ForeignCallChannel`,位于 `host_key("callChannel")`,由无依赖的 `CallChannel` 行提供)向其他语言提供 A.2 的 `callChannel`:其 `notify` 与 `closed` 用 `rutis_bridge::session::caller_row()` 读取调用行的实例,并最终落在 Rust 绑定所用同一次调用的 sink 上,两种绑定共用一条送达路径。 +`Callers` 是 CallChannel 和 Rpc 行通过 Rust 类型键共享的私有传输装配,不登记服务目录名称;公开操作面仍是 `callChannel`。`Callers` 是进程内唯一的调用方索引:按行实例保存该代际声明的通知名称,该实例的连接关闭后仍保留,因此先判定 `Undeclared` 再看连接状态;并按行实例与连接保存该连接的直接写入端与该行按 `callId` 记录的未完成调用。方法表的受理在调用的 sink、实例与提供方声明都可用的位置生成其他语言调用的 `callId` 并记录该调用;`Connection::answer` 在回复写出后移除它。连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除该连接的条目;声明的名称随该实例的代际一起删除。原生提供方保留自己的 `Caller`,不记录任何内容。App Server 以进程服务 `callChannel`(`ForeignCallChannel`,位于 `host_key("callChannel")`,由无依赖的 `CallChannel` 行提供)向其他语言提供 A.2 的 `callChannel`:其 `notify` 与 `closed` 用 `rutis_bridge::session::caller_row()` 读取调用行的实例,并最终落在 Rust 绑定所用同一次调用的 sink 上,两种绑定共用一条送达路径。 -外来 `register`(`ForeignMethods`,两张方法表共用)一次性解码声明,要求上列必填字段。它在调用来自连接时以 `{callId, method, params, origin: {connectionId}}`、否则以 `{callId, method, params}`、取消 Promise 及逐次调用的进度回调调用 `call`,并解码 `{kind:"value", value}` 或 `{code, message}` 错误,其中 `code` 即 `appError`;省略的 `value`(包括 JSON 序列化时省略的 JavaScript `undefined`)成为 JSON `null`。方法也可以重新抛出它收到的服务错误。不支持的声明/回复字段及损坏数据在此边界失败。尚未实现:最终回复交接、`origin.entry` 与 `origin.peer`,以及 `reply` 声明字段。 +外来注册经各自表的分发器:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。两者都一次性解码声明,并以调用方的函数调用同一个 `register`;`ForeignMethods` 离开。两种绑定都未实现:最终回复交接、`origin.entry`、`origin.peer` 与 `reply` 声明字段。 `ToolContribution` 与 `ToolHandler` 是 `dim-agent-capabilities/src/tool_registry.rs` 中的原生类型。`ToolRegistry::register(ctx, ToolContribution)` 代表拥有 `ctx` 的部件注册,直到该部件卸载;它拒绝不满足 `[A-Za-z0-9_-]{1,64}` 的名称、宿主工具名和已被注册的名称。其他语言经 ToolRegistry 的分发器访问 `toolRegistry`:`register(declaration, execute, options?)` 把声明解码为 `ToolDefinition` 一次,要求 `risk` 非空,并代表调用方行(桥的 `caller_row`)注册一个经桥回调 `execute` 的 `ToolHandler`。`options.concurrency` 取 `'concurrent'` 或缺省;它不属于声明,因为这个类别是绑定后处理器的执行属性,所以落盘的 `ToolDefinition` 形状不变。缺省表示该工具的调用单独执行,按调用顺序。该处理器持有调用方行的代次令牌:行开始卸载后,经保留的处理器发起的调用不会发出,在途调用以错误结束,错误提示它可能已经生效,不会改绑到新的代次;外部所有者仍负责结算其 JavaScript 工作。每次执行派生自己的子取消令牌,单个工具正常完成不会取消同批其他工具。 From 49d1420691840b460963351a3a1d72ae6b4c29ff Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:12:28 +0800 Subject: [PATCH 04/41] docs(sessionmethods): answer the second pre-review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A native handler receives A.2's `Caller` in `MethodCall.origin.caller`, and `call` takes the admission's site, so notifications work for native and foreign handlers alike. The handler error's code is the error's application code, not its type name; `closed` is one neutral kind for both tables; the appendix defines `Handler` once. A.1 and Appendix F stop naming a `caller` request field or the old provider read, and §9.4 hands the row-status answer to this table. --- .../rust-agent/plugins/SessionMethods.md | 14 ++- docs/design/contracts/session-boundary.md | 20 ++- docs/design/plugins/SessionMethods.md | 115 ++++++++++-------- docs/zh/design/contracts/session-boundary.md | 20 ++- 4 files changed, 90 insertions(+), 79 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 4f3f8c3a72..2012f979be 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -17,10 +17,16 @@ accepted. The value is also the data face `reservedMethods`: a row of another language asks `check {namespace, declarations}` the same question ([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个)). +The contract also answers a withdrawn namespace from the row that registered it. +Rpc reads that row today (`session_provider` in +[dim-app-server/src/methods.rs](../../../../crates/dim-app-server/src/methods.rs)); +the table itself has no readable face for it, and the read is raised in the +contract ([SessionMethods §4 rule 8](../../../design/plugins/SessionMethods.md#requirements-raised-to-mechanism-owners)). + ## Events and lifetime No Timeline events, worker tasks or I/O. A part depends on `sessionMethods` and -calls `register(ctx, namespace, declarations, handler)` from its own `apply`; +calls `register(ctx, namespace, declarations, call)` from its own `apply`, with the part's own function as `call`; the registration is withdrawn when that part unloads, and a namespace registered already fails ([rutis usage R6](../../../design/rutis-usage.md#r6-contributions-register-with-their-owner)). @@ -31,9 +37,9 @@ called back through the bridge. The table provides that entry itself, at its dispatcher key, with the native service. A name belongs to the longest namespace that holds it. When a namespace is -withdrawn, the table keeps the row that registered it, so Rpc answers a call -into it from that row's status (`service_reloading` or `service_unavailable`) -rather than `unknown_method`. Each registration owns the calls it admitted: its +withdrawn, the table keeps the row that registered it, so a call into it answers +`service_reloading` or `service_unavailable` from that row's status rather than +`unknown_method`. Each registration owns the calls it admitted: its part's unload interrupts `report` calls and waits for every admitted call. `session.methods` lists the methods of the namespaces registered now that no management namespace holds. diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 2b4cac3b35..986c74ef42 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -138,7 +138,7 @@ Methods have no model-visible effect. A method that changes model context does s | Service and method | Mode | Purpose | | --- | --- | --- | -| `sessionMethods.register(caller, namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; shape in [SessionMethods](../plugins/SessionMethods.md#own-contract) | +| `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; the registering row is the binding's `&Ctx`, not a request field, and the shape is [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | @@ -186,19 +186,13 @@ Withdrawn: rutis is an external dependency, so no requirement is raised to it. R ### 9.4 The Session's scope on its facade -| Item | Content | -| --- | --- | -| Blocked by | Rpc answers a withdrawn Session namespace from the copy, in that Session's instance, of the row that registered it (A.1). Rpc holds the `Session` handle, which does not say which instance its rows run in. | -| Existing mechanisms considered | `Session::diagnostics` walks the Session's plugin tree on every such call. A Session part that provides its own scope as a public service adds a part to every Session only to republish what the facade already holds. | -| Generic capability | `Session::instance()`, the Session's `InstanceId`, the instance its parts' names resolve in (`Names::instance`). Keys under it stay readable only from inside the Session (rutis refuses an instance key outside its instance), so it opens no service beyond `PublicService`. | -| Effect on sequence, batch, interrupt, reload | None. The Session scope plugin refuses to reload, so the instance does not change while the Session is loaded; on a closed Session the read fails with `Closed`, as the other facade reads do. | -| Owner and issue | Runtime (Session facade); implemented for [#207](https://github.com/arcships/dim/issues/207). | +The withdrawn-namespace answer moved to the Session table: `sessionMethods.call` answers `service_reloading` or `service_unavailable` from the registering row's status and that row's copy in this Session ([SessionMethods](../plugins/SessionMethods.md#own-contract)). The table is a Session part and knows its own instance from its names, so no facade read is needed. The row-status read itself is the §4 rule 8 request in [SessionMethods](../plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) ([#2021](https://github.com/arcships/dim/issues/2021)). The implemented foreign Session subset is [C4](../session-typescript.md); general plugin installation remains separate work. ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; a handler answers its own `{code, message}` failure, and the client receives every error in the Rpc envelope `{code, appError, message}`. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; a handler answers its own `{code, message}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError}}`. ### A.1 Method contributions @@ -208,7 +202,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own | Method | Mode | Request | Reply | | --- | --- | --- | --- | -| `register` (the table's) | async | `caller`, `namespace`, `MethodDecl[]`, `call` | Nothing once registered; an error when refused | +| `register` (the table's) | async | `namespace`, `MethodDecl[]`, `call` | Nothing once registered; an error when refused | | `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply` data: the handler's value, or its own `{code, message}` error | ```text @@ -222,7 +216,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (`origin.connectionId` on the wire); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, reply handoff, `origin.entry` and `origin.peer` are not implemented. +Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; the wire carries `origin.caller.connectionId` and `origin.caller.callId`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, reply handoff, `origin.entry` and `origin.peer` are not implemented. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. @@ -236,7 +230,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§9.4, §3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `CallerRef`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -555,7 +549,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382) | +| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc dispatches `call` per call and routes by `heldNamespaces` (§3.2); no provider is in Rpc's `Deps` | Implemented (#14, #382) | | `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 0358538718..a2b30a904e 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -27,7 +27,7 @@ Callers keep: | `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | | The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `reserved`; a pre-check races the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | -| A provider notifies its caller | Yes: the handler has the caller identity and uses `callChannel` (#2021) | Business | +| A provider notifies its caller | Yes: the handler has the call's `Caller` and uses `callChannel` (#2021) | Business | An operation or parameter exists only where the row says No. @@ -44,13 +44,13 @@ methods.register( ).await?; ``` -Rpc dispatches one wire call; the caller identity is data, the call's sink is the connection's, and the reply is `MethodReply` data: +Rpc dispatches one wire call; the caller is the admission's site for this call, the call's sink is the connection's, and the reply is `MethodReply` data: ```rust let reply = match methods.call( method.into(), params, - Some(CallerRef { connection_id, call_id: call_id.clone() }), + Some(site), cancelled.clone(), move |data| connection.progress(call_id.clone(), data), ).await { @@ -69,8 +69,14 @@ let reply = match methods.call( ```rust // A.1's longest-namespace rule: a name a held management namespace equals or // prefixes is routed to management and is never listed for the Session. -let held = management.held_namespaces(); -let listed = methods.methods()?.into_iter().filter(|decl| { +let Ok(held) = management.held_namespaces() else { + return Err(RpcError::service("service_unavailable", "The process is closing")); +}; +// `methods` fails only `closed`, which the client sees as `session_closed`. +let Ok(declarations) = methods.methods() else { + return Err(RpcError::closed()); +}; +let listed = declarations.into_iter().filter(|decl| { let covered = |ns: &str| decl.name == ns || decl.name.strip_prefix(ns).is_some_and(|rest| rest.starts_with('.')); !held.iter().any(|namespace| covered(&namespace.namespace)) }).collect::>(); @@ -83,7 +89,7 @@ let listed = methods.methods()?.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` | The host's reserved names, consulted at registration; a host that names none reserves only the name grammar. | -| `P:loader` (`rutis_loader::Loader`, App Server's loader row) | The row that registered a withdrawn namespace and its copy in this Session: `get(row)` answers the row's `EntryStatus`, and `entries()` lists its copies with their instances. Read when a call answers `reloading` or `unavailable`; the name is `internal(owner-api)` today, so the read is raised to the mechanism owner (§4 rule 8). | +| `loader` (rutis-loader; App Server's loader row) | The row that registered a withdrawn namespace and its copy in this Session: `get(row)` answers the row's `EntryStatus`, and `entries()` lists its copies with their instances. Read when a call answers `reloading` or `unavailable`. The catalog marks the name `internal(owner-api)`, and `loader.status()` is no substitute: it builds the process's whole diagnostics snapshot (rows, services, runtimes, calls) instead of one row's status and its copies in one instance. The read is therefore raised to the mechanism owner (§4 rule 8). | The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data, and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule; its contract states both. @@ -92,10 +98,10 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` and the call's progress sink are binding parameters, not request fields. The admitting Rpc load's unload and the provider's generation unload interrupt the call: `report` answers `interrupted` and settles, `drain` replies with its own result. A caller disconnect cancels nothing | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` is the caller's cancellation: the caller stops waiting, and the accepted call continues under the rule below. Its progress sink is a binding parameter too. The admitting Rpc load's unload and the provider's generation unload interrupt the call: `report` answers `interrupted` and settles, `drain` replies with its own result. A caller disconnect cancels nothing | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | -`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses; absent for an in-process call. The table passes the caller identity to the handler unchanged and writes no socket. The table hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's unload and on the admitting Rpc load's. +`caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, A.2), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's unload and on the admitting Rpc load's. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, its message the handler's `message`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). @@ -105,28 +111,26 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | --- | --- | --- | --- | | `reserved` | `register` | — | The namespace or a name is the host's; pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row must not register twice | -| `invalid` | `register` | `invalid_params` | The namespace or a declaration is outside the grammar | +| `invalid` | `register` | — | The namespace or a declaration is outside the grammar | | `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | | `interrupted` | `call` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | -| `closed` | all | `session_closed` | This Session is closing; a later generation serves the next Session | +| `closed` | all | `session_closed` (Session table) | The table is closing; a later generation serves the next Session or the next process | -`reserved`, `duplicate` and `invalid` answer a registration only, so no client sees them. +`reserved`, `duplicate` and `invalid` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the grammar, the reserved names and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | A disconnect cancels nothing; the accepted call settles by its declaration | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | `cancelled` ends the caller's wait only; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations | — | Nothing to release | Pending reads answer from the state they observed | SessionMethods | ## Exceptions with reasons -- The table reads the registering row's status through `rutis/loader`: the status is the mechanism's record of the row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. The name is `internal(owner-api)` today; §4 rule 8 records the read. -- A handler's notifications are not written here: the caller identity is data and `callChannel` (#2021) addresses the connection by call id, so no connection, `Caller` or caller index crosses this owner. -- The table remembers the registering row per namespace: a withdrawn namespace must answer from that row rather than fall through to a parent namespace. +- `MethodCall.origin.caller` hands the handler A.2's `Caller` for a native handler: an object crosses here because a handler needs its call's connection to notify and to observe its close, and no id alone can address a native row's connection. [A.2](../contracts/session-boundary.md#a2-call-channel) and its [Rust binding](../contracts/session-boundary.md#appendix-f-rust-binding) are the shared design: the table's admission builds it, the handler may keep it after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and it keeps no strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -135,8 +139,9 @@ Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are refused; a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. -- The caller identity reaches the handler unchanged for a wire call and is absent for an in-process call; the handler's notification with the same call id is written by `callChannel`. +- A native handler receives the call's `Caller`, and a handler of another language receives `{connectionId, callId}`; an in-process call has no caller. The handler's notification is written by `callChannel` with the same call id, and its `closed` resolves when the connection closes. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`; a callback that fails to cross is `failed`, not the binding's type name. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. ## Rule check @@ -155,10 +160,10 @@ Flow tests on the owner: | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. | | §4 rule 8 | No infrastructure change in this contract: the withdrawn-row answer uses the loader's existing row status, whose read is raised to the mechanism owner (see below). | | §4 rule 9 | No Timeline fact. | -| §7 values, ids and callbacks | The caller identity is data; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row; no object, channel or provider crosses. | -| §7 no proxy | The table answers its own registrations; the loader answers the row status. | +| §7 values, ids and callbacks | The caller is data on the wire and A.2's `Caller` for a native handler, an exception stated with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row; no provider or channel crosses. | +| §7 no proxy | The table answers its own registrations; the loader's row status is the mechanism's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | -| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the progress sink and the cancellation, neither of which is data. | +| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, the cancellation and the progress sink, none of which is data. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object or handle crosses; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | @@ -174,51 +179,46 @@ Flow tests on the owner: | Field | Value | | --- | --- | | Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and `loader` is `internal(owner-api)` in the catalog, so the table has no readable face for it. | -| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on the public `loader` name: blocked, it is `internal(owner-api)` and `dim-agent-capabilities` does not depend on `rutis-loader`. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | +| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on the public `loader` name: blocked, it is `internal(owner-api)` and `dim-agent-capabilities` does not depend on `rutis-loader`. `loader.status()`: it builds the process's whole diagnostics snapshot and answers each row's own state, not a row's status and its copies in one instance. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A data face over one loader row: `{row, instance}` → the row's `EntryStatus` and the status of its copy in that instance. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | | Who implements it, which issue | The mechanism owner: App Server's loader row and rutis-loader (`loader`, `crates/dim-app-server/src/lib.rs:1626`; the read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`), tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted`/`Caller`/`CallSite`/`Callers` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay A.2's; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. No client wire protocol or user-visible behavior changes: `register` keeps its wire form `register(namespace, declarations, call)` for a part of another language, and every client error keeps its application code. ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below, beside `MethodDecl`, `Interruption` and `Progress`. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below, beside `MethodDecl`, `Interruption`, `Progress`, `Caller` and `CallSite` (A.2). `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. -use rutis::host::CallError; - -/// Who called: the connection the call arrived on and the call id the reply -/// ordering uses; absent for an in-process call. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CallerRef { - pub connection_id: String, - pub call_id: String, -} +use rutis::host::{BoxFuture, CallError}; +use tokio_util::sync::CancellationToken; /// One admitted call as its handler receives it: the declared name, the raw /// params and who called. -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct MethodCall { pub method: String, pub params: serde_json::Value, pub origin: Origin, } -#[derive(Debug, Clone)] +/// Who called (A.2): the call's `Caller` for a native handler, built by the +/// admission from the calling connection and this generation's declared +/// notifications. +#[derive(Clone)] pub struct Origin { - pub caller: Option, + pub caller: Option, } /// A handler's own failure: its application code and message, which the client -/// sees as the Rpc envelope's `appError` and message. +/// sees as the Rpc envelope's `data.appError` and message. #[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[error("{code}: {message}")] @@ -229,14 +229,31 @@ pub struct MethodCallbackError { impl From for MethodCallbackError { fn from(error: CallError) -> Self { - match error.raw().and_then(|raw| raw.downcast_ref::()) { - Some(rutis_bridge::session::Error::Remote { name, message, .. }) => Self { code: name.clone(), message: message.clone() }, - Some(other) => Self { code: other.code().unwrap_or("failed").into(), message: other.to_string() }, - None => Self { code: "failed".into(), message: error.message().into() }, - } + let remote = error.raw().and_then(|raw| raw.downcast_ref::()); + // The application code the error carries; a remote's variant name + // without one, and `failed` for a plain failure. An `AgentError` a + // handler rethrows keeps Rpc's own mapping, not this code. + let code = remote + .and_then(|error| { + error.code().map(str::to_owned).or_else(|| match error { + rutis_bridge::session::Error::Remote { name, .. } => Some(name.clone()), + _ => None, + }) + }) + .unwrap_or_else(|| "failed".into()); + Self { code, message: error.message().into() } } } +/// The handler both tables store: the call, the serving generation's +/// cancellation token and the call's progress sink. +pub type Handler = std::sync::Arc< + dyn Fn(MethodCall, CancellationToken, Progress) + -> BoxFuture<'static, Result> + + Send + + Sync, +>; + /// The handler's reply: its value, or its own failure as data. The bridge /// writes a value as `{kind: "value", value}` and a failure as `{code, message}`. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -261,7 +278,9 @@ impl From for MethodReply { } } -/// The table's own failures, by kind. +/// The table's own failures, by kind. One kind set serves both tables; +/// `closed` reaches a client as `session_closed` for the Session table, and +/// the process table has no client code of its own. #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum MethodError { @@ -279,7 +298,7 @@ pub enum MethodError { Unavailable, #[error("the provider unloaded during the call")] Interrupted, - #[error("the Session is closing")] + #[error("the table is closing")] Closed, } ``` @@ -287,8 +306,6 @@ pub enum MethodError { ```rust // crates/dim-agent-capabilities/src/methods.rs: the owner, in the same module. use crate::host::CancelledFn; -use crate::methods::{MethodDecl, Progress}; -use rutis::host::BoxFuture; use rutis::Ctx; use rutis_bridge::session::{HostDispatch, Reply, Value as BridgeValue}; use tokio_util::sync::CancellationToken; @@ -314,14 +331,14 @@ impl SessionMethods { /// The declarations registered now. pub fn methods(&self) -> Result, MethodError> { /* ... */ } - /// One call, in process: the cancellation and the progress sink are - /// parameters, and the reply is data. + /// One call, in process: the caller's site, the cancellation and the + /// progress sink are parameters, and the reply is data. #[service(skip)] pub async fn call( &self, method: String, params: serde_json::Value, - caller: Option, + caller: Option, cancelled: CancelledFn, progress: impl Fn(serde_json::Value) + Send + Sync + 'static, ) -> Result { /* ... */ } @@ -338,4 +355,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face: `register` through the dispatch above, which decodes the declarations and the caller's function for the bridge's calling row, and `methods` through the marked service and that dispatch. `call` is the owner's in-process operation, so its cancellation and progress sink never cross a wire. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant, never carried in the data. +`register` and `methods` are the wire face: `register` through the dispatch above, which decodes the declarations and the caller's function for the bridge's calling row, and `methods` through the marked service and that dispatch. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant, never carried in the data. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 27647afead..baa65355dd 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -138,7 +138,7 @@ sequenceDiagram | 服务与方法 | 模式 | 用途 | | --- | --- | --- | -| `sessionMethods.register(caller, namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | +| `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;注册行是绑定的 `&Ctx`,不是请求字段,形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | @@ -186,19 +186,13 @@ sequenceDiagram ### 9.4 Session 门面上的 Session 作用域 -| 项 | 内容 | -| --- | --- | -| 被什么挡住 | Session 命名空间已撤回时,Rpc 按注册它的行在该 Session 实例中的副本作答(A.1)。Rpc 手里只有 `Session` 句柄,它不说明自己的行运行在哪个实例中。 | -| 考虑过的现有机制 | `Session::diagnostics` 每次这样的调用都要遍历 Session 的插件树。由一个 Session 部分把自己的作用域作为公开服务提供,会给每个 Session 增加一个部分,只为重新发布门面已经持有的信息。 | -| 需要的通用能力 | `Session::instance()`,即 Session 的 `InstanceId`,也就是它的部件解析名字时所在的实例(`Names::instance`)。其下的 key 只能在该 Session 内部读取(rutis 拒绝在实例之外读取实例 key),因此它不会开放 `PublicService` 之外的任何服务。 | -| 对序号、批次、中断、重载的影响 | 无。Session 作用域插件拒绝重载,因此 Session 装载期间实例不变;对已关闭的 Session,读取像其他门面读取一样以 `Closed` 失败。 | -| 由谁实现、对应 issue | 运行时(Session 门面);为 [#207](https://github.com/arcships/dim/issues/207) 实现。 | +已撤回命名空间的作答移到 Session 方法表:`sessionMethods.call` 按注册它的行的状态,以及该行在本 Session 中的副本,回答 `service_reloading` 或 `service_unavailable`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract))。方法表是 Session 部件,从自己的名字就得到所在实例,不需要门面读取。行状态的读取本身是 [SessionMethods](../../../design/plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) 的 §4 第 8 条请求([#2021](https://github.com/arcships/dim/issues/2021))。 外来 Session 服务的已实现子集见 [C4](../../../design/session-typescript.md);通用插件安装仍由其所有者推进。 ## 附录 A. 接口细节 -结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约;处理函数以自己的 `{code, message}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, appError, message}`。 +结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约;处理函数以自己的 `{code, message}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError}}`。 ### A.1 方法贡献 @@ -208,7 +202,7 @@ sequenceDiagram | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | -| `register`(方法表的) | async | `caller`、`namespace`、`MethodDecl[]`、`call` | 注册完成时无返回值;被拒绝时返回错误 | +| `register`(方法表的) | async | `namespace`、`MethodDecl[]`、`call` | 注册完成时无返回值;被拒绝时返回错误 | | `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply` 数据:处理函数的值,或它自己的 `{code, message}` 错误 | ```text @@ -222,7 +216,7 @@ sequenceDiagram // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(线上为 `origin.connectionId`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、回复交接、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;线上为 `origin.caller.connectionId` 与 `origin.caller.callId`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、回复交接、`origin.entry` 与 `origin.peer` 未实现。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 @@ -236,7 +230,7 @@ sequenceDiagram | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§9.4、§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`CallerRef`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | | `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | @@ -518,7 +512,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | +| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 按调用分发 `call`,并按 `heldNamespaces` 路由(§3.2);没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | | `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | From f94f5593720bcca124c95aec04216d63a4c6eef3 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:29:17 +0800 Subject: [PATCH 05/41] docs(sessionmethods): answer the third pre-review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The call data names `Caller` and `CallSite`, pointing at A.2 for their meaning and Appendix F for their shape, and A.1 states today's wire before the target's nested caller. Public failure keeps Rpc's mapping: a rethrown error goes through the same conversion, AgentError included, and a call that crosses nothing is `failed`. `cancelled` is the admitting Rpc load's signal, not a caller's stop. One kind answers the host's grammar and reserved refusals, registrations are per namespace, and §9.4 keeps the `Session::instance()` record it is cited for. --- docs/design/contracts/session-boundary.md | 22 +++-- docs/design/plugins/SessionMethods.md | 94 ++++++++++++-------- docs/zh/design/contracts/session-boundary.md | 22 +++-- 3 files changed, 88 insertions(+), 50 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 986c74ef42..3731a06c60 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -186,7 +186,15 @@ Withdrawn: rutis is an external dependency, so no requirement is raised to it. R ### 9.4 The Session's scope on its facade -The withdrawn-namespace answer moved to the Session table: `sessionMethods.call` answers `service_reloading` or `service_unavailable` from the registering row's status and that row's copy in this Session ([SessionMethods](../plugins/SessionMethods.md#own-contract)). The table is a Session part and knows its own instance from its names, so no facade read is needed. The row-status read itself is the §4 rule 8 request in [SessionMethods](../plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) ([#2021](https://github.com/arcships/dim/issues/2021)). +| Item | Content | +| --- | --- | +| Blocked by | Rpc answered a withdrawn Session namespace from the copy, in that Session's instance, of the row that registered it (A.1). Rpc holds the `Session` handle, which does not say which instance its rows run in. The answer moved to the Session table, which reads its own instance from its names ([SessionMethods](../plugins/SessionMethods.md#own-contract)); the capability below stays implemented and remains available to other callers. | +| Existing mechanisms considered | `Session::diagnostics` walks the Session's plugin tree on every such call. A Session part that provides its own scope as a public service adds a part to every Session only to republish what the facade already holds. | +| Generic capability | `Session::instance()`, the Session's `InstanceId`, the instance its parts' names resolve in (`Names::instance`). Keys under it stay readable only from inside the Session (rutis refuses an instance key outside its instance), so it opens no service beyond `PublicService`. | +| Effect on sequence, batch, interrupt, reload | None. The Session scope plugin refuses to reload, so the instance does not change while the Session is loaded; on a closed Session the read fails with `Closed`, as the other facade reads do. | +| Owner and issue | Runtime (Session facade); implemented for [#207](https://github.com/arcships/dim/issues/207). | + +The table's own row-status read is the §4 rule 8 request in [SessionMethods](../plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) ([#2021](https://github.com/arcships/dim/issues/2021)). The implemented foreign Session subset is [C4](../session-typescript.md); general plugin installation remains separate work. @@ -216,7 +224,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; the wire carries `origin.caller.connectionId` and `origin.caller.callId`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, reply handoff, `origin.entry` and `origin.peer` are not implemented. +Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, reply handoff, `origin.entry` and `origin.peer` are not implemented. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. @@ -228,7 +236,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | -| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§9.4, §3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | +| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | | Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | @@ -257,7 +265,7 @@ call | owner in the Session's sessionMethods? -------- none ------> -32601 unknown_method | withdrawn -> the registering row's copy - | in this Session (§9.4, §3.2): + | in this Session (§3.2): | starting or reloading, Active or no copy | -> -32000 service_reloading | Failed, Unresolved, Disposed or Stopped @@ -549,12 +557,12 @@ The neutral services map to the native owners below. Tools register with ToolReg | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc dispatches `call` per call and routes by `heldNamespaces` (§3.2); no provider is in Rpc's `Deps` | Implemented (#14, #382) | -| `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382) | +| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc dispatches `call` per call and routes by `heldNamespaces` (§3.2); no provider is in Rpc's `Deps` | Implemented (#14, #382); the target operations are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | +| `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#own-contract) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `CallerRef`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index a2b30a904e..94da1fdf3c 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -8,10 +8,10 @@ SessionMethods owns a Session's method table: the namespaces its parts register, SessionMethods owns: -- **Registrations.** One namespace per registering row, its declarations and its call callback; a registration ends when its row unloads. +- **Registrations.** One namespace per registration, its declarations and its call callback; a row may register several namespaces, and a registration ends when its row unloads. - **Admission.** One call: the name's owner, the interruption kind its declaration names, the caller identity, and the settlement of the calls a registration accepted. - **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers `reloading` or `unavailable` instead of falling through to a parent namespace. -- **Reserved names.** The host's own roots, built-ins and management namespaces are refused at registration; the host supplies the check as a process face. +- **Reserved names.** The host's own roots, built-ins and their notification names are refused at registration; a management namespace does not stop a Session namespace from registering (A.1 namespace collisions). The host supplies the check as a process face. - **The method list.** The declarations of the namespaces registered now, each under its owning namespace. Callers keep: @@ -22,10 +22,10 @@ Callers keep: | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the reserved-name check are the owner's | `register` | +| A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the host's refusal are the owner's | `register` | | Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | | `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | -| The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `reserved`; a pre-check races the next registration | Business | +| The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `invalid`; a pre-check races the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: the handler has the call's `Caller` and uses `callChannel` (#2021) | Business | @@ -89,19 +89,19 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` | The host's reserved names, consulted at registration; a host that names none reserves only the name grammar. | -| `loader` (rutis-loader; App Server's loader row) | The row that registered a withdrawn namespace and its copy in this Session: `get(row)` answers the row's `EntryStatus`, and `entries()` lists its copies with their instances. Read when a call answers `reloading` or `unavailable`. The catalog marks the name `internal(owner-api)`, and `loader.status()` is no substitute: it builds the process's whole diagnostics snapshot (rows, services, runtimes, calls) instead of one row's status and its copies in one instance. The read is therefore raised to the mechanism owner (§4 rule 8). | +| `rutis/loader` (rutis-loader's process face; App Server's loader row) | The row that registered a withdrawn namespace and its copies in this Session. The per-row read is `get(row)`, whose `EntryInfo.status` is the row's `EntryStatus`; `entries()` lists the row's copies with their instances. Read when a call answers `reloading` or `unavailable`. The face itself offers `status`, which builds the process's whole diagnostics snapshot for `rutis-host status`, so it answers neither one row's status nor its copies in one instance. The per-row read is therefore raised to the mechanism owner (§4 rule 8). | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data, and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule; its contract states both. +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` and `MethodCall` move to `CallSite`/`Caller` with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` is the caller's cancellation: the caller stops waiting, and the accepted call continues under the rule below. Its progress sink is a binding parameter too. The admitting Rpc load's unload and the provider's generation unload interrupt the call: `report` answers `interrupted` and settles, `drain` replies with its own result. A caller disconnect cancels nothing | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `invalid`, `duplicate`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | -`caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, A.2), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's unload and on the admitting Rpc load's. +`caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, its message the handler's `message`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). @@ -109,24 +109,23 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `reserved` | `register` | — | The namespace or a name is the host's; pick another name | -| `duplicate` | `register` | — | The namespace is registered already; the row must not register twice | -| `invalid` | `register` | — | The namespace or a declaration is outside the grammar | +| `invalid` | `register` | — | The host refuses the namespace or its declarations: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a built-in notification, or a declaration that is malformed or repeated. Fix the name or the declaration and register again | +| `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | | `interrupted` | `call` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | | `closed` | all | `session_closed` (Session table) | The table is closing; a later generation serves the next Session or the next process | -`reserved`, `duplicate` and `invalid` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. +`invalid` and `duplicate` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the grammar, the reserved names and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | `cancelled` ends the caller's wait only; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | -| `methods` | Read the registered namespaces' declarations | — | Nothing to release | Pending reads answer from the state they observed | SessionMethods | +| `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | +| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | +| `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A call in flight answers from the state it observed | SessionMethods | ## Exceptions with reasons @@ -136,37 +135,37 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err Flow tests on the owner: -- A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are refused; a refused registration fails the registering part. +- A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are all `invalid`, and a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. - A native handler receives the call's `Caller`, and a handler of another language receives `{connectionId, callId}`; an in-process call has no caller. The handler's notification is written by `callChannel` with the same call id, and its `closed` resolves when the connection closes. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. -- A handler of another language that returns `{code, message}` reaches the client with that `appError`; a callback that fails to cross is `failed`, not the binding's type name. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`; a handler that fails with an `AgentError` reaches it with the code Rpc maps for that error; a callback that fails to cross is `failed`, not the binding's type name. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. ## Rule check | Rule | Application | | --- | --- | -| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and reads the loader's row status. | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and reads `rutis/loader`. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | -| §3 orthogonality | No other business owner's state is read or changed; the reserved names and the loader's row status are the mechanism's faces. | +| §3 orthogonality | No other business owner's state is read or changed; `reservedMethods` and `rutis/loader` are the mechanism's faces. | | §4 rule 1 | No command event: a registration is the calling row's effect. | | §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | | §4 rule 3 | No before callback. | | §4 rule 4 | Core and assembly carry no method-specific meaning; a namespace's contents are its part's. | | §4 rule 5 | No batches. | | §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | -| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. | -| §4 rule 8 | No infrastructure change in this contract: the withdrawn-row answer uses the loader's existing row status, whose read is raised to the mechanism owner (see below). | +| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. A handler receives the call's `Caller`, the stated exception. | +| §4 rule 8 | No infrastructure change in this contract: the withdrawn-row answer uses the loader's existing row status, whose per-row read is raised to the mechanism owner (see below). | | §4 rule 9 | No Timeline fact. | -| §7 values, ids and callbacks | The caller is data on the wire and A.2's `Caller` for a native handler, an exception stated with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row; no provider or channel crosses. | -| §7 no proxy | The table answers its own registrations; the loader's row status is the mechanism's read, raised below. | +| §7 values, ids and callbacks | The caller is data on the wire and A.2's `Caller` for a native handler — the one exception, stated with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | +| §7 no proxy | The table answers its own registrations; `rutis/loader`'s row status is the mechanism's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, the cancellation and the progress sink, none of which is data. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | -| §7.2 review checks | No cross-owner call is left unmapped; no object or handle crosses; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | +| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated `Caller`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | | ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | | ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | @@ -178,25 +177,27 @@ Flow tests on the owner: | Field | Value | | --- | --- | -| Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and `loader` is `internal(owner-api)` in the catalog, so the table has no readable face for it. | -| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on the public `loader` name: blocked, it is `internal(owner-api)` and `dim-agent-capabilities` does not depend on `rutis-loader`. `loader.status()`: it builds the process's whole diagnostics snapshot and answers each row's own state, not a row's status and its copies in one instance. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | +| Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the face `rutis/loader` offers only `status` for the whole process, so the table has no per-row read. | +| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, its `status` builds the process's whole diagnostics snapshot (rows, services, runtimes, calls) and answers each row's own state, not a row's status and its copies in one instance; `dim-agent-capabilities` does not depend on `rutis-loader`. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A data face over one loader row: `{row, instance}` → the row's `EntryStatus` and the status of its copy in that instance. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The mechanism owner: App Server's loader row and rutis-loader (`loader`, `crates/dim-app-server/src/lib.rs:1626`; the read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`), tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The mechanism owner: rutis-loader's `rutis/loader` face and App Server's loader row (`crates/dim-app-server/src/lib.rs:1626`; the per-row read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`), tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay A.2's; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. +- [session typescript](../session-typescript.md) and [process rows](../process-typescript.md): the `call` paragraphs that pass `{callId, method, params, origin: {connectionId}}`; the target nests the caller as `origin.caller` and the two bindings follow this contract's appendix. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. No client wire protocol or user-visible behavior changes: `register` keeps its wire form `register(namespace, declarations, call)` for a part of another language, and every client error keeps its application code. ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below, beside `MethodDecl`, `Interruption`, `Progress`, `Caller` and `CallSite` (A.2). `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below, beside `MethodDecl`, `Interruption` and `Progress`, and beside `Caller` and `CallSite`, whose semantics are [A.2](../contracts/session-boundary.md#a2-call-channel)'s and whose Rust shape and lifecycle are [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)'s. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. +use dim_agent_runtime::AgentError; use rutis::host::{BoxFuture, CallError}; use tokio_util::sync::CancellationToken; @@ -209,9 +210,9 @@ pub struct MethodCall { pub origin: Origin, } -/// Who called (A.2): the call's `Caller` for a native handler, built by the +/// Who called: the call's `Caller` (A.2) for a native handler, built by the /// admission from the calling connection and this generation's declared -/// notifications. +/// notifications; Appendix F holds the type and its lifecycle. #[derive(Clone)] pub struct Origin { pub caller: Option, @@ -227,12 +228,32 @@ pub struct MethodCallbackError { pub message: String, } +impl MethodCallbackError { + /// The client code and message Rpc gives a runtime error. + fn from_wire(wire: RpcError) -> Self { + Self { + code: wire.data.as_ref().map(|data| data.app_error.clone()).unwrap_or_else(|| "failed".into()), + message: wire.message, + } + } +} + +impl From for MethodCallbackError { + fn from(error: AgentError) -> Self { + Self::from_wire(RpcError::from(error)) + } +} + impl From for MethodCallbackError { fn from(error: CallError) -> Self { let remote = error.raw().and_then(|raw| raw.downcast_ref::()); - // The application code the error carries; a remote's variant name - // without one, and `failed` for a plain failure. An `AgentError` a - // handler rethrows keeps Rpc's own mapping, not this code. + // An error a nested call rethrew keeps the client code Rpc gives it, + // `AgentError`'s mapping included. + if let Some(wire) = remote.and_then(rethrown) { + return Self::from_wire(wire); + } + // Otherwise the application code the error carries; a remote's variant + // name without one, and `failed` for a call that crossed nothing. let code = remote .and_then(|error| { error.code().map(str::to_owned).or_else(|| match error { @@ -331,8 +352,9 @@ impl SessionMethods { /// The declarations registered now. pub fn methods(&self) -> Result, MethodError> { /* ... */ } - /// One call, in process: the caller's site, the cancellation and the - /// progress sink are parameters, and the reply is data. + /// One call, in process: the caller's site (`CallSite`, Appendix F), the + /// cancellation and the progress sink are parameters, and the reply is + /// data. #[service(skip)] pub async fn call( &self, diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index baa65355dd..5cdcd48c7c 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -186,7 +186,15 @@ sequenceDiagram ### 9.4 Session 门面上的 Session 作用域 -已撤回命名空间的作答移到 Session 方法表:`sessionMethods.call` 按注册它的行的状态,以及该行在本 Session 中的副本,回答 `service_reloading` 或 `service_unavailable`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract))。方法表是 Session 部件,从自己的名字就得到所在实例,不需要门面读取。行状态的读取本身是 [SessionMethods](../../../design/plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) 的 §4 第 8 条请求([#2021](https://github.com/arcships/dim/issues/2021))。 +| 项 | 内容 | +| --- | --- | +| 被什么挡住 | 已撤回的 Session 命名空间原本由 Rpc 按注册它的行在该 Session 实例中的副本作答(A.1)。Rpc 手里只有 `Session` 句柄,它不说明自己的行运行在哪个实例中。该作答已移到 Session 方法表:方法表从自己的名字得到所在实例([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));下面这项能力仍然实现,其他调用方仍可用。 | +| 考虑过的现有机制 | `Session::diagnostics` 每次这样的调用都要遍历 Session 的插件树。由一个 Session 部分把自己的作用域作为公开服务提供,会给每个 Session 增加一个部分,只为重新发布门面已经持有的信息。 | +| 需要的通用能力 | `Session::instance()`,即 Session 的 `InstanceId`,也就是它的部件解析名字时所在的实例(`Names::instance`)。其下的 key 只能在该 Session 内部读取(rutis 拒绝在实例之外读取实例 key),因此它不会开放 `PublicService` 之外的任何服务。 | +| 对序号、批次、中断、重载的影响 | 无。Session 作用域插件拒绝重载,因此 Session 装载期间实例不变;对已关闭的 Session,读取像其他门面读取一样以 `Closed` 失败。 | +| 由谁实现、对应 issue | 运行时(Session 门面);为 [#207](https://github.com/arcships/dim/issues/207) 实现。 | + +方法表自己的行状态读取是 [SessionMethods](../../../design/plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) 的 §4 第 8 条请求([#2021](https://github.com/arcships/dim/issues/2021))。 外来 Session 服务的已实现子集见 [C4](../../../design/session-typescript.md);通用插件安装仍由其所有者推进。 @@ -216,7 +224,7 @@ sequenceDiagram // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;线上为 `origin.caller.connectionId` 与 `origin.caller.callId`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、回复交接、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、回复交接、`origin.entry` 与 `origin.peer` 未实现。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 @@ -228,7 +236,7 @@ sequenceDiagram | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | -| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§9.4、§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | +| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | | 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | @@ -256,7 +264,7 @@ sequenceDiagram | 该 Session 的 sessionMethods 中的所有者? ---- 没有 -----> -32601 unknown_method | 已撤回 ---> 注册它的行在本 Session 中的副本 - | (§9.4、§3.2): + | (§3.2): | 启动中或重载中、Active 或没有副本 | -> -32000 service_reloading | Failed、Unresolved、Disposed 或 Stopped @@ -512,12 +520,12 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 按调用分发 `call`,并按 `heldNamespaces` 路由(§3.2);没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | -| `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382) | +| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 按调用分发 `call`,并按 `heldNamespaces` 路由(§3.2);没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382);目标操作见进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | +| `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`CallerRef`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 From 9f3a726c7f9c3c5e9d02a0508452d54570f39372 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:45:50 +0800 Subject: [PATCH 06/41] docs(sessionmethods): answer the fourth pre-review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The binding appendix defines the declarations, the interruption, the progress sink and the admission's site, so the "one definition" sentences hold and the connection hand-out is an exception with its lifetime stated. The Session-method diagram shows `call` reaching the table and the handler. `MethodError::Reserved` is gone, the process table's row is left to #2021, §1/§4/§6 name the moved call data and its owner, and every reply, conversion and verification case is stated exactly. --- docs/design/contracts/session-boundary.md | 22 ++--- docs/design/plugins/SessionMethods.md | 90 +++++++++++++++----- docs/zh/design/contracts/session-boundary.md | 20 +++-- 3 files changed, 92 insertions(+), 40 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 3731a06c60..b3db3ac642 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: the two method tables and their registration, tool registration, `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError`, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: the two method tables and their registration, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -81,11 +81,11 @@ sequenceDiagram Rpc->>Rpc: not a built-in, no management namespace holds it, sessionId in params, authorize Session access Rpc->>AI: acquire(sessionId), restoring if unloaded AI-->>Rpc: Session lease - Rpc->>S: owner of session.question.respond - S-->>Rpc: provider of namespace session.question - Rpc->>Q: call(MethodCall) + Rpc->>S: call {method, params, caller} + S->>Q: the handler of the longest namespace holding the name Q->>H: hand the answer to the waiting call (branchId, requestId, callId) - Q-->>Rpc: MethodReply + Q-->>S: MethodReply + S-->>Rpc: MethodReply Rpc-->>CL: result ``` @@ -116,9 +116,9 @@ Each process part that serves management methods depends on `managementMethods` | Scenario | Order | Outcome | Owner | | --- | --- | --- | --- | | Session-scoped provider reloads mid-call | call < reload | `report`: `operation_interrupted`; `drain`: the call's own result; the provider's unload waits for every admitted call (AGENTS.md rule 8) | Provider | -| Session method while the Session's capabilities reload | — | `service_reloading` | Rpc | -| Session method whose namespace is withdrawn and whose registering part failed or cannot run | — | `service_unavailable` until the part is fixed (A.1) | Rpc | -| Session method that no namespace of the Session ever held | — | `unknown_method` | Rpc | +| Session method while the Session's capabilities reload | — | `service_reloading` | Session method table | +| Session method whose namespace is withdrawn and whose registering part failed or cannot run | — | `service_unavailable` until the part is fixed (A.1) | Session method table | +| Session method that no namespace of the Session ever held | — | `unknown_method` | Session method table | | Management owner reloads | — | Calls into its withdrawn namespace return `service_reloading` until the new generation registers it again; a Failed, Unresolved, Stopped or Disposed owner returns `service_unavailable` (§3.2); admitted calls belong to the provider and follow their `interruption`; Rpc does not reload and connections stay open | Rpc | | Management method or `daemon.shutdown` on a connection with a `deviceId` | — | `unknown_method` | Rpc | | Two parts register one namespace in one table | registration | The second registration is refused (` is registered already`) and the part that made it fails | Method table | @@ -141,6 +141,8 @@ Methods have no model-visible effect. A method that changes model context does s | `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; the registering row is the binding's `&Ctx`, not a request field, and the shape is [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | +| `sessionMethods.call {method, params, caller?}` | async | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable`, `interrupted` or `closed` ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.methods {}` | sync | The declarations of the namespaces the Session registered now | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | | `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented, Appendix F) | | `toolRegistry.register(ToolDeclaration, execute)` | async | Register a tool until the calling part unloads | @@ -336,7 +338,7 @@ Client A Rpc call admission provider han Delivery differs from progress: - **Reliable.** A notification is encoded once when the provider sends it. One sent while its call's reply is not written is admitted against the connection's held allowance: the same limits as the reply-and-notice allowance (1024 frames, 32 MiB), separate from it, so held notifications never take the room a reply needs. A call that holds past the held allowance is disconnected like a slow consumer, and later `notify` calls answer `gone`. The reply is admitted against the reply-and-notice allowance only. After the reply, the held frames are queued in order with the room they already hold, which is freed as each is written; the connection's queued frames are therefore bounded by the two allowances together, at most 2048 frames and 64 MiB. A notification over the frame limit is refused with `too_large`: nothing is written and the connection stays open. -- **After the reply.** A notification is written after the reply of the call named by its `callId`, which is the `callId` of the `MethodCall` that reported the work. One sent while that call is still running is held in order and written right after its reply, so a client never sees an event that names something the reply has not told it yet (for example an id the reply returns). Once that reply is written, or the id is not in flight, it is written straight to the outbound queue; another unfinished call on the same connection neither holds it nor reorders it. The reply is written on every path, including an interrupted call and a call whose connection is gone. +- **After the reply.** A notification is written after the reply of the call named by its `callId`, which is the id the `Caller` of the `MethodCall` that reported the work carries. One sent while that call is still running is held in order and written right after its reply, so a client never sees an event that names something the reply has not told it yet (for example an id the reply returns). Once that reply is written, or the id is not in flight, it is written straight to the outbound queue; another unfinished call on the same connection neither holds it nor reorders it. The reply is written on every path, including an interrupted call and a call whose connection is gone. - **Lifetime.** `closed` resolves, and later `notify` calls answer `gone`, once the connection has closed or the Rpc load that admitted the call has unloaded. A notification after the provider's generation unloads answers `gone` in both bindings: a native caller holds the generation's stopping signal, and the foreign index removes the instance's entries on the same unload. A caller's disconnect cancels no call. `notify` and `closed` answer `gone` for a connection the row received no call from. The service holds one entry per row instance and connection, with that connection's unfinished calls by `callId`; the entry is removed when the connection closes, when the admitting Rpc load unloads and when the row's generation unloads, and a call leaves it when its reply is written. - **Refusal order.** While the generation is loaded, `undeclared` is decided before the connection's state in both bindings: a closed connection does not hide a name the generation did not declare. A generation that has unloaded answers `gone` for every name, declared or not. @@ -557,7 +559,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc dispatches `call` per call and routes by `heldNamespaces` (§3.2); no provider is in Rpc's `Deps` | Implemented (#14, #382); the target operations are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | +| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc depends on the table and reads it per call (§3.2); no provider is in Rpc's `Deps` | Implemented (#14, #382) | | `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#own-contract) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 94da1fdf3c..67f266f27d 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -33,7 +33,7 @@ An operation or parameter exists only where the row says No. ## Caller example -A part registers from its `apply`; the registration belongs to that part's row: +A part registers from its `apply`; the registration belongs to that part's row. A refused registration fails the part, so the part turns the `MethodError` into its own `rutis::Error`: ```rust methods.register( @@ -41,7 +41,9 @@ methods.register( "session.input".into(), declarations, |call, cancelled, _progress| Box::pin(withdraw(call, cancelled)), -).await?; +) +.await +.map_err(|error| rutis::Error::from(rutis::host::ErrorKind::PluginFailed(error.to_string().into())))?; ``` Rpc dispatches one wire call; the caller is the admission's site for this call, the call's sink is the connection's, and the reply is `MethodReply` data: @@ -60,15 +62,15 @@ let reply = match methods.call( Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), Err(MethodError::Closed) => return Err(RpcError::closed()), - Err(MethodError::Reserved { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Invalid { .. }) => unreachable!("dispatch cannot register"), + Err(MethodError::Duplicate { .. }) | Err(MethodError::Invalid { .. }) => unreachable!("dispatch cannot register"), }; ``` `session.methods` composes the value with the process table's held namespaces: ```rust -// A.1's longest-namespace rule: a name a held management namespace equals or -// prefixes is routed to management and is never listed for the Session. +// A.1's longest-namespace rule: a declaration whose name equals or lies inside +// a held management namespace is routed to management, never listed for the Session. let Ok(held) = management.held_namespaces() else { return Err(RpcError::service("service_unavailable", "The process is closing")); }; @@ -88,10 +90,10 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | -| `P:reservedMethods` | The host's reserved names, consulted at registration; a host that names none reserves only the name grammar. | +| `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | | `rutis/loader` (rutis-loader's process face; App Server's loader row) | The row that registered a withdrawn namespace and its copies in this Session. The per-row read is `get(row)`, whose `EntryInfo.status` is the row's `EntryStatus`; `entries()` lists the row's copies with their instances. Read when a call answers `reloading` or `unavailable`. The face itself offers `status`, which builds the process's whole diagnostics snapshot for `rutis-host status`, so it answers neither one row's status nor its copies in one instance. The per-row read is therefore raised to the mechanism owner (§4 rule 8). | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` and `MethodCall` move to `CallSite`/`Caller` with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. ### Operations @@ -101,6 +103,8 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | +Each reply is data on the wire and a `Result` in Rust: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. + `caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, its message the handler's `message`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). @@ -109,12 +113,12 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `invalid` | `register` | — | The host refuses the namespace or its declarations: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a built-in notification, or a declaration that is malformed or repeated. Fix the name or the declaration and register again | +| `invalid` | `register` | — | The host refuses the namespace or its declarations: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | -| `interrupted` | `call` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | +| `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | | `closed` | all | `session_closed` (Session table) | The table is closing; a later generation serves the next Session or the next process | `invalid` and `duplicate` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. @@ -129,7 +133,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- `MethodCall.origin.caller` hands the handler A.2's `Caller` for a native handler: an object crosses here because a handler needs its call's connection to notify and to observe its close, and no id alone can address a native row's connection. [A.2](../contracts/session-boundary.md#a2-call-channel) and its [Rust binding](../contracts/session-boundary.md#appendix-f-rust-binding) are the shared design: the table's admission builds it, the handler may keep it after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and it keeps no strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour and [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding) the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -138,9 +142,9 @@ Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are all `invalid`, and a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. -- A native handler receives the call's `Caller`, and a handler of another language receives `{connectionId, callId}`; an in-process call has no caller. The handler's notification is written by `callChannel` with the same call id, and its `closed` resolves when the connection closes. +- A native handler receives the call's `Caller`, and a handler of another language receives `{connectionId, callId}`; an in-process call has no caller. The handler's notification is written by `callChannel` with the same call id, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. -- A handler of another language that returns `{code, message}` reaches the client with that `appError`; a handler that fails with an `AgentError` reaches it with the code Rpc maps for that error; a callback that fails to cross is `failed`, not the binding's type name. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name, and only a call that crossed nothing is `failed`. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. ## Rule check @@ -165,7 +169,7 @@ Flow tests on the owner: | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, the cancellation and the progress sink, none of which is data. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | -| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated `Caller`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | +| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site and `Caller`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | | ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | | ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | @@ -185,15 +189,14 @@ Flow tests on the owner: ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay A.2's; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session typescript](../session-typescript.md) and [process rows](../process-typescript.md): the `call` paragraphs that pass `{callId, method, params, origin: {connectionId}}`; the target nests the caller as `origin.caller` and the two bindings follow this contract's appendix. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No client wire protocol or user-visible behavior changes: `register` keeps its wire form `register(namespace, declarations, call)` for a part of another language, and every client error keeps its application code. +The client protocol and user-visible behavior stay as they are: `register` keeps its wire form `register(namespace, declarations, call)`, every client error keeps its application code, and a native handler already receives the `Caller`. Two changes touch a part of another language only: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler error `{code, message}` becomes the client's `appError` unchanged instead of the binding's type name. ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below, beside `MethodDecl`, `Interruption` and `Progress`, and beside `Caller` and `CallSite`, whose semantics are [A.2](../contracts/session-boundary.md#a2-call-channel)'s and whose Rust shape and lifecycle are [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)'s. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink, the caller and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `CallSite`, `Progress` and the connection; this block states their shape and lifecycle. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. @@ -201,6 +204,52 @@ use dim_agent_runtime::AgentError; use rutis::host::{BoxFuture, CallError}; use tokio_util::sync::CancellationToken; +/// One declared method of a namespace; another language receives +/// `{name, mutating}`. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MethodDecl { + pub name: String, + pub mutating: bool, + #[serde(skip_serializing)] + pub interruption: Interruption, + #[serde(skip_serializing)] + pub progress: bool, + #[serde(default, skip_serializing)] + pub notifications: Vec, +} + +/// How a provider answers an admitted call that an unload interrupts: `report` +/// answers `interrupted` and settles, `drain` answers with its own result. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Interruption { + Report, + Drain, +} + +/// The call's progress sink (A.2). The table hands it to a handler whose +/// declaration declares `progress` and closes it before the reply is written. +pub struct Progress(/* the calling connection's sink */); + +impl Progress { + /// Sends one progress value; best effort, and dropped once the reply is + /// handed over. + pub fn send(&self, data: serde_json::Value) { /* ... */ } +} + +/// One admitted call's connection, as Rpc passes it to `call`: the call's +/// channel, the connection's direct writer, the process's caller index (A.2) +/// and the connection's close signal. Rpc builds it for one call; the table +/// binds it to the serving generation's declarations. +#[derive(Clone)] +pub struct CallSite { + pub connection: std::sync::Arc, + pub direct: std::sync::Arc, + pub callers: std::sync::Arc, + pub closed: CancellationToken, +} + /// One admitted call as its handler receives it: the declared name, the raw /// params and who called. #[derive(Clone)] @@ -248,7 +297,8 @@ impl From for MethodCallbackError { fn from(error: CallError) -> Self { let remote = error.raw().and_then(|raw| raw.downcast_ref::()); // An error a nested call rethrew keeps the client code Rpc gives it, - // `AgentError`'s mapping included. + // `AgentError`'s mapping included. `rethrown` is this module's + // existing conversion: `fn rethrown(&session::Error) -> Option`. if let Some(wire) = remote.and_then(rethrown) { return Self::from_wire(wire); } @@ -305,8 +355,6 @@ impl From for MethodReply { #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum MethodError { - #[error("{message}")] - Reserved { message: String }, #[error("{message}")] Duplicate { message: String }, #[error("{message}")] @@ -377,4 +425,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face: `register` through the dispatch above, which decodes the declarations and the caller's function for the bridge's calling row, and `methods` through the marked service and that dispatch. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant, never carried in the data. +`register` and `methods` are the wire face: `register` through the dispatch above, which decodes the declarations and the caller's function for the bridge's calling row, and `methods` through the marked service and that dispatch. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant and never carried in the table's error data; the handler's `code` becomes it on the envelope. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 5cdcd48c7c..555f0b810a 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | 从没有命名空间持有过该名称,或注册它的行已禁用或不存在时返回 `unknown_method`;其他情况下,已撤回的命名空间按该行的状态作答(§3.2) | | 工具注册 | Session 挂载列表列出但没有部件注册的工具不声明,并在诊断中报告;有部件注册后从下一个请求起声明(A.5) | -本文定义的合同:这两张方法表及其注册、工具注册、`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 +本文定义的合同:这两张方法表及其注册、工具注册、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。调用数据——`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 ## 2. 数据与状态 @@ -81,11 +81,11 @@ sequenceDiagram Rpc->>Rpc: 非内建方法,没有管理命名空间持有它,params 中带 sessionId,授权 Session 访问 Rpc->>AI: acquire(sessionId),未装载时恢复 AI-->>Rpc: Session 租约 - Rpc->>S: session.question.respond 的所有者 - S-->>Rpc: 命名空间 session.question 的提供方 - Rpc->>Q: call(MethodCall) + Rpc->>S: call {method, params, caller} + S->>Q: 持有该名称的最长命名空间的处理函数 Q->>H: 把回答交给等待中的调用 (branchId, requestId, callId) - Q-->>Rpc: MethodReply + Q-->>S: MethodReply + S-->>Rpc: MethodReply Rpc-->>CL: 结果 ``` @@ -116,9 +116,9 @@ sequenceDiagram | 场景 | 顺序 | 结果 | 所有者 | | --- | --- | --- | --- | | Session 级提供方在调用中途重载 | call < reload | `report`:`operation_interrupted`;`drain`:调用自己的结果;提供方的卸载等待每个已受理的调用(AGENTS.md 规则 8) | 提供方 | -| Session 的 Capability 重载期间调用 Session 方法 | — | `service_reloading` | Rpc | +| Session 的 Capability 重载期间调用 Session 方法 | — | `service_reloading` | Session 方法表 | | 命名空间已撤回、且注册它的部件已失败或无法运行时调用 Session 方法 | — | 该部件修复前返回 `service_unavailable`(A.1) | Rpc | -| 调用该 Session 从没有命名空间持有过的 Session 方法 | — | `unknown_method` | Rpc | +| 调用该 Session 从没有命名空间持有过的 Session 方法 | — | `unknown_method` | Session 方法表 | | 管理方法所有者重载 | — | 新一代重新注册前,调用其已撤回的命名空间返回 `service_reloading`;处于 Failed、Unresolved、Stopped 或 Disposed 的所有者返回 `service_unavailable`(§3.2);已受理的调用属于提供方,按 `interruption` 处理;Rpc 不重载,连接保持打开 | Rpc | | 在带 `deviceId` 的连接上调用管理方法或 `daemon.shutdown` | — | `unknown_method` | Rpc | | 两个部件在同一张表中注册同一命名空间 | 注册 | 第二次注册被拒绝(` is registered already`),发起它的部件失败 | 方法表 | @@ -141,6 +141,8 @@ sequenceDiagram | `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;注册行是绑定的 `&Ctx`,不是请求字段,形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | +| `sessionMethods.call {method, params, caller?}` | async | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable`、`interrupted` 或 `closed`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.methods {}` | sync | 该 Session 现在注册的命名空间的声明 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | | `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现,附录 F) | | `toolRegistry.register(ToolDeclaration, execute)` | async | 注册一个工具,直到调用方部件卸载 | @@ -335,7 +337,7 @@ Client A Rpc call admission provider han 送达方式与进度不同: - **可靠。** 提供方发送通知时只编码一次。调用的回复尚未写出时发出的通知经连接的暂存额度受理:其上限与回复与通知额度相同(1024 帧、32 MiB)但彼此独立,因此暂存的通知不会占用回复所需的空间。一次调用暂存的通知超过暂存额度时,该客户端像慢消费者一样被断开,之后的 `notify` 返回 `gone`。回复只经回复与通知额度受理。回复写出后,暂存的通知按序连同它们已占用的额度进入发送队列,并在各自写出后释放;因此连接的排队帧由两个额度共同界定,至多 2048 帧、64 MiB。超过帧上限的通知返回 `too_large`:不写任何内容,连接保持。 -- **回复之后。** 通知写在它 `callId` 所指调用的回复之后,该 `callId` 即报告该工作的 `MethodCall` 的 `callId`。调用仍进行时发出的通知按序暂存,紧接回复之后写出,因此客户端不会先看到回复尚未告知的对象的通知(例如回复才返回的 id)。该回复写出后,或该 id 不在途时,通知直接进入发送队列;同一连接上另一个未完成的调用既不会暂存它,也不会改变它的顺序。每条路径都会写出回复,包括被中断的调用和连接已消失的调用。 +- **回复之后。** 通知写在它 `callId` 所指调用的回复之后,该 `callId` 即报告该工作的 `MethodCall` 的 `Caller` 携带的 id。调用仍进行时发出的通知按序暂存,紧接回复之后写出,因此客户端不会先看到回复尚未告知的对象的通知(例如回复才返回的 id)。该回复写出后,或该 id 不在途时,通知直接进入发送队列;同一连接上另一个未完成的调用既不会暂存它,也不会改变它的顺序。每条路径都会写出回复,包括被中断的调用和连接已消失的调用。 - **生命周期。** 连接关闭,或受理该调用的 Rpc 代际卸载后,`closed` 完成,之后的 `notify` 返回 `gone`。提供方代际卸载后发出的通知在两种绑定中都返回 `gone`:原生调用方持有该代际的停止信号,外来索引在同一次卸载时删除该实例的条目。调用方断开不取消任何调用。未从某连接收到过调用的行,其 `notify` 与 `closed` 对该连接返回 `gone`。服务按行实例与连接保存一个条目,内含该连接按 `callId` 记录的未完成调用;连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除条目,调用在回复写出后从条目中移除。 - **拒绝顺序。** 代际已装载时,两种绑定都先判定 `undeclared`,再看连接状态:连接已关闭也不会掩盖该代际未声明的名称。已卸载的代际对任何名称都返回 `gone`,无论是否声明过。 @@ -520,7 +522,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 按调用分发 `call`,并按 `heldNamespaces` 路由(§3.2);没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382);目标操作见进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | +| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 依赖这张表并按调用读取(§3.2);没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | | `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | From 62e839284ab596a1db10959a0c1109bd32d9ce92 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 02:43:12 +0800 Subject: [PATCH 07/41] docs(sessionmethods): answer the fifth pre-review A duplicate namespace is `duplicate` again, while reserved names and malformed declarations stay `invalid`. `MethodCallbackError` carries the owner's wire fields and keeps the ones Rpc's errors already have, so a native method's error reaches the client unchanged and `params(..)?`/`reply(..)?` convert. The declaration gains its reply mode, `Progress` is clonable, and A.2's notification id is the Caller's. --- docs/design/contracts/session-boundary.md | 12 +-- docs/design/plugins/SessionMethods.md | 84 ++++++++++++++------ docs/zh/design/contracts/session-boundary.md | 14 ++-- 3 files changed, 72 insertions(+), 38 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index b3db3ac642..590a2fb954 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its methods take and return serializable data; errors are data; cancellation is a protocol action. A part of any language depends on the service of its scope and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc reads the two method tables on each call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its registration takes serializable data, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on the service of its scope and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc reads the two method tables on each call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: the two method tables and their registration, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -141,7 +141,7 @@ Methods have no model-visible effect. A method that changes model context does s | `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; the registering row is the binding's `&Ctx`, not a request field, and the shape is [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | -| `sessionMethods.call {method, params, caller?}` | async | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable`, `interrupted` or `closed` ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable`, `interrupted` or `closed` ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | The declarations of the namespaces the Session registered now | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | | `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented, Appendix F) | @@ -280,7 +280,7 @@ Session namespaces registered today: `session.question` (Questions), `session.go ### A.2 Call channel -`progress`, `notify` and `closed` are implemented (C1, #1158); `takeFinalReply` is not. App Server provides the process service `callChannel` to method providers, from its own `CallChannel` row so that a row naming it does not reload with Rpc; the Rust binding is the handler's per-call `Progress` and `Caller` (Appendix F). +`progress`, `notify` and `closed` are implemented (C1, #1158); `takeFinalReply` is not. App Server provides the process service `callChannel` to method providers, from its own `CallChannel` row so that a row naming it does not reload with Rpc; the Rust binding is the handler's per-call `Progress` and `Caller` ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)). | Method | Mode | Request | Reply | | --- | --- | --- | --- | @@ -318,7 +318,7 @@ reply ----------> reply and notice allowance ----+ full: a slow consumer, the connection closes ``` -A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the `callId` of the `MethodCall` the provider received. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. +A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id of the `Caller` the provider's handler received. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. How a notification of one call reaches its caller: @@ -525,7 +525,7 @@ carry the native event whole, and the frozen fixtures stay unchanged. | Session reloading, or a withdrawn namespace whose registering row (or its copy in the Session) is not running and has not failed (not started yet, Pending, Loading, or between generations), or a withdrawn Session namespace whose copy is Active or absent | `-32000`, `service_reloading` (retryable) | | A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped | `-32000`, `service_unavailable` (not retryable) | | `report` call interrupted | `-32000`, `operation_interrupted` | -| Provider error | `-32000`, provider's `appError` | +| Handler error | the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` | Native method errors may include owner-defined JSON fields beside `data.appError`. The method owner defines and supplies their safe public shape; the method table diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 67f266f27d..cf34e9767f 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -25,9 +25,9 @@ Callers keep: | A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the host's refusal are the owner's | `register` | | Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | | `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | -| The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `invalid`; a pre-check races the next registration | Business | +| The caller learns why a registration was refused | Yes: `register` answers `duplicate` or `invalid`; a separate check would race the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | -| A provider notifies its caller | Yes: the handler has the call's `Caller` and uses `callChannel` (#2021) | Business | +| A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | An operation or parameter exists only where the row says No. @@ -46,7 +46,7 @@ methods.register( .map_err(|error| rutis::Error::from(rutis::host::ErrorKind::PluginFailed(error.to_string().into())))?; ``` -Rpc dispatches one wire call; the caller is the admission's site for this call, the call's sink is the connection's, and the reply is `MethodReply` data: +Rpc dispatches one wire call; the caller is the admission's site for this call, `progress` is Rpc's sink for it, and the reply is `MethodReply` data: ```rust let reply = match methods.call( @@ -54,7 +54,7 @@ let reply = match methods.call( params, Some(site), cancelled.clone(), - move |data| connection.progress(call_id.clone(), data), + progress, ).await { Ok(reply) => reply, Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), @@ -103,21 +103,21 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | -Each reply is data on the wire and a `Result` in Rust: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. +`register` and `methods` are data on the wire; `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. -A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, its message the handler's `message`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, the handler's `data` fields sit beside `appError`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). ### Errors | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `invalid` | `register` | — | The host refuses the namespace or its declarations: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated. Fix the name or the declaration and register again | +| `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | +| `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | -| `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | +| `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | | `closed` | all | `session_closed` (Session table) | The table is closing; a later generation serves the next Session or the next process | @@ -129,22 +129,23 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | --- | --- | --- | --- | --- | --- | | `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | | `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | -| `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A call in flight answers from the state it observed | SessionMethods | +| `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons +- A handler error's owner fields cross to the client untouched: `MethodCallbackError` keeps them in `data`, and the table and Rpc never interpret or drop them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). - The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour and [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding) the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification Flow tests on the owner: -- A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are all `invalid`, and a refused registration fails the registering part. +- A registration lives until its row unloads; a duplicate namespace is `duplicate`, while a reserved name or a malformed declaration is `invalid`; a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. - A native handler receives the call's `Caller`, and a handler of another language receives `{connectionId, callId}`; an in-process call has no caller. The handler's notification is written by `callChannel` with the same call id, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. -- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name, and only a call that crossed nothing is `failed`. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name; an error with no code and a call that crossed nothing are both `failed`. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. ## Rule check @@ -160,13 +161,13 @@ Flow tests on the owner: | §4 rule 4 | Core and assembly carry no method-specific meaning; a namespace's contents are its part's. | | §4 rule 5 | No batches. | | §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | -| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. A handler receives the call's `Caller`, the stated exception. | -| §4 rule 8 | No infrastructure change in this contract: the withdrawn-row answer uses the loader's existing row status, whose per-row read is raised to the mechanism owner (see below). | +| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | +| §4 rule 8 | The only infrastructure request is the loader's per-row read, raised below with its five fields; nothing else changes. | | §4 rule 9 | No Timeline fact. | | §7 values, ids and callbacks | The caller is data on the wire and A.2's `Caller` for a native handler — the one exception, stated with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | | §7 no proxy | The table answers its own registrations; `rutis/loader`'s row status is the mechanism's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | -| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, the cancellation and the progress sink, none of which is data. | +| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, the cancellation and the progress sink, none of which is data; the site's type is below. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site and `Caller`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | @@ -175,7 +176,7 @@ Flow tests on the owner: | ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | | ADR 002 D3 | No dependency on providers; a failed row affects only its namespaces. | | ADR 002 D4 | The namespace set is structural: parts bring their namespaces. | -| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | +| ADR 002 D5 | The wire operations and their data are language-neutral; `call` is the owner's in-process operation with the same reply data; the Rust binding is the appendix. | ## Requirements raised to mechanism owners @@ -192,11 +193,11 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -The client protocol and user-visible behavior stay as they are: `register` keeps its wire form `register(namespace, declarations, call)`, every client error keeps its application code, and a native handler already receives the `Caller`. Two changes touch a part of another language only: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler error `{code, message}` becomes the client's `appError` unchanged instead of the binding's type name. +The client protocol and user-visible behavior stay as they are: `register` keeps its wire form `register(namespace, declarations, call)`, every client error keeps its application code, and a native handler already receives the `Caller`. Two changes touch a part of another language only: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's `{code, message, ...data}` becomes the client's `appError`, message and owner fields unchanged. An error a handler rethrows from a nested call keeps the code Rpc gives it, as today. ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink, the caller and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `CallSite`, `Progress` and the connection; this block states their shape and lifecycle. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, and `Caller` and `RpcError` are A.2's and [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)'s own types, stated there. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. @@ -217,6 +218,18 @@ pub struct MethodDecl { pub progress: bool, #[serde(default, skip_serializing)] pub notifications: Vec, + #[serde(default, skip_serializing)] + pub reply: ReplyMode, +} + +/// A method's reply mode (A.1). Reply handoff is not implemented, so nothing +/// reads it yet. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReplyMode { + #[default] + Direct, + Handoff, } /// How a provider answers an admitted call that an unload interrupts: `report` @@ -230,6 +243,7 @@ pub enum Interruption { /// The call's progress sink (A.2). The table hands it to a handler whose /// declaration declares `progress` and closes it before the reply is written. +#[derive(Clone)] pub struct Progress(/* the calling connection's sink */); impl Progress { @@ -267,22 +281,28 @@ pub struct Origin { pub caller: Option, } -/// A handler's own failure: its application code and message, which the client -/// sees as the Rpc envelope's `data.appError` and message. +/// A handler's own failure: its application code, message and any owner-defined +/// fields the client receives beside `data.appError`. #[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[error("{code}: {message}")] pub struct MethodCallbackError { pub code: String, pub message: String, + /// Owner-defined wire fields, preserved by the table and Rpc; they must + /// not shadow `appError` or a built-in field. + #[serde(flatten, default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub data: std::collections::BTreeMap, } impl MethodCallbackError { - /// The client code and message Rpc gives a runtime error. + /// The client code, message and owner fields Rpc gives a runtime error. fn from_wire(wire: RpcError) -> Self { + let data = wire.data.as_ref(); Self { - code: wire.data.as_ref().map(|data| data.app_error.clone()).unwrap_or_else(|| "failed".into()), + code: data.map(|data| data.app_error.clone()).unwrap_or_else(|| "failed".into()), message: wire.message, + data: data.map(|data| data.details.clone()).unwrap_or_default(), } } } @@ -293,6 +313,14 @@ impl From for MethodCallbackError { } } +/// A handler's own `params(..)?` or `reply(..)?` failure keeps its client +/// code, message and owner fields. +impl From for MethodCallbackError { + fn from(wire: RpcError) -> Self { + Self::from_wire(wire) + } +} + impl From for MethodCallbackError { fn from(error: CallError) -> Self { let remote = error.raw().and_then(|raw| raw.downcast_ref::()); @@ -312,7 +340,7 @@ impl From for MethodCallbackError { }) }) .unwrap_or_else(|| "failed".into()); - Self { code, message: error.message().into() } + Self { code, message: error.message().into(), data: Default::default() } } } @@ -343,6 +371,12 @@ pub enum ValueReply { }, } +impl From for MethodReply { + fn from(value: serde_json::Value) -> Self { + Self::Value(ValueReply::Value { value }) + } +} + impl From for MethodReply { fn from(error: MethodCallbackError) -> Self { Self::Error(error) @@ -365,7 +399,7 @@ pub enum MethodError { Reloading, #[error("the registering row is unavailable")] Unavailable, - #[error("the provider unloaded during the call")] + #[error("the provider's generation or the admitting Rpc load unloaded during the call")] Interrupted, #[error("the table is closing")] Closed, diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 555f0b810a..739bb5b8db 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ 状态:草案。总体设计:[总览 §3 集成](../overview.md#3-基于现有机制的集成)、[附录 B Rpc 与 ToolRegistry](../overview.md#附录-b-现有插件的补充);规则:[ADR 002](../../adr/002-plugin-scope.md) D2、D3、D5。阶段:P0。语言:语言中立合同;Rust 绑定见[附录 F](#附录-f-rust-绑定)。[C4 绑定](../../../design/session-typescript.md) 已实现非 Rust Session 工具和方法子集;原生广播仍待定。 -本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其方法接收并返回可序列化数据;错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务,并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时读取这两张方法表,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 +本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其注册接收可序列化数据,Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务,并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时读取这两张方法表,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 | 服务 | 作用域 | 注册什么 | 注册方 | 读取方 | | --- | --- | --- | --- | --- | @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | 从没有命名空间持有过该名称,或注册它的行已禁用或不存在时返回 `unknown_method`;其他情况下,已撤回的命名空间按该行的状态作答(§3.2) | | 工具注册 | Session 挂载列表列出但没有部件注册的工具不声明,并在诊断中报告;有部件注册后从下一个请求起声明(A.5) | -本文定义的合同:这两张方法表及其注册、工具注册、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。调用数据——`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 +本文定义的合同:两张方法表共用的注册、工具注册、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。调用数据——`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 ## 2. 数据与状态 @@ -117,7 +117,7 @@ sequenceDiagram | --- | --- | --- | --- | | Session 级提供方在调用中途重载 | call < reload | `report`:`operation_interrupted`;`drain`:调用自己的结果;提供方的卸载等待每个已受理的调用(AGENTS.md 规则 8) | 提供方 | | Session 的 Capability 重载期间调用 Session 方法 | — | `service_reloading` | Session 方法表 | -| 命名空间已撤回、且注册它的部件已失败或无法运行时调用 Session 方法 | — | 该部件修复前返回 `service_unavailable`(A.1) | Rpc | +| 命名空间已撤回、且注册它的部件已失败或无法运行时调用 Session 方法 | — | 该部件修复前返回 `service_unavailable`(A.1) | Session 方法表 | | 调用该 Session 从没有命名空间持有过的 Session 方法 | — | `unknown_method` | Session 方法表 | | 管理方法所有者重载 | — | 新一代重新注册前,调用其已撤回的命名空间返回 `service_reloading`;处于 Failed、Unresolved、Stopped 或 Disposed 的所有者返回 `service_unavailable`(§3.2);已受理的调用属于提供方,按 `interruption` 处理;Rpc 不重载,连接保持打开 | Rpc | | 在带 `deviceId` 的连接上调用管理方法或 `daemon.shutdown` | — | `unknown_method` | Rpc | @@ -141,7 +141,7 @@ sequenceDiagram | `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;注册行是绑定的 `&Ctx`,不是请求字段,形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | -| `sessionMethods.call {method, params, caller?}` | async | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable`、`interrupted` 或 `closed`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable`、`interrupted` 或 `closed`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | 该 Session 现在注册的命名空间的声明 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | | `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现,附录 F) | @@ -279,7 +279,7 @@ sequenceDiagram ### A.2 调用通道 -`progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现。App Server 以自己的 `CallChannel` 行向方法提供方提供进程服务 `callChannel`,因此声明该名字的行不会随 Rpc 重载;Rust 绑定是处理函数按调用获得的 `Progress` 与 `Caller`(附录 F)。 +`progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现。App Server 以自己的 `CallChannel` 行向方法提供方提供进程服务 `callChannel`,因此声明该名字的行不会随 Rpc 重载;Rust 绑定是处理函数按调用获得的 `Progress` 与 `Caller`([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix))。 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | @@ -317,7 +317,7 @@ reply ----------> 回复与通知额度 ----------------+ 已满:慢消费者,关闭连接 ``` -通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即提供方收到的 `MethodCall` 的 `callId`。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 +通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即提供方的处理函数收到的 `Caller` 携带的 id。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 一次调用的通知如何到达调用方: @@ -494,7 +494,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | Session 正在重载,或已撤回命名空间的注册行(或其在该 Session 中的副本)未运行且未失败(尚未启动、Pending、Loading,或新旧两代之间),或已撤回 Session 命名空间的副本处于 Active 或不存在 | `-32000`,`service_reloading`(可重试) | | 已撤回命名空间的注册行,或该行在该 Session 中的副本,处于 Failed、Unresolved、Disposed 或 Stopped | `-32000`,`service_unavailable`(不可重试) | | `report` 调用被中断 | `-32000`,`operation_interrupted` | -| 提供方错误 | `-32000`,提供方的 `appError` | +| 处理函数错误 | Rpc 为服务错误选择的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` | ## 附录 D. 验收 From 55191f77fb6695db036d89515cd0b36caa3a1fbf Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 03:01:32 +0800 Subject: [PATCH 08/41] docs(sessionmethods): answer the sixth pre-review The row-status read becomes `loaderRows`, a dim-owned process face for one row, instead of a read of rutis-loader's own service. The handler's error keeps the JSON-RPC code it chooses and converts into Rpc's envelope, so the client's error is unchanged. The caller's id is minted by the table, `Caller` and `CallerConnection` are defined here, and the declaration's reply mode is optional and ignored until handoff exists. --- docs/design/contracts/session-boundary.md | 8 +- docs/design/plugins/README.md | 2 +- docs/design/plugins/SessionMethods.md | 109 +++++++++++++++---- docs/zh/design/contracts/session-boundary.md | 8 +- docs/zh/design/plugins/README.md | 2 +- 5 files changed, 96 insertions(+), 33 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 590a2fb954..7b9d4a3f5d 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -226,7 +226,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, reply handoff, `origin.entry` and `origin.peer` are not implemented. +Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is accepted and ignored until reply handoff exists; reply handoff, `origin.entry` and `origin.peer` are not implemented. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. @@ -318,7 +318,7 @@ reply ----------> reply and notice allowance ----+ full: a slow consumer, the connection closes ``` -A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id of the `Caller` the provider's handler received. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. +A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id the `Caller` carries for a native handler, and the `origin.caller.callId` a handler of another language received. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. How a notification of one call reaches its caller: @@ -525,7 +525,7 @@ carry the native event whole, and the frozen fixtures stay unchanged. | Session reloading, or a withdrawn namespace whose registering row (or its copy in the Session) is not running and has not failed (not started yet, Pending, Loading, or between generations), or a withdrawn Session namespace whose copy is Active or absent | `-32000`, `service_reloading` (retryable) | | A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped | `-32000`, `service_unavailable` (not retryable) | | `report` call interrupted | `-32000`, `operation_interrupted` | -| Handler error | the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` | +| Handler error | the handler's own JSON-RPC code when it carries one (a native handler that returns an `RpcError`), otherwise the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | Native method errors may include owner-defined JSON fields beside `data.appError`. The method owner defines and supplies their safe public shape; the method table @@ -559,7 +559,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`, a process service holding the method namespaces, provided by App Server's `ManagementMethodsPlugin` row | A process part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations and wire form are the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc depends on the table and reads it per call (§3.2); no provider is in Rpc's `Deps` | Implemented (#14, #382) | +| `managementMethods` | `ManagementMethods`, a process service holding a `MethodTable`, provided by App Server's `ManagementMethodsPlugin` row | A process part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Rpc depends on the table and reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382); target in the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | | `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#own-contract) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 7e4cf2baec..598d645c37 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -53,5 +53,5 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | | 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) | +| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, SessionMethods, 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) | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index cf34e9767f..8e19fc540f 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -64,6 +64,12 @@ let reply = match methods.call( Err(MethodError::Closed) => return Err(RpcError::closed()), Err(MethodError::Duplicate { .. }) | Err(MethodError::Invalid { .. }) => unreachable!("dispatch cannot register"), }; +// `MethodReply::Value` is the handler's value; `MethodReply::Error` is its own +// failure, which Rpc wraps in its envelope. +match reply { + MethodReply::Value(ValueReply::Value { value }) => value, + MethodReply::Error(error) => return Err(RpcError::from(error)), +} ``` `session.methods` composes the value with the process table's held namespaces: @@ -91,7 +97,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `rutis/loader` (rutis-loader's process face; App Server's loader row) | The row that registered a withdrawn namespace and its copies in this Session. The per-row read is `get(row)`, whose `EntryInfo.status` is the row's `EntryStatus`; `entries()` lists the row's copies with their instances. Read when a call answers `reloading` or `unavailable`. The face itself offers `status`, which builds the process's whole diagnostics snapshot for `rutis-host status`, so it answers neither one row's status nor its copies in one instance. The per-row read is therefore raised to the mechanism owner (§4 rule 8). | +| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{status, copies}`, the row's own state and one entry per copy with its instance, read when a call answers `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. @@ -99,15 +105,15 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `invalid`, `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `duplicate`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, connectionId?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | `register` and `methods` are data on the wire; `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is the calling connection and this call's id; absent for an in-process call. Another table's wire carries it as `{connectionId, callId}`; in Rust the caller passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal, and the table binds it to this generation's declared notifications. The handler receives it as `MethodCall.origin.caller`, A.2's `Caller`; a handler of another language receives `{connectionId, callId}`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`connectionId` is the calling connection; absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The table mints the call id: it is the id progress and notifications observe, the `Caller`'s `call_id()` for a native handler, and `origin.caller.callId` for a handler of another language. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. -A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, the handler's `data` fields sit beside `appError`, and the JSON-RPC code is the one Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000). +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language sends no wire code, so its errors take the rule. ### Errors @@ -115,11 +121,11 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | --- | --- | --- | --- | | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent; the client sees an unknown method | +| `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | -| `closed` | all | `session_closed` (Session table) | The table is closing; a later generation serves the next Session or the next process | +| `closed` | all | `session_closed` (Session table) | The table is closing. Call the replacement generation: the next Session for a Session table, the next process for the process table | `invalid` and `duplicate` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. @@ -133,7 +139,6 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- A handler error's owner fields cross to the client untouched: `MethodCallbackError` keeps them in `data`, and the table and Rpc never interpret or drop them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). - The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour and [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding) the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -152,7 +157,7 @@ Flow tests on the owner: | Rule | Application | | --- | --- | -| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and reads `rutis/loader`. | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and, once it exists, `loaderRows`. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | | §3 orthogonality | No other business owner's state is read or changed; `reservedMethods` and `rutis/loader` are the mechanism's faces. | | §4 rule 1 | No command event: a registration is the calling row's effect. | @@ -162,12 +167,12 @@ Flow tests on the owner: | §4 rule 5 | No batches. | | §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | -| §4 rule 8 | The only infrastructure request is the loader's per-row read, raised below with its five fields; nothing else changes. | +| §4 rule 8 | The only infrastructure request is `loaderRows`, a dim-owned process face for one loader row, raised below with its five fields; nothing else changes. | | §4 rule 9 | No Timeline fact. | | §7 values, ids and callbacks | The caller is data on the wire and A.2's `Caller` for a native handler — the one exception, stated with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | -| §7 no proxy | The table answers its own registrations; `rutis/loader`'s row status is the mechanism's read, raised below. | +| §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | -| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, the cancellation and the progress sink, none of which is data; the site's type is below. | +| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site and `Caller`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | @@ -182,11 +187,11 @@ Flow tests on the owner: | Field | Value | | --- | --- | -| Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the face `rutis/loader` offers only `status` for the whole process, so the table has no per-row read. | -| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, its `status` builds the process's whole diagnostics snapshot (rows, services, runtimes, calls) and answers each row's own state, not a row's status and its copies in one instance; `dim-agent-capabilities` does not depend on `rutis-loader`. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | -| Generic capability needed | A data face over one loader row: `{row, instance}` → the row's `EntryStatus` and the status of its copy in that instance. No business meaning. | +| Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the process's loader is `rutis-loader`'s own business state; the table has no dim-owned face for it. | +| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | +| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{status, copies}`, each copy naming its instance. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The mechanism owner: rutis-loader's `rutis/loader` face and App Server's loader row (`crates/dim-app-server/src/lib.rs:1626`; the per-row read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`), tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1626`; the per-row read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes @@ -197,7 +202,7 @@ The client protocol and user-visible behavior stay as they are: `register` keeps ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, and `Caller` and `RpcError` are A.2's and [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding)'s own types, stated there. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `Callers` and `NotifyError` are A.2's too, bound in [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding). `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. @@ -219,11 +224,12 @@ pub struct MethodDecl { #[serde(default, skip_serializing)] pub notifications: Vec, #[serde(default, skip_serializing)] - pub reply: ReplyMode, + pub reply: Option, } -/// A method's reply mode (A.1). Reply handoff is not implemented, so nothing -/// reads it yet. +/// A method's reply mode (A.1). The table accepts the field and ignores it: +/// reply handoff is not implemented, so a `handoff` declaration registers and +/// its replies are direct. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReplyMode { @@ -252,6 +258,37 @@ impl Progress { pub fn send(&self, data: serde_json::Value) { /* ... */ } } +/// The calling connection of one admitted call (A.2), bound to the serving +/// generation's declared notifications. Opaque: its methods are its whole +/// surface. It keeps the connection through `Arc`, +/// which holds no strong reference, so a retained `Caller` does not keep a +/// closed connection alive. +#[derive(Clone)] +pub struct Caller(/* the connection, its declared names and the generation */); + +impl Caller { + /// The contract's `connectionId`. + pub fn id(&self) -> &str { /* ... */ } + /// The call id notifications and progress address; `None` for a call that + /// came from no connection. + pub fn call_id(&self) -> Option<&str> { /* ... */ } + /// Sends a connection-bound notification (A.2): `undeclared` for a name + /// this generation did not declare, `gone` once it unloaded or the + /// connection closed, `too_large` over the frame limit. + pub fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError> { /* ... */ } + /// Resolves when the connection closes or the admitting Rpc load unloads. + pub fn closed(&self) -> impl std::future::Future + Send + 'static { async {} } +} + +/// A connection as the `methods` module uses it: its id, a write to it and its +///close signal. Rpc implements it; `Caller` and `CallSite` hold it through an +/// `Arc` that keeps no strong reference to the connection. +pub trait CallerConnection: Send + Sync + 'static { + fn id(&self) -> &str; + fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError>; + fn closed(&self) -> BoxFuture<'static, ()>; +} + /// One admitted call's connection, as Rpc passes it to `call`: the call's /// channel, the connection's direct writer, the process's caller index (A.2) /// and the connection's close signal. Rpc builds it for one call; the table @@ -275,7 +312,7 @@ pub struct MethodCall { /// Who called: the call's `Caller` (A.2) for a native handler, built by the /// admission from the calling connection and this generation's declared -/// notifications; Appendix F holds the type and its lifecycle. +/// notifications; its type and lifecycle are below and in A.2. #[derive(Clone)] pub struct Origin { pub caller: Option, @@ -289,6 +326,10 @@ pub struct Origin { pub struct MethodCallbackError { pub code: String, pub message: String, + /// The JSON-RPC code the handler chose; the service-error rule applies + /// when it is absent. Another language's handler sends none. + #[serde(skip, default)] + pub wire: Option, /// Owner-defined wire fields, preserved by the table and Rpc; they must /// not shadow `appError` or a built-in field. #[serde(flatten, default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] @@ -302,6 +343,7 @@ impl MethodCallbackError { Self { code: data.map(|data| data.app_error.clone()).unwrap_or_else(|| "failed".into()), message: wire.message, + wire: Some(wire.code), data: data.map(|data| data.details.clone()).unwrap_or_default(), } } @@ -340,7 +382,7 @@ impl From for MethodCallbackError { }) }) .unwrap_or_else(|| "failed".into()); - Self { code, message: error.message().into(), data: Default::default() } + Self { code, message: error.message().into(), wire: None, data: Default::default() } } } @@ -383,6 +425,27 @@ impl From for MethodReply { } } +/// Rpc's wrapping of a handler's failure: the handler's wire code, else the +/// service-error rule, with `appError` and its owner fields in `data`. +impl From for RpcError { + fn from(error: MethodCallbackError) -> Self { + let code = error.wire.unwrap_or(match error.code.as_str() { + "invalid_params" => -32602, + "unknown_method" => -32601, + _ => -32000, + }); + Self { + code, + message: error.message, + data: Some(ErrorData { + app_error: error.code, + details: error.data, + daemon_busy: None, + }), + } + } +} + /// The table's own failures, by kind. One kind set serves both tables; /// `closed` reaches a client as `session_closed` for the Session table, and /// the process table has no client code of its own. @@ -434,7 +497,7 @@ impl SessionMethods { /// The declarations registered now. pub fn methods(&self) -> Result, MethodError> { /* ... */ } - /// One call, in process: the caller's site (`CallSite`, Appendix F), the + /// One call, in process: the caller's site (`CallSite`, below), the /// cancellation and the progress sink are parameters, and the reply is /// data. #[service(skip)] diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 739bb5b8db..5c8a892c30 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -226,7 +226,7 @@ sequenceDiagram // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、回复交接、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 在回复交接落地前接受并忽略;回复交接、`origin.entry` 与 `origin.peer` 未实现。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 @@ -317,7 +317,7 @@ reply ----------> 回复与通知额度 ----------------+ 已满:慢消费者,关闭连接 ``` -通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即提供方的处理函数收到的 `Caller` 携带的 id。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 +通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即原生处理函数从 `Caller` 得到的 id,或另一种语言的处理函数收到的 `origin.caller.callId`。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 一次调用的通知如何到达调用方: @@ -494,7 +494,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | Session 正在重载,或已撤回命名空间的注册行(或其在该 Session 中的副本)未运行且未失败(尚未启动、Pending、Loading,或新旧两代之间),或已撤回 Session 命名空间的副本处于 Active 或不存在 | `-32000`,`service_reloading`(可重试) | | 已撤回命名空间的注册行,或该行在该 Session 中的副本,处于 Failed、Unresolved、Disposed 或 Stopped | `-32000`,`service_unavailable`(不可重试) | | `report` 调用被中断 | `-32000`,`operation_interrupted` | -| 处理函数错误 | Rpc 为服务错误选择的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` | +| 处理函数错误 | 处理函数自带的 JSON-RPC 码(返回 `RpcError` 的原生处理函数),否则为 Rpc 为服务错误选择的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` 与其所有者字段 | ## 附录 D. 验收 @@ -522,7 +522,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`,持有方法命名空间的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作与线上形状归进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | Rpc 依赖这张表并按调用读取(§3.2);没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | +| `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382);目标见进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | | `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | diff --git a/docs/zh/design/plugins/README.md b/docs/zh/design/plugins/README.md index 259484f5e4..652aef431f 100644 --- a/docs/zh/design/plugins/README.md +++ b/docs/zh/design/plugins/README.md @@ -46,5 +46,5 @@ | 作用域 | 部分 | | --- | --- | | 进程部件 | daemon 内的 Provider(管理补充提案)、Scheduler、Workflow、ExternalAgent、Modality、PluginManager、RuntimeManager、RemoteGateway、Skills(安装)、PromptSuggestion(Settings 来源)、`CodeMode`(安装时)、light-ocr、EventHub;接入方宿主进程内的 AcpGateway | -| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、Prompt(条目表)、Code Mode(启用时) | +| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、SessionMethods、Prompt(条目表)、Code Mode(启用时) | | 分支部件 | Goal(含 Pursuit)、ModelRecovery(拟议)、Hooks、Prompt、Code Mode(启用时) | From 7454d2918200252a47acf0835017dfb2f374aa0b Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 03:17:18 +0800 Subject: [PATCH 09/41] docs(sessionmethods): answer the seventh pre-review The owner serves one hand-written dispatcher: a marked service beside it would claim `sessionMethods` twice, so `register`, `methods` and `call` stay on the type and `HostDispatch` is the only wire entry. `loaderRows` answers each copy's state, the call id is minted for another language only and progress keeps Rpc's request id, and Appendix F points here for `Caller`, `CallerConnection`, `CallSite`, `Progress` and `NotifyError`. --- docs/design/contracts/session-boundary.md | 21 ++----- docs/design/plugins/README.md | 2 +- docs/design/plugins/SessionMethods.md | 58 ++++++++++++-------- docs/zh/design/contracts/session-boundary.md | 4 +- docs/zh/design/plugins/README.md | 2 +- 5 files changed, 46 insertions(+), 41 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 7b9d4a3f5d..bdd79ac137 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -81,7 +81,7 @@ sequenceDiagram Rpc->>Rpc: not a built-in, no management namespace holds it, sessionId in params, authorize Session access Rpc->>AI: acquire(sessionId), restoring if unloaded AI-->>Rpc: Session lease - Rpc->>S: call {method, params, caller} + Rpc->>S: call {method, params, caller?} S->>Q: the handler of the longest namespace holding the name Q->>H: hand the answer to the waiting call (branchId, requestId, callId) Q-->>S: MethodReply @@ -222,7 +222,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own "interruption": "report" | "drain", // the provider replies on unload: report → operation_interrupted; drain → the call's own result "progress": false, "notifications?": ["session.goal.changed"], // inside the namespace - "reply": "direct" | "handoff" } // handoff: daemon.shutdown + "reply?": "direct" | "handoff" } // handoff: daemon.shutdown; accepted and ignored until handoff exists // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` @@ -238,9 +238,9 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | -| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | +| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -564,22 +564,13 @@ The neutral services map to the native owners below. Tools register with ToolReg | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `RpcError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). `Progress` binds A.2 `progress` per call rather than through a `callChannel` process service: Rpc passes each admitted call a sink that writes `management.progress {id, method, data}` to the calling connection, and the table's `call` hands it to the handler only when the method declares `progress` and closes it before the reply is written. The sink queues progress under its own allowance on the connection, so progress never takes room from the reply or durable notifications. Management methods use the same path; `runtime.watch` and `schedule.watch` declare `progress` ([RuntimeManager §10](../plugins/RuntimeManager.md#10-client-change-notices); [Scheduler §11.2](../plugins/Scheduler.md#112-jobs-and-runs)). -```rust -// crates/dim-agent-capabilities/src/methods.rs, shared by both services -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum NotifyError { Undeclared, Gone, TooLarge } // code(): "undeclared", "gone", "too_large" -impl Caller { - pub fn id(&self) -> &str; // the contract's connectionId - pub fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError>; - pub fn closed(&self) -> impl Future + Send + 'static; -} -``` +`Caller`, `CallerConnection`, `CallSite`, `Progress` and `NotifyError` are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's; it states their shape and lifecycle, and this appendix keeps only the module they live in. `Caller` binds A.2 `notify` and `closed` per call, like `Progress`: the table's `call` builds it only when the call arrived on a client connection, bound to the notifications its declaration set declared, so a name outside that set is `Undeclared` before anything is written, and a generation that has unloaded is `Gone` first. It holds the connection through a trait object (`CallerConnection`) that keeps no strong reference to it, so a provider that keeps a `Caller` does not keep a closed connection alive. Rpc writes each notification after the reply of the call that produced the caller: one sent while the call runs is encoded once, admitted under the connection's held allowance, held in order and flushed right after the reply; one over the frame limit is `TooLarge` and the connection stays open, and one the held allowance cannot take closes the connection as a slow consumer. The caller resolves `closed` when the connection closes or the admitting Rpc load unloads. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 598d645c37..7e4cf2baec 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -53,5 +53,5 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | | 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, SessionMethods, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | +| 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) | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 8e19fc540f..bf3b3e0efb 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -66,10 +66,10 @@ let reply = match methods.call( }; // `MethodReply::Value` is the handler's value; `MethodReply::Error` is its own // failure, which Rpc wraps in its envelope. -match reply { +Ok(match reply { MethodReply::Value(ValueReply::Value { value }) => value, MethodReply::Error(error) => return Err(RpcError::from(error)), -} +}) ``` `session.methods` composes the value with the process table's held namespaces: @@ -97,7 +97,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{status, copies}`, the row's own state and one entry per copy with its instance, read when a call answers `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | +| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{status, copies: [{instance, status}]}`, the row's own state and each copy's state with its instance. The table reads it before it answers `reloading` or `unavailable`, and picks the copy in this Session. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. @@ -106,14 +106,16 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, connectionId?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | +`register`'s declarations follow A.1: at least one method; each name inside the namespace and unique; each declared notification inside the namespace, unique across the set, never a method's name and never a built-in notification's name. A declaration that breaks them is `invalid`. + `register` and `methods` are data on the wire; `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`connectionId` is the calling connection; absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The table mints the call id: it is the id progress and notifications observe, the `Caller`'s `call_id()` for a native handler, and `origin.caller.callId` for a handler of another language. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is `{connectionId}`: the connection the call arrived on, absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call from another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. -A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language sends no wire code, so its errors take the rule. +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. ### Errors @@ -122,7 +124,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | -| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | +| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, or its copy in this Session is Active because a child plugin reloads; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | | `closed` | all | `session_closed` (Session table) | The table is closing. Call the replacement generation: the next Session for a Session table, the next process for the process table | @@ -148,7 +150,7 @@ Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace is `duplicate`, while a reserved name or a malformed declaration is `invalid`; a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. -- A native handler receives the call's `Caller`, and a handler of another language receives `{connectionId, callId}`; an in-process call has no caller. The handler's notification is written by `callChannel` with the same call id, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. +- A native handler receives the call's `Caller` and notifies through its `CallerConnection`; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name; an error with no code and a call that crossed nothing are both `failed`. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. @@ -159,7 +161,7 @@ Flow tests on the owner: | --- | --- | | §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and, once it exists, `loaderRows`. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | -| §3 orthogonality | No other business owner's state is read or changed; `reservedMethods` and `rutis/loader` are the mechanism's faces. | +| §3 orthogonality | No other business owner's state is read or changed; `reservedMethods` and `loaderRows` are the mechanism's faces. | | §4 rule 1 | No command event: a registration is the calling row's effect. | | §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | | §4 rule 3 | No before callback. | @@ -189,9 +191,9 @@ Flow tests on the owner: | --- | --- | | Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the process's loader is `rutis-loader`'s own business state; the table has no dim-owned face for it. | | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | -| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{status, copies}`, each copy naming its instance. No business meaning. | +| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{status, copies: [{instance, status}]}`, each copy naming its instance and its state. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1626`; the per-row read Rpc does today at `crates/dim-app-server/src/methods.rs:222-262`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:222-262`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes @@ -202,7 +204,7 @@ The client protocol and user-visible behavior stay as they are: `register` keeps ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `Callers` and `NotifyError` are A.2's too, bound in [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding). `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `NotifyError` is A.2's too, stated below. `Callers` is the process's caller index, A.2's own wiring, and `CallSite` only references it. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. @@ -258,6 +260,17 @@ impl Progress { pub fn send(&self, data: serde_json::Value) { /* ... */ } } +/// Why a connection-bound notification was not written (A.2). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NotifyError { + /// A name the provider generation did not declare. + Undeclared, + /// The connection closed, or the generation or load that admitted the call unloaded. + Gone, + /// An encoded notification over the frame limit. + TooLarge, +} + /// The calling connection of one admitted call (A.2), bound to the serving /// generation's declared notifications. Opaque: its methods are its whole /// surface. It keeps the connection through `Arc`, @@ -269,8 +282,8 @@ pub struct Caller(/* the connection, its declared names and the generation */); impl Caller { /// The contract's `connectionId`. pub fn id(&self) -> &str { /* ... */ } - /// The call id notifications and progress address; `None` for a call that - /// came from no connection. + /// The call id a notification addresses, minted for a call from another + /// language; `None` for a native provider's call, which needs none. pub fn call_id(&self) -> Option<&str> { /* ... */ } /// Sends a connection-bound notification (A.2): `undeclared` for a name /// this generation did not declare, `gone` once it unloaded or the @@ -480,12 +493,11 @@ use tokio_util::sync::CancellationToken; /// stay private. pub struct SessionMethods { /* ... */ } -#[rutis::service(name = "sessionMethods")] impl SessionMethods { /// Publishes `namespace` for the lifetime of the row that owns `caller`. - /// The macro leaves it to the dispatch below: the callback's arguments are - /// not data. - #[service(skip)] + /// Another language's wire form is `register {namespace, declarations, call}` + /// through the dispatch below, because the callback's arguments are not + /// data. pub async fn register( &self, caller: &Ctx, @@ -500,7 +512,6 @@ impl SessionMethods { /// One call, in process: the caller's site (`CallSite`, below), the /// cancellation and the progress sink are parameters, and the reply is /// data. - #[service(skip)] pub async fn call( &self, method: String, @@ -511,8 +522,11 @@ impl SessionMethods { ) -> Result { /* ... */ } } -/// Another language reaches the table at its Session dispatcher key: -/// `register {namespace, declarations, call}` and `methods {}`. +/// The catalog name `sessionMethods` in the Session group, served to other +/// languages at its dispatcher key: `register {namespace, declarations, call}` +/// and `methods {}`. One dispatcher, hand-written: `#[rutis::service]` cannot +/// bind `register`'s callback, and a marked service beside this dispatch would +/// claim the same name twice. impl HostDispatch for SessionMethods { fn methods(&self) -> Option { Some(serde_json::json!({ "register": "async", "methods": "sync" })) @@ -522,4 +536,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face: `register` through the dispatch above, which decodes the declarations and the caller's function for the bridge's calling row, and `methods` through the marked service and that dispatch. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant and never carried in the table's error data; the handler's `code` becomes it on the envelope. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant and never carried in the table's error data; the handler's `code` becomes it on the envelope. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 5c8a892c30..19c87ef366 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -81,7 +81,7 @@ sequenceDiagram Rpc->>Rpc: 非内建方法,没有管理命名空间持有它,params 中带 sessionId,授权 Session 访问 Rpc->>AI: acquire(sessionId),未装载时恢复 AI-->>Rpc: Session 租约 - Rpc->>S: call {method, params, caller} + Rpc->>S: call {method, params, caller?} S->>Q: 持有该名称的最长命名空间的处理函数 Q->>H: 把回答交给等待中的调用 (branchId, requestId, callId) Q-->>S: MethodReply @@ -238,7 +238,7 @@ sequenceDiagram | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | -| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | +| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | | 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | diff --git a/docs/zh/design/plugins/README.md b/docs/zh/design/plugins/README.md index 652aef431f..259484f5e4 100644 --- a/docs/zh/design/plugins/README.md +++ b/docs/zh/design/plugins/README.md @@ -46,5 +46,5 @@ | 作用域 | 部分 | | --- | --- | | 进程部件 | daemon 内的 Provider(管理补充提案)、Scheduler、Workflow、ExternalAgent、Modality、PluginManager、RuntimeManager、RemoteGateway、Skills(安装)、PromptSuggestion(Settings 来源)、`CodeMode`(安装时)、light-ocr、EventHub;接入方宿主进程内的 AcpGateway | -| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、SessionMethods、Prompt(条目表)、Code Mode(启用时) | +| Session 部件 | Questions、ShellInput、Attachments、SessionTitle、PromptSuggestion、Goal、Web、Recall、EventHub、Hooks、Scheduler、Workflow、PromptSources、Prompt(条目表)、Code Mode(启用时) | | 分支部件 | Goal(含 Pursuit)、ModelRecovery(拟议)、Hooks、Prompt、Code Mode(启用时) | From f4e3160da4514fdb1852eb4949b1a4f29b6b856f Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 03:29:41 +0800 Subject: [PATCH 10/41] docs(sessionmethods): answer the eighth pre-review The zh mirror follows the English rows: no `impl Caller`, no `RpcError` in the call data, and `reply?` optional and ignored. A.2's notification id belongs to a call served by another language, a withdrawn namespace with no copy in this Session is `reloading`, and `loaderRows` states the absent-row answer. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 12 +++++++----- docs/zh/design/contracts/session-boundary.md | 19 +++++-------------- 3 files changed, 13 insertions(+), 20 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index bdd79ac137..9566863389 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -318,7 +318,7 @@ reply ----------> reply and notice allowance ----+ full: a slow consumer, the connection closes ``` -A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id the `Caller` carries for a native handler, and the `origin.caller.callId` a handler of another language received. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. +A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id minted for a call served by a registration of another language, which its `origin.caller.callId` carries. A native handler has no such id: it notifies through its `Caller`. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. How a notification of one call reaches its caller: diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index bf3b3e0efb..244ede827a 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -97,7 +97,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{status, copies: [{instance, status}]}`, the row's own state and each copy's state with its instance. The table reads it before it answers `reloading` or `unavailable`, and picks the copy in this Session. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | +| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{status, copies: [{instance, status}]}`, the row's own state and each copy's state with its instance. The table reads it before it answers `reloading` or `unavailable`, and picks the copy in this Session; a row that does not exist answers so, and the table then answers `unknown_method`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. @@ -124,7 +124,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | -| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, or its copy in this Session is Active because a child plugin reloads; retry after it is Active and registered the namespace again | +| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | | `closed` | all | `session_closed` (Session table) | The table is closing. Call the replacement generation: the next Session for a Session table, the next process for the process table | @@ -136,7 +136,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session, and no copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -148,10 +148,10 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace is `duplicate`, while a reserved name or a malformed declaration is `invalid`; a refused registration fails the registering part. -- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. +- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts, while its copy in this Session is Active or missing, and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. - A native handler receives the call's `Caller` and notifies through its `CallerConnection`; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. -- A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code` and its JSON-RPC code follows the service-error rule. +- A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name; an error with no code and a call that crossed nothing are both `failed`. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. @@ -528,6 +528,8 @@ impl SessionMethods { /// bind `register`'s callback, and a marked service beside this dispatch would /// claim the same name twice. impl HostDispatch for SessionMethods { + /// The dispatch's method list, not the owner's read: `invoke` forwards + /// `methods` to the inherent `SessionMethods::methods`. fn methods(&self) -> Option { Some(serde_json::json!({ "register": "async", "methods": "sync" })) } diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 19c87ef366..39a99c7df9 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -222,7 +222,7 @@ sequenceDiagram "interruption": "report" | "drain", // 卸载时由提供方回复:report → operation_interrupted;drain → 调用自己的结果 "progress": false, "notifications?": ["session.goal.changed"], // 位于命名空间内 - "reply": "direct" | "handoff" } // handoff:daemon.shutdown + "reply?": "direct" | "handoff" } // handoff:daemon.shutdown;交接落地前接受并忽略 // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` @@ -240,7 +240,7 @@ sequenceDiagram | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | | `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | @@ -317,7 +317,7 @@ reply ----------> 回复与通知额度 ----------------+ 已满:慢消费者,关闭连接 ``` -通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即原生处理函数从 `Caller` 得到的 id,或另一种语言的处理函数收到的 `origin.caller.callId`。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 +通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即另一种语言注册所提供的调用被铸出的 id,由 `origin.caller.callId` 携带。原生处理函数没有这个 id:它经自己的 `Caller` 通知。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 一次调用的通知如何到达调用方: @@ -527,22 +527,13 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `RpcError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 `Progress` 按调用绑定 A.2 的 `progress`,而不是通过 `callChannel` 进程服务:Rpc 给每个已受理调用一个 sink,把 `management.progress {id, method, data}` 写到发起调用的连接;方法表的 `call` 只在方法声明了 `progress` 时把它交给处理函数,并在回复写出之前关闭它。sink 在连接上按进度自己的额度排队,所以进度不会占用回复和持久通知的空间。管理方法走同一路径;`runtime.watch` 与 `schedule.watch` 声明了 `progress`([RuntimeManager §10](../plugins/RuntimeManager.md#10-客户端变更通知);[Scheduler §11.2](../plugins/Scheduler.md#112-任务与运行))。 -```rust -// crates/dim-agent-capabilities/src/methods.rs,两个服务共用 -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum NotifyError { Undeclared, Gone, TooLarge } // code():"undeclared"、"gone"、"too_large" -impl Caller { - pub fn id(&self) -> &str; // 合同中的 connectionId - pub fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError>; - pub fn closed(&self) -> impl Future + Send + 'static; -} -``` +`Caller`、`CallerConnection`、`CallSite`、`Progress` 与 `NotifyError` 是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;该附录给出它们的形状与生命周期,本附录只说明它们所在的模块。 `Caller` 与 `Progress` 一样按调用绑定 A.2 的 `notify` 与 `closed`:只有调用来自客户端连接时方法表的 `call` 才构造它,并绑定到该声明集声明的通知,因此集合外的名称在写入任何内容之前就是 `Undeclared`,已卸载的代际则先返回 `Gone`。它通过 `CallerConnection` 这个 trait 对象持有连接,而该对象不强引用连接,所以保留 `Caller` 的提供方不会让已关闭的连接存活。Rpc 在产生该 `Caller` 的调用回复之后写出每条通知:调用进行中发出的通知只编码一次,经连接的暂存额度受理,按序暂存,紧接回复之后写出;超过帧上限的通知是 `TooLarge`,连接保持;暂存额度收不下的通知作为慢消费者关闭连接。连接关闭或受理该调用的 Rpc 代际卸载时,`closed` 完成。 From 40575eb421eca479674650a5891fef02bde4e8ce Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 03:42:50 +0800 Subject: [PATCH 11/41] docs(sessionmethods): answer the ninth pre-review `loaderRows` carries `found`, so a row id nothing has is `unknown_method` and the table reads before it answers. A.2's held-notification rule belongs to a call from another language; a native handler notifies through its `Caller`. The declaration's failure shape names its owner fields, `call_id` stays crate private, and the architecture page includes the disabled-row answer. --- .../rust-agent/plugins/SessionMethods.md | 5 +++-- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 18 ++++++++++-------- docs/zh/design/contracts/session-boundary.md | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 2012f979be..2cbbbee56a 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -38,8 +38,9 @@ dispatcher key, with the native service. A name belongs to the longest namespace that holds it. When a namespace is withdrawn, the table keeps the row that registered it, so a call into it answers -`service_reloading` or `service_unavailable` from that row's status rather than -`unknown_method`. Each registration owns the calls it admitted: its +`service_reloading` or `service_unavailable` from that row's status. That row +being disabled or absent is `unknown_method`, as is a name no namespace of the +Session ever held. Each registration owns the calls it admitted: its part's unload interrupts `report` calls and waits for every admitted call. `session.methods` lists the methods of the namespaces registered now that no management namespace holds. diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 9566863389..de3506f2b4 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -338,7 +338,7 @@ Client A Rpc call admission provider han Delivery differs from progress: - **Reliable.** A notification is encoded once when the provider sends it. One sent while its call's reply is not written is admitted against the connection's held allowance: the same limits as the reply-and-notice allowance (1024 frames, 32 MiB), separate from it, so held notifications never take the room a reply needs. A call that holds past the held allowance is disconnected like a slow consumer, and later `notify` calls answer `gone`. The reply is admitted against the reply-and-notice allowance only. After the reply, the held frames are queued in order with the room they already hold, which is freed as each is written; the connection's queued frames are therefore bounded by the two allowances together, at most 2048 frames and 64 MiB. A notification over the frame limit is refused with `too_large`: nothing is written and the connection stays open. -- **After the reply.** A notification is written after the reply of the call named by its `callId`, which is the id the `Caller` of the `MethodCall` that reported the work carries. One sent while that call is still running is held in order and written right after its reply, so a client never sees an event that names something the reply has not told it yet (for example an id the reply returns). Once that reply is written, or the id is not in flight, it is written straight to the outbound queue; another unfinished call on the same connection neither holds it nor reorders it. The reply is written on every path, including an interrupted call and a call whose connection is gone. +- **After the reply.** A notification is written after the reply of the call named by its `callId`, which is the id minted for a call served by a registration of another language, carried as `origin.caller.callId`. A native handler has no id: its `Caller` holds the notification until that call's reply is written. One sent while that call is still running is held in order and written right after its reply, so a client never sees an event that names something the reply has not told it yet (for example an id the reply returns). Once that reply is written, or the id is not in flight, it is written straight to the outbound queue; another unfinished call on the same connection neither holds it nor reorders it. The reply is written on every path, including an interrupted call and a call whose connection is gone. - **Lifetime.** `closed` resolves, and later `notify` calls answer `gone`, once the connection has closed or the Rpc load that admitted the call has unloaded. A notification after the provider's generation unloads answers `gone` in both bindings: a native caller holds the generation's stopping signal, and the foreign index removes the instance's entries on the same unload. A caller's disconnect cancels no call. `notify` and `closed` answer `gone` for a connection the row received no call from. The service holds one entry per row instance and connection, with that connection's unfinished calls by `callId`; the entry is removed when the connection closes, when the admitting Rpc load unloads and when the row's generation unloads, and a call leaves it when its reply is written. - **Refusal order.** While the generation is loaded, `undeclared` is decided before the connection's state in both bindings: a closed connection does not hide a name the generation did not declare. A generation that has unloaded answers `gone` for every name, declared or not. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 244ede827a..2dc4b75c96 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -97,7 +97,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{status, copies: [{instance, status}]}`, the row's own state and each copy's state with its instance. The table reads it before it answers `reloading` or `unavailable`, and picks the copy in this Session; a row that does not exist answers so, and the table then answers `unknown_method`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | +| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. @@ -111,7 +111,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho `register`'s declarations follow A.1: at least one method; each name inside the namespace and unique; each declared notification inside the namespace, unique across the set, never a method's name and never a built-in notification's name. A declaration that breaks them is `invalid`. -`register` and `methods` are data on the wire; `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. +`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. `caller` is `{connectionId}`: the connection the call arrived on, absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call from another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. @@ -191,9 +191,9 @@ Flow tests on the owner: | --- | --- | | Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the process's loader is `rutis-loader`'s own business state; the table has no dim-owned face for it. | | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | -| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{status, copies: [{instance, status}]}`, each copy naming its instance and its state. No business meaning. | +| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:222-262`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-253`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes @@ -283,8 +283,9 @@ impl Caller { /// The contract's `connectionId`. pub fn id(&self) -> &str { /* ... */ } /// The call id a notification addresses, minted for a call from another - /// language; `None` for a native provider's call, which needs none. - pub fn call_id(&self) -> Option<&str> { /* ... */ } + /// language; `None` for a native provider's call, which needs none. The + /// module's own binding: a part never reads it. + pub(crate) fn call_id(&self) -> Option<&str> { /* ... */ } /// Sends a connection-bound notification (A.2): `undeclared` for a name /// this generation did not declare, `gone` once it unloaded or the /// connection closed, `too_large` over the frame limit. @@ -409,7 +410,8 @@ pub type Handler = std::sync::Arc< >; /// The handler's reply: its value, or its own failure as data. The bridge -/// writes a value as `{kind: "value", value}` and a failure as `{code, message}`. +/// writes a value as `{kind: "value", value}` and a failure as +/// `{code, message, ...owner fields}`. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum MethodReply { @@ -469,7 +471,7 @@ pub enum MethodError { Duplicate { message: String }, #[error("{message}")] Invalid { message: String }, - #[error("no namespace holds {method}")] + #[error("no namespace answers {method}")] UnknownMethod { method: String }, #[error("the registering row is reloading")] Reloading, diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 39a99c7df9..289cb89b33 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -337,7 +337,7 @@ Client A Rpc call admission provider han 送达方式与进度不同: - **可靠。** 提供方发送通知时只编码一次。调用的回复尚未写出时发出的通知经连接的暂存额度受理:其上限与回复与通知额度相同(1024 帧、32 MiB)但彼此独立,因此暂存的通知不会占用回复所需的空间。一次调用暂存的通知超过暂存额度时,该客户端像慢消费者一样被断开,之后的 `notify` 返回 `gone`。回复只经回复与通知额度受理。回复写出后,暂存的通知按序连同它们已占用的额度进入发送队列,并在各自写出后释放;因此连接的排队帧由两个额度共同界定,至多 2048 帧、64 MiB。超过帧上限的通知返回 `too_large`:不写任何内容,连接保持。 -- **回复之后。** 通知写在它 `callId` 所指调用的回复之后,该 `callId` 即报告该工作的 `MethodCall` 的 `Caller` 携带的 id。调用仍进行时发出的通知按序暂存,紧接回复之后写出,因此客户端不会先看到回复尚未告知的对象的通知(例如回复才返回的 id)。该回复写出后,或该 id 不在途时,通知直接进入发送队列;同一连接上另一个未完成的调用既不会暂存它,也不会改变它的顺序。每条路径都会写出回复,包括被中断的调用和连接已消失的调用。 +- **回复之后。** 通知写在它 `callId` 所指调用的回复之后,该 `callId` 即另一种语言注册所提供的调用被铸出的 id,由 `origin.caller.callId` 携带。原生处理函数没有这个 id:它的 `Caller` 把通知暂存到该调用的回复写出为止。调用仍进行时发出的通知按序暂存,紧接回复之后写出,因此客户端不会先看到回复尚未告知的对象的通知(例如回复才返回的 id)。该回复写出后,或该 id 不在途时,通知直接进入发送队列;同一连接上另一个未完成的调用既不会暂存它,也不会改变它的顺序。每条路径都会写出回复,包括被中断的调用和连接已消失的调用。 - **生命周期。** 连接关闭,或受理该调用的 Rpc 代际卸载后,`closed` 完成,之后的 `notify` 返回 `gone`。提供方代际卸载后发出的通知在两种绑定中都返回 `gone`:原生调用方持有该代际的停止信号,外来索引在同一次卸载时删除该实例的条目。调用方断开不取消任何调用。未从某连接收到过调用的行,其 `notify` 与 `closed` 对该连接返回 `gone`。服务按行实例与连接保存一个条目,内含该连接按 `callId` 记录的未完成调用;连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除条目,调用在回复写出后从条目中移除。 - **拒绝顺序。** 代际已装载时,两种绑定都先判定 `undeclared`,再看连接状态:连接已关闭也不会掩盖该代际未声明的名称。已卸载的代际对任何名称都返回 `gone`,无论是否声明过。 From b29e68bc2657e28aa106ca8a2a3bc7bca396d401 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 03:53:55 +0800 Subject: [PATCH 12/41] docs(sessionmethods): answer the tenth pre-review Every reply and envelope summary carries the handler's owner fields, and a missing copy in this Session is `reloading` in the flow as in the error table. The change note scopes itself to request and reply shapes for a part of another language, the loader row read states `found`, and the architecture page counts the per-call tasks the table tracks. --- .../rust-agent/plugins/SessionMethods.md | 2 +- docs/design/contracts/session-boundary.md | 10 +++++----- docs/design/plugins/SessionMethods.md | 17 +++++++++-------- docs/zh/design/contracts/session-boundary.md | 10 +++++----- 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 2cbbbee56a..d1c2d4f41b 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -25,7 +25,7 @@ contract ([SessionMethods §4 rule 8](../../../design/plugins/SessionMethods.md# ## Events and lifetime -No Timeline events, worker tasks or I/O. A part depends on `sessionMethods` and +No Timeline events or I/O. The table tracks the calls each registration accepted, so that registration's unload can interrupt them and wait. A part depends on `sessionMethods` and calls `register(ctx, namespace, declarations, call)` from its own `apply`, with the part's own function as `call`; the registration is withdrawn when that part unloads, and a namespace registered already fails diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index de3506f2b4..d3891ec6e0 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its registration takes serializable data, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on the service of its scope and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc reads the two method tables on each call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its registration takes serializable data, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's table and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | @@ -202,7 +202,7 @@ The implemented foreign Session subset is [C4](../session-typescript.md); genera ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; a handler answers its own `{code, message}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError}}`. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. ### A.1 Method contributions @@ -213,7 +213,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own | Method | Mode | Request | Reply | | --- | --- | --- | --- | | `register` (the table's) | async | `namespace`, `MethodDecl[]`, `call` | Nothing once registered; an error when refused | -| `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply` data: the handler's value, or its own `{code, message}` error | +| `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply` data: the handler's value, or its own `{code, message, ...owner fields}` error | ```text // MethodDecl @@ -226,7 +226,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is accepted and ignored until reply handoff exists; reply handoff, `origin.entry` and `origin.peer` are not implemented. +Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff, `origin.entry` and `origin.peer` are not implemented. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 2dc4b75c96..2317fe35b7 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -113,9 +113,9 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is `{connectionId}`: the connection the call arrived on, absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call from another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is `{connectionId}`: the connection the call arrived on, absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. -A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message, ...owner fields}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. ### Errors @@ -136,7 +136,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session, and no copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -200,11 +200,11 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -The client protocol and user-visible behavior stay as they are: `register` keeps its wire form `register(namespace, declarations, call)`, every client error keeps its application code, and a native handler already receives the `Caller`. Two changes touch a part of another language only: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's `{code, message, ...data}` becomes the client's `appError`, message and owner fields unchanged. An error a handler rethrows from a nested call keeps the code Rpc gives it, as today. +No client-visible method, reply or error kind changes, and every client error keeps its application code. A native handler already receives the `Caller`. Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; and its handler's `{code, message, ...data}` fields reach the client unchanged as `appError`, message and owner fields, where today the binding's type name stood in for the code. An error a handler rethrows from a nested call keeps the code Rpc gives it, as today. ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `NotifyError` is A.2's too, stated below. `Callers` is the process's caller index, A.2's own wiring, and `CallSite` only references it. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `NotifyError` is A.2's too, stated below. `Callers` is the process's caller index, A.2's own private wiring at its Rust type key, and `CallSite` only references it. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. @@ -282,8 +282,9 @@ pub struct Caller(/* the connection, its declared names and the generation */); impl Caller { /// The contract's `connectionId`. pub fn id(&self) -> &str { /* ... */ } - /// The call id a notification addresses, minted for a call from another - /// language; `None` for a native provider's call, which needs none. The + /// The call id a notification addresses, minted for a call served by a + /// registration of another language; `None` for a native provider's call, + /// which needs none. The /// module's own binding: a part never reads it. pub(crate) fn call_id(&self) -> Option<&str> { /* ... */ } /// Sends a connection-bound notification (A.2): `undeclared` for a name @@ -540,4 +541,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant and never carried in the table's error data; the handler's `code` becomes it on the envelope. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant and never carried in the table's error data; the handler's `code` becomes it on the envelope. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 289cb89b33..9d8d2eae6d 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ 状态:草案。总体设计:[总览 §3 集成](../overview.md#3-基于现有机制的集成)、[附录 B Rpc 与 ToolRegistry](../overview.md#附录-b-现有插件的补充);规则:[ADR 002](../../adr/002-plugin-scope.md) D2、D3、D5。阶段:P0。语言:语言中立合同;Rust 绑定见[附录 F](#附录-f-rust-绑定)。[C4 绑定](../../../design/session-typescript.md) 已实现非 Rust Session 工具和方法子集;原生广播仍待定。 -本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其注册接收可序列化数据,Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务,并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时读取这两张方法表,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 +本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其注册接收可序列化数据,Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的方法表,并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 | 服务 | 作用域 | 注册什么 | 注册方 | 读取方 | | --- | --- | --- | --- | --- | @@ -202,7 +202,7 @@ sequenceDiagram ## 附录 A. 接口细节 -结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约;处理函数以自己的 `{code, message}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError}}`。 +结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约;处理函数以自己的 `{code, message, ...所有者字段}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError, ...所有者字段}}`。 ### A.1 方法贡献 @@ -213,7 +213,7 @@ sequenceDiagram | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | | `register`(方法表的) | async | `namespace`、`MethodDecl[]`、`call` | 注册完成时无返回值;被拒绝时返回错误 | -| `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply` 数据:处理函数的值,或它自己的 `{code, message}` 错误 | +| `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply` 数据:处理函数的值,或它自己的 `{code, message, ...所有者字段}` 错误 | ```text // MethodDecl @@ -226,7 +226,7 @@ sequenceDiagram // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 在回复交接落地前接受并忽略;回复交接、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接、`origin.entry` 与 `origin.peer` 未实现。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 @@ -240,7 +240,7 @@ sequenceDiagram | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | | `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | From e1f61b7ce2be9419e6745a2fb9b9b80e2866cde4 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 04:06:28 +0800 Subject: [PATCH 13/41] docs(sessionmethods): answer the eleventh pre-review The change note separates what stays (methods, error kinds, application codes, rethrow) from what moves (the nested caller and a handler's owner fields). A declaration's `reply` field is accepted and ignored in both bindings, and the retired `RpcError`/`reply` claims and stale cross-references are corrected. --- docs/design/contracts/session-boundary.md | 8 ++++---- docs/design/plugins/SessionMethods.md | 16 +++++++++------- docs/zh/design/contracts/session-boundary.md | 8 ++++---- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index d3891ec6e0..edde696197 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -525,7 +525,7 @@ carry the native event whole, and the frozen fixtures stay unchanged. | Session reloading, or a withdrawn namespace whose registering row (or its copy in the Session) is not running and has not failed (not started yet, Pending, Loading, or between generations), or a withdrawn Session namespace whose copy is Active or absent | `-32000`, `service_reloading` (retryable) | | A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped | `-32000`, `service_unavailable` (not retryable) | | `report` call interrupted | `-32000`, `operation_interrupted` | -| Handler error | the handler's own JSON-RPC code when it carries one (a native handler that returns an `RpcError`), otherwise the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | +| Handler error | the handler's own JSON-RPC code when it carries one (`MethodCallbackError.wire`), otherwise the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | Native method errors may include owner-defined JSON fields beside `data.appError`. The method owner defines and supplies their safe public shape; the method table @@ -559,12 +559,12 @@ The neutral services map to the native owners below. Tools register with ToolReg | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`, a process service holding a `MethodTable`, provided by App Server's `ManagementMethodsPlugin` row | A process part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Rpc depends on the table and reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382); target in the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) | +| `managementMethods` | `ManagementMethods`, a process service holding a `MethodTable`, provided by App Server's `ManagementMethodsPlugin` row | A process part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Rpc depends on the table and reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382) | | `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#own-contract) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). @@ -576,6 +576,6 @@ A refused registration fails the registering part: the namespace and its declara `Callers` is private transport wiring shared by the CallChannel and Rpc rows at its Rust type key; it has no service catalog name. The public operation surface remains `callChannel`. `Callers` is the process's only caller index: per row instance it holds the notification names its generation declared, kept after a connection of that instance closes so `Undeclared` is decided before `Gone`, and per row instance and connection the connection's direct writer and the row's unfinished calls by `callId`. The table's admission mints a foreign call's `callId` where the call's sink, the instance and the provider's declarations meet, and records the call; `Connection::answer` removes it after the reply is written. The entries of a connection are removed when it closes, when the admitting Rpc load unloads and when the row's generation unloads; the declared names go with the instance's generation. A native provider keeps its own `Caller` and records nothing. App Server provides A.2 `callChannel` for other languages as the process service `callChannel` (`ForeignCallChannel`, at `host_key("callChannel")`, from the `CallChannel` row that has no dependencies): its `notify` and `closed` read the calling row's instance with `rutis_bridge::session::caller_row()` and end in the same call's sink the Rust binding uses, so both bindings share one delivery path. -Another language registers through the owning table's dispatch: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), the process table's is its own contract ([#2021](https://github.com/arcships/dim/issues/2021)). Each decodes the declarations once and calls the same `register` with the caller's function; `ForeignMethods` leaves. Not implemented in either binding: final-reply handoff, `origin.entry`, `origin.peer` and the `reply` declaration field. +Another language registers through the owning table's dispatch: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), the process table's is its own contract ([#2021](https://github.com/arcships/dim/issues/2021)). Each decodes the declarations once and calls the same `register` with the caller's function; `ForeignMethods` leaves. Not implemented in either binding: final-reply handoff, `origin.entry` and `origin.peer`. A declaration's `reply` field is accepted and ignored. `ToolContribution` and `ToolHandler` are the native types in `dim-agent-capabilities/src/tool_registry.rs`. `ToolRegistry::register(ctx, ToolContribution)` registers on behalf of the part that owns `ctx`, until that part unloads; it refuses a name outside `[A-Za-z0-9_-]{1,64}`, a host tool's name and a name registered already. Other languages reach `toolRegistry` through ToolRegistry's dispatcher: `register(declaration, execute, options?)` decodes the declaration as `ToolDefinition` once, requires a nonempty `risk`, and registers, on behalf of the calling row (the bridge's `caller_row`), a `ToolHandler` that calls `execute` back through the bridge. `options.concurrency` is `'concurrent'` or absent; it is not part of the declaration, because the class is an execution property of the bound handler, so the persisted `ToolDefinition` keeps its shape. Absent means the tool's calls run alone, in call order. That handler holds the calling row's generation token: once the row starts unloading, a call through a retained handler is not made, and a call in flight ends with an error warning that it may already have taken effect, without rebinding to a replacement generation; the foreign owner still settles its JavaScript work. Each execution derives a child cancellation token so completing one call cannot cancel other tools in the same batch. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 2317fe35b7..6db445e150 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -24,7 +24,7 @@ Callers keep: | --- | --- | --- | | A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the host's refusal are the owner's | `register` | | Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | -| `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | +| `session.methods` lists what a Session serves | No: the declarations and the namespace that owns each are the owner's | `methods` | | The caller learns why a registration was refused | Yes: `register` answers `duplicate` or `invalid`; a separate check would race the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | @@ -127,7 +127,8 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | -| `closed` | all | `session_closed` (Session table) | The table is closing. Call the replacement generation: the next Session for a Session table, the next process for the process table | +| `closed` | `register` | `session_closed` (Session table) | The table is closing; register again in the replacement generation: the next Session for a Session table, the next process for the process table | +| `closed` | `call`, `methods` | `session_closed` (Session table) | The table is closing; call the replacement generation: the next Session for a Session table, the next process for the process table | `invalid` and `duplicate` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. @@ -141,7 +142,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour and [Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding) the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour and the binding below the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -200,7 +201,7 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No client-visible method, reply or error kind changes, and every client error keeps its application code. A native handler already receives the `Caller`. Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; and its handler's `{code, message, ...data}` fields reach the client unchanged as `appError`, message and owner fields, where today the binding's type name stood in for the code. An error a handler rethrows from a nested call keeps the code Rpc gives it, as today. +No client-visible method, error kind or application code changes: a handler's `code` is the client's `appError` today and stays so, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; and the owner fields a handler sends beside its `code` and `message` now reach the client, where today the reply's `{code, message}` shape drops them. ## Binding appendix @@ -212,8 +213,9 @@ use dim_agent_runtime::AgentError; use rutis::host::{BoxFuture, CallError}; use tokio_util::sync::CancellationToken; -/// One declared method of a namespace; another language receives -/// `{name, mutating}`. +/// One declared method of a namespace. A declaration from another language +/// carries `name`, `mutating`, `interruption`, `progress` and its +/// `notifications`; the listing another language reads is `{name, mutating}`. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct MethodDecl { @@ -541,4 +543,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; the client's `appError` is chosen by Rpc from the variant and never carried in the table's error data; the handler's `code` becomes it on the envelope. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; Rpc chooses the client's `appError` and JSON-RPC code from the variant. A handler's failure carries its own `code`, which becomes the client's `appError`. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 9d8d2eae6d..0d8fa00ee4 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -494,7 +494,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | Session 正在重载,或已撤回命名空间的注册行(或其在该 Session 中的副本)未运行且未失败(尚未启动、Pending、Loading,或新旧两代之间),或已撤回 Session 命名空间的副本处于 Active 或不存在 | `-32000`,`service_reloading`(可重试) | | 已撤回命名空间的注册行,或该行在该 Session 中的副本,处于 Failed、Unresolved、Disposed 或 Stopped | `-32000`,`service_unavailable`(不可重试) | | `report` 调用被中断 | `-32000`,`operation_interrupted` | -| 处理函数错误 | 处理函数自带的 JSON-RPC 码(返回 `RpcError` 的原生处理函数),否则为 Rpc 为服务错误选择的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` 与其所有者字段 | +| 处理函数错误 | 处理函数自带的 JSON-RPC 码(`MethodCallbackError.wire`),否则为 Rpc 为服务错误选择的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` 与其所有者字段 | ## 附录 D. 验收 @@ -522,12 +522,12 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | -| `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382);目标见进程表的契约([#2021](https://github.com/arcships/dim/issues/2021)) | +| `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | | `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 @@ -539,6 +539,6 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 `Callers` 是 CallChannel 和 Rpc 行通过 Rust 类型键共享的私有传输装配,不登记服务目录名称;公开操作面仍是 `callChannel`。`Callers` 是进程内唯一的调用方索引:按行实例保存该代际声明的通知名称,该实例的连接关闭后仍保留,因此先判定 `Undeclared` 再看连接状态;并按行实例与连接保存该连接的直接写入端与该行按 `callId` 记录的未完成调用。方法表的受理在调用的 sink、实例与提供方声明都可用的位置生成其他语言调用的 `callId` 并记录该调用;`Connection::answer` 在回复写出后移除它。连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除该连接的条目;声明的名称随该实例的代际一起删除。原生提供方保留自己的 `Caller`,不记录任何内容。App Server 以进程服务 `callChannel`(`ForeignCallChannel`,位于 `host_key("callChannel")`,由无依赖的 `CallChannel` 行提供)向其他语言提供 A.2 的 `callChannel`:其 `notify` 与 `closed` 用 `rutis_bridge::session::caller_row()` 读取调用行的实例,并最终落在 Rust 绑定所用同一次调用的 sink 上,两种绑定共用一条送达路径。 -外来注册经各自表的分发器:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。两者都一次性解码声明,并以调用方的函数调用同一个 `register`;`ForeignMethods` 离开。两种绑定都未实现:最终回复交接、`origin.entry`、`origin.peer` 与 `reply` 声明字段。 +外来注册经各自表的分发器:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。两者都一次性解码声明,并以调用方的函数调用同一个 `register`;`ForeignMethods` 离开。两种绑定都未实现:最终回复交接、`origin.entry` 与 `origin.peer`。声明的 `reply` 字段接受并忽略。 `ToolContribution` 与 `ToolHandler` 是 `dim-agent-capabilities/src/tool_registry.rs` 中的原生类型。`ToolRegistry::register(ctx, ToolContribution)` 代表拥有 `ctx` 的部件注册,直到该部件卸载;它拒绝不满足 `[A-Za-z0-9_-]{1,64}` 的名称、宿主工具名和已被注册的名称。其他语言经 ToolRegistry 的分发器访问 `toolRegistry`:`register(declaration, execute, options?)` 把声明解码为 `ToolDefinition` 一次,要求 `risk` 非空,并代表调用方行(桥的 `caller_row`)注册一个经桥回调 `execute` 的 `ToolHandler`。`options.concurrency` 取 `'concurrent'` 或缺省;它不属于声明,因为这个类别是绑定后处理器的执行属性,所以落盘的 `ToolDefinition` 形状不变。缺省表示该工具的调用单独执行,按调用顺序。该处理器持有调用方行的代次令牌:行开始卸载后,经保留的处理器发起的调用不会发出,在途调用以错误结束,错误提示它可能已经生效,不会改绑到新的代次;外部所有者仍负责结算其 JavaScript 工作。每次执行派生自己的子取消令牌,单个工具正常完成不会取消同批其他工具。 From 55fd99973d36237d4df47509200b651c6f4a4df4 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 04:20:54 +0800 Subject: [PATCH 14/41] docs(sessionmethods): answer the twelfth pre-review A foreign reply carrying owner fields is rejected today, not silently trimmed, and a native handler's fields now reach the client. `closed` answers a registration without a client code, `interrupted` names the `report` condition, and the rule check counts the site and the `Caller` as the two stated objects. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 19 ++++++++++--------- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index edde696197..c2983e206b 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its registration takes serializable data, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's table and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its registration takes serializable data, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 6db445e150..b9e597d1ad 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -126,11 +126,11 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | -| `interrupted` | `call` | `operation_interrupted` | The provider's generation or the admitting Rpc load unloaded while the call ran; the call may have committed, so read the current state before retrying | -| `closed` | `register` | `session_closed` (Session table) | The table is closing; register again in the replacement generation: the next Session for a Session table, the next process for the process table | +| `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | +| `closed` | `register` | — | The table is closing; register again in the replacement generation: the next Session for a Session table, the next process for the process table | | `closed` | `call`, `methods` | `session_closed` (Session table) | The table is closing; call the replacement generation: the next Session for a Session table, the next process for the process table | -`invalid` and `duplicate` answer a registration only, so no client sees them. `closed` is one kind for both tables: the Session table's `closed` reaches a client as `session_closed`, and the process table has no client code of its own. +`invalid`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. ### Flows @@ -142,7 +142,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour and the binding below the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -172,7 +172,7 @@ Flow tests on the owner: | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | | §4 rule 8 | The only infrastructure request is `loaderRows`, a dim-owned process face for one loader row, raised below with its five fields; nothing else changes. | | §4 rule 9 | No Timeline fact. | -| §7 values, ids and callbacks | The caller is data on the wire and A.2's `Caller` for a native handler — the one exception, stated with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | +| §7 values, ids and callbacks | The caller is data on the wire, and the stated site and `Caller` are the two objects this contract hands out, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | @@ -201,7 +201,7 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No client-visible method, error kind or application code changes: a handler's `code` is the client's `appError` today and stays so, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; and the owner fields a handler sends beside its `code` and `message` now reach the client, where today the reply's `{code, message}` shape drops them. +No client-visible method, error kind or application code changes: a handler's `code` is the client's `appError` today and stays so, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; and the owner fields a native handler attaches to its failure now reach the client, where today the `{code, message}` decode rejects a foreign reply that carries them. ## Binding appendix @@ -214,8 +214,9 @@ use rutis::host::{BoxFuture, CallError}; use tokio_util::sync::CancellationToken; /// One declared method of a namespace. A declaration from another language -/// carries `name`, `mutating`, `interruption`, `progress` and its -/// `notifications`; the listing another language reads is `{name, mutating}`. +/// carries `name`, `mutating`, `interruption`, `progress`, its `notifications` +/// and an ignored `reply`; the listing another language reads is +/// `{name, mutating}`. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct MethodDecl { @@ -298,7 +299,7 @@ impl Caller { } /// A connection as the `methods` module uses it: its id, a write to it and its -///close signal. Rpc implements it; `Caller` and `CallSite` hold it through an +/// close signal. Rpc implements it; `Caller` and `CallSite` hold it through an /// `Arc` that keeps no strong reference to the connection. pub trait CallerConnection: Send + Sync + 'static { fn id(&self) -> &str; diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 0d8fa00ee4..8ecd92048c 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ 状态:草案。总体设计:[总览 §3 集成](../overview.md#3-基于现有机制的集成)、[附录 B Rpc 与 ToolRegistry](../overview.md#附录-b-现有插件的补充);规则:[ADR 002](../../adr/002-plugin-scope.md) D2、D3、D5。阶段:P0。语言:语言中立合同;Rust 绑定见[附录 F](#附录-f-rust-绑定)。[C4 绑定](../../../design/session-typescript.md) 已实现非 Rust Session 工具和方法子集;原生广播仍待定。 -本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其注册接收可序列化数据,Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的方法表,并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 +本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其注册接收可序列化数据,Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务(方法表或注册表),并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 | 服务 | 作用域 | 注册什么 | 注册方 | 读取方 | | --- | --- | --- | --- | --- | From 2dedbafaae304c915fd5cbe440d579e479e86a8d Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 04:35:25 +0800 Subject: [PATCH 15/41] docs(sessionmethods): answer the thirteenth pre-review The change note attributes the owner-field change to a handler of another language, keeps a native handler's existing fields, lists the missing application code and the declared `reply`. An absent or disabled registering row is `unknown_method` in the absence summaries too, and the introduction says a registration takes data plus the caller's function. --- docs/design/contracts/session-boundary.md | 6 +++--- docs/design/plugins/SessionMethods.md | 18 +++++++++--------- docs/zh/design/contracts/session-boundary.md | 6 +++--- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index c2983e206b..6a42f4ce0b 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its registration takes serializable data, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; a registration takes the namespace and its declarations as data and the caller's function as a callback, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | @@ -54,7 +54,7 @@ flowchart LR | Service | Absent | | --- | --- | -| `sessionMethods` | `unknown_method` when no namespace of the Session ever held the name; when the namespace that holds it is withdrawn, `service_reloading` while the part that registered it starts or reloads and `service_unavailable` once it failed or cannot run (A.1) | +| `sessionMethods` | `unknown_method` when no namespace of the Session ever held the name, or when the row that registered its withdrawn namespace is disabled or absent; when the namespace that holds it is withdrawn, `service_reloading` while the part that registered it starts or reloads or has no copy in the Session, and `service_unavailable` once it failed or cannot run (A.1) | | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | @@ -89,7 +89,7 @@ sequenceDiagram Rpc-->>CL: result ``` -The name belongs to the longest namespace registered in that Session that holds it (A.1). If no namespace of the Session ever held the name, for example because its plugin is not enabled for the Session, the result is `unknown_method`; if the namespace that holds it is withdrawn, the result is `service_reloading` while the part that registered it starts or reloads, and `service_unavailable` once that part failed or cannot run (A.1). Session methods carry no level: every connection that is served Session methods is served all of them, including `shell.*`. +The name belongs to the longest namespace registered in that Session that holds it (A.1). If no namespace of the Session ever held the name, for example because its plugin is not enabled for the Session, the result is `unknown_method`; if the namespace that holds it is withdrawn, the result is `service_reloading` while the part that registered it starts or reloads or has no copy in the Session, and `service_unavailable` once that part failed or cannot run; a registering row that is disabled or absent is `unknown_method` (A.1). Session methods carry no level: every connection that is served Session methods is served all of them, including `shell.*`. ### 3.2 Management method diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index b9e597d1ad..376cc368fd 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -10,7 +10,7 @@ SessionMethods owns: - **Registrations.** One namespace per registration, its declarations and its call callback; a row may register several namespaces, and a registration ends when its row unloads. - **Admission.** One call: the name's owner, the interruption kind its declaration names, the caller identity, and the settlement of the calls a registration accepted. -- **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers `reloading` or `unavailable` instead of falling through to a parent namespace. +- **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers `reloading` or `unavailable` from that row instead of falling through to a parent namespace; a row that is disabled or absent is `unknown_method`. - **Reserved names.** The host's own roots, built-ins and their notification names are refused at registration; a management namespace does not stop a Session namespace from registering (A.1 namespace collisions). The host supplies the check as a process face. - **The method list.** The declarations of the namespaces registered now, each under its owning namespace. @@ -75,8 +75,8 @@ Ok(match reply { `session.methods` composes the value with the process table's held namespaces: ```rust -// A.1's longest-namespace rule: a declaration whose name equals or lies inside -// a held management namespace is routed to management, never listed for the Session. +// A.1's routing precedence: a declaration whose name equals or lies inside a +// held management namespace is routed to management, never listed for the Session. let Ok(held) = management.held_namespaces() else { return Err(RpcError::service("service_unavailable", "The process is closing")); }; @@ -99,7 +99,7 @@ let listed = declarations.into_iter().filter(|decl| { | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | | `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's longest-namespace rule. +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's routing precedence. ### Operations @@ -113,7 +113,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is `{connectionId}`: the connection the call arrived on, absent for an in-process call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message, ...owner fields}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. @@ -201,7 +201,7 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No client-visible method, error kind or application code changes: a handler's `code` is the client's `appError` today and stays so, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; and the owner fields a native handler attaches to its failure now reach the client, where today the `{code, message}` decode rejects a foreign reply that carries them. +No client-visible method, error kind or application code changes: a handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. A native handler's failure that carried no application code now carries `appError: "failed"`. Three request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them; and a declaration may carry a `reply` field, accepted and ignored. ## Binding appendix @@ -214,9 +214,9 @@ use rutis::host::{BoxFuture, CallError}; use tokio_util::sync::CancellationToken; /// One declared method of a namespace. A declaration from another language -/// carries `name`, `mutating`, `interruption`, `progress`, its `notifications` -/// and an ignored `reply`; the listing another language reads is -/// `{name, mutating}`. +/// carries `name`, `mutating`, `interruption` and `progress`, may carry its +/// `notifications`, and may carry an ignored `reply`; the listing another +/// language reads is `{name, mutating}`. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct MethodDecl { diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 8ecd92048c..756b4cd840 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ 状态:草案。总体设计:[总览 §3 集成](../overview.md#3-基于现有机制的集成)、[附录 B Rpc 与 ToolRegistry](../overview.md#附录-b-现有插件的补充);规则:[ADR 002](../../adr/002-plugin-scope.md) D2、D3、D5。阶段:P0。语言:语言中立合同;Rust 绑定见[附录 F](#附录-f-rust-绑定)。[C4 绑定](../../../design/session-typescript.md) 已实现非 Rust Session 工具和方法子集;原生广播仍待定。 -本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其注册接收可序列化数据,Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务(方法表或注册表),并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 +本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;注册接收命名空间及其声明的数据,以及调用方的函数回调;Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务(方法表或注册表),并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 | 服务 | 作用域 | 注册什么 | 注册方 | 读取方 | | --- | --- | --- | --- | --- | @@ -54,7 +54,7 @@ flowchart LR | 服务 | 缺失时 | | --- | --- | -| `sessionMethods` | 该 Session 从没有命名空间持有过此名称时返回 `unknown_method`;持有它的命名空间已撤回时,注册它的部件正在启动或重载则返回 `service_reloading`,已失败或无法运行则返回 `service_unavailable`(A.1) | +| `sessionMethods` | 该 Session 从没有命名空间持有过此名称时返回 `unknown_method`;注册其已撤回命名空间的行已禁用或不存在时同样返回 `unknown_method`;持有它的命名空间已撤回时,注册它的部件正在启动或重载、或其在本 Session 中没有副本则返回 `service_reloading`,已失败或无法运行则返回 `service_unavailable`(A.1) | | `managementMethods` | 从没有命名空间持有过该名称,或注册它的行已禁用或不存在时返回 `unknown_method`;其他情况下,已撤回的命名空间按该行的状态作答(§3.2) | | 工具注册 | Session 挂载列表列出但没有部件注册的工具不声明,并在诊断中报告;有部件注册后从下一个请求起声明(A.5) | @@ -89,7 +89,7 @@ sequenceDiagram Rpc-->>CL: 结果 ``` -名称属于该 Session 中持有它的最长已注册命名空间(A.1)。如果该 Session 从没有命名空间持有过此名称(例如其插件未对该 Session 启用),结果为 `unknown_method`;如果持有它的命名空间已撤回,注册它的部件正在启动或重载时结果为 `service_reloading`,该部件已失败或无法运行时结果为 `service_unavailable`(A.1)。Session 方法没有级别:获得 Session 方法的连接获得全部 Session 方法,包括 `shell.*`。 +名称属于该 Session 中持有它的最长已注册命名空间(A.1)。如果该 Session 从没有命名空间持有过此名称(例如其插件未对该 Session 启用),结果为 `unknown_method`;如果持有它的命名空间已撤回,注册它的部件正在启动或重载、或其在本 Session 中没有副本时结果为 `service_reloading`,该部件已失败或无法运行时结果为 `service_unavailable`;注册它的行已禁用或不存在时结果为 `unknown_method`(A.1)。Session 方法没有级别:获得 Session 方法的连接获得全部 Session 方法,包括 `shell.*`。 ### 3.2 管理方法 From 247755407cd404a15b7e525d24a0d17998dd03ad Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 04:52:28 +0800 Subject: [PATCH 16/41] docs(sessionmethods): answer the fourteenth pre-review The change note lists the four client-visible failure changes: an absent registering row is `unknown_method`, a code-less or binding failure carries `appError: "failed"`, the nested caller and a handler's owner fields, and the declared `reply`. The declaration rules keep the host's built-in notification check with the host, `call`'s parameter is `site`, and `MethodTable` has one stated owner. --- docs/design/contracts/session-boundary.md | 6 +++--- docs/design/plugins/SessionMethods.md | 16 ++++++++++------ docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 6a42f4ce0b..c40ac78958 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is that owner's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is the Session table's private storage, not a shared type; the process table's own storage is its contract's business. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -535,7 +535,7 @@ existing wire shape. ## Appendix D. Acceptance -1. A Session-scoped method dispatches through the Session it names. A name no namespace of that Session ever held returns `unknown_method`; a withdrawn namespace returns `service_reloading` while the part that registered it starts or reloads and `service_unavailable` once that part is Failed or Unresolved; Rpc never names the provider. A Session namespace that overlaps a built-in or lies in a reserved root is refused when it registers, and one inside a management namespace never receives the names that namespace holds. +1. A Session-scoped method dispatches through the Session it names. A name no namespace of that Session ever held returns `unknown_method`, and so does one whose registering row is disabled or absent; a withdrawn namespace returns `service_reloading` while the part that registered it starts or reloads and `service_unavailable` once that part is Failed or Unresolved; Rpc never names the provider. A Session namespace that overlaps a built-in or lies in a reserved root is refused when it registers, and one inside a management namespace never receives the names that namespace holds. 2. A management method is reachable on the local entry, returns `unknown_method` on RemoteGateway, and is reachable over a link only when exported. A `shell.*` Session method is reachable on RemoteGateway like every Session method. 3. A recorded transcript of every migrated management method matches the pre-migration transcript, and `hello.features` is unchanged for v3 local profiles. 4. On a RemoteGateway test entry, `session.permission.update` and `session.exec.stop` succeed. @@ -564,7 +564,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. `MethodTable` is that table's private storage; the Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. `MethodTable` is the Session table's private storage; the Session table no longer derefs to it, and the process table's storage is its contract's business. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 376cc368fd..f8057ff8f6 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -2,7 +2,7 @@ Scope: session. Issue: #2026. -SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The call data both method tables serve — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — has one definition, in the `methods` module of `dim-agent-capabilities`; this contract states it. ManagementMethods (#2021) is the process table; Rpc, the registering parts and `session.methods` are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). +SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The call data both method tables serve — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — has one definition, in the `methods` module of `dim-agent-capabilities`; this contract states it. ManagementMethods (#2021) is the process table; Rpc, the registering parts, WebEntry's upload entry and `session.methods` are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). ## Use and scope: responsibility split @@ -109,7 +109,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name inside the namespace and unique; each declared notification inside the namespace, unique across the set, never a method's name and never a built-in notification's name. A declaration that breaks them is `invalid`. +`register`'s declarations follow A.1: at least one method; each name inside the namespace and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration that breaks them is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. @@ -127,7 +127,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | -| `closed` | `register` | — | The table is closing; register again in the replacement generation: the next Session for a Session table, the next process for the process table | +| `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | | `closed` | `call`, `methods` | `session_closed` (Session table) | The table is closing; call the replacement generation: the next Session for a Session table, the next process for the process table | `invalid`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. @@ -201,7 +201,11 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No client-visible method, error kind or application code changes: a handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. A native handler's failure that carried no application code now carries `appError: "failed"`. Three request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them; and a declaration may carry a `reply` field, accepted and ignored. +No method changes. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Four client-visible changes, all in failures: + +- A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-252`), which retrying could not fix. A disabled row already answers `unknown_method`. +- A handler's failure without an application code, and a failed or malformed foreign reply, carry `appError: "failed"`; today the binding failure is `-32603` "Method binding failed" with no `appError` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- Three request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them; and a declaration may carry a `reply` field, accepted and ignored. ## Binding appendix @@ -522,7 +526,7 @@ impl SessionMethods { &self, method: String, params: serde_json::Value, - caller: Option, + site: Option, cancelled: CancelledFn, progress: impl Fn(serde_json::Value) + Send + Sync + 'static, ) -> Result { /* ... */ } @@ -544,4 +548,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's wire code is its snake-case name; Rpc chooses the client's `appError` and JSON-RPC code from the variant. A handler's failure carries its own `code`, which becomes the client's `appError`. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. A handler's failure carries its own `code`, which becomes the client's `appError`. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 756b4cd840..f86a4899b8 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -498,7 +498,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 ## 附录 D. 验收 -1. Session 级方法经其指定的 Session 分发。该 Session 从没有命名空间持有过的名称返回 `unknown_method`;命名空间已撤回时,注册它的部件正在启动或重载则返回 `service_reloading`,该部件处于 Failed 或 Unresolved 则返回 `service_unavailable`;Rpc 从不点名提供方。与内建方法重叠或位于保留根之内的 Session 命名空间在注册时被拒绝,位于管理命名空间之内的 Session 命名空间从收不到该管理命名空间持有的名称。 +1. Session 级方法经其指定的 Session 分发。该 Session 从没有命名空间持有过的名称返回 `unknown_method`,注册它的行已禁用或不存在的名称同样返回 `unknown_method`;命名空间已撤回时,注册它的部件正在启动、重载或在本 Session 中没有副本则返回 `service_reloading`,该部件处于 Failed 或 Unresolved 则返回 `service_unavailable`;Rpc 从不点名提供方。与内建方法重叠或位于保留根之内的 Session 命名空间在注册时被拒绝,位于管理命名空间之内的 Session 命名空间从收不到该管理命名空间持有的名称。 2. 管理方法在本地入口上可达,在 RemoteGateway 上返回 `unknown_method`,只在导出时经链接可达。`shell.*` Session 方法与所有 Session 方法一样可在 RemoteGateway 上调用。 3. 每个迁移后的管理方法的录制记录与迁移前的记录一致,且 v3 本地 profile 的 `hello.features` 不变。 4. 在 RemoteGateway 测试入口上,`session.permission.update` 与 `session.exec.stop` 成功。 From 8f610529c4dd9cd356c18e86ada60b3428ee0cca Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 05:10:02 +0800 Subject: [PATCH 17/41] docs(sessionmethods): answer the fifteenth pre-review A binding failure keeps `-32603` and gains `appError: "failed"`; the change note splits the two client-visible failures from the two foreign-part shapes. The admission diagrams label `call`, `MethodTable` is named as one owner's storage, and WebEntry's in-process ask has its requirement row. --- docs/design/contracts/session-boundary.md | 8 +++--- docs/design/plugins/SessionMethods.md | 28 ++++++++++++-------- docs/zh/design/contracts/session-boundary.md | 8 +++--- 3 files changed, 25 insertions(+), 19 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index c40ac78958..afdbccfee7 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is the Session table's private storage, not a shared type; the process table's own storage is its contract's business. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is the Session table's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -296,7 +296,7 @@ How progress of one call reaches its caller: ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., sink of A) ---->|-- handler(.., progress) -->| + | |-- call(.., sink of A) ------>|-- handler(.., progress) -->| | | | (sink only if declared) | |<-- management.progress {id: 7, method: "x.run", data} ------- progress.send -->| | | |<-- result -----------------| @@ -325,7 +325,7 @@ How a notification of one call reaches its caller: ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., caller) ->|-- handler(.., caller) -->| + | |-- call(.., site) ----->|-- handler(.., caller) -->| | | | notify(callId, ..) | | | | held: after the reply | | | |<-- result ---------------| @@ -564,7 +564,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. `MethodTable` is the Session table's private storage; the Session table no longer derefs to it, and the process table's storage is its contract's business. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index f8057ff8f6..02fa8b547b 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -28,6 +28,7 @@ Callers keep: | The caller learns why a registration was refused | Yes: `register` answers `duplicate` or `invalid`; a separate check would race the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | +| A Session part asks the table in process, as WebEntry's upload entry does | Yes: the same `call` without a site | Business | An operation or parameter exists only where the row says No. @@ -194,18 +195,19 @@ Flow tests on the owner: | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-253`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1475-1481` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No method changes. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Four client-visible changes, all in failures: +No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Two client-visible failure changes: -- A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-252`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A handler's failure without an application code, and a failed or malformed foreign reply, carry `appError: "failed"`; today the binding failure is `-32603` "Method binding failed" with no `appError` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). -- Three request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`; its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them; and a declaration may carry a `reply` field, accepted and ignored. +- A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. +- A handler's failure without an application code, and a failed or malformed foreign reply, carry `appError: "failed"`; a binding failure keeps today's `-32603` and gains the code (`crates/dim-agent-capabilities/src/methods.rs:905-918`). + +Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. A declaration may also carry a `reply` field, accepted and ignored. ## Binding appendix @@ -395,16 +397,20 @@ impl From for MethodCallbackError { return Self::from_wire(wire); } // Otherwise the application code the error carries; a remote's variant - // name without one, and `failed` for a call that crossed nothing. - let code = remote - .and_then(|error| { + // name without one. A call that crossed nothing is the binding's own + // failure: `failed`, with today's `-32603`. + let (code, wire) = match remote { + Some(error) => ( error.code().map(str::to_owned).or_else(|| match error { rutis_bridge::session::Error::Remote { name, .. } => Some(name.clone()), _ => None, }) - }) - .unwrap_or_else(|| "failed".into()); - Self { code, message: error.message().into(), wire: None, data: Default::default() } + .unwrap_or_else(|| "failed".into()), + None, + ), + None => ("failed".into(), Some(-32603)), + }; + Self { code, message: error.message().into(), wire, data: Default::default() } } } diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index f86a4899b8..28a26e6fa5 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -240,7 +240,7 @@ sequenceDiagram | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是该所有者的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是 Session 方法表的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | | `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | @@ -295,7 +295,7 @@ sequenceDiagram ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., sink of A) ---->|-- handler(.., progress) -->| + | |-- call(.., sink of A) ------>|-- handler(.., progress) -->| | | | (sink only if declared) | |<-- management.progress {id: 7, method: "x.run", data} ------- progress.send -->| | | |<-- result -----------------| @@ -324,7 +324,7 @@ reply ----------> 回复与通知额度 ----------------+ ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., caller) ->|-- handler(.., caller) -->| + | |-- call(.., site) ----->|-- handler(.., caller) -->| | | | notify(callId, ..) | | | | 暂存:等回复之后 | | | |<-- result ---------------| @@ -527,7 +527,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。`MethodTable` 是该表的私有存储;Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 From c215e0acf6e42ce685b0a7dc3450c6233c3c622a Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 05:24:31 +0800 Subject: [PATCH 18/41] docs(sessionmethods): answer the sixteenth pre-review The foreign handler failure cases are stated one by one: a rethrown error keeps its code, a thrown error without one carries its name, and a reply that never crossed is `failed` with today's `-32603`. The change note counts three. Registrations of another language point at the owning table's binding, and the `call`/`methods` `closed` step says to re-acquire the Session. --- docs/design/contracts/session-boundary.md | 10 +++++----- docs/design/plugins/SessionMethods.md | 20 +++++++++++--------- docs/zh/design/contracts/session-boundary.md | 8 ++++---- 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index afdbccfee7..fbaf66e819 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -144,7 +144,7 @@ Methods have no model-visible effect. A method that changes model context does s | `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable`, `interrupted` or `closed` ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | The declarations of the namespaces the Session registered now | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | -| `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented, Appendix F) | +| `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented; `Progress` and `Caller` are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s) | | `toolRegistry.register(ToolDeclaration, execute)` | async | Register a tool until the calling part unloads | | `execute(ToolCall, cancelled) -> ToolResult` (the registering part's function) | async | Tool execution | @@ -170,7 +170,7 @@ Proposed (P3, with RemoteGateway; not implemented): the connection's `Connection | ADR 002 D2 | No port or Management plugin; method namespaces register with the method table of their scope and tools with ToolRegistry, which owns the Session's tools. | | ADR 002 D3 | Providers depend on their own or an enclosing scope, including the method table they register with. The method tables and ToolRegistry follow registration and withdrawal and do not depend on the parts that register (A.1, A.5); Rpc depends neither on management providers (§3.2) nor on Session method providers (A.1), so their reloads stay within their namespace. | | ADR 002 D4 | A link's management export is structural host-local configuration; no business configuration is defined here. | -| ADR 002 D5 | Every service is named with scope and data-only methods, and a part of any language registers a method namespace or a tool with the same data and its own function (`call`, `execute`); Rust types appear only in Appendix F. The implemented binding is a subset of these shapes (A.1, Appendix F). | +| ADR 002 D5 | Every service is named with scope and data-only methods, and a part of any language registers a method namespace or a tool with the same data and its own function (`call`, `execute`); Rust types appear only in the owning table's binding ([SessionMethods](../plugins/SessionMethods.md#binding-appendix) for the Session table). The implemented binding is a subset of these shapes (A.1). | ## 9. Requirements raised to mechanism owners @@ -208,7 +208,7 @@ Shapes are JSON with camelCase fields; a `?` after a field name marks it optiona The call data of both tables — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; this appendix keeps the client error, interruption and routing behavior that the redesign does not change. -`sessionMethods` (Session) and `managementMethods` (process) are method tables with the same method, `register`. A part registers each namespace it serves with the table of its scope, and the table calls back the part's own `call`. Parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)) and reach the native call admission of Appendix F. +`sessionMethods` (Session) and `managementMethods` (process) are method tables with the same method, `register`. A part registers each namespace it serves with the table of its scope, and the table calls back the part's own `call`. Parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)) and reach the owning table's binding: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), and the process table's is its contract's ([#2021](https://github.com/arcships/dim/issues/2021)). | Method | Mode | Request | Reply | | --- | --- | --- | --- | @@ -226,7 +226,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff, `origin.entry` and `origin.peer` are not implemented. +Implemented today ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff, `origin.entry` and `origin.peer` are not implemented. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding; `MethodTable` is the Session table's private storage, not a shared type. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 02fa8b547b..297eb7ad3a 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -28,7 +28,7 @@ Callers keep: | The caller learns why a registration was refused | Yes: `register` answers `duplicate` or `invalid`; a separate check would race the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | -| A Session part asks the table in process, as WebEntry's upload entry does | Yes: the same `call` without a site | Business | +| A process-side caller holding a Session asks the table in process, as WebEntry's upload entry does | Yes: the same `call` without a site | Business | An operation or parameter exists only where the row says No. @@ -129,7 +129,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | | `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | -| `closed` | `call`, `methods` | `session_closed` (Session table) | The table is closing; call the replacement generation: the next Session for a Session table, the next process for the process table | +| `closed` | `call`, `methods` | `session_closed` (Session table) | The table is gone with its Session or process; re-acquire it by id (Rpc restores an unloaded Session) and call again. Do not retry against the closed one | `invalid`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. @@ -154,7 +154,7 @@ Flow tests on the owner: - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. - A native handler receives the call's `Caller` and notifies through its `CallerConnection`; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. -- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name; an error with no code and a call that crossed nothing are both `failed`. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a call that crossed nothing is `failed` with `-32603`. - `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. ## Rule check @@ -195,17 +195,18 @@ Flow tests on the owner: | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1475-1481` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. -No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Two client-visible failure changes: +No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Three client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A handler's failure without an application code, and a failed or malformed foreign reply, carry `appError: "failed"`; a binding failure keeps today's `-32603` and gains the code (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- A handler's failure without an application code, and a failed or malformed foreign reply, carry `appError: "failed"`; a reply that failed to cross keeps today's `-32603` and gains the code (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. A declaration may also carry a `reply` field, accepted and ignored. @@ -396,9 +397,10 @@ impl From for MethodCallbackError { if let Some(wire) = remote.and_then(rethrown) { return Self::from_wire(wire); } - // Otherwise the application code the error carries; a remote's variant - // name without one. A call that crossed nothing is the binding's own - // failure: `failed`, with today's `-32603`. + // Otherwise: a remote error keeps its own application code, or its + // variant name when it has none, under the service-error rule; a call + // that crossed nothing is the binding's own failure, `failed`, and keeps + // today's `-32603`. let (code, wire) = match remote { Some(error) => ( error.code().map(str::to_owned).or_else(|| match error { diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 28a26e6fa5..2752fd4e82 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -144,7 +144,7 @@ sequenceDiagram | `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable`、`interrupted` 或 `closed`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | 该 Session 现在注册的命名空间的声明 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | -| `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现,附录 F) | +| `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现;`Progress` 与 `Caller` 归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)) | | `toolRegistry.register(ToolDeclaration, execute)` | async | 注册一个工具,直到调用方部件卸载 | | `execute(ToolCall, cancelled) -> ToolResult`(注册部件自己的函数) | async | 工具执行 | @@ -170,7 +170,7 @@ sequenceDiagram | ADR 002 D2 | 不新增端口或 Management 插件;方法命名空间注册到其作用域的方法表,工具注册到拥有本 Session 工具的 ToolRegistry。 | | ADR 002 D3 | 提供方只依赖自身或外层作用域,包括它注册时用的方法表。方法表与 ToolRegistry 跟随注册与撤回,不依赖注册的部件(A.1、A.5);Rpc 既不依赖管理方法提供方(§3.2),也不依赖 Session 方法提供方(A.1),因此它们的重载只影响自己的命名空间。 | | ADR 002 D4 | 链接的管理方法导出是宿主本地的结构性配置;本文不定义业务配置。 | -| ADR 002 D5 | 每个服务都有名称、作用域和纯数据方法,任何语言的部件都用同样的数据和自己的函数(`call`、`execute`)注册方法命名空间或工具;Rust 类型只出现在附录 F。已实现的绑定是这些结构的一个子集(A.1、附录 F)。 | +| ADR 002 D5 | 每个服务都有名称、作用域和纯数据方法,任何语言的部件都用同样的数据和自己的函数(`call`、`execute`)注册方法命名空间或工具;Rust 类型只出现在各表自己的绑定里(Session 表见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix))。已实现的绑定是这些结构的一个子集(A.1)。 | ## 9. 向机制所有者提出的需求 @@ -208,7 +208,7 @@ sequenceDiagram 两张表的调用数据——`MethodCall`、`MethodReply`、处理函数自己的错误与方法表的错误种类——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约定义;本附录保留重构不改的客户端错误、中断与路由行为。 -`sessionMethods`(Session)与 `managementMethods`(进程)是方法表,具有同一个方法 `register`。部件把它提供的每个命名空间注册到其作用域的方法表,方法表回调该部件自己的 `call`。其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md)),并进入附录 F 的原生调用受理。 +`sessionMethods`(Session)与 `managementMethods`(进程)是方法表,具有同一个方法 `register`。部件把它提供的每个命名空间注册到其作用域的方法表,方法表回调该部件自己的 `call`。其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md)),并进入各表自己的绑定:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | @@ -226,7 +226,7 @@ sequenceDiagram // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接、`origin.entry` 与 `origin.peer` 未实现。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 From e873bb9a5468e73847ef96dfea4414978082540d Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 05:36:53 +0800 Subject: [PATCH 19/41] docs(sessionmethods): answer the seventeenth pre-review The Supersedes bullet splits: the paragraphs that moved here are the binding below, while the deleted types leave. The change note scopes a code-less failure to the case with no remote error and counts the declaration's `reply` as an accepted, ignored third change, and `cancelled` names an in-process caller's own load. --- docs/design/contracts/session-boundary.md | 6 +++--- docs/design/plugins/SessionMethods.md | 10 +++++----- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index fbaf66e819..f2d0364c4c 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; a registration takes the namespace and its declarations as data and the caller's function as a callback, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; a registration takes the namespace and its declarations as data and the caller's function as a callback, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F and the owners' contracts, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -535,7 +535,7 @@ existing wire shape. ## Appendix D. Acceptance -1. A Session-scoped method dispatches through the Session it names. A name no namespace of that Session ever held returns `unknown_method`, and so does one whose registering row is disabled or absent; a withdrawn namespace returns `service_reloading` while the part that registered it starts or reloads and `service_unavailable` once that part is Failed or Unresolved; Rpc never names the provider. A Session namespace that overlaps a built-in or lies in a reserved root is refused when it registers, and one inside a management namespace never receives the names that namespace holds. +1. A Session-scoped method dispatches through the Session it names. A name no namespace of that Session ever held returns `unknown_method`, and so does one whose registering row is disabled or absent; a withdrawn namespace returns `service_reloading` while the part that registered it starts or reloads or has no copy in the Session, and `service_unavailable` once that part is Failed or Unresolved; Rpc never names the provider. A Session namespace that overlaps a built-in or lies in a reserved root is refused when it registers, and one inside a management namespace never receives the names that namespace holds. 2. A management method is reachable on the local entry, returns `unknown_method` on RemoteGateway, and is reachable over a link only when exported. A `shell.*` Session method is reachable on RemoteGateway like every Session method. 3. A recorded transcript of every migrated management method matches the pre-migration transcript, and `hello.features` is unchanged for v3 local profiles. 4. On a RemoteGateway test entry, `session.permission.update` and `session.exec.stop` succeed. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 297eb7ad3a..d3ccf4700b 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -107,7 +107,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the admitting Rpc load unloads; the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | `register`'s declarations follow A.1: at least one method; each name inside the namespace and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration that breaks them is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. @@ -195,20 +195,20 @@ Flow tests on the owner: | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` registers the row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its method-table paragraphs — `Handler`, `MethodProvider`, `Check`, `Owner`, `MethodTable`, the `SessionMethods` deref, the `MethodCall`/`Origin` block and the foreign `register` decode — are the binding below; Appendix F links here and keeps only what CallChannel and ToolRegistry bind. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, `MethodTable` and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods and ToolRegistry bind. No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Three client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A handler's failure without an application code, and a failed or malformed foreign reply, carry `appError: "failed"`; a reply that failed to cross keeps today's `-32603` and gains the code (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- A failure that carries no remote error — a native handler's error without a code, or a reply that failed to cross — carries `appError: "failed"`; a reply that never crossed keeps today's `-32603` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). - A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). -Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. A declaration may also carry a `reply` field, accepted and ignored. +Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. A third change is a declaration's `reply` field: accepted and ignored, so it is not client-visible. ## Binding appendix diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 2752fd4e82..36f051bbc3 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -240,7 +240,7 @@ sequenceDiagram | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;`MethodTable` 是 Session 方法表的私有存储,不是共享类型。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | | `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | From 86628bdf547c88d8bfeb00a2c3afcfcca020a354 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 05:55:14 +0800 Subject: [PATCH 20/41] docs(sessionmethods): answer the eighteenth pre-review The failure conversion and the change note state the cases: a remote error keeps its code or its name, a malformed reply is `bad-value`/-32000, a bridge error without a code is `failed`/-32000, and a call that never reached the bridge is `failed`/-32603. The orphan-rule note is corrected, and the rule-check row says Rpc calls the tables' operations. --- docs/design/contracts/session-boundary.md | 6 +++--- docs/design/plugins/SessionMethods.md | 21 +++++++++++--------- docs/zh/design/contracts/session-boundary.md | 6 +++--- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index f2d0364c4c..cb9b1c2d24 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -159,7 +159,7 @@ Proposed (P3, with RemoteGateway; not implemented): the connection's `Connection | §4 rule 1 (command events) | Not applicable: the services write no Timeline event themselves; a method that changes branch state calls its owner, which writes (for example InputQueue's `input/deleted` for `session.input.withdraw`). | | §4 rule 2 (handover) | Not applicable: methods and tool contributions hand nothing over; a tool call is handed to ToolExecutor by the existing `step/tool-call` contract. | | §4 rule 3 (before callbacks only) | Rpc validates only param shape and `sessionId` authorization; feature checks belong to the method's owner, and acting before a commit is left to Timeline before callbacks. | -| §4 rule 4 (no business meaning in core) | The method tables and ToolRegistry keep what parts register, and Rpc reads the tables; none names a provider or interprets a method. The effect declaration is carried on the result unchanged, and no part of the core names one of its kinds (A.6). | +| §4 rule 4 (no business meaning in core) | The method tables and ToolRegistry keep what parts register, and Rpc calls their operations; none names a provider or interprets a method. The effect declaration is carried on the result unchanged, and no part of the core names one of its kinds (A.6). | | §4 rule 5 (batch) | Not applicable: no decision here is taken on a Timeline event; owners decide from their own facts. | | §4 rule 6 (model context) | Methods have no model-visible effect, and a registered tool reaches the model only through its declaration and `ToolResult` (§5). | | §4 rule 7 (public events and services) | Providers reach branches only through the branch's public services, and Rpc dispatches only through the Session's `sessionMethods`. | @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with Rpc's `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` in dim-agent-types, `From for RpcError` could be implemented only there, which cannot depend on `AgentError`. In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | @@ -564,7 +564,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The Session table no longer derefs to it. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The Session table no longer derefs to `MethodTable`. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index d3ccf4700b..3466b2b22e 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -124,7 +124,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | --- | --- | --- | --- | | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No registered namespace holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `unknown_method` | `call` | `unknown_method` | No namespace holds the name — registered or withdrawn — the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | @@ -200,15 +200,16 @@ Flow tests on the owner: ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, `MethodTable` and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods and ToolRegistry bind. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Three client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A failure that carries no remote error — a native handler's error without a code, or a reply that failed to cross — carries `appError: "failed"`; a reply that never crossed keeps today's `-32603` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). -- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). +- A failure that carries no remote error — a native handler's error without a code — carries `appError: "failed"` under the service rule (`-32000`), where today it is `-32603` with none (`crates/dim-agent-capabilities/src/methods.rs:129-137,905-918`). +- A malformed foreign reply carries `appError: "bad-value"` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853,905-918`). -Two request and reply shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. A third change is a declaration's `reply` field: accepted and ignored, so it is not client-visible. +Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. ## Binding appendix @@ -397,10 +398,12 @@ impl From for MethodCallbackError { if let Some(wire) = remote.and_then(rethrown) { return Self::from_wire(wire); } - // Otherwise: a remote error keeps its own application code, or its - // variant name when it has none, under the service-error rule; a call - // that crossed nothing is the binding's own failure, `failed`, and keeps - // today's `-32603`. + // Otherwise, by case: a remote error keeps its own application code, + // or its variant name when it has none; a bridge error (`bad-value`, + // `peer-gone`, a `Binding` code) keeps its code; both take the + // service-error rule. A bridge error without a code is `failed`. A + // `CallError` that is not a session error is the binding's own failure: + // `failed`, keeping today's `-32603`. let (code, wire) = match remote { Some(error) => ( error.code().map(str::to_owned).or_else(|| match error { diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 36f051bbc3..b5e14740b5 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ 状态:草案。总体设计:[总览 §3 集成](../overview.md#3-基于现有机制的集成)、[附录 B Rpc 与 ToolRegistry](../overview.md#附录-b-现有插件的补充);规则:[ADR 002](../../adr/002-plugin-scope.md) D2、D3、D5。阶段:P0。语言:语言中立合同;Rust 绑定见[附录 F](#附录-f-rust-绑定)。[C4 绑定](../../../design/session-typescript.md) 已实现非 Rust Session 工具和方法子集;原生广播仍待定。 -本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;注册接收命名空间及其声明的数据,以及调用方的函数回调;Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务(方法表或注册表),并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 +本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;注册接收命名空间及其声明的数据,以及调用方的函数回调;Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务(方法表或注册表),并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 与各所有者契约的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 | 服务 | 作用域 | 注册什么 | 注册方 | 读取方 | | --- | --- | --- | --- | --- | @@ -159,7 +159,7 @@ sequenceDiagram | §4 第 1 条(指令事件) | 不适用:这些服务自身不写 Timeline 事件;改变分支状态的方法调用状态所有者,由所有者写入(例如 InputQueue 为 `session.input.withdraw` 写入的 `input/deleted`)。 | | §4 第 2 条(交接) | 不适用:方法与工具贡献不交接任何对象;工具调用按现有 `step/tool-call` 合同交给 ToolExecutor。 | | §4 第 3 条(只用 before 回调) | Rpc 只校验参数格式和 `sessionId` 授权;功能检查归方法所有者,提交前的处理只用 Timeline before 回调。 | -| §4 第 4 条(核心不带业务含义) | 方法表与 ToolRegistry 保存部件注册的内容,Rpc 读取方法表;它们都不点名提供方,也不解释方法。效果声明随结果原样携带,核心没有任何部分认识它的类型(A.6)。 | +| §4 第 4 条(核心不带业务含义) | 方法表与 ToolRegistry 保存部件注册的内容,Rpc 调用它们的操作;它们都不点名提供方,也不解释方法。效果声明随结果原样携带,核心没有任何部分认识它的类型(A.6)。 | | §4 第 5 条(批次) | 不适用:本文没有依据 Timeline 事件做的决定;所有者依据自己的事实决定。 | | §4 第 6 条(模型上下文) | 方法对模型不可见,注册的工具只通过其声明和 `ToolResult` 到达模型(§5)。 | | §4 第 7 条(公开事件与服务) | 提供方只通过分支的公开服务到达分支,Rpc 只经 Session 的 `sessionMethods` 分发。 | @@ -527,7 +527,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。Session 表不再对它 `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。Session 表不再对 `MethodTable` `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 From 245c92551cbcd09a1f16ada1c457d5046b328bce Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 06:07:37 +0800 Subject: [PATCH 21/41] docs(sessionmethods): answer the nineteenth pre-review The change note lists the five failure cases and their codes: an absent row is `unknown_method`, a native code-less failure is `failed` under the service rule, a malformed reply is `bad-value`, a thrown error without a code keeps its name, and an error that never reached the bridge keeps `-32603`. The orphan-rule note is restored, and `origin.entry`/`origin.peer` are removed by the target. --- docs/design/contracts/session-boundary.md | 4 ++-- docs/design/plugins/SessionMethods.md | 13 +++++++------ docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index cb9b1c2d24..e4f0cfc23f 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -226,7 +226,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). ``` -Implemented today ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff, `origin.entry` and `origin.peer` are not implemented. +Implemented today ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff is not implemented, and the target removes `origin.entry` and `origin.peer`. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. @@ -240,7 +240,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` in dim-agent-types, `From for RpcError` could be implemented only there, which cannot depend on `AgentError`. In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | | `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 3466b2b22e..b73fafadfe 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -124,12 +124,12 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | --- | --- | --- | --- | | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No namespace holds the name — registered or withdrawn — the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `unknown_method` | `call` | `unknown_method` | Either no namespace, registered or withdrawn, holds the name, or the name is outside the grammar, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | | `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | -| `closed` | `call`, `methods` | `session_closed` (Session table) | The table is gone with its Session or process; re-acquire it by id (Rpc restores an unloaded Session) and call again. Do not retry against the closed one | +| `closed` | `call`, `methods` | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | `invalid`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. @@ -202,12 +202,13 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Three client-visible failure changes: +No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A failure that carries no remote error — a native handler's error without a code — carries `appError: "failed"` under the service rule (`-32000`), where today it is `-32603` with none (`crates/dim-agent-capabilities/src/methods.rs:129-137,905-918`). -- A malformed foreign reply carries `appError: "bad-value"` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:905-918`). -- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853,905-918`). +- A native handler's failure without an application code carries `appError: "failed"` under the service rule (`-32000`); today it is `-32603` with none (`crates/dim-agent-capabilities/src/methods.rs:153,206`). +- A malformed foreign reply carries `appError: "bad-value"` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). +- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). +- A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index b5e14740b5..ef8cb2982a 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -226,7 +226,7 @@ sequenceDiagram // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` -目前已实现([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接未实现,目标删除 `origin.entry` 与 `origin.peer`。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 From 42c0273997abf642e8ecb7c897a6d9430e38beb0 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 06:24:33 +0800 Subject: [PATCH 22/41] docs(sessionmethods): answer the twentieth pre-review A native code-less failure keeps `-32603` and gains `appError: "failed"`, as the conversion and the verification say. Appendix F drops `origin.entry` and `origin.peer`, which the target removes, and the ADR D5 row names each owner's binding. `loaderRows` names the disabled row, and the declaration rule covers a name equal to its namespace. --- docs/design/contracts/session-boundary.md | 4 ++-- docs/design/plugins/SessionMethods.md | 12 ++++++------ docs/zh/design/contracts/session-boundary.md | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index e4f0cfc23f..83d39ac568 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -170,7 +170,7 @@ Proposed (P3, with RemoteGateway; not implemented): the connection's `Connection | ADR 002 D2 | No port or Management plugin; method namespaces register with the method table of their scope and tools with ToolRegistry, which owns the Session's tools. | | ADR 002 D3 | Providers depend on their own or an enclosing scope, including the method table they register with. The method tables and ToolRegistry follow registration and withdrawal and do not depend on the parts that register (A.1, A.5); Rpc depends neither on management providers (§3.2) nor on Session method providers (A.1), so their reloads stay within their namespace. | | ADR 002 D4 | A link's management export is structural host-local configuration; no business configuration is defined here. | -| ADR 002 D5 | Every service is named with scope and data-only methods, and a part of any language registers a method namespace or a tool with the same data and its own function (`call`, `execute`); Rust types appear only in the owning table's binding ([SessionMethods](../plugins/SessionMethods.md#binding-appendix) for the Session table). The implemented binding is a subset of these shapes (A.1). | +| ADR 002 D5 | Every service is named with scope and data-only methods, and a part of any language registers a method namespace or a tool with the same data and its own function (`call`, `execute`); Rust types appear only in each owner's binding: [SessionMethods](../plugins/SessionMethods.md#binding-appendix) for the Session table, the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) for it, and ToolRegistry's for tools. The implemented binding is a subset of these shapes (A.1). | ## 9. Requirements raised to mechanism owners @@ -576,6 +576,6 @@ A refused registration fails the registering part: the namespace and its declara `Callers` is private transport wiring shared by the CallChannel and Rpc rows at its Rust type key; it has no service catalog name. The public operation surface remains `callChannel`. `Callers` is the process's only caller index: per row instance it holds the notification names its generation declared, kept after a connection of that instance closes so `Undeclared` is decided before `Gone`, and per row instance and connection the connection's direct writer and the row's unfinished calls by `callId`. The table's admission mints a foreign call's `callId` where the call's sink, the instance and the provider's declarations meet, and records the call; `Connection::answer` removes it after the reply is written. The entries of a connection are removed when it closes, when the admitting Rpc load unloads and when the row's generation unloads; the declared names go with the instance's generation. A native provider keeps its own `Caller` and records nothing. App Server provides A.2 `callChannel` for other languages as the process service `callChannel` (`ForeignCallChannel`, at `host_key("callChannel")`, from the `CallChannel` row that has no dependencies): its `notify` and `closed` read the calling row's instance with `rutis_bridge::session::caller_row()` and end in the same call's sink the Rust binding uses, so both bindings share one delivery path. -Another language registers through the owning table's dispatch: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), the process table's is its own contract ([#2021](https://github.com/arcships/dim/issues/2021)). Each decodes the declarations once and calls the same `register` with the caller's function; `ForeignMethods` leaves. Not implemented in either binding: final-reply handoff, `origin.entry` and `origin.peer`. A declaration's `reply` field is accepted and ignored. +Another language registers through the owning table's dispatch: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), the process table's is its own contract ([#2021](https://github.com/arcships/dim/issues/2021)). Each decodes the declarations once and calls the same `register` with the caller's function; `ForeignMethods` leaves. Not implemented in either binding: final-reply handoff. A declaration's `reply` field is accepted and ignored. `ToolContribution` and `ToolHandler` are the native types in `dim-agent-capabilities/src/tool_registry.rs`. `ToolRegistry::register(ctx, ToolContribution)` registers on behalf of the part that owns `ctx`, until that part unloads; it refuses a name outside `[A-Za-z0-9_-]{1,64}`, a host tool's name and a name registered already. Other languages reach `toolRegistry` through ToolRegistry's dispatcher: `register(declaration, execute, options?)` decodes the declaration as `ToolDefinition` once, requires a nonempty `risk`, and registers, on behalf of the calling row (the bridge's `caller_row`), a `ToolHandler` that calls `execute` back through the bridge. `options.concurrency` is `'concurrent'` or absent; it is not part of the declaration, because the class is an execution property of the bound handler, so the persisted `ToolDefinition` keeps its shape. Absent means the tool's calls run alone, in call order. That handler holds the calling row's generation token: once the row starts unloading, a call through a retained handler is not made, and a call in flight ends with an error warning that it may already have taken effect, without rebinding to a replacement generation; the foreign owner still settles its JavaScript work. Each execution derives a child cancellation token so completing one call cannot cancel other tools in the same batch. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index b73fafadfe..3915b745eb 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -26,7 +26,7 @@ Callers keep: | Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | | `session.methods` lists what a Session serves | No: the declarations and the namespace that owns each are the owner's | `methods` | | The caller learns why a registration was refused | Yes: `register` answers `duplicate` or `invalid`; a separate check would race the next registration | Business | -| Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `held_namespaces`; Rpc reads `sessionId` | Business | +| Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `heldNamespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | | A process-side caller holding a Session asks the table in process, as WebEntry's upload entry does | Yes: the same `call` without a site | Business | @@ -98,9 +98,9 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | +| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `held_namespaces` so Rpc routes a name and filters `session.methods` by A.1's routing precedence. +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. ### Operations @@ -110,7 +110,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | | `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name inside the namespace and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration that breaks them is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. +`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration that breaks them is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. @@ -202,10 +202,10 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No method changes and no new error kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`, and new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A native handler's failure without an application code carries `appError: "failed"` under the service rule (`-32000`); today it is `-32603` with none (`crates/dim-agent-capabilities/src/methods.rs:153,206`). +- A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153,206`). - A malformed foreign reply carries `appError: "bad-value"` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). - A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index ef8cb2982a..47bfda9809 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -170,7 +170,7 @@ sequenceDiagram | ADR 002 D2 | 不新增端口或 Management 插件;方法命名空间注册到其作用域的方法表,工具注册到拥有本 Session 工具的 ToolRegistry。 | | ADR 002 D3 | 提供方只依赖自身或外层作用域,包括它注册时用的方法表。方法表与 ToolRegistry 跟随注册与撤回,不依赖注册的部件(A.1、A.5);Rpc 既不依赖管理方法提供方(§3.2),也不依赖 Session 方法提供方(A.1),因此它们的重载只影响自己的命名空间。 | | ADR 002 D4 | 链接的管理方法导出是宿主本地的结构性配置;本文不定义业务配置。 | -| ADR 002 D5 | 每个服务都有名称、作用域和纯数据方法,任何语言的部件都用同样的数据和自己的函数(`call`、`execute`)注册方法命名空间或工具;Rust 类型只出现在各表自己的绑定里(Session 表见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix))。已实现的绑定是这些结构的一个子集(A.1)。 | +| ADR 002 D5 | 每个服务都有名称、作用域和纯数据方法,任何语言的部件都用同样的数据和自己的函数(`call`、`execute`)注册方法命名空间或工具;Rust 类型只出现在各所有者自己的绑定里:Session 表见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表见其契约([#2021](https://github.com/arcships/dim/issues/2021)),工具见 ToolRegistry 的绑定。已实现的绑定是这些结构的一个子集(A.1)。 | ## 9. 向机制所有者提出的需求 @@ -539,6 +539,6 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 `Callers` 是 CallChannel 和 Rpc 行通过 Rust 类型键共享的私有传输装配,不登记服务目录名称;公开操作面仍是 `callChannel`。`Callers` 是进程内唯一的调用方索引:按行实例保存该代际声明的通知名称,该实例的连接关闭后仍保留,因此先判定 `Undeclared` 再看连接状态;并按行实例与连接保存该连接的直接写入端与该行按 `callId` 记录的未完成调用。方法表的受理在调用的 sink、实例与提供方声明都可用的位置生成其他语言调用的 `callId` 并记录该调用;`Connection::answer` 在回复写出后移除它。连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除该连接的条目;声明的名称随该实例的代际一起删除。原生提供方保留自己的 `Caller`,不记录任何内容。App Server 以进程服务 `callChannel`(`ForeignCallChannel`,位于 `host_key("callChannel")`,由无依赖的 `CallChannel` 行提供)向其他语言提供 A.2 的 `callChannel`:其 `notify` 与 `closed` 用 `rutis_bridge::session::caller_row()` 读取调用行的实例,并最终落在 Rust 绑定所用同一次调用的 sink 上,两种绑定共用一条送达路径。 -外来注册经各自表的分发器:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。两者都一次性解码声明,并以调用方的函数调用同一个 `register`;`ForeignMethods` 离开。两种绑定都未实现:最终回复交接、`origin.entry` 与 `origin.peer`。声明的 `reply` 字段接受并忽略。 +外来注册经各自表的分发器:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。两者都一次性解码声明,并以调用方的函数调用同一个 `register`;`ForeignMethods` 离开。两种绑定都未实现:最终回复交接。声明的 `reply` 字段接受并忽略。 `ToolContribution` 与 `ToolHandler` 是 `dim-agent-capabilities/src/tool_registry.rs` 中的原生类型。`ToolRegistry::register(ctx, ToolContribution)` 代表拥有 `ctx` 的部件注册,直到该部件卸载;它拒绝不满足 `[A-Za-z0-9_-]{1,64}` 的名称、宿主工具名和已被注册的名称。其他语言经 ToolRegistry 的分发器访问 `toolRegistry`:`register(declaration, execute, options?)` 把声明解码为 `ToolDefinition` 一次,要求 `risk` 非空,并代表调用方行(桥的 `caller_row`)注册一个经桥回调 `execute` 的 `ToolHandler`。`options.concurrency` 取 `'concurrent'` 或缺省;它不属于声明,因为这个类别是绑定后处理器的执行属性,所以落盘的 `ToolDefinition` 形状不变。缺省表示该工具的调用单独执行,按调用顺序。该处理器持有调用方行的代次令牌:行开始卸载后,经保留的处理器发起的调用不会发出,在途调用以错误结束,错误提示它可能已经生效,不会改绑到新的代次;外部所有者仍负责结算其 JavaScript 工作。每次执行派生自己的子取消令牌,单个工具正常完成不会取消同批其他工具。 From 56ecee961737c96931bd37434e6120c4ef86055e Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 06:45:52 +0800 Subject: [PATCH 23/41] docs(sessionmethods): answer the twenty-first pre-review `call` returns a `CallReply`: the reply, the foreign call's caller-index entry and a settlement signal, so the caller writes the reply, finishes the entry and awaits settlement as A.2 requires. `methods` is sorted by name, a declared name may equal its namespace, and `unavailable` names the copy that failed. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 74 +++++++++++++++----- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 57 insertions(+), 21 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 83d39ac568..cfab8c093b 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -233,7 +233,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Rule | Content | | --- | --- | | Namespace | `(.)*`, segments `[a-z][a-z0-9_]*`, at most 128 bytes, owned by the part that registers it; a namespace may itself be a method (`session.rename`). A namespace outside this grammar is refused when it registers, and a called name outside it is `unknown_method` without any lookup | -| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method, each unique and inside the namespace) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | +| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method, each unique and equal to or inside the namespace) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | | Ownership | A name belongs to the longest namespace registered in that table that prefixes or equals it. A withdrawn namespace keeps holding its names: the table remembers the row that registered it, and a call answers from that row's status (§3.2; Session-scoped call below). A name no namespace of the table ever held has no owner | | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 3915b745eb..3a9d413309 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -61,16 +61,31 @@ let reply = match methods.call( Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), Err(MethodError::Reloading) => return Err(RpcError::reloading()), Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), - Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), Err(MethodError::Closed) => return Err(RpcError::closed()), + Err(MethodError::Interrupted) => unreachable!("an interruption answers in the reply"), Err(MethodError::Duplicate { .. }) | Err(MethodError::Invalid { .. }) => unreachable!("dispatch cannot register"), }; +let CallReply { + reply, + registration, + settled, +} = reply; // `MethodReply::Value` is the handler's value; `MethodReply::Error` is its own -// failure, which Rpc wraps in its envelope. -Ok(match reply { - MethodReply::Value(ValueReply::Value { value }) => value, - MethodReply::Error(error) => return Err(RpcError::from(error)), -}) +// failure, which Rpc wraps in its envelope. An interrupted `report` call +// answers `interrupted` here and settles later. +let value = match reply { + Ok(MethodReply::Value(ValueReply::Value { value })) => value, + Ok(MethodReply::Error(error)) => return Err(RpcError::from(error)), + Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), + Err(_) => return Err(RpcError::closed()), +}; +// Rpc writes the reply first, then ends the foreign call's index entry and +// waits for the call to settle. +if let Some(registration) = registration { + registration.finish(); +} +settled.await; +Ok(value) ``` `session.methods` composes the value with the process table's held namespaces: @@ -107,14 +122,14 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | -| `methods` | The declarations registered now | `{}` | `{methods}` | None | `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply` | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration that breaks them is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. +`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. -`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply`. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. +`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message, ...owner fields}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. @@ -126,7 +141,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `unknown_method` | `call` | `unknown_method` | Either no namespace, registered or withdrawn, holds the name, or the name is outside the grammar, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | -| `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run. Retrying fails the same way until that row is fixed or restarted | +| `unavailable` | `call` | `service_unavailable` | The registering row's copy in this Session failed or cannot run; a missing copy is `reloading` instead. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | | `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | | `closed` | `call`, `methods` | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | @@ -155,7 +170,7 @@ Flow tests on the owner: - A native handler receives the call's `Caller` and notifies through its `CallerConnection`; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a call that crossed nothing is `failed` with `-32603`. -- `methods` lists the registered declarations; Rpc's filter removes the names a held management namespace owns. +- `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. ## Rule check @@ -193,7 +208,7 @@ Flow tests on the owner: | --- | --- | | Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the process's loader is `rutis-loader`'s own business state; the table has no dim-owned face for it. | | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | -| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has. No business meaning. | +| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has or a row that is disabled. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | | Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | @@ -206,7 +221,7 @@ No existing client method changes and no error kind is removed. The table adds o - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153,206`). -- A malformed foreign reply carries `appError: "bad-value"` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). +- A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). - A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). @@ -214,7 +229,7 @@ Three shapes change for a part of another language: its `call` request nests the ## Binding appendix -One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `NotifyError` is A.2's too, stated below. `Callers` is the process's caller index, A.2's own private wiring at its Rust type key, and `CallSite` only references it. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `NotifyError` is A.2's too, stated below. `Callers` is the process's caller index, A.2's own private wiring at its Rust type key, and `CallSite` only references it. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave the Session table; its storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. ```rust // crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. @@ -420,8 +435,29 @@ impl From for MethodCallbackError { } } -/// The handler both tables store: the call, the serving generation's -/// cancellation token and the call's progress sink. +/// One admitted call's answer, for the caller that writes its reply. +pub struct CallReply { + /// The handler's reply, or the table's own kind for an interrupted call. + pub reply: Result, + /// The foreign call's caller-index entry, finished once the reply is + /// written; `None` for a native call. + pub registration: Option, + /// Resolves once the call has settled, which may follow an interrupted reply. + pub settled: BoxFuture<'static, ()>, +} + +/// The caller-index entry one call from another language holds until its reply +/// is written (A.2). +pub struct CallRegistration(/* the index, the row instance, the connection and the call id */); + +impl CallRegistration { + /// The call's reply is written: a later notification with its `callId` is + /// written directly, and the index no longer holds the call. + pub fn finish(self) { /* ... */ } +} + +/// The handler both tables store: the call, a token that fires on either +/// unload, and the call's progress sink. pub type Handler = std::sync::Arc< dyn Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> @@ -541,7 +577,7 @@ impl SessionMethods { site: Option, cancelled: CancelledFn, progress: impl Fn(serde_json::Value) + Send + Sync + 'static, - ) -> Result { /* ... */ } + ) -> Result { /* ... */ } } /// The catalog name `sessionMethods` in the Session group, served to other diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 47bfda9809..8b27362853 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -233,7 +233,7 @@ sequenceDiagram | 规则 | 内容 | | --- | --- | | 命名空间 | `(.)*`,段为 `[a-z][a-z0-9_]*`,最多 128 字节,由注册它的部件拥有;命名空间本身可以是一个方法(`session.rename`)。不符合该语法的命名空间在注册时被拒绝,被调用的名称不符合该语法时不做任何查找,直接为 `unknown_method` | -| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法唯一且位于命名空间内)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | +| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法唯一且等于或位于命名空间内)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | | 所有权 | 名称属于该表中作为其前缀或与其相等的最长已注册命名空间。已撤回的命名空间仍持有它的名称:方法表记住注册它的行,调用按该行的状态作答(§3.2;见下文 Session 级调用)。该表从没有命名空间持有过的名称没有所有者 | | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | From 4788969c602407d7bab632f0c19776897ec9ad12 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 07:02:17 +0800 Subject: [PATCH 24/41] docs(sessionmethods): answer the twenty-second pre-review The dispatch example writes the reply on every path, then finishes the foreign call's index entry and awaits settlement, so an error or an interruption releases the same resources as a value. The process table's `call` returns the same `CallReply`, and notifications may equal their namespace. --- docs/design/plugins/SessionMethods.md | 35 +++++++++++++-------------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 3a9d413309..b6037b0b58 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -70,22 +70,21 @@ let CallReply { registration, settled, } = reply; -// `MethodReply::Value` is the handler's value; `MethodReply::Error` is its own -// failure, which Rpc wraps in its envelope. An interrupted `report` call -// answers `interrupted` here and settles later. -let value = match reply { - Ok(MethodReply::Value(ValueReply::Value { value })) => value, - Ok(MethodReply::Error(error)) => return Err(RpcError::from(error)), - Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), - Err(_) => return Err(RpcError::closed()), +// Write the reply on every path: the handler's value, its own failure, or an +// interrupted call's `interrupted`. +let written = match reply { + Ok(MethodReply::Value(ValueReply::Value { value })) => Ok(value), + Ok(MethodReply::Error(error)) => Err(RpcError::from(error)), + Err(MethodError::Interrupted) => Err(RpcError::interrupted()), + Err(_) => Err(RpcError::closed()), }; -// Rpc writes the reply first, then ends the foreign call's index entry and -// waits for the call to settle. +// The reply is written: end the foreign call's index entry and wait for the +// call to settle, whichever answer went out. if let Some(registration) = registration { registration.finish(); } settled.await; -Ok(value) +written ``` `session.methods` composes the value with the process table's held namespaces: @@ -115,17 +114,17 @@ let listed = declarations.into_iter().filter(|decl| { | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | | `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — its `call` takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, with this contract, recorded on #2021 — and answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data, and its `call` returns the same `CallReply` — it takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller` — recorded on #2021 — and answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply` | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply` | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. +`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. @@ -152,9 +151,9 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | +| `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with the Session and the next Session builds a new one | The registering row | | `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | -| `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; a read already answered is unaffected | SessionMethods | +| `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -167,7 +166,7 @@ Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace is `duplicate`, while a reserved name or a malformed declaration is `invalid`; a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts, while its copy in this Session is Active or missing, and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. -- A native handler receives the call's `Caller` and notifies through its `CallerConnection`; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. +- A native handler receives the call's `Caller` and notifies through it; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a call that crossed nothing is `failed` with `-32603`. - `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. @@ -220,7 +219,7 @@ Flow tests on the owner: No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`, and new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. -- A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153,206`). +- A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). - A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). - A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). From 44fc7c2b2f5135985f69416fec88d7d5d6c05e3c Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 07:16:14 +0800 Subject: [PATCH 25/41] docs(sessionmethods): answer the twenty-third pre-review The dispatch example writes the reply before it ends the caller-index entry and awaits settlement, and a process-side caller has its own example. The process table's reply is left to its contract, the `CallRegistration` joins the stated objects, and A.1's call-data links point at the binding appendix. --- docs/design/contracts/session-boundary.md | 16 +++++++------- docs/design/plugins/SessionMethods.md | 27 ++++++++++++++++++----- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index cfab8c093b..b850a45edf 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; a registration takes the namespace and its declarations as data and the caller's function as a callback, and the Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F and the owners' contracts, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope. A method registration takes the namespace and its declarations as data and the caller's function as a callback; a tool registration takes its declaration and its execute function. The Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F and the owners' contracts, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -202,11 +202,11 @@ The implemented foreign Session subset is [C4](../session-typescript.md); genera ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. ### A.1 Method contributions -The call data of both tables — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's; this appendix keeps the client error, interruption and routing behavior that the redesign does not change. +The call data of both tables — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; this appendix keeps the client error, interruption and routing behavior that the redesign does not change. `sessionMethods` (Session) and `managementMethods` (process) are method tables with the same method, `register`. A part registers each namespace it serves with the table of its scope, and the table calls back the part's own `call`. Parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)) and reach the owning table's binding: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), and the process table's is its contract's ([#2021](https://github.com/arcships/dim/issues/2021)). @@ -223,7 +223,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own "progress": false, "notifications?": ["session.goal.changed"], // inside the namespace "reply?": "direct" | "handoff" } // handoff: daemon.shutdown; accepted and ignored until handoff exists -// MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#own-contract). +// MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#binding-appendix). ``` Implemented today ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff is not implemented, and the target removes `origin.entry` and `origin.peer`. @@ -235,7 +235,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Namespace | `(.)*`, segments `[a-z][a-z0-9_]*`, at most 128 bytes, owned by the part that registers it; a namespace may itself be a method (`session.rename`). A namespace outside this grammar is refused when it registers, and a called name outside it is `unknown_method` without any lookup | | Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method, each unique and equal to or inside the namespace) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | | Ownership | A name belongs to the longest namespace registered in that table that prefixes or equals it. A withdrawn namespace keeps holding its names: the table remembers the row that registered it, and a call answers from that row's status (§3.2; Session-scoped call below). A name no namespace of the table ever held has no owner | -| Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | +| Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification lies equal to or inside its namespace. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | @@ -560,9 +560,9 @@ The neutral services map to the native owners below. Tools register with ToolReg | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | | `managementMethods` | `ManagementMethods`, a process service holding a `MethodTable`, provided by App Server's `ManagementMethodsPlugin` row | A process part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Rpc depends on the table and reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382) | -| `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#own-contract) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#own-contract) | +| `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#binding-appendix) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#binding-appendix) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | -| `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#own-contract)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | +| `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The Session table no longer derefs to `MethodTable`. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index b6037b0b58..d834c67fbf 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -78,13 +78,28 @@ let written = match reply { Err(MethodError::Interrupted) => Err(RpcError::interrupted()), Err(_) => Err(RpcError::closed()), }; +``` + +Rpc writes `written` on the calling connection and releases the call's held notifications, then: + +```rust // The reply is written: end the foreign call's index entry and wait for the // call to settle, whichever answer went out. if let Some(registration) = registration { registration.finish(); } settled.await; -written +``` + +A process-side caller holding a Session, such as WebEntry's upload entry, calls the table without a site and writes its own answer: + +```rust +let CallReply { reply, registration, settled } = methods + .call(method.into(), params, None, cancelled, |_| {}) + .await?; +// No connection wrote a reply here: the caller's own handler answers. +let outcome = reply; +settled.await; ``` `session.methods` composes the value with the process table's held namespaces: @@ -114,7 +129,7 @@ let listed = declarations.into_iter().filter(|decl| { | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | | `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data, and its `call` returns the same `CallReply` — it takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller` — recorded on #2021 — and answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. +The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — it takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, recorded on #2021 — and its own contract states its reply. It answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. ### Operations @@ -152,12 +167,12 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with the Session and the next Session builds a new one | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; a table reload interrupts its calls by their declarations and waits for them | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons -- The call's connection crosses this owner twice: Rpc passes the admission's `CallSite` to `call`, and the table hands the handler the `Caller` it builds from it. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- The call's connection crosses this owner twice, and one handle crosses back: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -187,13 +202,13 @@ Flow tests on the owner: | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | | §4 rule 8 | The only infrastructure request is `loaderRows`, a dim-owned process face for one loader row, raised below with its five fields; nothing else changes. | | §4 rule 9 | No Timeline fact. | -| §7 values, ids and callbacks | The caller is data on the wire, and the stated site and `Caller` are the two objects this contract hands out, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | +| §7 values, ids and callbacks | The caller is data on the wire; the site, the `Caller` and the `CallRegistration` are the stated objects, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | -| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site and `Caller`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | +| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller` and `CallRegistration`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | | ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | | ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | From 19099a989f636191ebc5847d7fe05b074b60c561 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 07:33:44 +0800 Subject: [PATCH 26/41] docs(sessionmethods): answer the twenty-fourth pre-review The shared `MethodError` keeps `reserved` for the process table's registration and gains `invalid` on `call`, as the organizer decided. Three handles cross the owner, notifications may equal their namespace in A.2 too, and the in-process example states its error mapping. `loaderRows` says when `status` and `copies` are present, and Appendix C's owner-field sentence is neutral. --- docs/design/contracts/session-boundary.md | 6 ++-- docs/design/plugins/SessionMethods.md | 29 +++++++++++++------- docs/zh/design/contracts/session-boundary.md | 4 +-- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index b850a45edf..aee6e8ffd9 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -221,7 +221,7 @@ The call data of both tables — `MethodCall`, `MethodReply`, the handler's own "mutating": true, "interruption": "report" | "drain", // the provider replies on unload: report → operation_interrupted; drain → the call's own result "progress": false, - "notifications?": ["session.goal.changed"], // inside the namespace + "notifications?": ["session.goal.changed"], // equal to or inside the namespace "reply?": "direct" | "handoff" } // handoff: daemon.shutdown; accepted and ignored until handoff exists // MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#binding-appendix). ``` @@ -318,7 +318,7 @@ reply ----------> reply and notice allowance ----+ full: a slow consumer, the connection closes ``` -A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id minted for a call served by a registration of another language, which its `origin.caller.callId` carries. A native handler has no such id: it notifies through its `Caller`. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. +A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id minted for a call served by a registration of another language, which its `origin.caller.callId` carries. A native handler has no such id: it notifies through its `Caller`. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, equal to or inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. How a notification of one call reaches its caller: @@ -527,7 +527,7 @@ carry the native event whole, and the frozen fixtures stay unchanged. | `report` call interrupted | `-32000`, `operation_interrupted` | | Handler error | the handler's own JSON-RPC code when it carries one (`MethodCallbackError.wire`), otherwise the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | -Native method errors may include owner-defined JSON fields beside `data.appError`. +A handler's failure may carry owner-defined JSON fields in `data` beside `data.appError`. The method owner defines and supplies their safe public shape; the method table and Rpc preserve them without interpreting them. These fields must not shadow `appError` or built-in error fields. An error without additional fields keeps its diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index d834c67fbf..e889a69a1b 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -63,7 +63,8 @@ let reply = match methods.call( Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), Err(MethodError::Closed) => return Err(RpcError::closed()), Err(MethodError::Interrupted) => unreachable!("an interruption answers in the reply"), - Err(MethodError::Duplicate { .. }) | Err(MethodError::Invalid { .. }) => unreachable!("dispatch cannot register"), + Err(MethodError::Invalid { .. }) => return Err(RpcError::invalid("Invalid request parameters")), + Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) => unreachable!("dispatch cannot register"), }; let CallReply { reply, @@ -94,10 +95,12 @@ settled.await; A process-side caller holding a Session, such as WebEntry's upload entry, calls the table without a site and writes its own answer: ```rust +// An admission failure (`MethodError`) fails this caller's own operation. let CallReply { reply, registration, settled } = methods .call(method.into(), params, None, cancelled, |_| {}) .await?; -// No connection wrote a reply here: the caller's own handler answers. +// No connection wrote a reply here: `reply` is the handler's answer, or the +// table's interruption, for this caller to use. let outcome = reply; settled.await; ``` @@ -127,7 +130,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`; otherwise `status` is the row's own state and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | +| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — it takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, recorded on #2021 — and its own contract states its reply. It answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. @@ -135,8 +138,8 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply` | +| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `reserved` (process table only), `duplicate`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `invalid`, `closed`; an interruption answers in `reply.reply` | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | `register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. @@ -152,7 +155,9 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | +| `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table's host check answers `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | +| `invalid` | `call` | `invalid_params` | The request cannot be read: the method name or params are malformed. Fix the request and call again | | `unknown_method` | `call` | `unknown_method` | Either no namespace, registered or withdrawn, holds the name, or the name is outside the grammar, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row's copy in this Session failed or cannot run; a missing copy is `reloading` instead. Retrying fails the same way until that row is fixed or restarted | @@ -160,19 +165,19 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | | `closed` | `call`, `methods` | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | -`invalid`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. +`reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with the Session and the next Session builds a new one | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its reply; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons -- The call's connection crosses this owner twice, and one handle crosses back: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -231,7 +236,7 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`, and new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration and gain `invalid` on `call`; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). @@ -533,10 +538,14 @@ impl From for RpcError { /// The table's own failures, by kind. One kind set serves both tables; /// `closed` reaches a client as `session_closed` for the Session table, and -/// the process table has no client code of its own. +/// the process table has no client code of its own. `reserved` answers the +/// process table's registration only: the Session table's host check answers +/// `invalid` for the same input. #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum MethodError { + #[error("{message}")] + Reserved { message: String }, #[error("{message}")] Duplicate { message: String }, #[error("{message}")] diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 8b27362853..f7225f2374 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -221,7 +221,7 @@ sequenceDiagram "mutating": true, "interruption": "report" | "drain", // 卸载时由提供方回复:report → operation_interrupted;drain → 调用自己的结果 "progress": false, - "notifications?": ["session.goal.changed"], // 位于命名空间内 + "notifications?": ["session.goal.changed"], // 等于或位于命名空间内 "reply?": "direct" | "handoff" } // handoff:daemon.shutdown;交接落地前接受并忽略 // MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 ``` @@ -317,7 +317,7 @@ reply ----------> 回复与通知额度 ----------------+ 已满:慢消费者,关闭连接 ``` -通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即另一种语言注册所提供的调用被铸出的 id,由 `origin.caller.callId` 携带。原生处理函数没有这个 id:它经自己的 `Caller` 通知。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 +通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即另一种语言注册所提供的调用被铸出的 id,由 `origin.caller.callId` 携带。原生处理函数没有这个 id:它经自己的 `Caller` 通知。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且等于或位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 一次调用的通知如何到达调用方: From a6f4ee68502a69e2e85c7def88ce1fafdaafc11d Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 07:48:15 +0800 Subject: [PATCH 27/41] docs(sessionmethods): answer the twenty-fifth pre-review The Session table's `call` never answers `invalid`: a name outside the grammar is `unknown_method` and params are the handler's, while the process table's `call` keeps `invalid` for a malformed request. The zh mirror's call-data links point at the binding appendix, and Exceptions counts three handles with none holding the connection. --- .../rust-agent/plugins/SessionMethods.md | 2 +- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 19 +++++++++---------- docs/zh/design/contracts/session-boundary.md | 14 +++++++------- 4 files changed, 18 insertions(+), 19 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index d1c2d4f41b..40ac33ede2 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -25,7 +25,7 @@ contract ([SessionMethods §4 rule 8](../../../design/plugins/SessionMethods.md# ## Events and lifetime -No Timeline events or I/O. The table tracks the calls each registration accepted, so that registration's unload can interrupt them and wait. A part depends on `sessionMethods` and +No Timeline events or I/O. Each registration tracks the calls it accepted, so its unload can interrupt them and wait. A part depends on `sessionMethods` and calls `register(ctx, namespace, declarations, call)` from its own `apply`, with the part's own function as `call`; the registration is withdrawn when that part unloads, and a namespace registered already fails diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index aee6e8ffd9..80f1a64739 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -141,7 +141,7 @@ Methods have no model-visible effect. A method that changes model context does s | `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; the registering row is the binding's `&Ctx`, not a request field, and the shape is [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | -| `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable`, `interrupted` or `closed` ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable` or `closed`, and an interruption answers in its reply ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | The declarations of the namespaces the Session registered now | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | | `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented; `Progress` and `Caller` are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s) | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index e889a69a1b..2299fa0144 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -63,8 +63,7 @@ let reply = match methods.call( Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), Err(MethodError::Closed) => return Err(RpcError::closed()), Err(MethodError::Interrupted) => unreachable!("an interruption answers in the reply"), - Err(MethodError::Invalid { .. }) => return Err(RpcError::invalid("Invalid request parameters")), - Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) => unreachable!("dispatch cannot register"), + Err(MethodError::Invalid { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) => unreachable!("a Session call answers none of these"), }; let CallReply { reply, @@ -96,7 +95,7 @@ A process-side caller holding a Session, such as WebEntry's upload entry, calls ```rust // An admission failure (`MethodError`) fails this caller's own operation. -let CallReply { reply, registration, settled } = methods +let CallReply { reply, settled, .. } = methods .call(method.into(), params, None, cancelled, |_| {}) .await?; // No connection wrote a reply here: `reply` is the handler's answer, or the @@ -139,7 +138,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `reserved` (process table only), `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `invalid`, `closed`; an interruption answers in `reply.reply` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` also answers `invalid` for a malformed request | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | `register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. @@ -155,9 +154,9 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | -| `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table's host check answers `invalid`. Pick another name | +| `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `invalid` | `call` | `invalid_params` | The request cannot be read: the method name or params are malformed. Fix the request and call again | +| `invalid` | process table's `call` | `invalid_params` | The request cannot be read: the method name or params are malformed. Fix the request and call again. The Session table answers `unknown_method` for a name outside the grammar and leaves params to the handler | | `unknown_method` | `call` | `unknown_method` | Either no namespace, registered or withdrawn, holds the name, or the name is outside the grammar, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row's copy in this Session failed or cannot run; a missing copy is `reloading` instead. Retrying fails the same way until that row is fixed or restarted | @@ -177,7 +176,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, its `closed` resolves when the connection closes or the admitting Rpc load unloads, and neither type keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the three keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -236,7 +235,7 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration and gain `invalid` on `call`; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration and gain `invalid` on the process table's `call`; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). @@ -539,8 +538,8 @@ impl From for RpcError { /// The table's own failures, by kind. One kind set serves both tables; /// `closed` reaches a client as `session_closed` for the Session table, and /// the process table has no client code of its own. `reserved` answers the -/// process table's registration only: the Session table's host check answers -/// `invalid` for the same input. +/// process table's registration only: the Session table maps the same input +/// to `invalid`. #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum MethodError { diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index f7225f2374..9539b42101 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | 从没有命名空间持有过该名称,或注册它的行已禁用或不存在时返回 `unknown_method`;其他情况下,已撤回的命名空间按该行的状态作答(§3.2) | | 工具注册 | Session 挂载列表列出但没有部件注册的工具不声明,并在诊断中报告;有部件注册后从下一个请求起声明(A.5) | -本文定义的合同:两张方法表共用的注册、工具注册、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。调用数据——`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 +本文定义的合同:两张方法表共用的注册、工具注册、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。调用数据——`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`——归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 ## 2. 数据与状态 @@ -141,7 +141,7 @@ sequenceDiagram | `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;注册行是绑定的 `&Ctx`,不是请求字段,形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | -| `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable`、`interrupted` 或 `closed`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable` 或 `closed`,中断在其回复里作答([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | 该 Session 现在注册的命名空间的声明 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | | `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现;`Progress` 与 `Caller` 归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)) | @@ -202,11 +202,11 @@ sequenceDiagram ## 附录 A. 接口细节 -结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约;处理函数以自己的 `{code, message, ...所有者字段}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError, ...所有者字段}}`。 +结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 契约;处理函数以自己的 `{code, message, ...所有者字段}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError, ...所有者字段}}`。 ### A.1 方法贡献 -两张表的调用数据——`MethodCall`、`MethodReply`、处理函数自己的错误与方法表的错误种类——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约定义;本附录保留重构不改的客户端错误、中断与路由行为。 +两张表的调用数据——`MethodCall`、`MethodReply`、处理函数自己的错误与方法表的错误种类——归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 契约定义;本附录保留重构不改的客户端错误、中断与路由行为。 `sessionMethods`(Session)与 `managementMethods`(进程)是方法表,具有同一个方法 `register`。部件把它提供的每个命名空间注册到其作用域的方法表,方法表回调该部件自己的 `call`。其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md)),并进入各表自己的绑定:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。 @@ -223,7 +223,7 @@ sequenceDiagram "progress": false, "notifications?": ["session.goal.changed"], // 等于或位于命名空间内 "reply?": "direct" | "handoff" } // handoff:daemon.shutdown;交接落地前接受并忽略 -// MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)。 +// MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)。 ``` 目前已实现([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接未实现,目标删除 `origin.entry` 与 `origin.peer`。 @@ -235,7 +235,7 @@ sequenceDiagram | 命名空间 | `(.)*`,段为 `[a-z][a-z0-9_]*`,最多 128 字节,由注册它的部件拥有;命名空间本身可以是一个方法(`session.rename`)。不符合该语法的命名空间在注册时被拒绝,被调用的名称不符合该语法时不做任何查找,直接为 `unknown_method` | | 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法唯一且等于或位于命名空间内)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | | 所有权 | 名称属于该表中作为其前缀或与其相等的最长已注册命名空间。已撤回的命名空间仍持有它的名称:方法表记住注册它的行,调用按该行的状态作答(§3.2;见下文 Session 级调用)。该表从没有命名空间持有过的名称没有所有者 | -| 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | +| 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知等于或位于其命名空间内。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | @@ -525,7 +525,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | | `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | -| `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | +| `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | 调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。Session 表不再对 `MethodTable` `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 From 02d86438686ae45bdd137ced2833cc5bb87219aa Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 08:02:17 +0800 Subject: [PATCH 28/41] docs(sessionmethods): answer the twenty-sixth pre-review `invalid` owns the grammar and duplicate checks for both tables and the host's reserved-name checks for the Session table only; the process table's registration answers those as `reserved`. The in-process example maps each admission kind, writes its own answer and returns it. --- docs/design/plugins/SessionMethods.md | 30 +++++++++++++------- docs/zh/design/contracts/session-boundary.md | 2 +- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 2299fa0144..b69e470a42 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -94,14 +94,22 @@ settled.await; A process-side caller holding a Session, such as WebEntry's upload entry, calls the table without a site and writes its own answer: ```rust -// An admission failure (`MethodError`) fails this caller's own operation. -let CallReply { reply, settled, .. } = methods - .call(method.into(), params, None, cancelled, |_| {}) - .await?; +// An admission failure fails this caller's own operation. +let admitted = match methods.call(method.into(), params, None, cancelled, |_| {}).await { + Ok(reply) => reply, + Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), + Err(MethodError::Reloading) => return Err(RpcError::reloading()), + Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), + Err(MethodError::Closed) => return Err(RpcError::closed()), + Err(MethodError::Invalid { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) | Err(MethodError::Interrupted) => unreachable!("a Session call answers none of these"), +}; +let CallReply { reply, settled, .. } = admitted; // No connection wrote a reply here: `reply` is the handler's answer, or the -// table's interruption, for this caller to use. -let outcome = reply; +// table's interruption, and this caller writes its own answer. +let answer = reply; +write_answer(&answer); settled.await; +answer ``` `session.methods` composes the value with the process table's held namespaces: @@ -109,6 +117,8 @@ settled.await; ```rust // A.1's routing precedence: a declaration whose name equals or lies inside a // held management namespace is routed to management, never listed for the Session. +// The process closing is not the Session's close: Rpc answers +// `service_unavailable` rather than list names it cannot filter. let Ok(held) = management.held_namespaces() else { return Err(RpcError::service("service_unavailable", "The process is closing")); }; @@ -145,7 +155,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and the call's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and that connection's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message, ...owner fields}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. @@ -153,7 +163,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, in a reserved root, equal to, containing or inside a built-in, a declared notification equal to a built-in notification's name, or a declaration that is malformed or repeated — the table checks the declarations and the host's check answers its reserved names. Fix the name or the declaration and register again | +| `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, malformed or repeated — the table checks these. For the Session table the host's check adds a reserved root, a name equal to, containing or inside a built-in, or a declared notification equal to a built-in notification's name; the process table's registration answers those as `reserved`. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `invalid` | process table's `call` | `invalid_params` | The request cannot be read: the method name or params are malformed. Fix the request and call again. The Session table answers `unknown_method` for a name outside the grammar and leaves params to the handler | @@ -176,7 +186,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states the two types: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the three keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all three: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the three keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -337,7 +347,7 @@ impl Caller { /// connection closed, `too_large` over the frame limit. pub fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError> { /* ... */ } /// Resolves when the connection closes or the admitting Rpc load unloads. - pub fn closed(&self) -> impl std::future::Future + Send + 'static { async {} } + pub fn closed(&self) -> impl std::future::Future + Send + 'static { /* ... */ } } /// A connection as the `methods` module uses it: its id, a write to it and its diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 9539b42101..72ea5c1a7d 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -523,7 +523,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | | `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | -| `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | +| `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | From 3b8804fe2fdf55935097d19e57c949761d64bec6 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 08:15:13 +0800 Subject: [PATCH 29/41] docs(sessionmethods): answer the twenty-seventh pre-review Every shared row that differs by table names it: the host's refusal is the Session table's `invalid`, the process table's `reserved`; a malformed name is the Session table's `unknown_method`, the process table's `invalid`; a table ends with its Session or process. The site is the table's to hold and drop, and the architecture page marks its absent-row answer as today's, not the target's. --- docs/architecture/rust-agent/plugins/SessionMethods.md | 7 ++++--- docs/design/plugins/SessionMethods.md | 10 +++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 40ac33ede2..6c7d764a84 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -38,9 +38,10 @@ dispatcher key, with the native service. A name belongs to the longest namespace that holds it. When a namespace is withdrawn, the table keeps the row that registered it, so a call into it answers -`service_reloading` or `service_unavailable` from that row's status. That row -being disabled or absent is `unknown_method`, as is a name no namespace of the -Session ever held. Each registration owns the calls it admitted: its +`service_reloading` or `service_unavailable` from that row's status. Today a +withdrawn namespace whose row is absent from the loader answers +`service_reloading`; the target contract answers `unknown_method` there, as it +already does for a disabled row and for a name no namespace ever held. Each registration owns the calls it admitted: its part's unload interrupts `report` calls and waits for every admitted call. `session.methods` lists the methods of the namespaces registered now that no management namespace holds. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index b69e470a42..a5832c72be 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -151,7 +151,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` also answers `invalid` for a malformed request | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`; so is one the host refuses, including a declared notification that takes a built-in notification's name. +`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`. The Session table's host check adds `invalid` for a name or notification it keeps; the process table's registration answers those as `reserved`. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. @@ -167,7 +167,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `invalid` | process table's `call` | `invalid_params` | The request cannot be read: the method name or params are malformed. Fix the request and call again. The Session table answers `unknown_method` for a name outside the grammar and leaves params to the handler | -| `unknown_method` | `call` | `unknown_method` | Either no namespace, registered or withdrawn, holds the name, or the name is outside the grammar, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent; for the Session table a name outside the grammar is this kind too, where the process table answers `invalid`. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row's copy in this Session failed or cannot run; a missing copy is `reloading` instead. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | @@ -180,13 +180,13 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the host's refusal and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with the Session and the next Session builds a new one | The registering row | +| `register` | Check the duplicate and, in the Session table, the host's refusal; record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | | `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | -| `methods` | Read the registered namespaces' declarations; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | +| `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons -- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all three: Rpc builds the site for one call and drops it when the call settles; the table binds the site to the serving generation's declared notifications; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the three keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all three: Rpc builds the site for one call and hands it to `call`; the table holds it, binds its serving generation's declared notifications to the `Caller`, and drops it when the call settles; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the three keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification From bb78cf475913de8b72cd0ea5ecb17a0c40c754a0 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 08:30:55 +0800 Subject: [PATCH 30/41] docs(sessionmethods): answer the twenty-eighth pre-review A name outside the grammar is `unknown_method` in both tables; the process table's `call` keeps `invalid` only for a request whose params are not an object. The register flow names both host refusals, and the reloading and unavailable rows and the call flow say which cells are the Session table's. --- docs/design/plugins/SessionMethods.md | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index a5832c72be..390da1cf8c 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -166,22 +166,22 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, malformed or repeated — the table checks these. For the Session table the host's check adds a reserved root, a name equal to, containing or inside a built-in, or a declared notification equal to a built-in notification's name; the process table's registration answers those as `reserved`. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `invalid` | process table's `call` | `invalid_params` | The request cannot be read: the method name or params are malformed. Fix the request and call again. The Session table answers `unknown_method` for a name outside the grammar and leaves params to the handler | -| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, or the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent; for the Session table a name outside the grammar is this kind too, where the process table answers `invalid`. Check the name and the namespace's declarations; an absent row is a configuration problem | -| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations; retry after it is Active and registered the namespace again | -| `unavailable` | `call` | `service_unavailable` | The registering row's copy in this Session failed or cannot run; a missing copy is `reloading` instead. Retrying fails the same way until that row is fixed or restarted | +| `invalid` | process table's `call` | `invalid_params` | The request cannot be read: `params` is not an object. A name outside the grammar is `unknown_method` in both tables, and the Session table leaves `params` to the handler | +| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | +| `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | | `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | | `closed` | `call`, `methods` | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | -`reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table has no client code of its own. +`reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the duplicate and, in the Session table, the host's refusal; record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | +| `register` | Check the table's host refusal and the duplicate — the Session table answers `invalid`, the process table `reserved` — then record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -326,6 +326,11 @@ pub enum NotifyError { TooLarge, } +impl NotifyError { + /// The code a bridge error carries: `undeclared`, `gone` or `too_large`. + pub fn code(self) -> &'static str { /* ... */ } +} + /// The calling connection of one admitted call (A.2), bound to the serving /// generation's declared notifications. Opaque: its methods are its whole /// surface. It keeps the connection through `Arc`, @@ -600,8 +605,8 @@ impl SessionMethods { pub fn methods(&self) -> Result, MethodError> { /* ... */ } /// One call, in process: the caller's site (`CallSite`, below), the - /// cancellation and the progress sink are parameters, and the reply is - /// data. + /// cancellation and the progress sink are parameters, and the reply is the + /// `CallReply` above. pub async fn call( &self, method: String, From 060063419b1f185a02a008fb5f145d63c865d4b0 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 08:44:45 +0800 Subject: [PATCH 31/41] docs(sessionmethods): answer the twenty-ninth pre-review A.1's routing diagram dispatches through `sessionMethods.call`, and the table finds the owner; the zh diagram mirrors it. The process table's `call` kinds are left to its contract, so the invented `invalid` trigger is gone. The table checks the grammar and declarations before consulting the host's reserved names. --- docs/design/contracts/session-boundary.md | 5 +++-- docs/design/plugins/SessionMethods.md | 9 ++++----- docs/zh/design/contracts/session-boundary.md | 5 +++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 80f1a64739..9008bfed8f 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -265,7 +265,8 @@ call authorize; index.acquire (restores an unloaded Session; | an unknown id -> session_closed) | - owner in the Session's sessionMethods? -------- none ------> -32601 unknown_method + sessionMethods.call {method, params, caller?} -> the table finds the owner + | none ------> -32601 unknown_method | withdrawn -> the registering row's copy | in this Session (§3.2): | starting or reloading, Active or no copy @@ -273,7 +274,7 @@ call | Failed, Unresolved, Disposed or Stopped | -> -32000 service_unavailable | registered - provider call --> reply (an undeclared name: -32601 unknown_method) + the handler -> CallReply (an undeclared name: -32601 unknown_method) ``` Session namespaces registered today: `session.question` (Questions), `session.goal` (Goal), `session.rename` (SessionTitle), `session.input` (InputQueue), `session.context` (ContextCompaction), `session.exec.output` (WorkspaceTools, [background task output](../background-task-output.md)), `session.agent` ([model configuration](../model-configuration.md)), `session.language` (App Server, [PromptSources §3](../plugins/PromptSources.md#3-the-agent-prompt-language-state-source)), `attachment` (Attachments), `shell` (ShellInput), `session.wakeup` (Scheduler, [Scheduler §10](../plugins/Scheduler.md#10-session-scoped-wakeup)), `session.collaboration` (Collaboration, [Collaboration §6.7](../plugins/Collaboration.md#67-stopping-a-member-from-the-client)). `approval.respond` is a built-in Session method, not a part registration. The branch methods — `session.branch_create`, `session.branch_end`, `session.branch_set_default`, `session.branches` and `session.branch.get` — are built-ins too, and their contract is [timeline branches §9, §10 and §14](../timeline-branches.md#14-clients): each `branchId` they take names one line, and one that is omitted names the Session's default branch, not its root. `session.branch_set_default` accepts the root as a target whenever it is not the default branch and refuses only a target that is already the default branch; `session.branch_end` refuses the default branch for every caller, so ending it takes a move of the default branch first. Hooks registers no Session namespace: its `hooks.*` methods are management methods ([Hooks A.7](../plugins/Hooks.md#a7-management-methods)). Each plugin document is authoritative for its methods. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 390da1cf8c..7796516876 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -151,7 +151,7 @@ The process table (#2021) serves the same `MethodCall`, `MethodReply` and `Metho | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` also answers `invalid` for a malformed request | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. A declaration set that breaks them, or that cannot be decoded from another language's request, is `invalid`. The Session table's host check adds `invalid` for a name or notification it keeps; the process table's registration answers those as `reserved`. +`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. @@ -163,10 +163,9 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `invalid` | `register` | — | The namespace or a declaration is refused: outside the name grammar, malformed or repeated — the table checks these. For the Session table the host's check adds a reserved root, a name equal to, containing or inside a built-in, or a declared notification equal to a built-in notification's name; the process table's registration answers those as `reserved`. Fix the name or the declaration and register again | +| `invalid` | `register` | — (Session); `invalid_params` (process table) | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `invalid` | process table's `call` | `invalid_params` | The request cannot be read: `params` is not an object. A name outside the grammar is `unknown_method` in both tables, and the Session table leaves `params` to the handler | | `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | @@ -195,7 +194,7 @@ Flow tests on the owner: - A registration lives until its row unloads; a duplicate namespace is `duplicate`, while a reserved name or a malformed declaration is `invalid`; a refused registration fails the registering part. - `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts, while its copy in this Session is Active or missing, and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. -- A native handler receives the call's `Caller` and notifies through it; a handler of another language receives `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. +- A native handler receives the call's `Caller` and notifies through it; a handler of another language receives the same caller encoded by the bridge as `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a call that crossed nothing is `failed` with `-32603`. - `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. @@ -245,7 +244,7 @@ Flow tests on the owner: - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration and gain `invalid` on the process table's `call`; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration and `invalid` for a malformed request; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 72ea5c1a7d..6e628f51c8 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -264,7 +264,8 @@ sequenceDiagram 授权;index.acquire(恢复未装载的 Session; | 未知 id -> session_closed) | - 该 Session 的 sessionMethods 中的所有者? ---- 没有 -----> -32601 unknown_method + sessionMethods.call {method, params, caller?} -> 方法表查找所有者 + | 没有 -----> -32601 unknown_method | 已撤回 ---> 注册它的行在本 Session 中的副本 | (§3.2): | 启动中或重载中、Active 或没有副本 @@ -272,7 +273,7 @@ sequenceDiagram | Failed、Unresolved、Disposed 或 Stopped | -> -32000 service_unavailable | 已注册 - 提供方调用 --> 回复(未声明的名称:-32601 unknown_method) + 处理函数 --> CallReply(未声明的名称:-32601 unknown_method) ``` 目前注册的 Session 命名空间:`session.question`(Questions)、`session.goal`(Goal)、`session.rename`(SessionTitle)、`session.input`(InputQueue)、`session.context`(ContextCompaction)、`session.exec.output`(WorkspaceTools,[后台任务输出](../../../design/background-task-output.md))、`session.agent`([模型配置](../../../design/model-configuration.md))、`attachment`(Attachments)、`shell`(ShellInput)、`session.wakeup`(Scheduler,[Scheduler §10](../plugins/Scheduler.md#10-session-作用域的一次性唤醒))、`session.collaboration`(Collaboration,[Collaboration §6.7](../plugins/Collaboration.md#67-从客户端停止成员))。`approval.respond` 是内建的 Session 方法,不是部件注册。分支方法——`session.branch_create`、`session.branch_end`、`session.branch_set_default`、`session.branches` 与 `session.branch.get`——同样都是内建方法,它们的契约见[timeline branches §9、§10 与 §14](../timeline-branches.md#14-客户端):它们接受的每个 `branchId` 各指名一条线,省略的那个指名Session 的主线,而不是它的根。`session.branch_set_default` 在根不是主线时接受根作为目标,只拒绝已经是主线的目标;`session.branch_end` 对任何调用方都拒绝当前主线,所以要结束它,先移动主线。Hooks 不注册 Session 命名空间:它的 `hooks.*` 方法是管理方法([Hooks A.7](../plugins/Hooks.md#a7-管理方法))。各插件文档对其方法具有权威性。 From ec4868850d84e8970ec37dbe932bbfaad97c167f Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 08:54:50 +0800 Subject: [PATCH 32/41] docs(sessionmethods): answer the thirtieth pre-review The process table's `call` kinds stay with its contract: no `invalid` claim here and none in the change note. Its shape is a requirement to #2021, not a dependency, and the Dependencies row keeps only `heldNamespaces`. The closing paragraph says the bridge encodes the `Caller`, and the flows and architecture page name their tables and wrap. --- .../rust-agent/plugins/SessionMethods.md | 12 +++++----- docs/design/plugins/SessionMethods.md | 24 +++++++++++++------ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 6c7d764a84..b661f41d8f 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -25,10 +25,11 @@ contract ([SessionMethods §4 rule 8](../../../design/plugins/SessionMethods.md# ## Events and lifetime -No Timeline events or I/O. Each registration tracks the calls it accepted, so its unload can interrupt them and wait. A part depends on `sessionMethods` and -calls `register(ctx, namespace, declarations, call)` from its own `apply`, with the part's own function as `call`; -the registration is withdrawn when that part unloads, and a namespace registered -already fails +No Timeline events or I/O. Each registration tracks the calls it accepted, so +its unload can interrupt them and wait. A part depends on `sessionMethods` and +calls `register(ctx, namespace, declarations, call)` from its own `apply`, with +the part's own function as `call`; the registration is withdrawn when that part +unloads, and a namespace registered already fails ([rutis usage R6](../../../design/rutis-usage.md#r6-contributions-register-with-their-owner)). A refused registration fails the part. A part of another language calls `sessionMethods.register(namespace, declarations, call)` through the bridge; @@ -41,8 +42,7 @@ withdrawn, the table keeps the row that registered it, so a call into it answers `service_reloading` or `service_unavailable` from that row's status. Today a withdrawn namespace whose row is absent from the loader answers `service_reloading`; the target contract answers `unknown_method` there, as it -already does for a disabled row and for a name no namespace ever held. Each registration owns the calls it admitted: its -part's unload interrupts `report` calls and waits for every admitted call. +already does for a disabled row and for a name no namespace ever held. `session.methods` lists the methods of the namespaces registered now that no management namespace holds. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 7796516876..5e5d22ea2c 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -25,7 +25,7 @@ Callers keep: | A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the host's refusal are the owner's | `register` | | Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | | `session.methods` lists what a Session serves | No: the declarations and the namespace that owns each are the owner's | `methods` | -| The caller learns why a registration was refused | Yes: `register` answers `duplicate` or `invalid`; a separate check would race the next registration | Business | +| The caller learns why a registration was refused | Yes: `register` answers `duplicate`, `invalid` or, in the process table, `reserved`; a separate check would race the next registration | Business | | Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `heldNamespaces`; Rpc reads `sessionId` | Business | | A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | | A process-side caller holding a Session asks the table in process, as WebEntry's upload entry does | Yes: the same `call` without a site | Business | @@ -138,17 +138,17 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | -| `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | +| `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. The Session table answers `invalid` for a name it keeps; the process table's registration answers `reserved`. | | `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | -The process table (#2021) serves the same `MethodCall`, `MethodReply` and `MethodError` data — it takes the admission's `CallSite` and its `MethodCall.origin` carries the `Caller`, recorded on #2021 — and its own contract states its reply. It answers `heldNamespaces` (Rust `held_namespaces`) so Rpc routes a name and filters `session.methods` by A.1's routing precedence. +The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so Rpc routes a name and filters `session.methods` by A.1's routing precedence. Its own contract states its operations, data and kinds. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `reserved` (process table only), `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` also answers `invalid` for a malformed request | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` kinds are its contract's | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | `register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. @@ -180,7 +180,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the table's host refusal and the duplicate — the Session table answers `invalid`, the process table `reserved` — then record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The registration's accepted calls settle by their declarations | A withdrawn namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -239,12 +239,22 @@ Flow tests on the owner: | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | | Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +The process table (#2021) does not have to change to serve this contract, but the two tables share the call data and the dispatch's shape, so the process table's contract states the same: + +| Field | Value | +| --- | --- | +| Which feature is blocked, by which rule | Rpc dispatches both tables on every call and depends on no provider (§3.2); a shared `MethodCall`, `MethodReply` and `MethodError` that only one table serves would leave Rpc with two paths. | +| Existing mechanisms considered | Rpc adapting each table's own shapes: rejected, §7 one interface requires one reply per table. Leaving the process table's `call` returning `MethodReply`: blocked by A.2, which needs the caller-index entry and the settlement the reply carries. | +| Generic capability needed | The process table's `call` returns `CallReply { reply, registration, settled }` and takes `Option` like this one, and its `MethodCall.origin` carries the `Caller`. No business meaning. | +| Effect on sequence, batches, interruption, reload | None: the same reply, entry and settlement it serves today, named once. | +| Who implements it, which issue | ManagementMethods' owner, tracked in [#2021](https://github.com/arcships/dim/issues/2021) at head `ff47fb6c8`. | + ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration and `invalid` for a malformed request; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). @@ -632,4 +642,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. A handler's failure carries its own `code`, which becomes the client's `appError`. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. A handler's failure carries its own `code`, which becomes the client's `appError`. From 6ac0401b14fa10c4e18929874929b05fec1fc621 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 09:12:32 +0800 Subject: [PATCH 33/41] docs(sessionmethods): answer the thirty-first pre-review A refused registration never reaches a client in either table, so `invalid`'s client cell is empty and the kind joins the registration-only list. A bridge error without a code is the sixth client-visible failure, and A.1's Registration row carries the notification rules this contract's paragraph points at. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 25 ++++++++++---------- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 9008bfed8f..942d9576da 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -233,7 +233,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Rule | Content | | --- | --- | | Namespace | `(.)*`, segments `[a-z][a-z0-9_]*`, at most 128 bytes, owned by the part that registers it; a namespace may itself be a method (`session.rename`). A namespace outside this grammar is refused when it registers, and a called name outside it is `unknown_method` without any lookup | -| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method, each unique and equal to or inside the namespace) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | +| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method; each name unique and equal to or inside the namespace; each declared notification equal to or inside the namespace, unique across the set and never a method's name) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | | Ownership | A name belongs to the longest namespace registered in that table that prefixes or equals it. A withdrawn namespace keeps holding its names: the table remembers the row that registered it, and a call answers from that row's status (§3.2; Session-scoped call below). A name no namespace of the table ever held has no owner | | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification lies equal to or inside its namespace. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 5e5d22ea2c..6901e33ffb 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -138,7 +138,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | -| `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. The Session table answers `invalid` for a name it keeps; the process table's registration answers `reserved`. | +| `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | | `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so Rpc routes a name and filters `session.methods` by A.1's routing precedence. Its own contract states its operations, data and kinds. @@ -151,7 +151,7 @@ The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` kinds are its contract's | | `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | -`register`'s declarations follow A.1: at least one method; each name equal to or inside the namespace, and unique; each declared notification equal to or inside the namespace, unique across the set and never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. +`register`'s declarations follow A.1's Registration row: at least one method; each name equal to or inside the namespace and unique; each declared notification equal to or inside the namespace, unique across the set, never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. @@ -163,7 +163,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `invalid` | `register` | — (Session); `invalid_params` (process table) | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | +| `invalid` | `register` | — | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | | `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | @@ -171,9 +171,9 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | | `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | -| `closed` | `call`, `methods` | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | +| `closed` | `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | -`reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. +`invalid`, `reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. ### Flows @@ -196,7 +196,7 @@ Flow tests on the owner: - A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. - A native handler receives the call's `Caller` and notifies through it; a handler of another language receives the same caller encoded by the bridge as `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. -- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a call that crossed nothing is `failed` with `-32603`. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a bridge error without a code is `failed` under the rule, and a call that crossed nothing is `failed` with `-32603`. - `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. ## Rule check @@ -213,13 +213,13 @@ Flow tests on the owner: | §4 rule 5 | No batches. | | §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | -| §4 rule 8 | The only infrastructure request is `loaderRows`, a dim-owned process face for one loader row, raised below with its five fields; nothing else changes. | +| §4 rule 8 | The infrastructure requests are `loaderRows`, a dim-owned process face for one loader row, and the shared call shape the process table serves; both are raised below with their five fields. Nothing else changes. | | §4 rule 9 | No Timeline fact. | | §7 values, ids and callbacks | The caller is data on the wire; the site, the `Caller` and the `CallRegistration` are the stated objects, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | -| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations and their last rows are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | +| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller` and `CallRegistration`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | @@ -239,7 +239,7 @@ Flow tests on the owner: | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | | Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | -The process table (#2021) does not have to change to serve this contract, but the two tables share the call data and the dispatch's shape, so the process table's contract states the same: +The process table (#2021) must serve the same shared shape, because Rpc dispatches both tables on one path: | Field | Value | | --- | --- | @@ -251,16 +251,17 @@ The process table (#2021) does not have to change to serve this contract, but th ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the `MethodTable`/`MethodProvider`/`Accepted` shapes and the Session table's `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the Session table's `MethodTable`/`MethodProvider`/`Accepted` shapes and its `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Five client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). - A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). - A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- A bridge error that carries no code of its own is `failed` under the service rule (`-32000`), where today it is `-32603` "Method binding failed" (`crates/dim-agent-capabilities/src/methods.rs:912-918`). Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. @@ -642,4 +643,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. A handler's failure carries its own `code`, which becomes the client's `appError`. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. `MethodCall` carries the `Caller`; the bridge encodes it as `{connectionId, callId}` for another language, which is the only place those two ids appear as a pair. A handler's failure carries its own `code`, which becomes the client's `appError`. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 6e628f51c8..f00a03ab24 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -233,7 +233,7 @@ sequenceDiagram | 规则 | 内容 | | --- | --- | | 命名空间 | `(.)*`,段为 `[a-z][a-z0-9_]*`,最多 128 字节,由注册它的部件拥有;命名空间本身可以是一个方法(`session.rename`)。不符合该语法的命名空间在注册时被拒绝,被调用的名称不符合该语法时不做任何查找,直接为 `unknown_method` | -| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法唯一且等于或位于命名空间内)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | +| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法名唯一且等于或位于命名空间内;每个声明的通知等于或位于命名空间内、在集合内唯一且不等于任何方法名)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | | 所有权 | 名称属于该表中作为其前缀或与其相等的最长已注册命名空间。已撤回的命名空间仍持有它的名称:方法表记住注册它的行,调用按该行的状态作答(§3.2;见下文 Session 级调用)。该表从没有命名空间持有过的名称没有所有者 | | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知等于或位于其命名空间内。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | From 1eb71ac03865adba1de87bc32abca8523f703e39 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 09:29:15 +0800 Subject: [PATCH 34/41] docs(sessionmethods): answer the thirty-second pre-review The lifecycle row restores both unload-ordering guarantees: a registration stops admitting at the first step of its row's unload and waits for its calls, and a foreign row's calls settle while its plugin still runs. The wire's `register` reaches the table's private `register_foreign`, which records the same registration against the bridge's row and mints no call id. --- docs/design/contracts/session-boundary.md | 4 ++-- docs/design/plugins/SessionMethods.md | 20 +++++++++++--------- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 942d9576da..8ad1749660 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -233,7 +233,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Rule | Content | | --- | --- | | Namespace | `(.)*`, segments `[a-z][a-z0-9_]*`, at most 128 bytes, owned by the part that registers it; a namespace may itself be a method (`session.rename`). A namespace outside this grammar is refused when it registers, and a called name outside it is `unknown_method` without any lookup | -| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method; each name unique and equal to or inside the namespace; each declared notification equal to or inside the namespace, unique across the set and never a method's name) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | +| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations and its `call`. The declaration rules — at least one method; names unique and equal to or inside the namespace; notifications equal to or inside it, unique and never a method's name — are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. | In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | | Ownership | A name belongs to the longest namespace registered in that table that prefixes or equals it. A withdrawn namespace keeps holding its names: the table remembers the row that registered it, and a call answers from that row's status (§3.2; Session-scoped call below). A name no namespace of the table ever held has no owner | | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification lies equal to or inside its namespace. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | @@ -526,7 +526,7 @@ carry the native event whole, and the frozen fixtures stay unchanged. | Session reloading, or a withdrawn namespace whose registering row (or its copy in the Session) is not running and has not failed (not started yet, Pending, Loading, or between generations), or a withdrawn Session namespace whose copy is Active or absent | `-32000`, `service_reloading` (retryable) | | A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped | `-32000`, `service_unavailable` (not retryable) | | `report` call interrupted | `-32000`, `operation_interrupted` | -| Handler error | the handler's own JSON-RPC code when it carries one (`MethodCallbackError.wire`), otherwise the code Rpc chooses for a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | +| Handler error | the JSON-RPC code the handler chose, when it chose one, otherwise the code Rpc gives a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | A handler's failure may carry owner-defined JSON fields in `data` beside `data.appError`. The method owner defines and supplies their safe public shape; the method table diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 6901e33ffb..6bd659dccd 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -2,7 +2,7 @@ Scope: session. Issue: #2026. -SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The call data both method tables serve — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — has one definition, in the `methods` module of `dim-agent-capabilities`; this contract states it. ManagementMethods (#2021) is the process table; Rpc, the registering parts, WebEntry's upload entry and `session.methods` are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). +SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The call data both method tables serve — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — has one definition, in the `methods` module of `dim-agent-capabilities`; this contract states it. ManagementMethods (#2021) is the process table; Rpc, the registering parts and WebEntry's upload entry are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). ## Use and scope: responsibility split @@ -101,7 +101,8 @@ let admitted = match methods.call(method.into(), params, None, cancelled, |_| {} Err(MethodError::Reloading) => return Err(RpcError::reloading()), Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), Err(MethodError::Closed) => return Err(RpcError::closed()), - Err(MethodError::Invalid { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) | Err(MethodError::Interrupted) => unreachable!("a Session call answers none of these"), + Err(MethodError::Invalid { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) => unreachable!("a Session call answers none of these"), + Err(MethodError::Interrupted) => unreachable!("an interruption answers in reply.reply, not as the outer error"), }; let CallReply { reply, settled, .. } = admitted; // No connection wrote a reply here: `reply` is the handler's answer, or the @@ -153,7 +154,7 @@ The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so `register`'s declarations follow A.1's Registration row: at least one method; each name equal to or inside the namespace and unique; each declared notification equal to or inside the namespace, unique across the set, never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. -`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. +`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. A registration of another language has no part `&Ctx`, so the dispatch calls the table's private `register_foreign(instance, namespace, declarations, call)`: it records the same registration against the row instance the bridge names, and `register` is the native entry that passes its part's instance and generation. Neither entry mints a call id or records a caller-index entry — both belong to a call, and `call` derives them from the site it is given. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. `caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and that connection's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. @@ -170,7 +171,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | -| `closed` | `register` | — | The table is closing. The registration fails with the part that made it; the replacement part registers in the next generation: the next Session for a Session table, the next process for the process table | +| `closed` | `register` | — | The table is closing. The registration fails with the part that made it, and the row's next generation registers again: the next Session for a Session table, the next process for the process table | | `closed` | `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | `invalid`, `reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. @@ -179,7 +180,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the table's host refusal and the duplicate — the Session table answers `invalid`, the process table `reserved` — then record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `register` | Check the namespace grammar and the declarations (A.1), then the table's host refusal and the duplicate — the Session table answers `invalid`, the process table `reserved` — then record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | | `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | @@ -217,9 +218,9 @@ Flow tests on the owner: | §4 rule 9 | No Timeline fact. | | §7 values, ids and callbacks | The caller is data on the wire; the site, the `Caller` and the `CallRegistration` are the stated objects, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | -| §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the Rust binding and the wire call the same functions. | +| §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the two entries record one registration: the wire's `register` reaches `register_foreign` and the Rust one `register`. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | -| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. A registration lives until its row unloads; the table ends with its Session, and its admitted calls settle by their declarations first. | +| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller` and `CallRegistration`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | @@ -251,7 +252,7 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the Session table's `MethodTable`/`MethodProvider`/`Accepted` shapes and its `owner`/`provider`/`holds`/`listed` readers are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the shapes it used to define — the Session table's `MethodTable`/`MethodProvider`/`Accepted` and its `owner`/`provider`/`holds`/`listed` readers — are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible failure changes: @@ -315,7 +316,8 @@ pub enum Interruption { } /// The call's progress sink (A.2). The table hands it to a handler whose -/// declaration declares `progress` and closes it before the reply is written. +/// declaration declares `progress`; one whose declaration does not receives a +/// sink whose sends are dropped. It closes before the reply is written. #[derive(Clone)] pub struct Progress(/* the calling connection's sink */); diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index f00a03ab24..1542772197 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -233,7 +233,7 @@ sequenceDiagram | 规则 | 内容 | | --- | --- | | 命名空间 | `(.)*`,段为 `[a-z][a-z0-9_]*`,最多 128 字节,由注册它的部件拥有;命名空间本身可以是一个方法(`session.rename`)。不符合该语法的命名空间在注册时被拒绝,被调用的名称不符合该语法时不做任何查找,直接为 `unknown_method` | -| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法名唯一且等于或位于命名空间内;每个声明的通知等于或位于命名空间内、在集合内唯一且不等于任何方法名)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | +| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明和它的 `call` 注册到其作用域的方法表。声明规则——至少一个方法;方法名唯一且等于或位于命名空间内;通知等于或位于其命名空间内、在集合内唯一且不等于任何方法名——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | | 所有权 | 名称属于该表中作为其前缀或与其相等的最长已注册命名空间。已撤回的命名空间仍持有它的名称:方法表记住注册它的行,调用按该行的状态作答(§3.2;见下文 Session 级调用)。该表从没有命名空间持有过的名称没有所有者 | | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知等于或位于其命名空间内。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | From 35d8f848dc16534bc2b1b4056d664cd3c0f65181 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 09:45:51 +0800 Subject: [PATCH 35/41] docs(sessionmethods): answer the thirty-third pre-review `register_foreign` takes the calling row's `&Ctx`, so a registration of another language binds the same generation and unload and is recorded as foreign. A.1's Registration row is two cells again, and its declaration rules point here. The bridge's `MethodCall` shape, the foreign registration's `invalid` and the Supersedes bullets for A.2 are stated. --- docs/design/contracts/session-boundary.md | 8 ++++---- docs/design/plugins/SessionMethods.md | 13 +++++++------ docs/zh/design/contracts/session-boundary.md | 6 +++--- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 8ad1749660..08980046da 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -202,7 +202,7 @@ The implemented foreign Session subset is [C4](../session-typescript.md); genera ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. A handler of another language receives its call as `{method, params, origin?: {caller: {connectionId, callId?}}}`, the bridge's encoding of `MethodCall`. ### A.1 Method contributions @@ -233,9 +233,9 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Rule | Content | | --- | --- | | Namespace | `(.)*`, segments `[a-z][a-z0-9_]*`, at most 128 bytes, owned by the part that registers it; a namespace may itself be a method (`session.rename`). A namespace outside this grammar is refused when it registers, and a called name outside it is `unknown_method` without any lookup | -| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations and its `call`. The declaration rules — at least one method; names unique and equal to or inside the namespace; notifications equal to or inside it, unique and never a method's name — are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. | In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | +| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations and its `call`. The declaration rules — at least one method; names unique and equal to or inside the namespace; notifications equal to or inside it, unique and never a method's name — are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | | Ownership | A name belongs to the longest namespace registered in that table that prefixes or equals it. A withdrawn namespace keeps holding its names: the table remembers the row that registered it, and a call answers from that row's status (§3.2; Session-scoped call below). A name no namespace of the table ever held has no owner | -| Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification lies equal to or inside its namespace. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | +| Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). The declaration and notification rules are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | @@ -571,7 +571,7 @@ A refused registration fails the registering part: the namespace and its declara `Progress` binds A.2 `progress` per call rather than through a `callChannel` process service: Rpc passes each admitted call a sink that writes `management.progress {id, method, data}` to the calling connection, and the table's `call` hands it to the handler only when the method declares `progress` and closes it before the reply is written. The sink queues progress under its own allowance on the connection, so progress never takes room from the reply or durable notifications. Management methods use the same path; `runtime.watch` and `schedule.watch` declare `progress` ([RuntimeManager §10](../plugins/RuntimeManager.md#10-client-change-notices); [Scheduler §11.2](../plugins/Scheduler.md#112-jobs-and-runs)). -`Caller`, `CallerConnection`, `CallSite`, `Progress` and `NotifyError` are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's; it states their shape and lifecycle, and this appendix keeps only the module they live in. +`Caller`, `CallerConnection`, `CallSite`, `Progress` and `NotifyError` live in the module's binding, stated by [SessionMethods](../plugins/SessionMethods.md#binding-appendix); this appendix states what CallChannel does with them, not their shape. `Caller` binds A.2 `notify` and `closed` per call, like `Progress`: the table's `call` builds it only when the call arrived on a client connection, bound to the notifications its declaration set declared, so a name outside that set is `Undeclared` before anything is written, and a generation that has unloaded is `Gone` first. It holds the connection through a trait object (`CallerConnection`) that keeps no strong reference to it, so a provider that keeps a `Caller` does not keep a closed connection alive. Rpc writes each notification after the reply of the call that produced the caller: one sent while the call runs is encoded once, admitted under the connection's held allowance, held in order and flushed right after the reply; one over the frame limit is `TooLarge` and the connection stays open, and one the held allowance cannot take closes the connection as a slow consumer. The caller resolves `closed` when the connection closes or the admitting Rpc load unloads. diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 6bd659dccd..51612885b6 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -154,7 +154,7 @@ The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so `register`'s declarations follow A.1's Registration row: at least one method; each name equal to or inside the namespace and unique; each declared notification equal to or inside the namespace, unique across the set, never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. -`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. A registration of another language has no part `&Ctx`, so the dispatch calls the table's private `register_foreign(instance, namespace, declarations, call)`: it records the same registration against the row instance the bridge names, and `register` is the native entry that passes its part's instance and generation. Neither entry mints a call id or records a caller-index entry — both belong to a call, and `call` derives them from the site it is given. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. +`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. The dispatch calls the table's private `register_foreign(caller: &Ctx, namespace, declarations, call)`: the bridge hands it the calling row's `&Ctx`, so the registration is bound to that row's generation and unload exactly as a native one is, and the table records it as foreign so its `call` mints a call id. `register` is the native entry with the same body minus that record. Neither entry records a caller-index entry — that belongs to a call, and `call` derives it from the site it is given. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. `caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and that connection's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. @@ -180,7 +180,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the namespace grammar and the declarations (A.1), then the table's host refusal and the duplicate — the Session table answers `invalid`, the process table `reserved` — then record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `register` | Check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | | `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | @@ -238,7 +238,7 @@ Flow tests on the owner: | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has or a row that is disabled. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1307-1315` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | The process table (#2021) must serve the same shared shape, because Rpc dispatches both tables on one path: @@ -253,14 +253,15 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the shapes it used to define — the Session table's `MethodTable`/`MethodProvider`/`Accepted` and its `owner`/`provider`/`holds`/`listed` readers — are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F keeps what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F states what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind, and `Callers` stays its own private wiring. +- [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible failure changes: - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). - A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). -- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). +- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). A registration of another language whose declarations cannot be decoded fails as `invalid`, where today the bridge's `bad-value` names the decode; no client sees either. - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). - A bridge error that carries no code of its own is `failed` under the service rule (`-32000`), where today it is `-32603` "Method binding failed" (`crates/dim-agent-capabilities/src/methods.rs:912-918`). @@ -645,4 +646,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. `MethodCall` carries the `Caller`; the bridge encodes it as `{connectionId, callId}` for another language, which is the only place those two ids appear as a pair. A handler's failure carries its own `code`, which becomes the client's `appError`. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. `MethodCall` carries the `Caller`; a handler of another language receives it as the bridge's JSON shape. A handler's failure carries its own `code`, which becomes the client's `appError`. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 1542772197..cd22fa827f 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -235,7 +235,7 @@ sequenceDiagram | 命名空间 | `(.)*`,段为 `[a-z][a-z0-9_]*`,最多 128 字节,由注册它的部件拥有;命名空间本身可以是一个方法(`session.rename`)。不符合该语法的命名空间在注册时被拒绝,被调用的名称不符合该语法时不做任何查找,直接为 `unknown_method` | | 注册 | 部件在自己的 `apply` 中把命名空间连同其声明和它的 `call` 注册到其作用域的方法表。声明规则——至少一个方法;方法名唯一且等于或位于命名空间内;通知等于或位于其命名空间内、在集合内唯一且不等于任何方法名——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | | 所有权 | 名称属于该表中作为其前缀或与其相等的最长已注册命名空间。已撤回的命名空间仍持有它的名称:方法表记住注册它的行,调用按该行的状态作答(§3.2;见下文 Session 级调用)。该表从没有命名空间持有过的名称没有所有者 | -| 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知等于或位于其命名空间内。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | +| 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明与通知的规则归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | | Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | @@ -495,7 +495,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | Session 正在重载,或已撤回命名空间的注册行(或其在该 Session 中的副本)未运行且未失败(尚未启动、Pending、Loading,或新旧两代之间),或已撤回 Session 命名空间的副本处于 Active 或不存在 | `-32000`,`service_reloading`(可重试) | | 已撤回命名空间的注册行,或该行在该 Session 中的副本,处于 Failed、Unresolved、Disposed 或 Stopped | `-32000`,`service_unavailable`(不可重试) | | `report` 调用被中断 | `-32000`,`operation_interrupted` | -| 处理函数错误 | 处理函数自带的 JSON-RPC 码(`MethodCallbackError.wire`),否则为 Rpc 为服务错误选择的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` 与其所有者字段 | +| 处理函数错误 | 处理函数自选的 JSON-RPC 码,未选则为 Rpc 为服务错误给出的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` 与其所有者字段 | ## 附录 D. 验收 @@ -534,7 +534,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 `Progress` 按调用绑定 A.2 的 `progress`,而不是通过 `callChannel` 进程服务:Rpc 给每个已受理调用一个 sink,把 `management.progress {id, method, data}` 写到发起调用的连接;方法表的 `call` 只在方法声明了 `progress` 时把它交给处理函数,并在回复写出之前关闭它。sink 在连接上按进度自己的额度排队,所以进度不会占用回复和持久通知的空间。管理方法走同一路径;`runtime.watch` 与 `schedule.watch` 声明了 `progress`([RuntimeManager §10](../plugins/RuntimeManager.md#10-客户端变更通知);[Scheduler §11.2](../plugins/Scheduler.md#112-任务与运行))。 -`Caller`、`CallerConnection`、`CallSite`、`Progress` 与 `NotifyError` 是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定;该附录给出它们的形状与生命周期,本附录只说明它们所在的模块。 +`Caller`、`CallerConnection`、`CallSite`、`Progress` 与 `NotifyError` 位于模块的绑定里,形状由 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 给出;本附录说明 CallChannel 如何用它们,不说明其形状。 `Caller` 与 `Progress` 一样按调用绑定 A.2 的 `notify` 与 `closed`:只有调用来自客户端连接时方法表的 `call` 才构造它,并绑定到该声明集声明的通知,因此集合外的名称在写入任何内容之前就是 `Undeclared`,已卸载的代际则先返回 `Gone`。它通过 `CallerConnection` 这个 trait 对象持有连接,而该对象不强引用连接,所以保留 `Caller` 的提供方不会让已关闭的连接存活。Rpc 在产生该 `Caller` 的调用回复之后写出每条通知:调用进行中发出的通知只编码一次,经连接的暂存额度受理,按序暂存,紧接回复之后写出;超过帧上限的通知是 `TooLarge`,连接保持;暂存额度收不下的通知作为慢消费者关闭连接。连接关闭或受理该调用的 Rpc 代际卸载时,`closed` 完成。 From 86a909a4d056dfbf3db69991df2434916dd75acf Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 10:01:25 +0800 Subject: [PATCH 36/41] docs(sessionmethods): answer the thirty-fourth pre-review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The settlement future is the fourth hand-out in Exceptions and the §7 rows. A.1's foreign call shape carries `callId` inside `caller` and its zh mirror is restored, the loader row's citation is `lib.rs:1476-1482`, and Supersedes scopes Appendix F to the Session table's paragraphs. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 10 +++++----- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 08980046da..b09cb10faf 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -202,7 +202,7 @@ The implemented foreign Session subset is [C4](../session-typescript.md); genera ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. A handler of another language receives its call as `{method, params, origin?: {caller: {connectionId, callId?}}}`, the bridge's encoding of `MethodCall`. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. A handler of another language receives its call as `{method, params, origin?: {caller: {connectionId, callId}}}`, the bridge's encoding of `MethodCall`; `callId` is present exactly when the call arrived on a connection, and `origin` is absent for a call that did not. ### A.1 Method contributions diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 51612885b6..2bf4aa791c 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -186,7 +186,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err ## Exceptions with reasons -- Three handles cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all three: Rpc builds the site for one call and hands it to `call`; the table holds it, binds its serving generation's declared notifications to the `Caller`, and drops it when the call settles; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the three keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- Four hand-outs cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written, plus the `settled` future that resolves when the call has settled. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all four: Rpc builds the site for one call and hands it to `call`; the table holds it, binds its serving generation's declared notifications to the `Caller`, and drops it when the call settles; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the four keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -216,13 +216,13 @@ Flow tests on the owner: | §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | | §4 rule 8 | The infrastructure requests are `loaderRows`, a dim-owned process face for one loader row, and the shared call shape the process table serves; both are raised below with their five fields. Nothing else changes. | | §4 rule 9 | No Timeline fact. | -| §7 values, ids and callbacks | The caller is data on the wire; the site, the `Caller` and the `CallRegistration` are the stated objects, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | +| §7 values, ids and callbacks | The caller is data on the wire; the site, the `Caller`, the `CallRegistration` and the settlement future are the stated objects, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the two entries record one registration: the wire's `register` reaches `register_foreign` and the Rust one `register`. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | | §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | -| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller` and `CallRegistration`; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | +| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller`, `CallRegistration` and settlement future; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | | ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | | ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | @@ -238,7 +238,7 @@ Flow tests on the owner: | Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | | Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has or a row that is disabled. No business meaning. | | Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | -| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1307-1315` creates the loader row; the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader (`LoaderPlugin`); the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | The process table (#2021) must serve the same shared shape, because Rpc dispatches both tables on one path: @@ -253,7 +253,7 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch ## Supersedes - [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the shapes it used to define — the Session table's `MethodTable`/`MethodProvider`/`Accepted` and its `owner`/`provider`/`holds`/`listed` readers — are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its `Handler`, `MethodCall`/`Origin` and foreign `register` decode are this contract's [binding below](#binding-appendix), and Appendix F links here. `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref leave; Appendix F states what CallChannel, ManagementMethods (its own storage and read) and ToolRegistry bind, and `Callers` stays its own private wiring. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its Session-table paragraphs — `Handler`, `MethodCall`/`Origin`, the foreign `register` decode, `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. - [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible failure changes: diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index cd22fa827f..1a93422729 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -202,7 +202,7 @@ sequenceDiagram ## 附录 A. 接口细节 -结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 契约;处理函数以自己的 `{code, message, ...所有者字段}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError, ...所有者字段}}`。 +结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 契约;处理函数以自己的 `{code, message, ...所有者字段}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError, ...所有者字段}}`。另一种语言的处理函数收到的调用是 `{method, params, origin?: {caller: {connectionId, callId}}}`,即 `MethodCall` 的桥接编码;`callId` 只在调用来自连接时出现,未来自连接的调用没有 `origin`。 ### A.1 方法贡献 From 501486abfed2fc072bfa7fb7383204ecd3810d1e Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 10:11:03 +0800 Subject: [PATCH 37/41] docs(sessionmethods): answer the mock-zb review The Session's close ends admission: the table injects `sessionLifecycle` and answers `closed` from `closing()` before any row unloads, and no handler runs. `loaderRows` is optional, falling back to today's `reloading` for a withdrawn namespace, and `session.methods` names its `service_unavailable` while the process closes. Withdrawal order and the handler's freedom from the table lock are stated. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 29 +++++++++++--------- docs/zh/design/contracts/session-boundary.md | 2 +- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index b09cb10faf..93a0af96df 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -141,7 +141,7 @@ Methods have no model-visible effect. A method that changes model context does s | `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; the registering row is the binding's `&Ctx`, not a request field, and the shape is [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | -| `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `unknown_method`, `reloading`, `unavailable` or `closed`, and an interruption answers in its reply ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `closed` once the Session is closing, else `unknown_method`, `reloading` or `unavailable`, and an interruption answers in its reply ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | The declarations of the namespaces the Session registered now | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | | `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented; `Progress` and `Caller` are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s) | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 2bf4aa791c..3e8883bceb 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -140,7 +140,8 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `P:loaderRows` (proposed dim-owned process face) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. | +| `sessionLifecycle` (the Session's own lifecycle service) | The Session's publication and close. The table reads `closing()`: once the Session starts closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. | +| `P:loaderRows` (proposed dim-owned process face; optional) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. It is an `Option>`: while the assembly names none, a withdrawn namespace answers `reloading`, as today; once it is installed, the rules above apply. | The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so Rpc routes a name and filters `session.methods` by A.1's routing precedence. Its own contract states its operations, data and kinds. @@ -149,14 +150,14 @@ The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `reserved` (process table only), `duplicate`, `closed` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `unknown_method`, `reloading`, `unavailable`, `closed`; an interruption answers in `reply.reply`. The process table's `call` kinds are its contract's | -| `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `closed` once the Session is closing, else `unknown_method`, `reloading`, `unavailable`; an interruption answers in `reply.reply`. The process table's `call` kinds are its contract's | +| `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed`, `unavailable` (the process is closing) | `register`'s declarations follow A.1's Registration row: at least one method; each name equal to or inside the namespace and unique; each declared notification equal to or inside the namespace, unique across the set, never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. `register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. The dispatch calls the table's private `register_foreign(caller: &Ctx, namespace, declarations, call)`: the bridge hands it the calling row's `&Ctx`, so the registration is bound to that row's generation and unload exactly as a native one is, and the table records it as foreign so its `call` mints a call id. `register` is the native entry with the same body minus that record. Neither entry records a caller-index entry — that belongs to a call, and `call` derives it from the site it is given. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. -`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and that connection's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. +`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and that connection's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The handler runs outside the table's lock: the table serializes only its own state changes, and two calls run concurrently. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message, ...owner fields}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. @@ -171,8 +172,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | -| `closed` | `register` | — | The table is closing. The registration fails with the part that made it, and the row's next generation registers again: the next Session for a Session table, the next process for the process table | -| `closed` | `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table ended with its Session or process. A Session table: re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | +| `closed` | `register`, `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table is closing or has ended. A Session table: the Session's `closing()` already answers it, before any row unloads, and no handler runs; re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | `invalid`, `reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. @@ -180,8 +180,8 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | +| `register` | Refuse at once while the Session is closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `call` | Refuse at once while the Session is closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | A namespace stops being registered before its last row is recorded, so a call sees it registered or finds the recorded row after it is withdrawn. A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -198,7 +198,9 @@ Flow tests on the owner: - A native handler receives the call's `Caller` and notifies through it; a handler of another language receives the same caller encoded by the bridge as `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a bridge error without a code is `failed` under the rule, and a call that crossed nothing is `failed` with `-32603`. -- `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. +- `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns, and a closing process makes it answer `service_unavailable`. +- Once the Session starts closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. +- While `loaderRows` is not installed, a withdrawn namespace answers `reloading`; installed, a missing row or a disabled one is `unknown_method`. ## Rule check @@ -206,7 +208,7 @@ Flow tests on the owner: | --- | --- | | §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and, once it exists, `loaderRows`. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | -| §3 orthogonality | No other business owner's state is read or changed; `reservedMethods` and `loaderRows` are the mechanism's faces. | +| §3 orthogonality | No other business owner's state is read or changed; `sessionLifecycle`, `reservedMethods` and `loaderRows` are the mechanism's services. | | §4 rule 1 | No command event: a registration is the calling row's effect. | | §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | | §4 rule 3 | No before callback. | @@ -220,7 +222,7 @@ Flow tests on the owner: | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the two entries record one registration: the wire's `register` reaches `register_foreign` and the Rust one `register`. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | -| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | +| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. The Session closing ends admission first: `closing()` answers `closed` for `register` and `call` before any row unloads, and no handler runs. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller`, `CallRegistration` and settlement future; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | @@ -256,8 +258,9 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its Session-table paragraphs — `Handler`, `MethodCall`/`Origin`, the foreign `register` decode, `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. - [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Seven client-visible failure changes: +- A Session that is closing answers `closed` for `register` and `call` from `closing()`, before any row unloads; today the table keeps admitting until its rows unload. - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). - A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). @@ -265,7 +268,7 @@ No existing client method changes and no error kind is removed. The table adds o - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). - A bridge error that carries no code of its own is `failed` under the service rule (`-32000`), where today it is `-32603` "Method binding failed" (`crates/dim-agent-capabilities/src/methods.rs:912-918`). -Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. +`session.methods` gains one failure: while the process is closing, it cannot filter the names a management namespace holds and answers `service_unavailable`. Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. ## Binding appendix diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 1a93422729..bbe30245c5 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -141,7 +141,7 @@ sequenceDiagram | `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;注册行是绑定的 `&Ctx`,不是请求字段,形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | -| `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;方法表回答 `unknown_method`、`reloading`、`unavailable` 或 `closed`,中断在其回复里作答([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;Session 一开始 closing 就答 `closed`,否则为 `unknown_method`、`reloading` 或 `unavailable`,中断在其回复里作答([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | | `sessionMethods.methods {}` | sync | 该 Session 现在注册的命名空间的声明 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | | `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现;`Progress` 与 `Caller` 归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)) | From baa113e81606bbebbac2a35d3ec6ab0fc6edd139 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 10:18:38 +0800 Subject: [PATCH 38/41] docs(sessionmethods): answer the mock-yy review The row is recorded before the namespace stops being registered, because its effect was registered last and runs first. A caller that stops waiting leaves its call running. A.1's Call ownership speaks of a registration, not a provider generation, and the shared handler and call types are credited to Appendix F. --- .../rust-agent/plugins/SessionMethods.md | 5 +++-- docs/design/contracts/session-boundary.md | 6 +++--- docs/design/plugins/SessionMethods.md | 14 +++++++------- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index b661f41d8f..fae3f6eaa6 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -34,8 +34,9 @@ unloads, and a namespace registered already fails A refused registration fails the part. A part of another language calls `sessionMethods.register(namespace, declarations, call)` through the bridge; the registration belongs to the calling row, and `call` is the row's function, -called back through the bridge. The table provides that entry itself, at its -dispatcher key, with the native service. +called back through the bridge. Today `ForeignMethods` provides that entry; +the target removes it, and the table serves the entry itself at its dispatcher +key. A name belongs to the longest namespace that holds it. When a namespace is withdrawn, the table keeps the row that registered it, so a call into it answers diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 93a0af96df..b376ba432a 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table; `MethodDecl` is A.1's declaration block below. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -239,7 +239,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | | Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | -| Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | +| Call ownership | Each registration owns the calls it admitted, as a management registration does: it replies to them, its row's unload interrupts them per `interruption` and waits for them (Cancellation above) | | Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | @@ -526,7 +526,7 @@ carry the native event whole, and the frozen fixtures stay unchanged. | Session reloading, or a withdrawn namespace whose registering row (or its copy in the Session) is not running and has not failed (not started yet, Pending, Loading, or between generations), or a withdrawn Session namespace whose copy is Active or absent | `-32000`, `service_reloading` (retryable) | | A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped | `-32000`, `service_unavailable` (not retryable) | | `report` call interrupted | `-32000`, `operation_interrupted` | -| Handler error | the JSON-RPC code the handler chose, when it chose one, otherwise the code Rpc gives a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | +| Handler error | the JSON-RPC code the handler's failure carries, when it carries one, otherwise the code Rpc gives a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | A handler's failure may carry owner-defined JSON fields in `data` beside `data.appError`. The method owner defines and supplies their safe public shape; the method table diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 3e8883bceb..13c022678e 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -168,7 +168,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `invalid` | `register` | — | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, or the row that registered its withdrawn namespace is disabled or absent. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, the row that registered its withdrawn namespace is disabled or absent, or — for the process table — its row is Active without registering the namespace again. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | @@ -181,12 +181,12 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Refuse at once while the Session is closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Refuse at once while the Session is closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops the future; the accepted call settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | A namespace stops being registered before its last row is recorded, so a call sees it registered or finds the recorded row after it is withdrawn. A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | +| `call` | Refuse at once while the Session is closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | A namespace's last row is recorded before it stops being registered, so a call sees it registered or finds the recorded row | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — the row's effect was registered last, so it runs first — and a call therefore sees the namespace registered or finds the recorded row. A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons -- Four hand-outs cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written, plus the `settled` future that resolves when the call has settled. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all four: Rpc builds the site for one call and hands it to `call`; the table holds it, binds its serving generation's declared notifications to the `Caller`, and drops it when the call settles; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. None of the four keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. +- Four hand-outs cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written, plus the `settled` future that resolves when the call has settled. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all four: Rpc builds the site for one call and hands it to `call`; the table holds it, binds its serving generation's declared notifications to the `Caller`, and drops it when the call settles; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. No handle keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. ## Verification @@ -250,12 +250,12 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch | Existing mechanisms considered | Rpc adapting each table's own shapes: rejected, §7 one interface requires one reply per table. Leaving the process table's `call` returning `MethodReply`: blocked by A.2, which needs the caller-index entry and the settlement the reply carries. | | Generic capability needed | The process table's `call` returns `CallReply { reply, registration, settled }` and takes `Option` like this one, and its `MethodCall.origin` carries the `Caller`. No business meaning. | | Effect on sequence, batches, interruption, reload | None: the same reply, entry and settlement it serves today, named once. | -| Who implements it, which issue | ManagementMethods' owner, tracked in [#2021](https://github.com/arcships/dim/issues/2021) at head `ff47fb6c8`. | +| Who implements it, which issue | ManagementMethods' owner, tracked in [#2021](https://github.com/arcships/dim/issues/2021); its PR is not open yet, and the link is added when it is. | ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the shapes it used to define — the Session table's `MethodTable`/`MethodProvider`/`Accepted` and its `owner`/`provider`/`holds`/`listed` readers — are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its Session-table paragraphs — `Handler`, `MethodCall`/`Origin`, the foreign `register` decode, `MethodProvider`, `Check`, `Owner`, the Session table's `MethodTable` storage and the `SessionMethods` deref — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the Session table's `owner`/`provider`/`holds`/`listed` readers it used to define are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its paragraphs for the Session table's shapes and the shared call data — `MethodProvider`, `Accepted`, `Check`, `Owner`, the Session table's `MethodTable` storage, the `SessionMethods` deref, `Handler`, `MethodCall`/`Origin` and the foreign `register` decode — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. - [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Seven client-visible failure changes: @@ -649,4 +649,4 @@ impl HostDispatch for SessionMethods { } ``` -`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. `MethodCall` carries the `Caller`; a handler of another language receives it as the bridge's JSON shape. A handler's failure carries its own `code`, which becomes the client's `appError`. +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. `MethodCall` carries the `Caller`; a handler of another language receives it as the bridge's JSON shape. A handler's failure carries a `code`, or Rpc's mapping supplies one for an `AgentError` or a rethrown nested error; that code becomes the client's `appError`. From c86233adea10569a1b61aa15c09eeafebaa56477 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 10:21:58 +0800 Subject: [PATCH 39/41] docs(sessionmethods): answer the mock-zb delta MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `call` flow row is six cells again, with caller unload, owner close and settlement in their own columns. `methods` names `service_unavailable` with its next step, §1 lists the three injections, and a declaration's wire fields and the call data's types each have one home. --- docs/design/contracts/session-boundary.md | 4 ++-- docs/design/plugins/SessionMethods.md | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index b376ba432a..4881c9e69b 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table; `MethodDecl` is A.1's declaration block below. The call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. A declaration's wire fields are A.1's declaration block below; the types that carry the call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -243,7 +243,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | -| `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | +| `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. It answers `service_unavailable` while the process is closing, because it cannot read the names a management namespace holds. v3 `hello.features` lists it where Session operations are served | | Ready latch | The native binding waits for its required process providers before the first `hello`. The [TS process binding](../process-typescript.md#21-startup-and-availability) excludes optional extension rows from host startup/restart readiness; `hello.features` lists only the namespaces registered at that call, with later ones visible at the next `hello`. | How Rpc routes a call once the connection's entry admits it: diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 13c022678e..169daa349f 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -165,6 +165,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | +| `unavailable` | `methods` | `service_unavailable` | The process is closing, so Rpc cannot filter the names a management namespace holds. Read the listing from the next process; the Session's own methods keep working through `call` | | `invalid` | `register` | — | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | @@ -181,7 +182,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Refuse at once while the Session is closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Refuse at once while the Session is closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement; on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | A namespace's last row is recorded before it stops being registered, so a call sees it registered or finds the recorded row | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — the row's effect was registered last, so it runs first — and a call therefore sees the namespace registered or finds the recorded row. A withdrawn Session namespace answers from its row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The table for admission and settlement; the handler for its effects | +| `call` | Refuse at once while the Session is closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement — and on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — its effect was registered last, so it runs first — and a withdrawn Session namespace answers from that row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The registration's unload effect for settlement; the table for admission | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -206,7 +207,7 @@ Flow tests on the owner: | Rule | Application | | --- | --- | -| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and, once it exists, `loaderRows`. | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the Session's lifecycle, the host's reserved names when the assembly names them and, once it exists, `loaderRows`. | | §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | | §3 orthogonality | No other business owner's state is read or changed; `sessionLifecycle`, `reservedMethods` and `loaderRows` are the mechanism's services. | | §4 rule 1 | No command event: a registration is the calling row's effect. | From 409bb35900bcb0830683cea71ace88bb6357f0b1 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 10:24:07 +0800 Subject: [PATCH 40/41] docs(sessionmethods): answer both mock deltas The register flow records the row before the registration is withdrawn, and the call flow keeps six cells. `methods` no longer claims `unavailable`; that failure stays in the change note and A.4. The closing check is the synchronous `phase()`, `loaderRows`' absence is stated in the two absence kinds, and the wire-code, MethodDecl, deref and Supersedes wording is corrected. --- docs/design/contracts/session-boundary.md | 4 +-- docs/design/plugins/SessionMethods.md | 34 +++++++++++------------ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 4881c9e69b..a4f176edfc 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -58,7 +58,7 @@ flowchart LR | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. A declaration's wire fields are A.1's declaration block below; the types that carry the call data — `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError` — are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. A declaration's wire fields are A.1's declaration block below; the call-data types it names — `MethodDecl`, `MethodCall`, `MethodReply` and `MethodError` — are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -565,7 +565,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | | `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The Session table no longer derefs to `MethodTable`. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The target removes the deref: the Session table holds its own storage and does not deref to `MethodTable`. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 169daa349f..3715c4c742 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -140,7 +140,7 @@ let listed = declarations.into_iter().filter(|decl| { | Service | Purpose | | --- | --- | | `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | -| `sessionLifecycle` (the Session's own lifecycle service) | The Session's publication and close. The table reads `closing()`: once the Session starts closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. | +| `sessionLifecycle` (the Session's own lifecycle service) | The Session's publication and close. The table reads `phase()`: `SessionPhase::Closing` is a synchronous check, and once it reads closing — before any row unloads — `register` and `call` answer `closed` and no handler runs. | | `P:loaderRows` (proposed dim-owned process face; optional) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. It is an `Option>`: while the assembly names none, a withdrawn namespace answers `reloading`, as today; once it is installed, the rules above apply. | The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so Rpc routes a name and filters `session.methods` by A.1's routing precedence. Its own contract states its operations, data and kinds. @@ -151,7 +151,7 @@ The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `reserved` (process table only), `duplicate`, `closed` | | `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `closed` once the Session is closing, else `unknown_method`, `reloading`, `unavailable`; an interruption answers in `reply.reply`. The process table's `call` kinds are its contract's | -| `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed`, `unavailable` (the process is closing) | +| `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | `register`'s declarations follow A.1's Registration row: at least one method; each name equal to or inside the namespace and unique; each declared notification equal to or inside the namespace, unique across the set, never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. @@ -165,15 +165,14 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Kind | Operation | Client `appError` | What the caller does next | | --- | --- | --- | --- | -| `unavailable` | `methods` | `service_unavailable` | The process is closing, so Rpc cannot filter the names a management namespace holds. Read the listing from the next process; the Session's own methods keep working through `call` | | `invalid` | `register` | — | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, the row that registered its withdrawn namespace is disabled or absent, or — for the process table — its row is Active without registering the namespace again. Check the name and the namespace's declarations; an absent row is a configuration problem | -| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | +| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, the row that registered its withdrawn namespace is disabled or absent — `loaderRows` installed —, or — for the process table — its row is Active without registering the namespace again. While `loaderRows` is absent a withdrawn namespace answers `reloading`, never this kind. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. While `loaderRows` is absent, every withdrawn namespace answers this. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | -| `closed` | `register`, `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table is closing or has ended. A Session table: the Session's `closing()` already answers it, before any row unloads, and no handler runs; re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | +| `closed` | `register`, `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table is closing or has ended. A Session table: `phase()` reads `Closing`, before any row unloads, and no handler runs; re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | `invalid`, `reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. @@ -181,8 +180,8 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Refuse at once while the Session is closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Refuse at once while the Session is closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement — and on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — its effect was registered last, so it runs first — and a withdrawn Session namespace answers from that row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The registration's unload effect for settlement; the table for admission | +| `register` | Refuse at once once `phase()` reads closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | Its last row is recorded before the registration is withdrawn — the record's effect was registered last, so it runs first — and the registration ends with the row | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `call` | Refuse at once once `phase()` reads closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement — and on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — its effect was registered last, so it runs first — and a withdrawn Session namespace answers from that row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The registration's unload effect for settlement; the table for admission | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -200,7 +199,7 @@ Flow tests on the owner: - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a bridge error without a code is `failed` under the rule, and a call that crossed nothing is `failed` with `-32603`. - `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns, and a closing process makes it answer `service_unavailable`. -- Once the Session starts closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. +- Once `phase()` reads closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. - While `loaderRows` is not installed, a withdrawn namespace answers `reloading`; installed, a missing row or a disabled one is `unknown_method`. ## Rule check @@ -223,7 +222,7 @@ Flow tests on the owner: | §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | | §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the two entries record one registration: the wire's `register` reaches `register_foreign` and the Rust one `register`. | | §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | -| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. The Session closing ends admission first: `closing()` answers `closed` for `register` and `call` before any row unloads, and no handler runs. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | +| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. The Session closing ends admission first: `phase()` reading `Closing` answers `closed` for `register` and `call` before any row unloads, and no handler runs. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | | §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | | §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller`, `CallRegistration` and settlement future; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | | §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | @@ -255,21 +254,21 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch ## Supersedes -- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): the Session table's `owner`/`provider`/`holds`/`listed` readers it used to define are replaced by `register`, `call` and `methods`; `Caller`, `CallSite` and `Callers` stay the binding's, stated below and in A.2; the `MethodCall`, `MethodReply` and `MethodError` shapes of A.1's interface block are defined in `crate::methods` as stated here, and A.1 links to them. -- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its paragraphs for the Session table's shapes and the shared call data — `MethodProvider`, `Accepted`, `Check`, `Owner`, the Session table's `MethodTable` storage, the `SessionMethods` deref, `Handler`, `MethodCall`/`Origin` and the foreign `register` decode — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): its Session-scoped call paragraph is replaced by `register`, `call` and `methods`, and the call data A.1's interface block names — `MethodCall`, `MethodReply`, `MethodError` — are the binding below, which A.1 links to. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its paragraphs for the Session table's shapes and the shared call data — `MethodProvider`, `Accepted`, `Check`, `Owner`, the Session table's `MethodTable` storage, its `owner`/`provider`/`holds`/`listed` readers, the `SessionMethods` deref, `Handler`, `MethodCall`/`Origin` and the foreign `register` decode — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. - [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Seven client-visible failure changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible changes: -- A Session that is closing answers `closed` for `register` and `call` from `closing()`, before any row unloads; today the table keeps admitting until its rows unload. +- A Session that is closing answers `closed` for `call` from `phase()`, before any row unloads, and no handler runs; today the table keeps admitting until its rows unload. - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. - A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). - A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). -- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). A registration of another language whose declarations cannot be decoded fails as `invalid`, where today the bridge's `bad-value` names the decode; no client sees either. +- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). - A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). - A bridge error that carries no code of its own is `failed` under the service rule (`-32000`), where today it is `-32603` "Method binding failed" (`crates/dim-agent-capabilities/src/methods.rs:912-918`). -`session.methods` gains one failure: while the process is closing, it cannot filter the names a management namespace holds and answers `service_unavailable`. Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. +`session.methods` gains one failure: while the process is closing, it cannot filter the names a management namespace holds and answers `service_unavailable`; a registration's `closed` reaches no client, and a registration of another language whose declarations cannot be decoded now fails as `invalid` where the bridge's `bad-value` named the decode, which no client sees either. Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. ## Binding appendix @@ -418,7 +417,8 @@ pub struct Origin { pub struct MethodCallbackError { pub code: String, pub message: String, - /// The JSON-RPC code the handler chose; the service-error rule applies + /// The JSON-RPC code the handler's failure carries; the service-error rule + /// applies /// when it is absent. Another language's handler sends none. #[serde(skip, default)] pub wire: Option, From 8b07db140eb95a2ec8b4d5f8b0a064db29acec51 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 10:28:29 +0800 Subject: [PATCH 41/41] docs(sessionmethods): answer the final mock deltas The change list counts eight client-visible changes, the two non-client ones following it. `Refuse as soon as` replaces the doubled word, `unknown_method`'s condition is parenthesized, and the methods verification attributes the listing's `service_unavailable` to Rpc's filter. A.1's routing rows carry the `loaderRows`-absent `reloading` condition in both languages. --- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/SessionMethods.md | 10 +++++----- docs/zh/design/contracts/session-boundary.md | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index a4f176edfc..b87d0821e7 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -238,7 +238,7 @@ Cancellation and interruption: the provider replies to its own calls, not Rpc. T | Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). The declaration and notification rules are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | -| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | +| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`; while `loaderRows` is not installed, a withdrawn namespace answers `service_reloading` instead. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | | Call ownership | Each registration owns the calls it admitted, as a management registration does: it replies to them, its row's unload interrupts them per `interruption` and waits for them (Cancellation above) | | Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md index 3715c4c742..d41cd02ad9 100644 --- a/docs/design/plugins/SessionMethods.md +++ b/docs/design/plugins/SessionMethods.md @@ -168,7 +168,7 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | `invalid` | `register` | — | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | | `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | | `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | -| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, the row that registered its withdrawn namespace is disabled or absent — `loaderRows` installed —, or — for the process table — its row is Active without registering the namespace again. While `loaderRows` is absent a withdrawn namespace answers `reloading`, never this kind. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, the row that registered its withdrawn namespace is disabled or absent (when `loaderRows` is installed), or, for the process table, its row is Active without registering the namespace again. While `loaderRows` is absent a withdrawn namespace answers `reloading`, never this kind. Check the name and the namespace's declarations; an absent row is a configuration problem | | `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. While `loaderRows` is absent, every withdrawn namespace answers this. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | | `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | | `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | @@ -180,8 +180,8 @@ A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own err | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `register` | Refuse at once once `phase()` reads closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | Its last row is recorded before the registration is withdrawn — the record's effect was registered last, so it runs first — and the registration ends with the row | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | -| `call` | Refuse at once once `phase()` reads closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement — and on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — its effect was registered last, so it runs first — and a withdrawn Session namespace answers from that row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The registration's unload effect for settlement; the table for admission | +| `register` | Refuse as soon as `phase()` reads closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | Its last row is recorded before the registration is withdrawn — the record's effect was registered last, so it runs first — and the registration ends with the row | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `call` | Refuse as soon as `phase()` reads closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement — and on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — its effect was registered last, so it runs first — and a withdrawn Session namespace answers from that row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The registration's unload effect for settlement; the table for admission | | `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | ## Exceptions with reasons @@ -198,7 +198,7 @@ Flow tests on the owner: - A native handler receives the call's `Caller` and notifies through it; a handler of another language receives the same caller encoded by the bridge as `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. - A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. - A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a bridge error without a code is `failed` under the rule, and a call that crossed nothing is `failed` with `-32603`. -- `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns, and a closing process makes it answer `service_unavailable`. +- `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. That filter is Rpc's, so the listing's `service_unavailable` while the process closes belongs to `session.methods`, not this table. - Once `phase()` reads closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. - While `loaderRows` is not installed, a withdrawn namespace answers `reloading`; installed, a missing row or a disabled one is `unknown_method`. @@ -258,7 +258,7 @@ The process table (#2021) must serve the same shared shape, because Rpc dispatch - [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its paragraphs for the Session table's shapes and the shared call data — `MethodProvider`, `Accepted`, `Check`, `Owner`, the Session table's `MethodTable` storage, its `owner`/`provider`/`holds`/`listed` readers, the `SessionMethods` deref, `Handler`, `MethodCall`/`Origin` and the foreign `register` decode — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. - [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. -No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Six client-visible changes: +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Eight client-visible changes: - A Session that is closing answers `closed` for `call` from `phase()`, before any row unloads, and no handler runs; today the table keeps admitting until its rows unload. - A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index bbe30245c5..9b916d815a 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -238,12 +238,12 @@ sequenceDiagram | 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明与通知的规则归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | -| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | +| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`;未安装 `loaderRows` 时,已撤回的命名空间答 `service_reloading`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | | 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | -| `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | +| `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。进程正在关闭时它答 `service_unavailable`,因为它读不到管理命名空间持有的名字。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | | 就绪闩 | 原生绑定在首个 `hello` 前等待必需进程提供方;[TS 进程绑定](../../../design/process-typescript.md#21-startup-and-availability) 不把可选扩展行纳入宿主启动/重启就绪条件。`hello.features` 只列出调用时已注册的命名空间,后来注册的在下次 `hello` 出现。 | 连接的入口接纳调用后,Rpc 如何路由: @@ -528,7 +528,7 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | | `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。Session 表不再对 `MethodTable` `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。目标去掉这一 `Deref`:Session 表持有自己的存储,不对 `MethodTable` `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。