From 4c8cce4a0f9dce22e6962e30936554ca0659a1ca Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:32:55 +0800 Subject: [PATCH 01/12] docs(design): the connection, entry and UI owner contracts Refs #2021 Refs #2015 --- docs/design/plugins/CallChannel.md | 156 +++++++++++++++ docs/design/plugins/Connection.md | 229 ++++++++++++++++++++++ docs/design/plugins/EnvironmentClients.md | 4 +- docs/design/plugins/ManagementMethods.md | 176 +++++++++++++++++ docs/design/plugins/ProcessRoot.md | 147 ++++++++++++++ docs/design/plugins/README.md | 11 +- docs/design/plugins/Report.md | 210 +++++++++++++++----- docs/design/plugins/Rpc.md | 146 ++++++++++++++ docs/design/plugins/ServerControl.md | 160 +++++++++++++++ docs/design/plugins/Transport.md | 111 +++++++++++ docs/design/plugins/UiExtensions.md | 169 ++++++++++++++++ docs/design/plugins/UiHost.md | 196 ++++++++++++++++++ docs/design/plugins/UiResources.md | 159 +++++++++++++++ 13 files changed, 1824 insertions(+), 50 deletions(-) create mode 100644 docs/design/plugins/CallChannel.md create mode 100644 docs/design/plugins/Connection.md create mode 100644 docs/design/plugins/ManagementMethods.md create mode 100644 docs/design/plugins/ProcessRoot.md create mode 100644 docs/design/plugins/Rpc.md create mode 100644 docs/design/plugins/ServerControl.md create mode 100644 docs/design/plugins/Transport.md create mode 100644 docs/design/plugins/UiExtensions.md create mode 100644 docs/design/plugins/UiHost.md create mode 100644 docs/design/plugins/UiResources.md diff --git a/docs/design/plugins/CallChannel.md b/docs/design/plugins/CallChannel.md new file mode 100644 index 0000000000..c587637831 --- /dev/null +++ b/docs/design/plugins/CallChannel.md @@ -0,0 +1,156 @@ +# CallChannel + +Scope: process. Issue: #2021. + +CallChannel owns the binding between one admitted call and the connection it arrived on: which notifications the provider may send, whether the call is still answerable, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. + +## Use and scope: responsibility split + +CallChannel owns: + +- **Bindings.** For each admitted call that may notify, the connection id, the call id, the row instance that registered the namespace, and the notification names that namespace declared. +- **The declared-name answer.** A name the registration did not declare is refused before anything is written. +- **The connection's end.** A binding resolves when its connection closes, when the reply is written, or when the registering row unloads. +- **Routing the write.** A notification is written by Connection, addressed by the call id so it follows the reply. + +CallChannel writes no socket and holds no connection state. + +Callers keep: + +- What a notification means: the provider chooses the name and the payload. +- The reply: Rpc returns it; Connection writes it. +- The declarations: the registering part declared them; the table admitted the call with them. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Rpc must make an admitted call addressable before the handler can notify | No: the binding's lifetime and the declared-name answer are the owner's | `bind` | +| A provider must send a notification to the calling connection, in order after its reply | No: the declared-name check, the binding lookup and the ordering are the owner's | `notify` | +| A provider must stop when the connection closes | Yes: `closed` composes | `closed` | +| Rpc must end a binding once the reply is written | No: the end and the removal are the owner's | `finish` | + +An operation or parameter exists only where the row says No. + +## Caller example + +Rpc binds the call before invoking the handler: + +```rust +channel.bind(BindRequest { + connection_id: caller.connection_id.clone(), + call_id: caller.call_id.clone(), + instance: row_instance.clone(), + notifications: declarations.iter().flat_map(|d| d.notifications.clone()).collect(), +}).await?; +let reply = table.call(CallRequest { method, params, caller: Some(caller.clone()) }).await?; +connection.write_after(WriteAfter { connection_id, call_id, frame: reply.frame }).await?; +channel.finish(FinishRequest { connection_id, call_id }).await?; +``` + +A provider notifies and waits for the end: + +```rust +match channel.notify(NotifyRequest { connection_id, call_id, method, params }).await { + Ok(()) => {} + Err(NotifyError::Undeclared) => return Err(ProviderError::Programming), + Err(NotifyError::Gone) => return Ok(()), // the caller left; nothing to do + Err(NotifyError::TooLarge) => return Err(ProviderError::TooLarge), +} +channel.closed(ClosedRequest { connection_id, call_id }).await; +``` + +## Own contract + +### Dependencies + +Connection's `write_after` and `closed`. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `bind` | Make one admitted call addressable by its notifications | `{connection_id, call_id, instance, notifications}` | `{}` | None | `duplicate` | +| `notify` | Send a notification to the calling connection, after the call's reply | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `undeclared`, `gone`, `too_large` | +| `closed` | Wait until the calling connection is gone | `{connection_id, call_id}` | `{}` when the connection closes | The provider's task ends; the wait ends | none | +| `finish` | The call's reply was written; the binding ends | `{connection_id, call_id}` | `{}` | None | none | + +`instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name, and the binding belongs to the row that admitted the call. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `duplicate` | The call id is bound already; this is a programming error in the caller | +| `undeclared` | The registration did not declare the name; fix the declaration, nothing was written | +| `gone` | The connection closed or the row unloaded; stop notifying for this call | +| `too_large` | The notification exceeds the connection's frame budget; shorten it — the connection stays open | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `bind` | Record the binding under the row instance and the connection | — | The row's bindings are removed | New bindings are refused; existing ones resolve as gone | CallChannel | +| `notify` | Find the binding, check the declared name, ask Connection to write after the call | The provider's task ends before the write; nothing is written | The binding is removed; `gone` | Pending notifications are `gone` | Connection: the frame; CallChannel: the binding | +| `closed` | Wait on Connection's `closed` for the binding's connection | The provider stops waiting | The wait ends | The wait ends | Connection | +| `finish` | Remove the binding; later notifications are `gone` | — | Already removed | Already removed | CallChannel | + +## Exceptions with reasons + +- `bind`/`finish` are called by Rpc, not by the table: the table is in another crate and must not depend on the App Server; Rpc knows both the admitted call and the connection. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | CallChannel is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: call bindings belong to process rows and connections. | +| §3 orthogonality | No other owner's state is read; Connection is asked to write and to report its close. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use these operations; no caller sees the binding table. | +| §7 no proxy | The binding, the declared-name answer and the connection's end are this owner's state; Connection writes the frame. | +| §7 no handle | The binding is addressed by `{connection_id, call_id}`; no writer crosses. | +| ADR 002 D1 | Process scope: calls span rows and connections. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | Dependencies point to Connection as an operation. | +| ADR 002 D4 | No business setting. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. The call id is data minted by Rpc; no runtime change is needed. + +## Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BindRequest { + pub connection_id: String, + pub call_id: String, + pub instance: String, + pub notifications: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NotifyRequest { + pub connection_id: String, + pub call_id: String, + pub method: String, + #[serde(default)] + pub params: serde_json::Map, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NotifyError { Undeclared, Gone, TooLarge } + +#[rutis::service(name = "callChannel")] +impl CallChannel { + pub async fn bind(&self, request: BindRequest) -> Result<(), BindError> { /* ... */ } + pub async fn notify(&self, request: NotifyRequest) -> Result<(), NotifyError> { /* ... */ } + pub async fn closed(&self, request: ClosedRequest) { /* waits */ } + pub async fn finish(&self, request: FinishRequest) { /* ... */ } +} +``` + +The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same two operations. diff --git a/docs/design/plugins/Connection.md b/docs/design/plugins/Connection.md new file mode 100644 index 0000000000..2ec3ec4c3d --- /dev/null +++ b/docs/design/plugins/Connection.md @@ -0,0 +1,229 @@ +# Connection + +Scope: process. Issue: #2021. + +Connection owns the process's live client connections. This document is the owner's target contract; the current implementation is described in the [Tui design](Tui.md#36-ui-registry-and-ui-leaves) and the [App Server assembly](../../architecture/rust-agent/generated/app-server/services.md). Transport, Rpc, UiHost, CallChannel, UiExtensions, UiResources and Report are separate owners with their own contracts; their calls appear in the delivery tables as caller rows. + +## Use and scope: responsibility split + +Connection owns: + +- **Admission.** Whether a client may join now: the hello/attach admission that races with the idle-close decision, and the connection limit inside a frame budget. +- **Connections.** Each accepted client's reader, writer, outbound queue and reply ordering. A connection lives until its reader ends, its client closes, or the daemon closes. +- **Session attachments.** Which Sessions a connection is viewing, each holding one Session lease and one broadcast subscription. Detaching is not closing a Session. +- **Presence.** The live clients of one Session, as the value the model-facing branch reads. +- **The inbound handover.** Each frame is handed to Rpc's current generation; Connection never interprets a method. + +Connection keeps no Timeline fact, no Session state and no protocol meaning. + +Callers keep: + +- HTTP routing, authentication and the web entry's own routes: WebEntry decides which request becomes a connection upgrade. +- Protocol semantics: hello fields, built-in methods, Session routing and method errors are Rpc's. +- Listener binding and endpoint cleanup: Transport owns the sockets that produce accepted streams. +- The UI registry: UiHost owns interface registrations; Connection tells UiHost that a connection ended. +- The model-facing client snapshot: EnvironmentClientsBranch owns the `` text; Connection gives the presence value. +- The decision to close the daemon: Rpc's `daemon.shutdown` reads the facts each owner publishes; Connection contributes the connection counts and commits the refusal. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Transport and WebEntry need an accepted stream to become a live connection | No: creating the record, admitting it against the idle-close decision and owning the read loop are the owner's; the stream is the one handover | `accept` | +| A frame must reach the protocol generation that is current now | No: storing the handler in Connection makes a reload a stale object; the owner asks Rpc per frame | dependency on Rpc's `hello` and `request` | +| A provider or Rpc must write a frame after the reply of a call | No: the reply ordering is the connection's outbound queue | `write`, `write_after` | +| A client views a Session | No: the attachment holds one Session lease and one subscription, released on every path | `attach`, `detach` | +| UiHost needs to know whether a connection views a Session | Yes: a read composes | `attached` | +| The model needs the live clients of a Session | No: the value must come from the owner's own records, not from another owner's registry | `presences` | +| An idle close needs connection counts and an atomic refusal | No: counting and refusing in two calls races with hello and attach | `counts`, `close_for_idle` | +| The daemon closes every connection and waits for its tasks | No: the owner settles the writers and readers | `close_all` | +| A connection ends and its attachment and UI registration must go | No: one settlement releases the lease, the subscription and the UI registration | `settle` | + +An operation or parameter exists only where the row says No. + +## Caller example + +Transport accepts a stream and hands it over: + +```rust +// Refused only while the daemon is closing; nothing was created. +let connection = match connections.accept(stream, Entry::Local).await { + Ok(connection) => connection, + Err(AcceptError::Closing) => return, +}; +``` + +EnvironmentClientsBranch reads the presence value and writes its own input: + +```rust +let presences = connections.presences(session_id.clone()).await?; +let body = render(&presences); // the branch owns the text +append_snapshot(&timeline, body)?; +``` + +The idle-close handler reads the other owners' facts, then commits the refusal in one call: + +```rust +let running = agents.running_sessions(); +let held = process_activity.holds(); // a count, not a guard +let quiet = agents.sessions_quiescent(); +match connections.close_for_idle(CloseForIdle { + exclude_connection_id: caller.clone(), + running_sessions: running, + held_work: held, + sessions_quiet: quiet, +}) { + Ok(counts) => shutdown.request(ShutdownMode::Graceful), + Err(CloseForIdleError::Busy(busy)) => return Err(busy.into()), +} +``` + +A provider that notifies the calling connection uses CallChannel, which calls `write_after`: + +```rust +channel.notify(NotifyRequest { connection_id, call_id, method, params }).await?; +``` + +## Own contract + +### Dependencies + +Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach` and `release`; Agents' `acquire`/`release` for attachment leases ([Agents #2020](../contracts/process-owner-operations.md)). + +### Operations + +The owner type is `ConnectionHub`. `accept` is crate-internal because a socket cannot be data; every other operation is on the `connection` face. + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `accept` (crate-internal) | Turn an accepted stream into a live connection | `{stream, entry}` | `{connection_id, generation}` | None; the caller either accepts it or drops the stream | `closing` | +| `write` | Write one frame to a connection | `{connection_id, frame}` | `{}` | None; the frame is queued or refused | `unknown_connection`, `gone`, `too_large`, `slow` | +| `write_after` | Write one notification after the reply of one call | `{connection_id, call_id, frame}` | `{}` | None | `unknown_connection`, `gone`, `too_large`, `slow` | +| `write_deferred` | Write one frame when the connection settles, before its writer ends | `{connection_id, frame}` | `{}`; a connection that already settled drops the frame | None | none | +| `closed` | Wait until a connection ends | `{connection_id}` | `{}` when the connection ends; an unknown id resolves at once | The caller's task ends | none | +| `attach` | A connection views a Session | `{connection_id, session_id}` | `{generation}` | While the Session lease is acquired and the listener registered; nothing is attached | `unknown_connection`, `closed`, `session_unavailable`, `cancelled` | +| `detach` | A connection stops viewing a Session | `{connection_id, session_id}` | `{}` | None; the owner completes the release | none | +| `attached` | Whether a connection views a Session now | `{connection_id, session_id}` | `{attached}` | None | none | +| `presences` | The live clients of a Session | `{session_id}` | `{presences: [{channel, label?}]}` | None | none | +| `counts` | Live connections and attached Sessions, excluding one connection | `{exclude_connection_id}` | `{connections, attached_sessions}` | None | none | +| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running_sessions, held_work, sessions_quiet}` | `{counts}` | None | `busy{connections, attached_sessions, running_sessions}` | +| `close_all` | Close every connection and wait for its tasks | `{}` | `{}` | None; the owner completes the close | none | +| `settle` (internal) | One connection ended: release its attachment, tell UiHost, end its writer | `{connection_id, reason}` | `{}` | None | none | + +`write` and `write_after` are one operation family: `write_after` exists because a notification sent while a call runs must follow that call's reply, and only the connection's outbound queue knows the reply has been written. `write` refuses a frame over the connection's frame budget with `too_large`, and closes a connection whose reliable allowance is exhausted, reporting `slow` to the writer of that frame. + +`close_for_idle` reads the other owners' facts from its request: the caller read them immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. A fact that changes afterwards is settled by the shutdown sequence; the refusal is not undone. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `closing` | The daemon has refused new clients; stop accepting on this listener | +| `unknown_connection` | The connection is gone; drop the write or the attachment and read the current state | +| `gone` | The connection closed or its generation unloaded; nothing was written | +| `too_large` | The frame exceeds the connection's frame budget; the connection stays open — the provider must shorten its notification | +| `slow` | The connection's reliable allowance is exhausted; the connection is closed and the caller drops the frame | +| `session_unavailable` | The Session cannot be acquired now; report it to the client and retry the attach later | +| `cancelled` | Nothing was attached; the caller stopped waiting | +| `closed` | This generation is unloading; reconnect to the replacement generation | +| `busy` | Somebody is using the daemon; answer the client with the three counts and do not close | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `accept` | Admit under the lock, create the record and the writer, spawn the reader, count it | The stream is dropped before the record exists; nothing was admitted | The reader ends with the stream | New accepts are refused as `closing`; every connection is closed | Connection: the record, reader and writer | +| `write`, `write_after` | Encode once, admit into the outbound queue, write in order | None; a frame is queued or refused | A closed connection is `gone` | Pending writes end `gone` | Connection: the queue and writer | +| `write_deferred` | Hold the frame until the connection settles | — | — | `close_all` writes it after the queue drains and before the writer ends | Connection | +| `closed` | Resolve when the reader or the owner ends the connection | — | The waiter ends | Resolves for every waiter | Connection | +| `attach` | Acquire the Session lease, register the subscription, attach under the connection lock | Before the reply: lease released, listener disposed, nothing attached | The attachment is released with the connection | Pending calls end `closed`; every attachment is released | Connection: the attachment; Agents: the lease | +| `detach` | Remove the attachment and release its lease and listener | — | — | The attachment is already gone | Connection | +| `close_for_idle` | Recheck counts under the lock, set the refusal, return the counts | None | — | The refusal is the close | Connection | +| `close_all` | Tell UiHost the connections ended, cancel each reader and writer, wait for the tasks | — | — | It is the close | Connection | + +## Exceptions with reasons + +- `accept` takes an accepted stream: a socket cannot be represented as data. The shared lifecycle is fixed here: Transport creates the stream by accepting on a listener it owns, calls `accept` once, and never reads or writes the stream afterwards; Connection owns it from the call boundary and settles it in `settle` or `close_all`; when Transport reloads, the listeners close and existing connections stay with Connection; when Connection reloads, every connection settles and Transport's accept calls are refused as `closing` until the new generation is installed. +- Attachment leases are agents' ids, not guards: the connection stores the lease id and releases it in one settlement path, so a connection that dies on any path leaves no lease. +- `presences` labels are self-declared and never identities; the value says so by naming the field `label`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Connection is one process part. It writes no Timeline fact and folds no state, so it is not a Capability. | +| §2 scopes | Process. A connection is shared by every Session it views; attachments are the Session-facing part of the same resource. | +| §3 orthogonality | No other owner's state is read. UiHost and Agents are asked through their operations; presence is Connection's own projection over its records. | +| §4 rule 1 | No command event: Connection writes no Timeline fact. | +| §4 rule 2 | No Timeline handoff. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning: method names and replies are Rpc's. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No model context: the presence value reaches the model only through EnvironmentClientsBranch's input. | +| §4 rule 7 | Callers use these operations; no caller reads the connection index or the outbound queue. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact. | +| §7 object handover | `accept` is the only object handover; its lifecycle is the exception above. | +| §7 no proxy | Presence is computed from Connection's own records; the UI-leaf attribution arrives as UiHost's fact, not as a read of its registry. | +| ADR 002 D1 | Process scope: connections outlive Sessions and are shared by them. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | Dependencies point to extensions: Rpc, Transport, UiHost and Agents are used as operations; none is stored as an object. | +| ADR 002 D4 | The listener configuration is structural; no business setting is involved. | +| ADR 002 D5 | The contract is language-neutral except `accept`; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Agents (#2020)**: attachment leases as ids bound to the calling row (`acquire(sessionId) → leaseId`, `release(leaseId)`); a value for the running Session count and a value for Session quiescence used by `close_for_idle`; an operation that settles the Sessions for shutdown after `close_for_idle` commits. +- **rutis (runtime)**: none. + +## Binding appendix + +```rust +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PresencesRequest { pub session_id: String } + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PresencesReply { pub presences: Vec } + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Counts { pub connections: usize, pub attached_sessions: usize } + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Busy { + pub connections: usize, + pub attached_sessions: usize, + pub running_sessions: usize, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum CloseForIdleError { + #[error("The App Server is in use")] + Busy(Busy), +} + +#[rutis::service(name = "connection")] +impl ConnectionHub { + pub async fn write(&self, request: WriteRequest) -> Result<(), WriteError> { /* ... */ } + pub async fn write_after(&self, request: WriteAfterRequest) -> Result<(), WriteError> { /* ... */ } + pub async fn write_deferred(&self, request: DeferredRequest) { /* ... */ } + pub async fn closed(&self, request: ClosedRequest) { /* waits */ } + pub async fn attach(&self, request: AttachRequest) -> Result { /* ... */ } + pub async fn detach(&self, request: DetachRequest) { /* ... */ } + pub async fn attached(&self, request: AttachedRequest) -> AttachedReply { /* ... */ } + pub async fn presences(&self, request: PresencesRequest) -> PresencesReply { /* ... */ } + pub async fn counts(&self, request: CountsRequest) -> Counts { /* ... */ } + pub async fn close_for_idle(&self, request: CloseForIdleRequest) -> Result { /* ... */ } + pub async fn close_all(&self, request: Empty) { /* ... */ } +} + +impl ConnectionHub { + /// Crate-internal: a socket cannot be data. See the exception in this contract. + pub(crate) async fn accept(&self, stream: ClientStream, entry: Entry) -> Result { /* ... */ } + pub(crate) async fn settle(&self, connection_id: &str, reason: SettleReason) { /* ... */ } +} +``` + +`ClientStream` is the accepted socket (Unix stream, named pipe or WebSocket); it never crosses a language boundary. `Entry` is `local`, `bare` or `web`. diff --git a/docs/design/plugins/EnvironmentClients.md b/docs/design/plugins/EnvironmentClients.md index 84604b6e3e..d97e75b45d 100644 --- a/docs/design/plugins/EnvironmentClients.md +++ b/docs/design/plugins/EnvironmentClients.md @@ -69,7 +69,7 @@ ClientPresence { label: Option, } -sessionClientsHost.presences {sessionId} -> {presences: [ClientPresence]} +connection.presences {sessionId} -> {presences: [ClientPresence]} ``` A UI leaf takes the label of the connection that hosts it; without one, only the channel is present. @@ -152,7 +152,7 @@ The in-memory presence read is infallible; it returns an empty list for an unkno | `BranchLifecycle` | Wait for publication before appending; stop when the branch closes | | Process bus (`ClientsChanged`) | Wake on a connection change | -The process `sessionClientsHost` is a data face with the request and reply defined in [service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个). `sessionIdentity`, `timeline` and `branchLifecycle` are also data faces in the [owner catalog](../../architecture/rust-agent/generated/catalog.md#services). This Rust projection still uses owner methods outside the dispatched operations and is not a leaf-ready foreign part. +The process `connection` face answers `presences` with the request and reply defined in the [Connection contract](Connection.md). `sessionIdentity`, `timeline` and `branchLifecycle` are also data faces in the [owner catalog](../../architecture/rust-agent/generated/catalog.md#services). This Rust projection still uses owner methods outside the dispatched operations and is not a leaf-ready foreign part. No Prompt registry, no configure control, no version. diff --git a/docs/design/plugins/ManagementMethods.md b/docs/design/plugins/ManagementMethods.md new file mode 100644 index 0000000000..c8b7bd8888 --- /dev/null +++ b/docs/design/plugins/ManagementMethods.md @@ -0,0 +1,176 @@ +# ManagementMethods + +Scope: process. Issue: #2021. + +ManagementMethods owns the process namespace table: which namespaces a process part registered, what each declared, and who answers a name now. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/methods.rs` and `crates/dim-agent-capabilities/src/methods.rs`. Rpc, the Session method table ([#2026](../contracts/session-boundary.md)) and the registering parts are separate owners. + +## Use and scope: responsibility split + +ManagementMethods owns: + +- **Registrations.** One namespace per registering row, its declarations and its call handler; 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 accepted calls on unload. +- **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers from that row's status instead of leaking to a parent namespace. +- **Reserved names.** The host's own namespaces and built-ins are refused at registration. + +Callers keep: + +- What the methods mean: each registering part declares and implements its namespaces. +- The client methods themselves: Rpc serves them; this table only dispatches. +- When to call: Rpc decides routing; the table answers one name. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A process part publishes its namespace for the row's lifetime | No: the registration's lifetime and the duplicate check are the owner's | `register` | +| Rpc must dispatch one call to the namespace that holds the name now | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | + +An operation or parameter exists only where the row says No. + +## Caller example + +A process part registers from `apply`: + +```rust +table.register(RegisterRequest { + namespace: "settings".into(), + declarations, + call: handler, // a callback by reference; never called inside a commit lock +}).await?; +``` + +Rpc dispatches: + +```rust +// `reloading` and `unavailable` are answered from the registering row's status. +let reply = table.call(CallRequest { + method: method.into(), + params, + caller: Some(CallerRef { connection_id, call_id }), +}).await?; +``` + +## Own contract + +### Dependencies + +The loader's row status (`rutis/loader`), read when a withdrawn namespace answers; the registering rows' `ctx` for the registration lifetime. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish a namespace for the registering row's lifetime | `{namespace, declarations, call}` | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | The calling connection closing ends the call as interrupted; an unload ends it by its declaration (`report` or `drain`) | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `invalid` | + +`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses. It is absent for an in-process call. The table passes it to the handler unchanged; a handler that notifies uses it with `callChannel` or the native binding. + +A call's reply is `MethodReply` data: a value, or the handler's own error with its `code` and `message`. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `reserved` | The namespace or a name is the host's; pick another name | +| `duplicate` | The namespace is registered already; the registering row must not register twice | +| `invalid` | The namespace or declaration is outside the name grammar | +| `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | +| `reloading` | The registering row is starting or reloading; retry after it is Active | +| `unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | +| `interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Check the name and declarations, record them under the row, refuse a duplicate | — | The registration is withdrawn and the row recorded | New registrations are refused; the table reloads with the process | The registering row | +| `call` | Find the owner, admit the call, run the handler, return the reply; on unload, interrupt `report` and wait for `drain` | A closing connection ends the call as interrupted | The call ends and its commands settle | A withdrawn namespace answers from its row's status | The table for the call's settlement; the handler for its effects | + +## Exceptions with reasons + +- The table remembers the registering row per namespace: a withdrawn namespace must answer `reloading` or `unavailable` rather than fall through to a parent namespace. +- `call` takes the caller as data, not as a connection handle: the reply ordering belongs to Connection, and the table never writes a socket. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | ManagementMethods is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: one table serves every connection. | +| §3 orthogonality | No other owner's state is read; the loader's row status is the mechanism's read. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use `register` and `call`; no caller sees the registration table. | +| §8 rule | An unloading table settles its accepted calls before its services go. | +| §7 no proxy | The handler's error data is returned unchanged; the table adds no business meaning. | +| ADR 002 D1 | Process scope: namespaces belong to process rows. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | No dependency on providers; a disabled or failed provider affects only its namespaces. | +| ADR 002 D4 | The namespace set is structural: rows bring their namespaces. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Session registration (#2026)**: the Session method table takes the same `call` request and reply data, so Rpc has one call path for both tables. + +## Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallerRef { pub connection_id: String, pub call_id: String } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallRequest { + pub method: String, + pub params: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub caller: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallReply { pub reply: serde_json::Value } + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Interruption { Report, Drain } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MethodDecl { + pub name: String, + pub mutating: bool, + pub interruption: Interruption, + #[serde(default)] + pub notifications: Vec, + #[serde(default)] + pub progress: bool, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum TableError { + #[error("{message}")] + Reserved { message: String }, + #[error("{message}")] + Duplicate { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("Unknown method")] + UnknownMethod, + #[error("Service is reloading; retry")] + Reloading, + #[error("Service is unavailable until it is fixed or restarted")] + Unavailable, + #[error("Service reloaded; the call may have committed")] + Interrupted, +} + +#[rutis::service(name = "managementMethods")] +impl MethodTable { + pub async fn register(&self, request: RegisterRequest) -> Result<(), TableError> { /* ... */ } + pub async fn call(&self, request: CallRequest) -> Result { /* ... */ } +} +``` + +`RegisterRequest.call` is a callback by reference: the handler runs on the registering row's runtime and is never called inside a commit lock. diff --git a/docs/design/plugins/ProcessRoot.md b/docs/design/plugins/ProcessRoot.md new file mode 100644 index 0000000000..642a32a7ea --- /dev/null +++ b/docs/design/plugins/ProcessRoot.md @@ -0,0 +1,147 @@ +# ProcessRoot + +Scope: process. Issue: #2021. + +The process root is the assembly's provider of process-scope values. This document is the owner's target contract for the three values the root provides, `reservedMethods`, `credentialVariablesHost` and the daemon's peer id. The current implementation is in `crates/dim-app-server/src/lib.rs`. The consuming owners — the Session method table and Mcp — are separate owners. + +## Use and scope: responsibility split + +The root owns: + +- **The Session name reservation policy.** Which namespaces and built-in method names the host keeps for itself, consulted before a Session table registers a namespace. +- **The daemon's credential variable names.** The environment variable names the daemon's model configuration reads credentials from; the names only, never values. +- **The daemon's peer id value.** The `rutis_bridge::LocalId` the bridge reads when it greets a peer. + +The root holds no resource that needs settling: all three are values fixed at assembly. + +Callers keep: + +- What a reserved name means: the Session method table refuses a registration; the root only answers. +- What a credential variable is used for: Mcp decides where a name may not be expanded. +- The bridge handshake: the root provides the value; rutis-bridge reads it. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A Session table must know the host's reserved names before registering | No: the policy is the host's, and a caller that guessed it would duplicate the protocol's own list | `reservedMethods.check` | +| Mcp must not expand a credential variable into a third-party configuration | No: only the daemon knows which names its model configuration reads | `credentialVariablesHost.variables` | +| A peer needs the daemon's id | Yes: rutis-bridge reads the `LocalId` value; no service call is involved | value | + +An operation or parameter exists only where the row says No. + +## Caller example + +The Session method table consults the policy when it registers a namespace: + +```rust +// Registered by the part that owns the namespace; refused names fail the registration. +table.register(RegisterRequest { namespace: "session.goal".into(), declarations, call }).await?; +// The table's own check calls reservedMethods.check with the same declarations. +``` + +Mcp reads the names once per catalog build: + +```rust +let protected = credentials.variables().await?.variables; // names only +if protected.contains(name) { + return String::new(); // a guarded field never expands a host credential +} +``` + +## Own contract + +### Dependencies + +None. The root reads the assembly's configuration and provides the values. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `check` | Refuse a namespace or a declaration the host keeps | `{namespace, declarations}` | `{}` | None; the owner completes it | `reserved` | +| `variables` | The daemon's credential variable names | `{}` | `{variables}` | None | none | + +`check` is synchronous with the caller's registration: a table that proceeds without it would accept a namespace the protocol cannot route. The policy is a callback by reference the assembly binds; the check itself is data in and out. + +`localId` has no operation. The peer id is a value (`rutis_bridge::LocalId`); the data face `localId.get` had no caller and is retired. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `reserved` | The namespace or a name is the host's; choose another name | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `check` | Read the policy value and answer | None | — | The value is fixed for the process generation; a reload provides the same policy | Root | +| `variables` | Read the configuration's names | — | — | Same value across generations | Root | + +## Exceptions with reasons + +- The root has no plugin row: the assembly is the provider, and a process-scope value needs no `apply`. It provides no resource, so no settlement path exists. +- `credentialVariablesHost` covers the configured model catalog's names only; the managed provider's credentials are not environment variables and are not listed. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | The root is the assembly, not a part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: the values are read by process and Session parts. | +| §3 orthogonality | No other owner's state is read. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use the two operations; no caller sees the configuration. | +| §7 no proxy | Each value is the owner's own; no facade stands between. | +| ADR 002 D1 | Process scope: values read at assembly. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Dependencies point to the root; it depends on nothing. | +| ADR 002 D4 | The values are structural configuration. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckRequest { + pub namespace: String, + #[serde(default)] + pub declarations: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReservedMethod { + pub name: String, + pub mutating: bool, + #[serde(default)] + pub notifications: Vec, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ReservedError { + #[error("{message}")] + Reserved { message: String }, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VariablesReply { pub variables: std::collections::BTreeSet } + +#[rutis::service(name = "reservedMethods")] +impl ReservedMethods { + pub async fn check(&self, request: CheckRequest) -> Result<(), ReservedError> { /* ... */ } +} + +#[rutis::service(name = "credentialVariablesHost")] +impl CredentialVariablesHost { + pub async fn variables(&self, request: Empty) -> VariablesReply { /* ... */ } +} +``` + +The Session table's Rust binding calls the same `check` through the policy value the assembly binds; no second path exists. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..9fb82b710c 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -13,6 +13,15 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | | [ShellInput](ShellInput.md) | — | `shell.*` methods, command runs | — | P1 | | [Attachments](Attachments.md) | — | `attachment.put`, Session files | — | P1 | +| [Connection](Connection.md) | client connections, hello/attach admission, attachments and presence; `connection` | — | — | #2021 | +| [Transport](Transport.md) | listening endpoints, accepting and bound addresses; `listenAddresses` | — | — | #2021 | +| [ServerControl](ServerControl.md) | publication gate, shutdown intent and accepted-work holds; `processActivity` | — | — | #2021 | +| [Rpc](Rpc.md) | handshake, built-in methods and dispatch of one call; `rpc` | — | — | #2021 | +| [ManagementMethods](ManagementMethods.md) | the process namespace table; `managementMethods` | — | — | #2021 | +| [ProcessRoot](ProcessRoot.md) | process values: reserved names and credential variable names | — | — | #2021 | +| [CallChannel](CallChannel.md) | call bindings for connection-bound notifications; `callChannel` | — | — | #2021 | +| [UiHost](UiHost.md) | interface registrations and UI leaves; `uiHost` | — | — | #2021 | +| [UiExtensions](UiExtensions.md) | the UI content catalog; `uiExtensions` | UiResources | — | #2021 | | [Report](Report.md) | error-only `report.*` and its connection-bound drafts | `session.report.*` and its connection-bound drafts | — | [#1319](https://github.com/arcships/dim/issues/1319) | | [SessionTitle](SessionTitle.md) | — | observes adoption of the first user input, `session.rename` | — | P1 | | [PromptSuggestion](PromptSuggestion.md) | `PromptSuggestionSettings` in App Server: the `prompt-suggestion` Settings source | observes the completed turn's events, `session.suggestion.request` and `session.suggestion.respond`, the offer in flight and the shown offer; no events | — | P1; [#943](https://github.com/arcships/dim/issues/943) | @@ -23,7 +32,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [ContextCompaction](ContextCompaction.md) (supplements to Loop and ContextPreparation; [ContextUsage proposal](ContextUsage.md)) | — | `ContextModelHost`, summary `CompactionStrategyHost`, `session.context.*` | `context/compact` command and compaction step in Loop; K-turn cut and usage query in ContextPreparation | P2 | | [Prompt](Prompt.md) | — | `guideEntries`: the input guide's frame, the entries in force and their composition | `Prompt`: the System its publisher adopts carries the composition over the entries in force, and a host-prepared request carries the same composition, placed by Loop | #548 | | [PromptSources](PromptSources.md) | — | the named sources, their policy texts at the factory configuration, and the state and rule entries | — | #548 | -| [EnvironmentClients](EnvironmentClients.md) | App Server read-only `sessionClientsHost` presence (Connection and UiHost) | — | presence snapshots as `` inputs at branch open and on `ClientsChanged` | #1019 | +| [EnvironmentClients](EnvironmentClients.md) | App Server read-only `connection.presences` (Connection and UiHost) | — | presence snapshots as `` inputs at branch open and on `ClientsChanged` | #1019 | | [EnvironmentSettings](EnvironmentSettings.md) | — (reads each setting module's read port) | — | settings snapshots as `` inputs at branch open and on a Settings change | #1020 | | [ClientView](ClientView.md) | per-connection viewed-line record in App Server | — | — | #1021, deferred for model state | | [AgentSettings](AgentSettings.md) | — | one `settings` tool: `list`, `get` | — | #1022 | diff --git a/docs/design/plugins/Report.md b/docs/design/plugins/Report.md index 456b8e3be9..6dfd02e977 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -1,29 +1,52 @@ -# Report plugin +# Report -The [target Session tree binding](../contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. +Scope: process and Session. Issue: [#1319](https://github.com/arcships/dim/issues/1319), contract #2021. -Status: Draft. Scope: Session reports and a process entry for errors without a readable Session. -Issue: [#1319](https://github.com/arcships/dim/issues/1319). +Report owns the drafts behind `/report` and the error-only report a client opens when no Session can be read. This document is the owner's target contract; the client interaction and the evidence rules below are the same design, restated in the contract's shape. The TimelineTree, SessionScope, ManagementMethods and SessionMethods owners are separate; their operations are dependencies. -## 1. Ownership +## 1. Use and scope: responsibility split -Report captures a bounded snapshot when a client opens the dialog. It owns evidence selection, filtering, the model-send preview, one-shot generation, and the final report and ZIP. The client owns the error hint or action, confirmation, and local save or sharing. App Server assembles the parts and admits RPC. The first integration uses both TUI renderers. Desktop and Web use the same report shapes and archive. +Report owns: -```text -TUI /report Desktop or Web "Report this error" - \ / - authenticated App Server connection - | | - session.report.* report.* - Session evidence Error-only evidence - \ / - Report preview, generation and ZIP -``` +- **Drafts.** One per calling connection in each part instance: the captured snapshot, the plan, at most one generation in flight, a five-minute expiry, and the Session hold that keeps the dialog's Session loaded. +- **Evidence.** Which records of the admitted Session or the observed error are selected, filtered, bounded and redacted, and what the caller sees before a plan. +- **Plans and generation.** The immutable plan, its consumption, one-shot generation, cancellation and the settlement of accepted work. +- **The archive.** `report.md`, `diagnostics.json` and the bounded ZIP returned to the client. + +Callers keep: -The Session part owns the draft and reads only the admitted Session. If its history read fails, the draft proceeds with an explicit missing-evidence reason and any captured error supplied by the client. If Session admission fails, the process part can prepare an error-only draft from a client-observed error. The process request accepts neither a Session nor a branch ID. +- The error hint or action, confirmation and local save or sharing: the client owns all three. +- Session admission: Rpc and Agents decide whether the Session can be read; Report reads only the admitted Session. +- The model's transport and retry policy: the Provider and auxiliary-model owners. +- The TUI menu entry: the CLI command owner. -The error-only entry uses `managementMethods` on the local App Server connection and requires explicit admission on the authenticated local Web entry (§7). Paired connections can use `session.report.*` while Session admission succeeds. The paired error-only entry is a separate admission decision in §7. Preparing a report requires a live connection. A TUI that already received the generated ZIP can still save it after the connection closes. +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client prepares a report on the Session it views | No: the draft, its expiry, its hold and the captured cutoff are the owner's | `prepare` (Session namespace) | +| A client on Home reports a conversation-open failure | No: the process part has no Session and drafts from the observed error | `prepare` (process namespace) | +| A client reviews the exact material and chooses redaction and instructions | No: an immutable plan is the owner's state | `plan` | +| A client generates and receives the preview and the ZIP | No: plan consumption, one-shot generation and the archive are the owner's | `generate` | +| A client cancels a plan or the draft | No: only the owner can stop its generation and discard the draft | `cancel` | + +An operation or parameter exists only where the row says No. + +## Caller example + +The TUI's `/report` flow: + +```rust +let prepared = report.prepare(PrepareRequest { error: None }).await?; // Session namespace +let plan = report.plan(PlanRequest { + report_id: prepared.report_id, + generation: Generation::Local, + redact: true, + instructions: None, +}).await?; // the exact material and the directives, reviewed before Generate +let report = report.generate(GenerateRequest { report_id, plan_id: plan.plan_id }).await?; +save(report.archive); // the client saves after the connection may close +``` +Home's error-only flow uses the same three calls in the process namespace with `error` present. ## 2. Client interaction In both TUI modes, `/report` opens a report for the current Session, including while a turn is running. It needs no captured error. Users can report an unsatisfactory answer or a repeating turn without waiting for a failure or stopping the turn. The dialog keeps the Session selected when it opened, including when preparing again after expiry. Returning to the composer and running `/report` again selects the Session shown at that time. @@ -79,26 +102,51 @@ The Timeline read is branch-local and bounded by 32 candidate events ending at t Diagnostics never include message bodies, raw logs, workspace files, tool input or output, or raw model requests. Their fields come from typed sources or fixed renderings, and correlation IDs come from verified metadata. With redaction on, remove correlation IDs and do not select conversation text. Only an explicit local plan with redaction off may add a recent excerpt to the Session report. Do not collect hidden reasoning, tool calls or results, attachments, instructions, or full history for the excerpt. User and assistant text can itself contain sensitive details; the user should inspect the ZIP before attaching it. Options maps recognized omit or keep instructions to field directives and shows unsupported instructions in the dialog. A keep directive cannot override redaction. The generation result cannot add new evidence. -## 4. Report methods +## 4. Own contract -Register the Session namespace in `sessionMethods` and discover it via `session.methods`. The local error-only namespace is `report`, discovered as an admitted management contribution. Below, methods are suffixes of either namespace. Session calls include the ordinary `sessionId` required by the methods contract. Report calls require a live authenticated caller origin. [Session method contributions](../contracts/session-boundary.md#a1-method-contributions). +### Dependencies -| Method | Inputs | Reply | -| --- | --- | --- | -| `prepare` | Session calls accept optional `error`. Omit it for a report on the admitted Session. When supplied, `error` is `{kind: "timeline", branchId, sequence, observed}` or `{kind: "observed", observed}`. The process part requires `error` in the observed variant. | `{reportId, defaultModel?, plan}`. Evidence availability is included in the plan. The default plan lets the dialog open with a preview without an extra round trip. | -| `plan` | `{reportId, generation, redact, instructions?}`, with generation `{kind: "local"}` or `{kind: "model", model: {providerId, modelId}}` | `{planId, generation, evidence, instructionsStatus}`. A model plan includes `material`, `maxOutputTokens` and `estimatedCost` as `{amount, currency}` or `null` for unknown. A successful replacement invalidates the previous plan. | -| `generate` | `{reportId, planId}` | `{title, body, files: {"report.md", "diagnostics.json"}, archive: {filename, base64}, sharing: {githubIssueUrl, discordUrl, description}}` | -| `cancel` | `{reportId, target: "generation", planId}` or `{reportId, target: "report"}` | `{cancelled: boolean}`. Generation cancellation affects only the named in-flight plan and keeps the evidence available for a new plan. An inactive plan returns `{cancelled: false}`. Report cancellation drops the draft. | +TimelineTree's bounded branch read and branch summary ([#2024](https://github.com/arcships/dim/issues/2024)); SessionScope's hold and closing ([#2025](https://github.com/arcships/dim/issues/2025)); ManagementMethods' `register` (process namespace) and the Session method table's registration; the process build label and protocol version for diagnostics. -The TUI omits `error` for a Session report and sends the `observed` variant to the process entry for a conversation-open failure. Clients with an error-bound action, such as the Desktop and Web action in §2, can use the `timeline` variant to attach a known failure position in an admitted Session. +### Operations -The local plan uses `generation: {kind: "local"}`. The `evidence` object includes the filtered diagnostic sources and a Timeline availability reason when activity records are absent. For a Session report, only a local plan with `redact: false` and Timeline enabled may also return `evidence.conversation` (an ordered array of `{role, sequence, text}`); the field is absent if no eligible text is available. `generate` renders that plan without reading later messages. Options recognizes comma- or newline-separated `omit` and `keep` directives for `timeline`, `error codes`, and `correlation ids`. The reply reports `instructionsStatus` as `none`, `applied`, `partially_applied`, or `unsupported`. It does not echo the entered text. Redaction always removes correlation IDs, so `keep correlation ids` is unsupported while redaction is on. +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `prepare` | Capture a bounded snapshot and open a draft | `{error?}`; the process namespace requires `error` in the observed variant | `{reportId, defaultModel?, plan}` | Before the snapshot is captured; nothing is drafted | `caller_required`, `invalid`, `unavailable` | +| `plan` | Bind the exact material, generation and directives | `{reportId, generation, redact, instructions?}` | `{planId, generation, evidence, instructionsStatus}` | None; the plan is a value | `not_found`, `invalid`, `busy`, `model_unavailable` | +| `generate` | Consume the plan and produce the archive | `{reportId, planId}` | `{title, body, files, archive, sharing}` | The named plan stops; the evidence stays for a new plan | `not_found`, `stale`, `busy`, `generation_failed`, `cancelled` | +| `cancel` | Stop a generation or drop a draft | `{reportId, target: "generation", planId}` or `{reportId, target: "report"}` | `{cancelled}` | — | `not_found` | -The observed error contains `operation` (`session_read`, `session_fork`, `branch_create` or `model_generation`), `code?`, `observedAt` (UTC timestamp) and `clientVersion` (the reporting client's build label, as the client's own `--version` prints it). No reader orders or compares it; it is display only. These fields carry neither Session authority nor a provider connection. The report ID and plan ID are opaque. Access requires the same caller connection and, for a Session draft, the same admitted Session. A missing, expired or foreign draft returns `report_not_found`. Invalid fields return `invalid_params`. A replaced or consumed plan returns `report_plan_stale`. A concurrent generation returns `report_busy`. A missing or changed model selection returns `report_model_unavailable` before a request. The other execution failures use `report_generation_failed` or `report_cancelled`. Error messages use stable summaries. Prepare returns a local plan when no usable model is available and retains the adopted model identity when known. +The draft is keyed by the calling connection and the part instance; a missing, expired or foreign draft is `not_found`. A new `prepare` replaces an idle draft for that connection. At most 16 drafts per part instance; a seventeenth is `busy`. The observed input and instructions are bounded to 1 KiB each; the prepared model material to 8 KiB; the encoded ZIP to 64 KiB before the reply. -An immutable plan binds the exact material, selected model connection revision and output allowance. Generate atomically consumes the plan before starting work. Duplicate or late requests cannot resend it. Changing settings or retrying requires a new plan and a new explicit Generate. A model timeout or an ambiguous provider failure consumes the plan. Cancellation fences late replies, and a new generation waits for the old work to settle. Successful generation releases the draft and transfers the finished preview to the client. Closing the dialog or losing the connection releases any draft still open. The part cancels and settles accepted work on Session closing or unload using the existing call lifecycle and caller-closed signal. A bounded Session hold keeps the dialog alive between calls. [Part lifecycle](../plugin-contract.md#7-lifecycle-of-a-part), [call channels](../contracts/session-boundary.md#a2-call-channel), [activity holds](../appserver/idle-unload.md#51-activity-hold). +### Errors -Use one draft per caller connection in each part instance, with a five-minute expiry and at most one generation in flight per draft. A new prepare replaces an idle draft for that connection. Allow up to 16 simultaneous drafts per part instance and return `report_busy` when full. Refuse replacement while a generation is settling. Bound the observed input and instructions to 1 KiB each and the prepared model material to 8 KiB. Bound model output to the lower of 1,024 tokens and the owner's allowance, with a 30-second generation deadline. Limit the encoded ZIP before constructing the RPC reply (§6). Expiry, connection loss, and close discard unsettled outputs. Drafts are ephemeral and have no on-disk store. +| Kind | What the caller does next | +| --- | --- | +| `caller_required` | The method needs a client connection; an in-process caller cannot prepare a report | +| `invalid` | Fix the request: a missing or malformed error reference, a model id outside the admitted catalog, an out-of-range field | +| `unavailable` | No draft can be prepared now: the Session is closing or its evidence cannot be read; use the local template or retry later | +| `not_found` | The draft expired or belongs to another connection; prepare again | +| `stale` | The plan was replaced or consumed; review the new plan before generating | +| `busy` | A generation is running for this draft; cancel it or wait for it to settle | +| `model_unavailable` | The selected model cannot serve this request; choose another or generate locally | +| `generation_failed` | The generation failed; the draft keeps its evidence and the caller retries with a new plan or generates locally | +| `cancelled` | The generation stopped; the draft keeps its evidence | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `prepare` | Capture the snapshot at the published cutoff within the bounds, take the Session hold, open the draft | The snapshot read stops; no draft | The draft is discarded with the part | Every draft is discarded and its hold released | Report: the draft and its hold | +| `plan` | Validate the request, compute the reviewed evidence, replace the previous plan | — | The draft is discarded | The plan is discarded with the draft | Report | +| `generate` | Consume the plan atomically, render or run the one-shot model call, return the archive | The named plan stops; late output is discarded; the evidence stays | The draft and its work are discarded | Accepted work settles; late output is discarded | Report | +| `cancel` | Stop the named generation or drop the draft | — | — | — | Report | + +### Exceptions with reasons + +- The process namespace accepts no Session or branch id: an error-only report must work when Session admission failed, so the part has no Session to name. +- The archive is returned in the `generate` reply: the client must be able to save after the connection closes, and a second download resource would be another owner's store. +- Evidence is read at the published cutoff and rendered later: the snapshot is a projection Report owns, so a later turn cannot change a reviewed plan. ## 5. Generation @@ -122,27 +170,30 @@ The client keeps the completed preview and bytes when a share action fails. The ## 7. Requirements raised to mechanism owners -| Blocker and existing alternatives | Required capability and ordering | Owner | +| Owner | Required operation or value | Why the caller cannot compose it | | --- | --- | --- | -| Session contribution admission requires a loaded Session. A conversation read may fail before that load completes. Local management contributions work outside a Session, but Web exposes only explicitly admitted names and paired entries serve only Session methods. | Admit the error-only methods on the authenticated local Web entry via its explicit allowlist. A paired error-only path needs an agreed authenticated admission contract for narrowly scoped client operations without a Session. Reject such calls under the current paired contract. The entry grants no Session access, adds no facts, and keeps existing disconnect and reload semantics. | App Server Web entry and Rpc owners, [#1319](https://github.com/arcships/dim/issues/1319). [Web admission](../web-workspace.md#23-http-surface), [paired entry](RemoteGateway.md). | -| The auxiliary call accepts one request from its consumer but invokes the shared retry and credential-recovery policy underneath. A report cannot enforce its request budget from the caller side. | Offer a caller-selectable single-attempt policy through the auxiliary boundary, including its provider transport. The owner enforces the prepared target revision and never retries or substitutes after a send. Preserve cancellation, reload settlement and other callers' policy. Enable model-assisted reports only where the owner can honor this contract. | Auxiliary model and provider owners, [#1319](https://github.com/arcships/dim/issues/1319). [Auxiliary model interface](../appserver/auxiliary-model.md#4-interfaces), [model retry policy](../model-failures.md). | -| The curated TUI list has no `/report` slot. A hidden command would leave the documented command discoverability incomplete. | The CLI command owner adds the menu entry with the order and behavior in §2. This is client-side and does not affect Timeline ordering, interruption or reload. | CLI command owner, [#1319](https://github.com/arcships/dim/issues/1319). [Command menu](../cli-commands.md#command-menu). | - -## 8. Dependencies and rule check +| TimelineTree ([#2024](https://github.com/arcships/dim/issues/2024)) | A bounded branch read `{branchId, through, kinds, limit} → {events, truncated}` and a branch summary `{head, adoptedModel}`; the default branch id | The read must stop at a committed cutoff and stay inside the owner's pages; composing it from raw queries would let the caller re-fold branch state | +| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `hold() → holdId`, `release(holdId)`, `closing()` | The hold keeps the Session loaded while the dialog is open; its settlement is the Session owner's | +| Session registration ([#2026](https://github.com/arcships/dim/issues/2026)) | The Session method table's `call` request carries `{method, params, caller: {connectionId, callId}}` | Report binds its draft to the calling connection; the caller identity is data | +| Provider ([#2019](https://github.com/arcships/dim/issues/2019)) | A one-shot completion with a caller-selected no-retry policy and the exact prepared material | Model-assisted generation is outside this contract until the owner offers that operation; the local template stays the default | +| Web entry (App Server, this block) | Admit the process `report.*` namespace on the authenticated local Web entry | The error-only entry is served to the web client; the admission list is the entry's | -The Session part declares the `sessionMethods`, `sessionLifecycle` and `treeCommands` data faces. It uses the [public branch read surface](../timeline-read-ownership.md#8-binding-appendix) for the published cutoff and adopted model selection. The process part declares the `managementMethods` and `partRegistry` data faces. Both use caller origin and the process build metadata already available to App Server. With no approved typed diagnostics source, build and platform information are sufficient process evidence. Model-assisted generation depends on the model owners in §7. App Server composes the parts as one feature. [Service catalog](../../architecture/rust-agent/generated/catalog.md). +## 8. Rule check -| Rule | Check | +| Rule | Application | | --- | --- | -| Principles §1 and ADR 002 D1 | Report has a Session part and a process part for its respective draft scopes. Neither is a Capability. They read a bounded snapshot and do not fold or write Timeline state. | -| §4 rules 1 and 2 | Neither part commands another state owner or hands off an object through the Timeline. The client explicitly submits an immutable plan to its owner. | +| Principles §1 and ADR 002 D1 | Report has a Session part and a process part for their draft scopes; neither is a Capability. | +| §2 scopes | The Session part drafts for its Session; the process part drafts for errors without a readable Session. | +| §3 orthogonality | No other owner's state is read; TimelineTree, SessionScope and the method tables are asked through their operations. | +| §4 rules 1 and 2 | Neither part commands another state owner or hands off an object through the Timeline; the client submits an immutable plan. | | §4 rules 3 and 5 | No before callback or event batch applies. | -| §4 rules 4 and 8 | Report uses generic method admission, public reads and lifecycle. Owner changes needed for Web admission and model policy are listed in §7. | -| §4 rule 6 | Source context is untouched. The isolated operation uses only reviewed material. | -| §4 rule 7 and ADR 002 D3 | Dependencies point to public read, lifecycle, and model services. Report reads no private storage or provider state. | -| §4 rule 9 | No Timeline events or broadcast notices are added. Results go to the originating RPC caller. | -| ADR 002 D2 | The feature owns the report work and state. Its parts register their own methods. | -| ADR 002 D4 and D5 | Per-report settings live in the draft. The RPC contract is language-neutral. | +| §4 rules 4 and 8 | Report uses generic method admission, public reads and lifecycle; the requirements above are the only owner changes. | +| §4 rule 6 | Source context is untouched; the one-shot operation uses only reviewed material. | +| §4 rule 7 and ADR 002 D3 | Dependencies point to public read, lifecycle and model services; no private storage or provider state is read. | +| §4 rule 9 | No Timeline events or broadcast notices; results go to the originating caller. | +| §7 no handle | The draft, the plan and the ZIP are values addressed by ids; the Session hold is an id. | +| ADR 002 D2 | The feature owns the report work and state; its parts register their own methods. | +| ADR 002 D4 and D5 | Per-report options live in the draft; the RPC contract is language-neutral. | ## 9. Verification @@ -157,3 +208,68 @@ The Session part declares the `sessionMethods`, `sessionLifecycle` and `treeComm ## 10. Ablation The Session namespace serves current-Session reports through the existing prepare method. The process entry is needed for a conversation-open error that fails Session admission and uses the same flow with fewer evidence sources. The plan ID ties a paid request to the exact preview the user confirmed. The bounded ZIP in the generation reply lets the client save without a second download resource or archive store. An isolated one-shot model operation supplies drafting and redaction without a general-purpose report Session. + +## 11. Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PrepareRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PrepareReply { + pub report_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_model: Option, + pub plan: Plan, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PlanRequest { + pub report_id: String, + pub generation: Generation, + pub redact: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GenerateReply { + pub title: String, + pub body: String, + pub files: std::collections::BTreeMap, + pub archive: Archive, + pub sharing: Sharing, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ReportError { + #[error("Report methods require a client connection")] + CallerRequired, + #[error("{message}")] + Invalid { message: String }, + #[error("The report cannot be prepared now")] + Unavailable, + #[error("The report draft is missing or expired")] + NotFound, + #[error("The plan was replaced or consumed")] + Stale, + #[error("A generation is running for this report")] + Busy, + #[error("The selected model is unavailable")] + ModelUnavailable, + #[error("The generation failed")] + GenerationFailed, + #[error("The generation was cancelled")] + Cancelled, +} +``` + +The two namespaces register the same four operations: `session.report.*` on the Session method table and `report.*` on the process table. diff --git a/docs/design/plugins/Rpc.md b/docs/design/plugins/Rpc.md new file mode 100644 index 0000000000..a98bb63f6a --- /dev/null +++ b/docs/design/plugins/Rpc.md @@ -0,0 +1,146 @@ +# Rpc + +Scope: process. Issue: #2021. + +Rpc owns the daemon's inbound protocol entry: the handshake, the built-in methods, the routing to method namespaces, and the settlement of accepted commands. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/connection.rs` (`RpcService`, `RpcPlugin`). Connection, ManagementMethods, CallChannel, Agents and ServerControl are separate owners with their own contracts. + +## Use and scope: responsibility split + +Rpc owns: + +- **The handshake.** Which protocol versions a connection may greet with, what the greeting records, and what the greeting reply carries. +- **Built-in methods.** `daemon.ping`, `daemon.shutdown`, `session.*` and the other methods the protocol reserves; each built-in's admission and reply. +- **Routing.** For each call: the management table, the Session's table, or a built-in; the caller identity the table receives; the call id notifications are addressed by. +- **Command settlement.** The commands a call starts, their drain on unload, and the interruption kinds their declarations name. + +Rpc writes no Timeline fact and holds no connection. + +Callers keep: + +- Reading frames and writing replies: Connection owns the socket, the outbound queue and the reply ordering. +- The namespace table and the registered handlers: ManagementMethods and the Session's method table own them. +- Authorizing Session access: Agents decides whether a Session may be acquired; the built-in methods carry the decision. +- The shutdown sequence: ServerControl owns the intent; the assembly runs the sequence. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A greeting must be answered or refused with the current generation | No: the version window, the records and the method list are the owner's state | `hello` | +| A frame must be dispatched by the protocol rules | No: built-ins, routing and the caller identity are the owner's | `request` | +| A call's commands must drain when this generation unloads | No: the command set is the owner's | `request` (settlement) | + +An operation or parameter exists only where the row says No. + +## Caller example + +```rust +// Connection reads one frame and asks the current generation. +let hello = rpc.hello(HelloRequest { connection_id: id.clone(), params }).await?; +connection.write(hello.reply); + +let reply = rpc.request(RequestCall { connection_id: id, call_id, request }).await?; +connection.write_after(WriteAfter { connection_id: id, call_id, frame: reply.frame }).await?; +``` + +## Own contract + +### Dependencies + +Connection's `write_after` and `attached`; ManagementMethods' `call`; the Session's method table (the same shape, per [ManagementMethods](ManagementMethods.md)); Agents' `acquire` and running/close operations; CallChannel's `bind` and `finish`; ServerControl's `shutdown`. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `hello` | Answer a client's greeting for this generation | `{connection_id, params}` | `{reply, records}` | None; the handshake is one step | `reloading` (no generation is serving), `invalid` (version, entry or hello fields), `closed` | +| `request` | Dispatch one call and settle what it starts | `{connection_id, call_id, request}` | `{reply}` | The calling connection closing ends the call as interrupted; an unload ends it by the method's declaration | `reloading`, `unknown_method`, `interrupted`, `invalid`, and the method's own error | + +`request` mints nothing: the `call_id` comes from Connection, so the provider, CallChannel and the reply ordering name one call. The method's own errors are the data the table returns; Rpc maps them to the protocol envelope and does not add kinds. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `reloading` | Retry after the next generation is installed; the connection stays open | +| `unknown_method` | The name no namespace holds; the client sees the method error | +| `interrupted` | The call may have committed; read the current state before retrying | +| `invalid` | The frame or the greeting is malformed; answer the client with the protocol error | +| `closed` | The connection is gone; nothing was dispatched | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `hello` | Check the version window and the entry, record the greeting, build the method list | — | — | New hellos are refused as `reloading`; open connections stay | Rpc | +| `request` | Route, admit through the table with the caller identity and `call_id`, return the reply; commands settle in Rpc's tracker | A closing connection ends the call as interrupted | The call ends and its commands settle | An unloading generation cancels its commands, answers pending waits as interrupted and drains before unload; connections stay open | Rpc: the commands | + +## Exceptions with reasons + +- The built-in methods are a closed set on the owner type, not registrations: they are the protocol's own methods and never appear in the management table. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Rpc is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: the dispatcher serves every connection and every Session. | +| §3 orthogonality | No other owner's state is read; Connection, the tables, CallChannel and Agents are asked through their operations. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use `hello` and `request`; no caller sees the command set or the routing tables. | +| §8 rule | An unloading generation settles its accepted commands before its services go. | +| §7 no proxy | The reply is returned as data and written by Connection; Rpc does not hold the socket. | +| ADR 002 D1 | Process scope: one dispatcher per process generation. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | Dependencies point to the owners being asked; none is stored. | +| ADR 002 D4 | No business setting. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Session registration (#2026)**: the Session method table's dispatch takes the same `{method, params, caller: {connectionId, callId}}` request and returns the same reply data, so one call path serves both tables. + +## Binding appendix + +```rust +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HelloRequest { pub connection_id: String, pub params: HelloParams } + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HelloReply { pub reply: Frame, pub records: Vec } + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestCall { + pub connection_id: String, + pub call_id: String, + pub request: Request, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestReply { pub reply: Reply } + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum RpcError { + #[error("Service is reloading; retry")] + Reloading, + #[error("Unknown method")] + UnknownMethod, + #[error("Service reloaded; the call may have committed")] + Interrupted, + #[error("{message}")] + Invalid { message: String }, + #[error("The connection is closed")] + Closed, +} + +#[rutis::service(name = "rpc")] +impl RpcService { + pub async fn hello(&self, request: HelloRequest) -> Result { /* ... */ } + pub async fn request(&self, request: RequestCall) -> Result { /* ... */ } +} +``` + +`Connection` looks the `rpc` service up on each frame; a generation that is unloading refuses new frames as `reloading`. diff --git a/docs/design/plugins/ServerControl.md b/docs/design/plugins/ServerControl.md new file mode 100644 index 0000000000..a88e08323b --- /dev/null +++ b/docs/design/plugins/ServerControl.md @@ -0,0 +1,160 @@ +# ServerControl + +Scope: process. Issue: #2021. + +ServerControl owns the process's publication gate, its shutdown intent and its admission of accepted work. `processActivity` is the one name this owner publishes; the current `serverControl` object and its second `processActivity` name are replaced. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/control.rs`. The assembly that runs the shutdown sequence keeps its own sequence; Connection, Agents and Rpc are separate owners. + +## Use and scope: responsibility split + +ServerControl owns: + +- **Publication.** Whether the host has opened: every required process row is Active and the runtimes released their rows. A row reload does not reset it. +- **Shutdown intent.** One request, its mode and its force flag. The first request wins; later requests are refused. +- **Accepted work.** Holds taken before work starts and released after the last owned effect settles. A hold keeps a shutdown graceful. +- **Listener faults.** The first listener exit becomes the process fault and begins the close. + +Callers keep: + +- The shutdown sequence: settling Agents, draining Rpc's commands, closing connections and answering the initiating client are the assembly's. +- What counts as accepted work: each holder takes a hold around its own effects. +- Session pauses: Agents owns them; ServerControl does not store another owner's guard. +- The client methods: `daemon.ping` and `daemon.shutdown` are Rpc's; this owner answers the intent they carry. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A process part must wait for the host to open before starting work | Yes: `activated` composes | `activated` | +| A part must stop when the daemon starts closing | Yes: `closing` composes | `closing` | +| A holder must stop a graceful close while its accepted work runs | No: only the owner sees every hold and can decide the intent | `hold`, `release` | +| The idle-close decision needs to know whether accepted work is held | Yes: `holds` composes | `holds` | +| A client asks the daemon to shut down | No: one intent, one mode and one force flag are the owner's state | `shutdown` | +| A listener exit must end the daemon | No: the first fault is the owner's state | `fault` | + +An operation or parameter exists only where the row says No. + +## Caller example + +A process part that starts work before any Session exists: + +```rust +if !activity.activated().await { + return Err(WorkError::HostClosed); // startup failed or shutdown began +} +let hold = activity.hold().ok_or(WorkError::HostClosed)?; +let result = run_work().await; +activity.release(hold); +``` + +The `daemon.shutdown` handler: + +```rust +match activity.shutdown(ShutdownMode::Graceful) { + Ok(()) => { /* hold the reply until the assembly settles, then write it */ } + Err(ShutdownError::Conflict) => return Err(RpcError::invalid("Shutdown already requested")), +} +``` + +A part that must stop: + +```rust +tokio::select! { + _ = activity.closing() => return, + frame = read_frame() => handle(frame).await, +} +``` + +## Own contract + +### Dependencies + +None. The owner injects no service. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `activated` | Whether the host has opened; a reload does not reset it | `{}` | `{activated}` | None | none | +| `closing` | Wait until the daemon starts closing | `{}` | `{}` when closing begins | The caller's token; the wait ends | none | +| `hold` | Keep a graceful close until the work settles | `{}` | `{hold_id}` | None; the id is settled by `release` or the row's unload | `closed` | +| `release` | The work settled | `{hold_id}` | `{released}`; an already released id is `false` | None | none | +| `holds` | Whether any accepted work is held now | `{}` | `{count}` | None | none | +| `shutdown` | Ask the process to close | `{mode: graceful \| forced}` | `{}` accepted | None; the close cannot be cancelled | `conflict` | +| `fault` | A listener exited; end the process | `{listener, message}` | `{}` | None | none | + +A hold is released by the calling row's unload as well as by `release`: an id that outlives its row is released when the row unloads, and the reply to a later `release` is `false`. A row that crashes without unloading keeps its hold until the process ends, and the close is forced. + +`shutdown` does not run the sequence. It records the intent; `closing` resolves for every waiter; the assembly settles Agents, drains Rpc, closes connections and answers the initiating client. A second `shutdown` with any mode is `conflict`. + +`fault` records the first listener failure; the assembly reports it as the exit reason. A later fault does not replace it. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `closed` | The daemon is closing; stop starting work | +| `conflict` | A shutdown was already requested; answer the client as already requested | + +No other error exists: the owner has no "not found", "invalid input" or "too large" state. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `hold` | Increment under the admission check; a closing owner refuses | — | The row's holds are released | New holds are refused as `closed`; held work keeps the close graceful | The holder and the owner | +| `shutdown` | Record the mode and the force flag, resolve `closing` | — | — | The intent survives until the process ends | The owner | +| `closing` | Resolve every waiter once | The caller stops waiting; the intent stands | The waiter disappears | — | The owner | +| `fault` | Record the first fault, resolve `closing` | — | — | A later fault is ignored | The owner | + +## Exceptions with reasons + +- `processActivity` is the single published name for a merged owner: the publication gate, the holds and the shutdown intent share one plugin and one lifecycle, and `serverControl` had no method of its own. Keeping the name avoids a wire rename for Workflow and Scheduler. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | ServerControl is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: the gate, the intent and the holds outlive every Session. | +| §3 orthogonality | No other owner's state is read. Session pauses are Agents'. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use these operations; no caller sees the gate, the intent or the hold table. | +| §4 rule 8 | No infrastructure change. | +| §7 no proxy | The owner does not hold another owner's guard; `holds` is a count, not a list of ids. | +| ADR 002 D1 | Process scope: one per process, shared by every Session. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | No dependency; every part may depend on it. | +| ADR 002 D4 | No business setting. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Agents (#2020)**: the Session pause and settle that the assembly runs after `shutdown` is accepted. The owner keeps no `SessionPause` value. + +## Binding appendix + +```rust +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ShutdownMode { Graceful, Forced } + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ActivityError { + #[error("The daemon is closing")] + Closed, + #[error("Shutdown already requested")] + Conflict, +} + +#[rutis::service(name = "processActivity")] +impl ProcessActivity { + pub async fn activated(&self, request: Empty) -> ActivatedReply { /* ... */ } + pub async fn closing(&self, request: Empty) { /* waits */ } + pub async fn hold(&self, request: Empty) -> Result { /* ... */ } + pub async fn release(&self, request: ReleaseRequest) -> ReleasedReply { /* ... */ } + pub async fn holds(&self, request: Empty) -> HoldsReply { /* ... */ } + pub async fn shutdown(&self, request: ShutdownRequest) -> Result<(), ActivityError> { /* ... */ } + pub async fn fault(&self, request: FaultRequest) { /* ... */ } +} +``` + +`HoldId` is a `u64`; the id is not authority — the owner releases it by id or by the calling row's unload. diff --git a/docs/design/plugins/Transport.md b/docs/design/plugins/Transport.md new file mode 100644 index 0000000000..4ff06e3f9b --- /dev/null +++ b/docs/design/plugins/Transport.md @@ -0,0 +1,111 @@ +# Transport + +Scope: process. Issue: #2021. + +Transport owns the daemon's listening endpoints. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/transport.rs`. Connection, ServerControl and Rpc are separate owners with their own contracts; their calls appear in the delivery tables as caller rows. + +## Use and scope: responsibility split + +Transport owns: + +- **Endpoints.** The Unix socket, the named pipe and the TCP listener, their files, their private directory and their lock. An endpoint exists only because Transport bound it. +- **Binding order.** Endpoints bind after the database lock is held, when the host has one, and accepting starts only after the host publishes. +- **Accepting.** The accept loop that turns a listener event into an accepted stream, and the stop when the daemon closes. +- **Endpoint faults.** The first listener exit is reported once as a process fault. + +Callers keep: + +- What a connection is and what happens to its frames: Connection owns admitted streams. +- The daemon's shutdown sequence: ServerControl owns the intent; the assembly runs the sequence. +- How a launcher learns the address: the value `read` returns; the CLI's startup output is a launcher's transport. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A launcher or an entry plugin needs the addresses actually bound | No: the bound port after a bind to zero and a non-UTF-8 socket path are the owner's knowledge | `read` | + +An operation or parameter exists only where the row says No. + +## Caller example + +```rust +let bound = transport.read().await?; +if let Some(path) = bound.unix_path { + connect(path).await?; // the caller decides which endpoint it uses +} +``` + +## Own contract + +### Dependencies + +Connection's `accept`, called once per accepted stream; ServerControl's `activated` and `fault`. Neither is stored. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `read` | The addresses this process bound | `{}` | `{unixPath?, pipeName?, websocketAddress?}` | None | `invalid` | + +`read` converts the bound addresses to UTF-8 text; a Unix path that is not UTF-8 is `invalid`, and the rest of the reply is not sent. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The bound Unix path is not UTF-8; use another endpoint or start the daemon with a UTF-8 path | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `read` | Read the owner's bound values | — | — | Pending calls end with the generation | Transport | +| (accept loop) | Wait for `activated`, accept, call `Connection::accept`, repeat | — | The listener task ends with the owner | The loop stops on `closing`; the socket file is removed only when its inode is still the one this generation created | Transport: the listener and its file | + +## Exceptions with reasons + +- The accept loop is internal: a listener event is not data. Transport calls `Connection::accept` crate-internally; the stream's lifecycle is fixed in the [Connection contract](Connection.md). + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Transport is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: endpoints outlive every Session. | +| §3 orthogonality | No other owner's state is read; Connection and ServerControl are asked through their operations. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use `read`; no caller sees a listener or a socket file. | +| §4 rule 8 | No infrastructure change. | +| §7 object handover | Only the accepted stream, by `Connection::accept`; fixed in the Connection contract. | +| ADR 002 D1 | Process scope: endpoints are process resources. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | Transport depends on Connection and ServerControl as operations. | +| ADR 002 D4 | Endpoints are structural configuration from the loader row; no business setting. | +| ADR 002 D5 | `read` is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BoundAddresses { + pub unix_path: Option, + pub pipe_name: Option, + pub websocket_address: Option, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ListenError { + #[error("{message}")] + Invalid { message: String }, +} + +#[rutis::service(name = "listenAddresses")] +impl Transport { + pub async fn read(&self, request: Empty) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/UiExtensions.md b/docs/design/plugins/UiExtensions.md new file mode 100644 index 0000000000..99d3ca2caf --- /dev/null +++ b/docs/design/plugins/UiExtensions.md @@ -0,0 +1,169 @@ +# UiExtensions + +Scope: process. Issue: #2021. + +UiExtensions owns the daemon's UI content catalog: which plugin packages contribute interface panels, what each declared, the prepared generation of each, and the directory clients read. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/ui_extensions/`, and the public contract of the client methods is [client UI extensions](../client-ui-extensions.md). PluginManager, FileStorage, Connection and UiResources are separate owners. + +## Use and scope: responsibility split + +UiExtensions owns: + +- **Registrations.** One entry per plugin id: the declaration, the prepared generation and the refusal reason when preparation failed. +- **Preparation.** Copying the declared content into the owner's cache, validating versions, roots and panel files, and publishing a generation atomically. +- **The directory value.** Revisions, extensions and errors as clients read them. +- **Bounded reads.** A page of a prepared file, by generation and path. +- **The change event.** One process event carrying the revision when the published directory changes. + +Callers keep: + +- Which package is installed and enabled: PluginManager decides and forwards the plugin id and declaration. +- What a panel renders: the client owns mounting and selection. +- Writing the cache: the cache is UiExtensions' own directory. +- Telling a client: Connection turns the change event into the client's notification. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| PluginManager registers a package's UI declaration by plugin id | No: validation, preparation and the atomic generation switch are the owner's | `register` | +| PluginManager withdraws a package | No: the generation and its reads must be settled | `withdraw` | +| PluginManager lists the packages with content and asks why one was refused | Yes: `plugins` and `refusal` compose | `plugins`, `refusal` | +| A client reads the directory and a panel file | No: the revision and the prepared generation are the owner's | `directory`, `read` | +| A client is told the directory changed | Yes: the change event composes | event | + +An operation or parameter exists only where the row says No. + +## Caller example + +PluginManager registers a package's declaration: + +```rust +ui.register(RegisterRequest { plugin: id, manifest: Some(declaration) }).await?; +// A refusal is reported in the directory; the package's code row is unaffected. +``` + +A client reads the directory and one panel file: + +```rust +let directory = ui.directory().await?; // revision, extensions, errors +let page = ui.read(ReadRequest { generation, path, offset: 0, limit: None }).await?; +``` + +## Own contract + +### Dependencies + +FileStorage (`add_root`, `list`, `read`) for the declared roots and files; ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish one package's UI content | `{plugin, manifest?}` | `{}`; a failed preparation is recorded as a refusal, not an error | While the files are copied; nothing is published | `invalid` (unknown plugin id, unsupported version, bad declaration) | +| `withdraw` | Remove a package's content | `{plugin}` | `{}` | None; the owner settles admitted reads | none | +| `plugins` | The packages with content now | `{}` | `{plugins: [id]}` | None | none | +| `refusal` | Why a package's content was refused | `{plugin}` | `{message?}` | None | none | +| `directory` | The published directory | `{}` | `{revision, extensions, errors}` | None | none | +| `read` | One page of a prepared file | `{generation, path, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The calling connection's task ends; the page stops | `unavailable` | + +`register` with no manifest withdraws the package's content, the same as `withdraw`. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The package id is unknown, the version unsupported or the declaration invalid; the reason is recorded as the package's refusal | +| `unavailable` | The file is gone or unreadable; the client shows the panel as unavailable | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Validate, copy into a new generation directory, swap the catalog entry, bump the revision, emit the change event | The generation directory is removed, the old entry stays | The registration is dropped with the process row | Sources are retained and restored on the next generation | UiExtensions: the generation directory and its reads | +| `withdraw` | Remove the entry, cancel admitted reads, wait for them, remove the directory, emit the change event | — | — | — | UiExtensions | +| `read` | Resolve the generation and the path, read one bounded page under the read counter | The page stops; nothing changes | The read token is released | Admitted reads are cancelled and awaited before the directory goes | UiExtensions | + +## Exceptions with reasons + +- `register` takes the declaration as an optional value: a package with no UI member withdraws, and the owner resolves the installation directory by plugin id through PluginManager, so no path or handle crosses. +- The change event is the owner's fact, not a subscription: a subscriber reads `directory` when the revision differs, so no freshness state crosses. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | UiExtensions is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: content serves every connection and every Session. | +| §3 orthogonality | No other owner's state is read; PluginManager and FileStorage are asked through operations. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact; the change event is a process event, not a Timeline fact. | +| §4 rule 7 | Callers use these operations; no caller sees the catalog or a prepared file handle. | +| §7 no proxy | The catalog, the generation and the reads are this owner's; FileStorage supplies bytes. | +| ADR 002 D1 | Process scope: content outlives Sessions. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | PluginManager and the client entry depend on this owner; it depends on FileStorage and the method table. | +| ADR 002 D4 | Content declarations are structural (the package manifest); no business setting. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. FileStorage's contract (#2016) supplies `add_root`, `list` and `read`. + +## Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterRequest { + pub plugin: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub manifest: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectoryReply { + pub revision: u64, + pub extensions: Vec, + pub errors: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadRequest { + pub generation: String, + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub offset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Page { + pub offset: u64, + pub bytes: usize, + pub total: u64, + pub media_type: String, + pub data: String, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ContentError { + #[error("{message}")] + Invalid { message: String }, + #[error("The UI content file is unavailable")] + Unavailable, +} + +#[rutis::service(name = "uiExtensions")] +impl UiExtensions { + pub async fn register(&self, request: RegisterRequest) -> Result<(), ContentError> { /* ... */ } + pub async fn withdraw(&self, request: PluginRef) { /* ... */ } + pub async fn plugins(&self, request: Empty) -> PluginsReply { /* ... */ } + pub async fn refusal(&self, request: PluginRef) -> RefusalReply { /* ... */ } + pub async fn directory(&self, request: Empty) -> DirectoryReply { /* ... */ } + pub async fn read(&self, request: ReadRequest) -> Result { /* ... */ } +} +``` + +The process event is `uiExtensions/changed {revision}`; Connection carries the revision to clients that asked for it. diff --git a/docs/design/plugins/UiHost.md b/docs/design/plugins/UiHost.md new file mode 100644 index 0000000000..ffdb87e5f5 --- /dev/null +++ b/docs/design/plugins/UiHost.md @@ -0,0 +1,196 @@ +# UiHost + +Scope: process. Issue: #2021. + +UiHost owns the daemon's interface registrations: which interfaces are alive on which Session, their generations, their one-time attach tokens, and the UI leaf sessions the daemon mounts for interactive `dimcode` processes. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/ui_host.rs` and `ui_leaf.rs`, and its behaviour is described in the [Tui design](Tui.md#36-ui-registry-and-ui-leaves). Connection, Rpc and UiExtensions are separate owners. + +## Use and scope: responsibility split + +UiHost owns: + +- **Registrations.** One record per interface: the Session it views, its kind, its generation, and the connection that registered it. +- **Leaves.** The rutis session mounted for an interactive leaf, its one-time token, its twenty-second start window, and its disposal when the session or the interface ends. +- **Replacement.** Claiming the interface a replacement replaces, and closing it once the replacement attaches. +- **Notices.** The advisory close notice on the interface's connection. + +Callers keep: + +- Whether the calling connection views the Session: Connection answers `attached`. +- Writing to the connection: Connection writes the advisory notice. +- What an interface shows: the client's own tree. +- The UI content catalog: UiExtensions owns it; UiHost only names the kind. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client opens an interface on a Session it views | No: the token, the generation and the leaf session are the owner's | `open` | +| A connection registers itself on a Session | No: one registration per connection and Session and the generation are the owner's | `attach` | +| A connection replaces another interface | No: the claim and the expected generation are the owner's | `replace` | +| A client lists the live interfaces | Yes: `status` composes | `status` | +| A client or the daemon closes an interface | No: the notice, the leaf disposal and the registration removal are one settlement | `close` | +| The daemon advises an interface to leave without closing it | No: the notice is the owner's | `shutdown` | +| A connection stopped viewing a Session | No: the registration's connection binding is the owner's | `detach` | +| A connection ended | No: every registration naming it is the owner's | `release` | + +An operation or parameter exists only where the row says No. + +## Caller example + +Rpc opens an interface for a leaf that is waiting on its address: + +```rust +let opened = ui_host.open(OpenRequest { + connection_id: caller.clone(), + session_id, + kind: "tui".into(), + peer, + address, + replace, + expected_generation, +}).await?; +// The reply carries the one-time token the leaf passes to `attach`. +``` + +A browser registers a plain interface: + +```rust +let attached = ui_host.attach(AttachRequest { + connection_id: caller, session_id, kind: "web".into(), ui_id: None, token: None, +}).await?; +``` + +## Own contract + +### Dependencies + +Connection's `attached` and `write`; the process root for mounting a leaf session. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `open` | Reserve an interface and mount a leaf's session | `{connection_id, session_id, kind, peer, address, replace?, expected_generation?}` | `{ui_id, generation, token}` | While the leaf session is mounted; a failed start leaves nothing registered | `not_attached`, `invalid`, `ui_unknown`, `ui_generation`, `ui_leaf_failed` | +| `attach` | Register a connection as an interface of a Session | `{connection_id, session_id, kind, ui_id?, token?}` | `{ui_id, generation}` | None | `not_attached`, `invalid`, `ui_token`, `ui_in_use`, `ui_unknown` | +| `replace` | Replace an interface with a new registration | `{connection_id, session_id, kind, ui_id, expected_generation?}` | `{ui_id, generation}` | None | `not_attached`, `invalid`, `ui_unknown`, `ui_generation` | +| `status` | The live interfaces and the count of web connections | `{}` | `{instances, web_connections}` | None | none | +| `close` | Remove an interface; a leaf's session ends | `{ui_id, reason?}` | `{}` | None; the owner settles the notice and the leaf | `ui_unknown` | +| `shutdown` | Advise an interface to leave, without closing it | `{ui_id, reason?}` | `{}` | None | `ui_unknown`, `ui_detached` | +| `detach` | A connection stopped viewing a Session | `{connection_id, session_id}` | `{}` | None | none | +| `release` | A connection ended | `{connection_id}` | `{}` | None | none | + +`open` and `attach` require that `connection_id` views `session_id`; the owner asks Connection rather than reading its attachments. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `not_attached` | Attach to the Session before registering an interface | +| `invalid` | Fix the request: an unsupported kind, a missing address, a malformed peer, a token without an id | +| `ui_token` | The one-time token is wrong; the leaf cannot attach | +| `ui_in_use` | Another connection already is this leaf; close it first or replace it | +| `ui_unknown` | The interface is gone; list the live interfaces | +| `ui_generation` | The interface changed since the caller looked; re-read `status` | +| `ui_leaf_failed` | The leaf did not start; nothing is registered | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `open` | Check the attachment, reserve the registration and the token, mount the leaf session and record its view | The reservation is removed and the leaf is disposed | The leaf ends with its session | Every leaf is disposed and every registration removed | UiHost: the leaf session | +| `attach` | Check the attachment, verify the token, bind the connection, close the replaced interface once attached | — | The connection binding is released | Registrations are removed | UiHost | +| `close` | Remove the registration, write the notice, dispose the leaf, wake presence | — | — | The registrations are already gone | UiHost: the notice and the leaf; Connection: the frame | +| `detach`, `release` | Clear the connection binding; a leaf stays and can reattach | — | — | — | UiHost | + +## Exceptions with reasons + +- `open` takes the leaf's waiting address as a string: the leaf chose it and the daemon dials it; no file or socket handle crosses. +- The twenty-second start window is the owner's state: a leaf that does not attach is closed as `close` would. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | UiHost is one process part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: registrations and leaves outlive Connections and Sessions' branches. | +| §3 orthogonality | No other owner's state is read; Connection answers attachment and writes notices. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use these operations; no caller sees the registration map. | +| §7 no handle | Every operation is addressed by `connection_id` or `ui_id`; the leaf is mounted inside the owner. | +| ADR 002 D1 | Process scope: one registry per daemon. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | Connection is asked through its operations. | +| ADR 002 D4 | No business setting. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Connection (#2021)**: `attached` and `write`, used by this owner and defined here as dependencies. + +## Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OpenRequest { + pub connection_id: String, + pub session_id: String, + pub kind: String, + pub peer: String, + pub address: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub replace: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expected_generation: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OpenReply { pub ui_id: String, pub generation: u64, pub token: String } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Instance { + pub ui_id: String, + pub session_id: String, + pub kind: String, + pub since_ms: u64, + pub generation: u64, + pub state: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StatusReply { pub instances: Vec, pub web_connections: usize } + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum UiError { + #[error("Attach to the Session before registering an interface on it")] + NotAttached, + #[error("{message}")] + Invalid { message: String }, + #[error("The UI leaf token is not valid")] + UiToken, + #[error("Another connection already is this UI leaf")] + UiInUse, + #[error("No such interface is registered")] + UiUnknown, + #[error("The UI generation is not current")] + UiGeneration, + #[error("{message}")] + UiLeafFailed { message: String }, +} + +#[rutis::service(name = "uiHost")] +impl UiHost { + pub async fn open(&self, request: OpenRequest) -> Result { /* ... */ } + pub async fn attach(&self, request: AttachRequest) -> Result { /* ... */ } + pub async fn replace(&self, request: ReplaceRequest) -> Result { /* ... */ } + pub async fn status(&self, request: Empty) -> StatusReply { /* ... */ } + pub async fn close(&self, request: CloseRequest) -> Result<(), UiError> { /* ... */ } + pub async fn shutdown(&self, request: ShutdownRequest) -> Result<(), UiError> { /* ... */ } + pub async fn detach(&self, request: DetachRequest) { /* ... */ } + pub async fn release(&self, request: ReleaseRequest) { /* ... */ } +} +``` + +`ui_detached` is the `shutdown` error for an interface between a detach and its reattach; the leaf can reattach and receive a later notice. diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md new file mode 100644 index 0000000000..e9dbaea432 --- /dev/null +++ b/docs/design/plugins/UiResources.md @@ -0,0 +1,159 @@ +# UiResources + +Scope: Session. Issue: #2021. + +UiResources owns the finished files a Session's parts publish for interfaces to read: their references, their reads and their withdrawal. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/ui_extensions/resources.rs`. FileStorage, UiExtensions and the publishing parts are separate owners. + +## Use and scope: responsibility split + +UiResources owns: + +- **Published references.** One per published file: the Session, the reference id, the open file, the media type and the publishing row instance. +- **Reads.** Bounded pages over one published file, counted so a withdrawal waits for them. +- **Ownership.** A reference belongs to the row that published it and ends when that row unloads or the Session closes; another row cannot withdraw it. +- **The Session's end.** Every reference and every read ends when the Session closes, without waiting for the part's unload. + +Callers keep: + +- Which file to publish: the publishing part chose a finalized regular file inside an authorized FileStorage root. +- What the interface shows: the client decides. +- The HTTP bytes: WebEntry's media route is a transport over the same read. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A Session part publishes a file for interfaces to read | No: the reference, its ownership and its reads are the owner's | `publish` | +| The publishing part withdraws the reference | No: withdrawal must wait for admitted reads | `withdraw` | +| An interface reads a page | No: the open file and the read counter are the owner's | `read` | + +An operation or parameter exists only where the row says No. + +## Caller example + +A Session part publishes a render it produced: + +```rust +let reference = resources.publish(PublishRequest { + path: "/home/u/.dimcode/renders/chart.png".into(), + media_type: "image/png".into(), +}).await?; // the reference names this Session; this row owns it +``` + +An interface reads it in pages: + +```rust +let page = resources.read(ReadRequest { reference: reference.clone(), offset: 0, limit: None }).await?; +``` + +## Own contract + +### Dependencies + +FileStorage (`open_read`, `read_at`, `close_read`) for the file; SessionLifecycle's `closing` for the Session's end. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While the file is opened; nothing is registered | `invalid`, `unavailable`, `closed` | +| `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `gone`, `invalid`, `closed` | +| `read` | One bounded page of a published file | `{reference, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The caller's token; the page stops, the reference stays | `gone`, `invalid` | + +`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. + +The media type decides inline display: a listed image, audio, video, text or PDF type is served as declared; any other type is served as `application/octet-stream` and marked as an attachment. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The path is relative or outside every authorized root, the reference names another Session, or a page offset is beyond the file | +| `unavailable` | The file is gone or unreadable; publish again or show the caller that the resource is unavailable | +| `gone` | The reference was withdrawn or the Session is closing; stop reading | +| `closed` | The Session is closing; the reference is settled | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `publish` | Check the Session phase, resolve the path in FileStorage, open the file, register the reference and the row's cleanup | The file is closed, nothing is registered | The reference is removed by the row's cleanup | Every reference is closed and removed | UiResources: the reference and the file | +| `withdraw` | Check the owner row, cancel and wait for admitted reads, remove the reference | — | Already removed | Already removed | UiResources | +| `read` | Resolve the reference, take a read token, read one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference goes | UiResources | + +## Exceptions with reasons + +- `publish` takes `caller: &Ctx`: ownership and cleanup must bind the calling row, and only rutis knows which row is calling; a caller-supplied id would let one row publish a reference owned by another. The parameter is not a request field and no caller sends a row. +- WebEntry's media route calls `read` directly: the browser needs an HTTP response with range handling, and the route is a transport over the same read, not a second business path. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | UiResources is one Session part; it writes no Timeline fact and is not a Capability. | +| §2 scopes | Session: references belong to one Session and end with it. | +| §3 orthogonality | No other owner's state is read; FileStorage and SessionLifecycle are asked. | +| §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | +| §4 rule 7 | Callers use these operations; no caller sees an open file. | +| §7 no handle | The reference is a value with an id; the open file stays in the owner. | +| ADR 002 D1 | Session scope: a published reference is Session data. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | FileStorage is a process service this Session part may depend on. | +| ADR 002 D4 | No business setting; the root and the file are the caller's choice. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. FileStorage's contract (#2016) supplies `open_read`, `read_at` and `close_read`. + +## Binding appendix + +```rust +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PublishRequest { pub path: String, pub media_type: String } + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ResourceRef { pub session_id: String, pub id: String } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadRequest { + pub reference: ResourceRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub offset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Page { + pub offset: u64, + pub bytes: usize, + pub total: u64, + pub media_type: String, + pub data: String, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ResourceError { + #[error("UI resource is unavailable")] + Gone, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + Unavailable { message: String }, + #[error("The Session is closing")] + Closed, +} + +#[rutis::service(name = "uiResources")] +impl UiResources { + pub async fn publish(&self, caller: &rutis::Ctx, request: PublishRequest) -> Result { /* ... */ } + pub async fn withdraw(&self, caller: &rutis::Ctx, request: ResourceRef) -> Result<(), ResourceError> { /* ... */ } + pub async fn read(&self, request: ReadRequest) -> Result { /* ... */ } +} +``` + +`caller: &Ctx` is rutis's caller parameter, filled by the wire dispatch from the calling row; it is not a request field. From 88db66e3804d5b6f9fa18dca3488b3e9d4103363 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:44:28 +0800 Subject: [PATCH 02/12] docs(design): settle holds, generation checks and the consumer's split Refs #2021 Refs #2015 --- docs/design/plugins/EnvironmentClients.md | 42 ++++++++++++++++------- docs/design/plugins/Report.md | 25 +++++++------- docs/design/plugins/ServerControl.md | 7 ++-- docs/design/plugins/UiHost.md | 7 ++-- 4 files changed, 52 insertions(+), 29 deletions(-) diff --git a/docs/design/plugins/EnvironmentClients.md b/docs/design/plugins/EnvironmentClients.md index d97e75b45d..22d4dd364a 100644 --- a/docs/design/plugins/EnvironmentClients.md +++ b/docs/design/plugins/EnvironmentClients.md @@ -4,7 +4,23 @@ Status: Draft. Parent: [agent environment awareness](../agent-environment.md). I EnvironmentClients tells the model which client connections are attached to its Session. It is a read projection of the App Server's connection and UI registries; it owns no connection state. The snapshot is appended directly to the branch input. It is not a Prompt source and has no version, keyed state or compaction replay. -## 1. Decisions +## Use and scope: responsibility split + +EnvironmentClientsBranch is a pure consumer with no public face. It owns the model-facing snapshot — the `` body, its bounds, its escaping and the decision to append — and nothing else. Connection owns live connections; UiHost owns interface registrations; the branch only reads the presence value and folds it into its own branch input. + +- **Responsibilities.** Build one snapshot at branch open and one per observed change; compare it with the last appended body; append an `input/message` with one Append-mode Raw block. No Prompt source, no version, no replay. +- **Left with callers.** Which clients exist and what they are: `connection.presences` is a value; the branch decides how to render it. +- **Not owned.** No connection, no registration, no presence state. The branch does not poll and does not read either registry. + +| Requirement (callers) | Can callers compose it from existing operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The model must know which clients are attached to its Session | Yes: the branch reads `connection.presences` and writes its own input | Business composes the value | +| The snapshot must refresh when a client attaches or leaves | Yes: the process event `ClientsChanged` wakes the branch, which re-reads the value | Business composes the event and the read | +| A repeated body must not append twice | Yes: the branch compares with the last appended body | Business | + +No operation or parameter exists for this owner: every row composes. + +## Decisions - One snapshot at branch open, and one snapshot per observed connection change. - The snapshot is an `input/message` event with an Append-mode Raw block and no key. @@ -15,7 +31,7 @@ EnvironmentClients tells the model which client connections are attached to its - Only the matching Session receives the snapshot; no broadcast. - The shared `dim-state` guide entry is registered by `PromptGuide` ([Prompt](Prompt.md#4-the-built-in-entries-and-their-writers)); this part does not register a second entry. -## 2. Snapshot body +## Snapshot body No connection: @@ -50,7 +66,7 @@ Rules: - The body states connections; it does not claim how many people are present. - No ids, device names, entry names, attach times or departure history. -## 3. Data +## Data The App Server stores, per connection: @@ -74,7 +90,7 @@ connection.presences {sessionId} -> {presences: [ClientPresence]} A UI leaf takes the label of the connection that hosts it; without one, only the channel is present. -## 4. Channels +## Channels | Channel | Source | | --- | --- | @@ -90,7 +106,7 @@ A UI leaf and its own protocol connection produce one `tui` entry, never an addi An ACP gateway is one connection. Several logical clients behind the gateway are not distinguished; the label, if any, is the gateway's. -## 5. Trigger and append +## Trigger and append ### Branch open @@ -115,7 +131,7 @@ No polling or broadcast. The snapshot uses the existing `input/message` event; n A change that arrives during a turn is appended when it arrives. The input-ordering consequence is tracked separately; this design does not work around it. -## 6. Plugin structure +## Plugin structure - `ConnectionPlugin` provides `SessionClientsHost`. - `ConnectionPlugin` emits `ClientsChanged` on attach, detach, UI attach/close/replace and connection finish. @@ -123,14 +139,14 @@ A change that arrives during a turn is appended when it arrives. The input-order - There is no Session part for this projection. - No new process plugin. -## 7. Privacy +## Privacy - The model sees channel and an optional claimed label only. - No client id, device id, token, entry name or connection id. - A label is untrusted text: escaped and bounded. - Presence grants no permission and changes no approval. -## 8. Errors and absence +## Errors and absence | Situation | Result | | --- | --- | @@ -143,7 +159,7 @@ A change that arrives during a turn is appended when it arrives. The input-order The in-memory presence read is infallible; it returns an empty list for an unknown Session. -## 9. Dependencies +## Dependencies | Dependency | Purpose | | --- | --- | @@ -156,11 +172,11 @@ The process `connection` face answers `presences` with the request and reply def No Prompt registry, no configure control, no version. -### Requirements raised to mechanism owners +## Requirements raised to mechanism owners None to the runtime or rutis. -## 10. Rule check +## Rule check | Rule | How this design complies | | --- | --- | @@ -180,7 +196,7 @@ None to the runtime or rutis. | ADR 002 D4 | No new configuration. | | ADR 002 D5 | The body is data; Rust is a binding. | -## 11. Verification +## Verification | Scenario | Expected | | --- | --- | @@ -196,7 +212,7 @@ None to the runtime or rutis. | Remote connection | Not reported | | Compaction | The snapshot may be removed; no replay | -## 12. Open decisions +## Open decisions 1. Whether the body lists every connection or caps a long list. 2. Whether a claimed label is shown by default or only when the client opts in. diff --git a/docs/design/plugins/Report.md b/docs/design/plugins/Report.md index 6dfd02e977..e40756af03 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -4,7 +4,7 @@ Scope: process and Session. Issue: [#1319](https://github.com/arcships/dim/issue Report owns the drafts behind `/report` and the error-only report a client opens when no Session can be read. This document is the owner's target contract; the client interaction and the evidence rules below are the same design, restated in the contract's shape. The TimelineTree, SessionScope, ManagementMethods and SessionMethods owners are separate; their operations are dependencies. -## 1. Use and scope: responsibility split +## Use and scope: responsibility split Report owns: @@ -47,7 +47,7 @@ save(report.archive); // the client saves after the connection may close ``` Home's error-only flow uses the same three calls in the process namespace with `error` present. -## 2. Client interaction +## Client interaction In both TUI modes, `/report` opens a report for the current Session, including while a turn is running. It needs no captured error. Users can report an unsatisfactory answer or a repeating turn without waiting for a failure or stopping the turn. The dialog keeps the Session selected when it opened, including when preparing again after expiry. Returning to the composer and running `/report` again selects the Session shown at that time. @@ -83,7 +83,7 @@ The error-only overlay uses `Report this error`. The Session overlay shows when The overlay follows the TUI's focus and list conventions. Up and Down move between controls, and Tab and Shift+Tab cycle focus. Enter activates the focused control. Esc closes a picker first, cancels generation while busy, or closes the report. Focus starts on Model. The TUI shortens the error and report title to fit the overlay and keeps the focused action visible. The result lists the archive contents and shows the saved path so users can inspect the files with their own tools. Place `/report` immediately before `/exit` in both curated menus with the description `report the current session`, following the existing exact-name, Enter and Tab behavior. The CLI command owner owns the menu (§7). [TUI design](Tui.md), [command menu contract](../cli-commands.md#command-menu). -## 3. Evidence and redaction +## Evidence and redaction For a report about the Session, the admitted Session is the entire client-supplied reference. The Report part captures recent activity from its main branch at the published head. Error actions can supply a typed Timeline failure reference with an observed-error fallback, or an observed error alone. A typed reference contains the branch and committed sequence in the admitted Session. An observed error contains a registered client operation, a stable error code if present, the observation time and the client version. The client keeps the displayed message for the dialog. The report projects a stable operation summary and registered error code from that input. Unknown codes collapse to a generic failure for that operation. The request has no field for that message, since an error string can contain a credential, provider response or file path. @@ -102,7 +102,7 @@ The Timeline read is branch-local and bounded by 32 candidate events ending at t Diagnostics never include message bodies, raw logs, workspace files, tool input or output, or raw model requests. Their fields come from typed sources or fixed renderings, and correlation IDs come from verified metadata. With redaction on, remove correlation IDs and do not select conversation text. Only an explicit local plan with redaction off may add a recent excerpt to the Session report. Do not collect hidden reasoning, tool calls or results, attachments, instructions, or full history for the excerpt. User and assistant text can itself contain sensitive details; the user should inspect the ZIP before attaching it. Options maps recognized omit or keep instructions to field directives and shows unsupported instructions in the dialog. A keep directive cannot override redaction. The generation result cannot add new evidence. -## 4. Own contract +## Own contract ### Dependencies @@ -142,19 +142,20 @@ The draft is keyed by the calling connection and the part instance; a missing, e | `generate` | Consume the plan atomically, render or run the one-shot model call, return the archive | The named plan stops; late output is discarded; the evidence stays | The draft and its work are discarded | Accepted work settles; late output is discarded | Report | | `cancel` | Stop the named generation or drop the draft | — | — | — | Report | -### Exceptions with reasons + +## Exceptions with reasons - The process namespace accepts no Session or branch id: an error-only report must work when Session admission failed, so the part has no Session to name. - The archive is returned in the `generate` reply: the client must be able to save after the connection closes, and a second download resource would be another owner's store. - Evidence is read at the published cutoff and rendered later: the snapshot is a projection Report owns, so a later turn cannot change a reviewed plan. -## 5. Generation +## Generation Local generation renders a template from the approved snapshot and uses zero model calls. The optional short-lived report Agent performs one isolated drafting operation using only the reviewed material. Its input is the fixed system instruction, filtered snapshot and resolved redaction directives. It has no inherited Session, tools, workspace, credentials or publishing access. The Provider owner resolves and authenticates the request. The report plan shows the exact prompt material, the chosen provider/model, output limit and an estimate when the necessary price and token count are available. A plan cannot silently fall back to a different connection, model or request payload. The Agent's operation uses the one-shot auxiliary model boundary, with the single-attempt policy requested in §7. It does not create a general-purpose chat Session. The model proposes the title template, body section order and evidence selections and omissions using a bounded schema of known fields. Report validates the selection and renders the actual text from approved values. Invalid output fails generation and offers the local template. Neither path includes reproduction steps unless approved evidence establishes them. -## 6. Preview and sharing +## Preview and sharing Build `report.md` and versioned `diagnostics.json` from the same approved content used for the report. The `Dim` line names the daemon build's display label and protocol version, and a `Client` line names the reporting client's label when it differs from the daemon's: a CLI talking to a daemon of another build is exactly what a report must reveal. Error reports use diagnostics v1 (`{version: 1, evidence, unavailable}`), with `evidence.capturedError` and any referenced failure evidence. Reports on the current Session use diagnostics v2 (`{version: 2, evidence, unavailable}`), with `evidence.process` and, when included, `evidence.timeline` containing `recent` records and `truncated`. The generated title is `Session report`. The ZIP contains exactly those two files. Return the two UTF-8 file contents and the base64-encoded ZIP in the direct reply so clients can save after the connection closes. Cap the ZIP at 64 KiB before encoding. The TUI exposes share actions after the ZIP has been saved and the user can open it. It leaves the saved path in the transcript when the dialog closes. Clients with inline previews display the body and both file contents before exposing share actions and treat them as data when rendering them. @@ -168,7 +169,7 @@ After a successful save, both TUI modes show a hint below the saved path. Users The client keeps the completed preview and bytes when a share action fails. The plugin cannot publish an issue or upload an archive. The browser flow is sufficient without an authenticated `gh`. [GitHub's attachment flow](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files). -## 7. Requirements raised to mechanism owners +## Requirements raised to mechanism owners | Owner | Required operation or value | Why the caller cannot compose it | | --- | --- | --- | @@ -178,7 +179,7 @@ The client keeps the completed preview and bytes when a share action fails. The | Provider ([#2019](https://github.com/arcships/dim/issues/2019)) | A one-shot completion with a caller-selected no-retry policy and the exact prepared material | Model-assisted generation is outside this contract until the owner offers that operation; the local template stays the default | | Web entry (App Server, this block) | Admit the process `report.*` namespace on the authenticated local Web entry | The error-only entry is served to the web client; the admission list is the entry's | -## 8. Rule check +## Rule check | Rule | Application | | --- | --- | @@ -195,7 +196,7 @@ The client keeps the completed preview and bytes when a share action fails. The | ADR 002 D2 | The feature owns the report work and state; its parts register their own methods. | | ADR 002 D4 and D5 | Per-report options live in the draft; the RPC contract is language-neutral. | -## 9. Verification +## Verification - Exercise `/report` in both TUI modes with an error-free Session, during a running turn, and after switching from a Session with an earlier error. Verify that the report stays bound to the Session selected when it opened and that a fresh command targets the newly shown Session. Cover Home with and without a failed conversation open. - Generate a ZIP from a Session with successful and repeated activity. Verify the excerpt comes from the main branch at the captured head, excludes later activity, respects the window and record bounds, and supports an empty excerpt. Verify both archive versions through their corresponding prepare inputs. @@ -205,11 +206,11 @@ The client keeps the completed preview and bytes when a share action fails. The - Generate a report on a daemon and confirm its `Dim` line carries the same label the binary prints, and that a client whose `clientVersion` names another build adds one `Client` line, in the body and in `evidence.process.clientVersion`. `crates/dim-report/tests/report_flow.rs` covers this at RPC level; `crates/dimcode/tests/cli_flow/report.rs` covers the product daemon and binary. - Save a report ZIP on a client connected to another host and exercise the GitHub draft and Discord flows without `gh`. Verify explicit sharing follows review or local save and that a failed share leaves the saved bytes available. -## 10. Ablation +## Ablation The Session namespace serves current-Session reports through the existing prepare method. The process entry is needed for a conversation-open error that fails Session admission and uses the same flow with fewer evidence sources. The plan ID ties a paid request to the exact preview the user confirmed. The bounded ZIP in the generation reply lets the client save without a second download resource or archive store. An isolated one-shot model operation supplies drafting and redaction without a general-purpose report Session. -## 11. Binding appendix +## Binding appendix ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] diff --git a/docs/design/plugins/ServerControl.md b/docs/design/plugins/ServerControl.md index a88e08323b..b70b394ce4 100644 --- a/docs/design/plugins/ServerControl.md +++ b/docs/design/plugins/ServerControl.md @@ -24,7 +24,7 @@ Callers keep: | --- | --- | --- | | A process part must wait for the host to open before starting work | Yes: `activated` composes | `activated` | | A part must stop when the daemon starts closing | Yes: `closing` composes | `closing` | -| A holder must stop a graceful close while its accepted work runs | No: only the owner sees every hold and can decide the intent | `hold`, `release` | +| A holder must stop a graceful close while its accepted work runs | No: only the owner sees every hold and can decide the intent; the work can outlive the call that started it, so no callback-scoped operation fits | `hold`, `release` | | The idle-close decision needs to know whether accepted work is held | Yes: `holds` composes | `holds` | | A client asks the daemon to shut down | No: one intent, one mode and one force flag are the owner's state | `shutdown` | | A listener exit must end the daemon | No: the first fault is the owner's state | `fault` | @@ -80,7 +80,9 @@ None. The owner injects no service. | `shutdown` | Ask the process to close | `{mode: graceful \| forced}` | `{}` accepted | None; the close cannot be cancelled | `conflict` | | `fault` | A listener exited; end the process | `{listener, message}` | `{}` | None | none | -A hold is released by the calling row's unload as well as by `release`: an id that outlives its row is released when the row unloads, and the reply to a later `release` is `false`. A row that crashes without unloading keeps its hold until the process ends, and the close is forced. +`hold` and `release` are not a `withHold(work)` callback. The accepted work outlives the call that started it: a Workflow run spans several calls and several Sessions, and a Scheduler delivery settles after the launching call returned. No single function represents that work, and a callback form would make the owner keep the caller's future alive across those calls. The id lets the caller's business object own the hold while the owner only tracks it. + +The pair is one id's acquire and release, not a multi-step session: `release` is idempotent, a lost id never corrupts owner state and only keeps a graceful close waiting, and the row's unload releases it. A hold released by the row's unload answers `false` to a later `release`. A row that crashes without unloading keeps its hold until the process ends, and `shutdown(forced)` proceeds without it. `shutdown` does not run the sequence. It records the intent; `closing` resolves for every waiter; the assembly settles Agents, drains Rpc, closes connections and answers the initiating client. A second `shutdown` with any mode is `conflict`. @@ -107,6 +109,7 @@ No other error exists: the owner has no "not found", "invalid input" or "too lar ## Exceptions with reasons - `processActivity` is the single published name for a merged owner: the publication gate, the holds and the shutdown intent share one plugin and one lifecycle, and `serverControl` had no method of its own. Keeping the name avoids a wire rename for Workflow and Scheduler. +- `hold`/`release` are two calls rather than `withHold(work)`: the accepted work outlives the call (a Workflow run, a Scheduler delivery), so no callback represents it. Settlement: the calling row's unload releases its holds; the owner refuses new holds once closing starts and waits for the released ones; a lost owner keeps the close graceful until the process ends, and a forced close does not wait. ## Rule check diff --git a/docs/design/plugins/UiHost.md b/docs/design/plugins/UiHost.md index ffdb87e5f5..789039dfa2 100644 --- a/docs/design/plugins/UiHost.md +++ b/docs/design/plugins/UiHost.md @@ -44,8 +44,8 @@ let opened = ui_host.open(OpenRequest { kind: "tui".into(), peer, address, - replace, - expected_generation, + replace, // the interface the client confirmed replacing; expected_generation is optional + expected_generation: None, }).await?; // The reply carries the one-time token the leaf passes to `attach`. ``` @@ -79,6 +79,8 @@ Connection's `attached` and `write`; the process root for mounting a leaf sessio `open` and `attach` require that `connection_id` views `session_id`; the owner asks Connection rather than reading its attachments. +`expected_generation` is the generation the client read from `status` when it asked the user to confirm a replacement. It is a business version, not an owner-internal revision: the owner cannot decide it, because a client that saw interface A may have confirmed replacing A, and replacing whatever is current instead would close an interface the user never saw. The claim is atomic in `open`/`replace`; the attach token authorizes the leaf's attach and is a different value. + ### Errors | Kind | What the caller does next | @@ -104,6 +106,7 @@ Connection's `attached` and `write`; the process root for mounting a leaf sessio - `open` takes the leaf's waiting address as a string: the leaf chose it and the daemon dials it; no file or socket handle crosses. - The twenty-second start window is the owner's state: a leaf that does not attach is closed as `close` would. +- `expected_generation` stays a request field: it is the version the client observed and confirmed, so the owner cannot choose it; a stale client is refused with `ui_generation` instead of silently replacing a newer interface. ## Rule check From 1d9dce7bf4631dc4751690ceddb971f2716d373a Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:15:58 +0800 Subject: [PATCH 03/12] docs(design): align connection with the Agents operations Refs #2021 Refs #2015 --- docs/design/plugins/Connection.md | 23 +++++++++++++---------- docs/design/plugins/ServerControl.md | 2 +- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/design/plugins/Connection.md b/docs/design/plugins/Connection.md index 2ec3ec4c3d..b7dcfb907f 100644 --- a/docs/design/plugins/Connection.md +++ b/docs/design/plugins/Connection.md @@ -62,16 +62,17 @@ append_snapshot(&timeline, body)?; The idle-close handler reads the other owners' facts, then commits the refusal in one call: ```rust -let running = agents.running_sessions(); -let held = process_activity.holds(); // a count, not a guard -let quiet = agents.sessions_quiescent(); +let running = agents.sessions().await?.sessions.iter().filter(|s| s.running).count(); +let held = process_activity.holds().await?.count; // a count, not a guard match connections.close_for_idle(CloseForIdle { exclude_connection_id: caller.clone(), running_sessions: running, held_work: held, - sessions_quiet: quiet, }) { - Ok(counts) => shutdown.request(ShutdownMode::Graceful), + Ok(counts) => { + // The refusal is committed; the assembly quiesces Agents and closes. + shutdown.request(ShutdownMode::Graceful); + } Err(CloseForIdleError::Busy(busy)) => return Err(busy.into()), } ``` @@ -86,7 +87,7 @@ channel.notify(NotifyRequest { connection_id, call_id, method, params }).await?; ### Dependencies -Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach` and `release`; Agents' `acquire`/`release` for attachment leases ([Agents #2020](../contracts/process-owner-operations.md)). +Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach` and `release`; Agents' `acquire {sessionId} → {useId, generation}`, `release {useId}` and `sessions` ([Agents contract](Agents.md)). ### Operations @@ -104,13 +105,15 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c | `attached` | Whether a connection views a Session now | `{connection_id, session_id}` | `{attached}` | None | none | | `presences` | The live clients of a Session | `{session_id}` | `{presences: [{channel, label?}]}` | None | none | | `counts` | Live connections and attached Sessions, excluding one connection | `{exclude_connection_id}` | `{connections, attached_sessions}` | None | none | -| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running_sessions, held_work, sessions_quiet}` | `{counts}` | None | `busy{connections, attached_sessions, running_sessions}` | +| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running_sessions, held_work}` | `{counts}` | None | `busy{connections, attached_sessions, running_sessions}` | | `close_all` | Close every connection and wait for its tasks | `{}` | `{}` | None; the owner completes the close | none | | `settle` (internal) | One connection ended: release its attachment, tell UiHost, end its writer | `{connection_id, reason}` | `{}` | None | none | `write` and `write_after` are one operation family: `write_after` exists because a notification sent while a call runs must follow that call's reply, and only the connection's outbound queue knows the reply has been written. `write` refuses a frame over the connection's frame budget with `too_large`, and closes a connection whose reliable allowance is exhausted, reporting `slow` to the writer of that frame. -`close_for_idle` reads the other owners' facts from its request: the caller read them immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. A fact that changes afterwards is settled by the shutdown sequence; the refusal is not undone. +`close_for_idle` reads the other owners' facts from its request: `running_sessions` from Agents' `sessions` value and `held_work` from `processActivity.holds`, both read immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. + +After the commit the assembly asks Agents to `quiesce` every Session. A `running` answer means a Session accepted work between the read and the pause; the refusal stands and the graceful close settles that work — admission is never reopened after the commit. ### Errors @@ -136,7 +139,7 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c | `closed` | Resolve when the reader or the owner ends the connection | — | The waiter ends | Resolves for every waiter | Connection | | `attach` | Acquire the Session lease, register the subscription, attach under the connection lock | Before the reply: lease released, listener disposed, nothing attached | The attachment is released with the connection | Pending calls end `closed`; every attachment is released | Connection: the attachment; Agents: the lease | | `detach` | Remove the attachment and release its lease and listener | — | — | The attachment is already gone | Connection | -| `close_for_idle` | Recheck counts under the lock, set the refusal, return the counts | None | — | The refusal is the close | Connection | +| `close_for_idle` | Recheck counts under the lock, set the refusal, return the counts; the caller then asks Agents to quiesce | None | — | The refusal is the close; a `running` quiesce answer does not reopen it | Connection | | `close_all` | Tell UiHost the connections ended, cancel each reader and writer, wait for the tasks | — | — | It is the close | Connection | ## Exceptions with reasons @@ -171,7 +174,7 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c ## Requirements raised to mechanism owners -- **Agents (#2020)**: attachment leases as ids bound to the calling row (`acquire(sessionId) → leaseId`, `release(leaseId)`); a value for the running Session count and a value for Session quiescence used by `close_for_idle`; an operation that settles the Sessions for shutdown after `close_for_idle` commits. +- **Agents (#2020)**: the operations are the ones in the Agents contract ([#2098](https://github.com/arcships/dim/pull/2098)): `acquire {sessionId} → {useId, generation}` and `release {useId}` for the attachment lease, `sessions` for the running count, and `quiesce` for the shutdown pause. No new operation is required; the caller passes the read values into `close_for_idle` and quiesces after the commit. - **rutis (runtime)**: none. ## Binding appendix diff --git a/docs/design/plugins/ServerControl.md b/docs/design/plugins/ServerControl.md index b70b394ce4..f361d098d7 100644 --- a/docs/design/plugins/ServerControl.md +++ b/docs/design/plugins/ServerControl.md @@ -130,7 +130,7 @@ No other error exists: the owner has no "not found", "invalid input" or "too lar ## Requirements raised to mechanism owners -- **Agents (#2020)**: the Session pause and settle that the assembly runs after `shutdown` is accepted. The owner keeps no `SessionPause` value. +- **Agents (#2020)**: `quiesce` ([#2098](https://github.com/arcships/dim/pull/2098)) — the assembly calls it after `shutdown` is accepted; the pause lives in Agents until its generation unloads, so no guard crosses to this owner. ## Binding appendix From 84e598b7e3203184e91ca3f8adf5e9121d4667d1 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:32:02 +0800 Subject: [PATCH 04/12] docs(design): name the Agents lease id as leaseId Refs #2021 Refs #2015 --- docs/design/plugins/Connection.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/plugins/Connection.md b/docs/design/plugins/Connection.md index b7dcfb907f..e453be0316 100644 --- a/docs/design/plugins/Connection.md +++ b/docs/design/plugins/Connection.md @@ -87,7 +87,7 @@ channel.notify(NotifyRequest { connection_id, call_id, method, params }).await?; ### Dependencies -Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach` and `release`; Agents' `acquire {sessionId} → {useId, generation}`, `release {useId}` and `sessions` ([Agents contract](Agents.md)). +Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach` and `release`; Agents' `acquire {sessionId} → {leaseId, generation}`, `release {leaseId}` and `sessions` ([Agents contract](Agents.md)). ### Operations @@ -174,7 +174,7 @@ After the commit the assembly asks Agents to `quiesce` every Session. A `running ## Requirements raised to mechanism owners -- **Agents (#2020)**: the operations are the ones in the Agents contract ([#2098](https://github.com/arcships/dim/pull/2098)): `acquire {sessionId} → {useId, generation}` and `release {useId}` for the attachment lease, `sessions` for the running count, and `quiesce` for the shutdown pause. No new operation is required; the caller passes the read values into `close_for_idle` and quiesces after the commit. +- **Agents (#2020)**: the operations are the ones in the Agents contract ([#2098](https://github.com/arcships/dim/pull/2098)): `acquire {sessionId} → {leaseId, generation}` and `release {leaseId}` for the attachment lease, `sessions` for the running count, and `quiesce` for the shutdown pause. No new operation is required; the caller passes the read values into `close_for_idle` and quiesces after the commit. - **rutis (runtime)**: none. ## Binding appendix From 364c3415190c7d084a953ca626f95f4902754139 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 19:32:21 +0800 Subject: [PATCH 05/12] docs(design): run a table call under one call binding Refs #2021 Refs #2015 --- docs/design/plugins/CallChannel.md | 82 +++++++++++++++++------------- docs/design/plugins/Rpc.md | 2 +- 2 files changed, 47 insertions(+), 37 deletions(-) diff --git a/docs/design/plugins/CallChannel.md b/docs/design/plugins/CallChannel.md index c587637831..67a0bc7541 100644 --- a/docs/design/plugins/CallChannel.md +++ b/docs/design/plugins/CallChannel.md @@ -2,15 +2,15 @@ Scope: process. Issue: #2021. -CallChannel owns the binding between one admitted call and the connection it arrived on: which notifications the provider may send, whether the call is still answerable, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. +CallChannel owns the binding between one admitted table call and the connection it arrived on: which notifications the provider may send while the call runs, whether a notification is declared, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. ## Use and scope: responsibility split CallChannel owns: -- **Bindings.** For each admitted call that may notify, the connection id, the call id, the row instance that registered the namespace, and the notification names that namespace declared. +- **The call binding.** One per admitted table call: the connection id, the call id, the registering row instance and the notification names that namespace declared. The binding lives for the call's extent — from `run` until the callback ends or the caller's future is dropped — and the owner always removes it. - **The declared-name answer.** A name the registration did not declare is refused before anything is written. -- **The connection's end.** A binding resolves when its connection closes, when the reply is written, or when the registering row unloads. +- **The connection's end.** `closed` resolves when the connection closes; the binding does not have to be alive. - **Routing the write.** A notification is written by Connection, addressed by the call id so it follows the reply. CallChannel writes no socket and holds no connection state. @@ -18,35 +18,37 @@ CallChannel writes no socket and holds no connection state. Callers keep: - What a notification means: the provider chooses the name and the payload. -- The reply: Rpc returns it; Connection writes it. +- The reply: the callback produces it; Rpc writes it after `run` returns. - The declarations: the registering part declared them; the table admitted the call with them. | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Rpc must make an admitted call addressable before the handler can notify | No: the binding's lifetime and the declared-name answer are the owner's | `bind` | +| Rpc must run one admitted table call with the caller's notifications enabled and its reply ordered | No: the binding, the declared-name answer and the write ordering are the owner's; a `bind`/`finish` pair would make Rpc drive three owners and could leave the binding behind on an error path | `run` | | A provider must send a notification to the calling connection, in order after its reply | No: the declared-name check, the binding lookup and the ordering are the owner's | `notify` | -| A provider must stop when the connection closes | Yes: `closed` composes | `closed` | -| Rpc must end a binding once the reply is written | No: the end and the removal are the owner's | `finish` | +| A provider must stop when the connection closes, including after the call returned | Yes: `closed` composes, and it is addressed by the connection alone | `closed` | An operation or parameter exists only where the row says No. ## Caller example -Rpc binds the call before invoking the handler: +Rpc runs the call once; the owner binds, invokes and settles: ```rust -channel.bind(BindRequest { +let reply = channel.run(RunRequest { connection_id: caller.connection_id.clone(), call_id: caller.call_id.clone(), instance: row_instance.clone(), - notifications: declarations.iter().flat_map(|d| d.notifications.clone()).collect(), -}).await?; -let reply = table.call(CallRequest { method, params, caller: Some(caller.clone()) }).await?; -connection.write_after(WriteAfter { connection_id, call_id, frame: reply.frame }).await?; -channel.finish(FinishRequest { connection_id, call_id }).await?; + notifications: declared_notifications.clone(), + call: Arc::new(move || { + let table = table.clone(); + let (method, params) = (method.clone(), params.clone()); + Box::pin(async move { table.call(CallRequest { method, params, caller: None }).await }) + }), +}, cancel).await?; +// Notifications sent inside the callback were held by Connection; the reply releases them in order. ``` -A provider notifies and waits for the end: +A provider inside the callback builds a notification and waits for the caller to leave: ```rust match channel.notify(NotifyRequest { connection_id, call_id, method, params }).await { @@ -55,7 +57,7 @@ match channel.notify(NotifyRequest { connection_id, call_id, method, params }).a Err(NotifyError::Gone) => return Ok(()), // the caller left; nothing to do Err(NotifyError::TooLarge) => return Err(ProviderError::TooLarge), } -channel.closed(ClosedRequest { connection_id, call_id }).await; +channel.closed(ClosedRequest { connection_id }).await; // also usable after the call returned ``` ## Own contract @@ -68,12 +70,11 @@ Connection's `write_after` and `closed`. | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `bind` | Make one admitted call addressable by its notifications | `{connection_id, call_id, instance, notifications}` | `{}` | None | `duplicate` | -| `notify` | Send a notification to the calling connection, after the call's reply | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `undeclared`, `gone`, `too_large` | -| `closed` | Wait until the calling connection is gone | `{connection_id, call_id}` | `{}` when the connection closes | The provider's task ends; the wait ends | none | -| `finish` | The call's reply was written; the binding ends | `{connection_id, call_id}` | `{}` | None | none | +| `run` | Run one admitted table call with its caller's notifications enabled | `{connection_id, call_id, instance, notifications, call}` | the callback's reply | The caller's token: the callback stops and the binding is removed | the callback's own error; `duplicate` | +| `notify` | Send a notification to the calling connection while the call runs | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `undeclared`, `gone`, `too_large` | +| `closed` | Wait until the calling connection is gone | `{connection_id}` | `{}` when the connection closes; an unknown id resolves at once | The caller's task ends; the wait ends | none | -`instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name, and the binding belongs to the row that admitted the call. +`run`'s `call` is a callback by reference. The owner invokes it once with the binding open and removes the binding when the callback ends or the caller's future is dropped; no caller frees the binding on any path. `instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name. ### Errors @@ -81,21 +82,21 @@ Connection's `write_after` and `closed`. | --- | --- | | `duplicate` | The call id is bound already; this is a programming error in the caller | | `undeclared` | The registration did not declare the name; fix the declaration, nothing was written | -| `gone` | The connection closed or the row unloaded; stop notifying for this call | +| `gone` | The call ended or the connection closed; stop notifying for the call | | `too_large` | The notification exceeds the connection's frame budget; shorten it — the connection stays open | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `bind` | Record the binding under the row instance and the connection | — | The row's bindings are removed | New bindings are refused; existing ones resolve as gone | CallChannel | -| `notify` | Find the binding, check the declared name, ask Connection to write after the call | The provider's task ends before the write; nothing is written | The binding is removed; `gone` | Pending notifications are `gone` | Connection: the frame; CallChannel: the binding | -| `closed` | Wait on Connection's `closed` for the binding's connection | The provider stops waiting | The wait ends | The wait ends | Connection | -| `finish` | Remove the binding; later notifications are `gone` | — | Already removed | Already removed | CallChannel | +| `run` | Record the binding under the row instance and the connection, invoke the callback, remove the binding | The callback stops; the binding is removed; nothing else changes | The caller's future drops; a guard removes the binding | A connection close interrupts the call through its cancellation; the binding is removed | CallChannel: the binding; the caller: the callback's future | +| `notify` | Find the binding, check the declared name, ask Connection to write after the call | The provider's task ends before the write; nothing is written | The binding is gone; `gone` | Pending notifications are `gone` | Connection: the frame; CallChannel: the binding | +| `closed` | Wait on Connection's `closed` for the connection | The provider stops waiting | The wait ends | The wait ends | Connection | ## Exceptions with reasons -- `bind`/`finish` are called by Rpc, not by the table: the table is in another crate and must not depend on the App Server; Rpc knows both the admitted call and the connection. +- `run` takes the callback by reference, like SessionScope's `withHold`: the callback is never called inside a commit lock, and it may notify through this owner while it runs. +- A notification sent after the callback returned is `gone`: the binding is the call's, not the connection's, so a provider that wants to react to the caller leaving uses `closed`, which is addressed by the connection and needs no binding. ## Rule check @@ -106,28 +107,33 @@ Connection's `write_after` and `closed`. | §3 orthogonality | No other owner's state is read; Connection is asked to write and to report its close. | | §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | | §4 rule 7 | Callers use these operations; no caller sees the binding table. | +| §7 one operation | `run` binds, invokes and settles in one call; there is no `bind` or `finish` to pair or leak. | | §7 no proxy | The binding, the declared-name answer and the connection's end are this owner's state; Connection writes the frame. | | §7 no handle | The binding is addressed by `{connection_id, call_id}`; no writer crosses. | | ADR 002 D1 | Process scope: calls span rows and connections. | | ADR 002 D2 | No wiring plugin: the service is on the owner type. | | ADR 002 D3 | Dependencies point to Connection as an operation. | | ADR 002 D4 | No business setting. | -| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | +| ADR 002 D5 | The contract is data and one callback; the Rust binding is the appendix. | ## Requirements raised to mechanism owners -None. The call id is data minted by Rpc; no runtime change is needed. +None. The callback is the same binding rutis already gives `withHold` and FileStorage's `write` source; no runtime change is needed. ## Binding appendix ```rust -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BindRequest { +pub type CallFn = Arc< + dyn Fn() -> BoxFuture<'static, Result> + Send + Sync, +>; + +#[derive(Clone)] +pub struct RunRequest { pub connection_id: String, pub call_id: String, pub instance: String, - pub notifications: Vec, + pub notifications: BTreeSet, + pub call: CallFn, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -140,17 +146,21 @@ pub struct NotifyRequest { pub params: serde_json::Map, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClosedRequest { pub connection_id: String } + #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum NotifyError { Undeclared, Gone, TooLarge } #[rutis::service(name = "callChannel")] impl CallChannel { - pub async fn bind(&self, request: BindRequest) -> Result<(), BindError> { /* ... */ } + pub async fn run(&self, request: RunRequest, cancel: CancellationToken) + -> Result { /* ... */ } pub async fn notify(&self, request: NotifyRequest) -> Result<(), NotifyError> { /* ... */ } pub async fn closed(&self, request: ClosedRequest) { /* waits */ } - pub async fn finish(&self, request: FinishRequest) { /* ... */ } } ``` -The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same two operations. +`CallFn` is passed by reference; the owner invokes it once and removes the binding when it returns or the caller's future is dropped. The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same two operations. diff --git a/docs/design/plugins/Rpc.md b/docs/design/plugins/Rpc.md index a98bb63f6a..b4ae5b2736 100644 --- a/docs/design/plugins/Rpc.md +++ b/docs/design/plugins/Rpc.md @@ -45,7 +45,7 @@ connection.write_after(WriteAfter { connection_id: id, call_id, frame: reply.fra ### Dependencies -Connection's `write_after` and `attached`; ManagementMethods' `call`; the Session's method table (the same shape, per [ManagementMethods](ManagementMethods.md)); Agents' `acquire` and running/close operations; CallChannel's `bind` and `finish`; ServerControl's `shutdown`. +Connection's `write_after` and `attached`; ManagementMethods' `call`; the Session's method table (the same shape, per [ManagementMethods](ManagementMethods.md)); Agents' `acquire` and running/close operations; CallChannel's `run`; ServerControl's `shutdown`. ### Operations From 152d99a3d62df6ba1937d177c39118b664abd573 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 21:33:44 +0800 Subject: [PATCH 06/12] docs(design): restore the client contract and settle the bindings Refs #2021 Refs #2015 --- docs/design/client-ui-extensions.md | 4 +- .../contracts/process-owner-operations.md | 6 +- docs/design/plugins/CallChannel.md | 138 +++++++++---- docs/design/plugins/Connection.md | 193 +++++++++++------- docs/design/plugins/EnvironmentClients.md | 15 +- docs/design/plugins/ManagementMethods.md | 110 +++++++--- docs/design/plugins/ProcessRoot.md | 8 + docs/design/plugins/README.md | 4 +- docs/design/plugins/Report.md | 71 ++++--- docs/design/plugins/Rpc.md | 93 +++++---- docs/design/plugins/ServerControl.md | 81 ++++++-- docs/design/plugins/Transport.md | 15 +- docs/design/plugins/Tui.md | 2 + docs/design/plugins/UiExtensions.md | 26 ++- docs/design/plugins/UiHost.md | 31 ++- docs/design/plugins/UiResources.md | 38 ++-- docs/design/resource-faces.md | 2 +- docs/design/service-faces.md | 10 +- 18 files changed, 558 insertions(+), 289 deletions(-) diff --git a/docs/design/client-ui-extensions.md b/docs/design/client-ui-extensions.md index 69de4c7b52..19d25562aa 100644 --- a/docs/design/client-ui-extensions.md +++ b/docs/design/client-ui-extensions.md @@ -430,8 +430,8 @@ type PreviewMethods = { | 名称 | 范围 | 输入与结果 | | --- | --- | --- | -| `uiExtensions` | process,后端命名服务 | 接受 PluginManager 的已验证内容注册/撤下;提供目录快照及变化观察,不供页面发布内容 | -| `uiResources` | Session,后端命名服务 | `publishFile({path, mediaType}) -> ResourceRef`;`withdraw(ref)` 等到读取结束;注册自动归调用者生命周期,调用者不能撤下其他注册 | +| `uiExtensions` | process,后端命名服务 | 操作见 [UiExtensions 契约](plugins/UiExtensions.md):按插件 id 注册/撤下内容、目录快照与变化事实,不供页面发布内容 | +| `uiResources` | Session,后端命名服务 | 操作见 [UiResources 契约](plugins/UiResources.md):`publish`/`withdraw`/`read`,引用归发布者行,调用者不能撤下其他注册 | | `ui.extensions.list` | 已授权客户端的精确只读方法 | `{}` → `{revision, extensions, errors}`;extension 包含插件名、generation 和面板声明,不含 URL;errors 仅含 UiExtensions 自己产生的内容错误且不含绝对路径 | | `ui.extensions.read` | 已授权客户端的精确只读方法(local) | `{generation, path, offset?, limit?}` → `{offset, bytes, total, mediaType, data}`;`data` 为标准 base64;默认 1 MiB、上限 4 MiB;不在 `WEB_MANAGEMENT_METHODS` | | `session.ui.resources.read` | UiResources part 注册的 Session 方法 | `{sessionId, id, offset?, limit?}` → `{offset, bytes, total, mediaType, data}`;同一页边界;经 `session.methods` 发现;id 只在发布它的 Session 实例内有效 | diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 3b9d8f234c..7048b368ca 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -11,9 +11,9 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Management clients → Provider / Grok OAuth / OpenAI Codex OAuth | Existing [Provider management RPCs](../appserver/provider-management.md) and account status, begin, attempt status, cancel and logout RPCs. Codex also handles its browser callback. | | Session consumers → Agent directory | [`sessions` operations](../appserver/sessions-service.md). Agent administration and Session creation/fork retain the existing `agent.create/list/close` and `session.create/fork` client RPCs. RPC, Agent configuration, Collaboration and Provider lifecycle consumers use directory-owned admission, generation observation, close and rollback. The directory keeps the Session lease through each admitted operation. | | Plugin management → loader | `rutis/loader.create/reload/remove/status`. The loader owns native profile construction and group instantiation with the original parent and group. | -| Presence consumers → Connection | `sessionClientsHost.presences`. Connection serves this operation directly and handles broadcast, socket registration, writes, close and detach. | -| Activity consumers / daemon clients → ServerControl | `processActivity.activated/hold/release`; existing `daemon.ping/shutdown` RPCs. Shutdown settles the initiating reply before transport teardown. | -| UI clients → UiHost / UiExtensions | Existing `ui.open/attach/replace/status/shutdown/close` RPCs and [extension listing, resources and notices](../client-ui-extensions.md). Transport supplies the authenticated connection identity. UiHost owns attach tokens, generations and disconnect cleanup. | +| Presence consumers → Connection | `connection.presences` ([Connection](../../plugins/Connection.md)). Connection serves this operation directly and handles broadcast, socket registration, writes, close and detach. | +| Activity consumers / daemon clients → ServerControl | `processActivity.activated/closing/hold/release/holds/shutdown/fault` ([ServerControl](../../plugins/ServerControl.md)); existing `daemon.ping/shutdown` RPCs. Shutdown settles the initiating reply before transport teardown. | +| UI clients → UiHost / UiExtensions | Existing `ui.open/attach/replace/status/shutdown/close` RPCs ([UiHost](../../plugins/UiHost.md)) and [extension listing, resources and notices](../client-ui-extensions.md) ([UiExtensions](../../plugins/UiExtensions.md), [UiResources](../../plugins/UiResources.md)). Transport supplies the authenticated connection identity. | | Prompt, scenario and summary evaluation tools → active profile | Use `providerService` for their catalog/selection calls and `modelHost.invoke` for execution. | | Media execution and realtime → native adapter | Existing native connection binding and credential owner ([#1613](https://github.com/arcships/dim/issues/1613), [#1634](https://github.com/arcships/dim/issues/1634)). | | Transport, Web entry and Session subscriptions → Connection | Connection-owned attach, broadcast, close and detach using the authenticated connection identity. | diff --git a/docs/design/plugins/CallChannel.md b/docs/design/plugins/CallChannel.md index 67a0bc7541..f977a8babf 100644 --- a/docs/design/plugins/CallChannel.md +++ b/docs/design/plugins/CallChannel.md @@ -2,53 +2,59 @@ Scope: process. Issue: #2021. -CallChannel owns the binding between one admitted table call and the connection it arrived on: which notifications the provider may send while the call runs, whether a notification is declared, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. +CallChannel owns the binding between an admitted table call and the connection it arrived on: which notifications the provider may send, whether a notification is declared, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. The notification, progress and closed semantics are the [methods contract](../contracts/session-boundary.md) A.2; this document states the owner's operations. ## Use and scope: responsibility split CallChannel owns: -- **The call binding.** One per admitted table call: the connection id, the call id, the registering row instance and the notification names that namespace declared. The binding lives for the call's extent — from `run` until the callback ends or the caller's future is dropped — and the owner always removes it. +- **The call binding.** One per admitted table call: the connection id, the call id, the registering row instance and the notification names that namespace declared. The binding lives until the connection closes or the registering row unloads; a notification sent after the call returned still finds it. - **The declared-name answer.** A name the registration did not declare is refused before anything is written. -- **The connection's end.** `closed` resolves when the connection closes; the binding does not have to be alive. -- **Routing the write.** A notification is written by Connection, addressed by the call id so it follows the reply. +- **The connection's end.** `closed` resolves when the binding's connection closes. +- **Routing the write.** A notification is written by Connection: `write_after` while the call runs, `write` after it returned. Progress is written under the call's own allowance. CallChannel writes no socket and holds no connection state. Callers keep: - What a notification means: the provider chooses the name and the payload. -- The reply: the callback produces it; Rpc writes it after `run` returns. +- The reply: the callback produces it; Rpc writes it. - The declarations: the registering part declared them; the table admitted the call with them. | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Rpc must run one admitted table call with the caller's notifications enabled and its reply ordered | No: the binding, the declared-name answer and the write ordering are the owner's; a `bind`/`finish` pair would make Rpc drive three owners and could leave the binding behind on an error path | `run` | -| A provider must send a notification to the calling connection, in order after its reply | No: the declared-name check, the binding lookup and the ordering are the owner's | `notify` | -| A provider must stop when the connection closes, including after the call returned | Yes: `closed` composes, and it is addressed by the connection alone | `closed` | +| Rpc must run one admitted table call with the caller's notifications enabled | No: the binding, the declared-name answer and the write ordering are the owner's; a `bind`/`finish` pair would make Rpc drive three owners and could leave the binding behind on an error path | `run` | +| A provider must send a notification while or after the call runs, in order after its reply | No: the declared-name check, the binding lookup and the ordering are the owner's | `notify` | +| A provider must report progress under the call's own allowance | No: progress is bounded by the connection's progress budget and the declaration | `progress` | +| A provider must stop when the connection closes | Yes: `closed` composes | `closed` | An operation or parameter exists only where the row says No. ## Caller example -Rpc runs the call once; the owner binds, invokes and settles: +Rpc runs the call once; the owner binds, invokes, and leaves the binding until the connection closes: ```rust -let reply = channel.run(RunRequest { - connection_id: caller.connection_id.clone(), - call_id: caller.call_id.clone(), - instance: row_instance.clone(), - notifications: declared_notifications.clone(), - call: Arc::new(move || { +let reply = channel.run( + ctx, + RunRequest { + connection_id: caller.connection_id.clone(), + call_id: caller.call_id.clone(), + instance: row_instance.clone(), + notifications: declared_notifications.clone(), + }, + Arc::new(move || { let table = table.clone(); let (method, params) = (method.clone(), params.clone()); - Box::pin(async move { table.call(CallRequest { method, params, caller: None }).await }) + Box::pin(async move { table.call(CallRequest { method, params, caller: None }, cancelled).await }) }), -}, cancel).await?; -// Notifications sent inside the callback were held by Connection; the reply releases them in order. + cancelled, +) +.await?; +// The provider may notify after this returned; the binding ends with the connection or the row. ``` -A provider inside the callback builds a notification and waits for the caller to leave: +A provider inside the callback notifies, reports progress, and waits for the caller to leave: ```rust match channel.notify(NotifyRequest { connection_id, call_id, method, params }).await { @@ -57,6 +63,7 @@ match channel.notify(NotifyRequest { connection_id, call_id, method, params }).a Err(NotifyError::Gone) => return Ok(()), // the caller left; nothing to do Err(NotifyError::TooLarge) => return Err(ProviderError::TooLarge), } +channel.progress(ProgressRequest { connection_id, call_id, data }).await; channel.closed(ClosedRequest { connection_id }).await; // also usable after the call returned ``` @@ -64,42 +71,49 @@ channel.closed(ClosedRequest { connection_id }).await; // also usable after the ### Dependencies -Connection's `write_after` and `closed`. +Connection's `write_after`, `write` and `closed`. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `run` | Run one admitted table call with its caller's notifications enabled | `{connection_id, call_id, instance, notifications, call}` | the callback's reply | The caller's token: the callback stops and the binding is removed | the callback's own error; `duplicate` | -| `notify` | Send a notification to the calling connection while the call runs | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `undeclared`, `gone`, `too_large` | -| `closed` | Wait until the calling connection is gone | `{connection_id}` | `{}` when the connection closes; an unknown id resolves at once | The caller's task ends; the wait ends | none | +| `run` | Run one admitted table call with its caller's notifications enabled | `{connection_id, call_id, instance, notifications}` + `caller: &Ctx` + `call` | the callback's `MethodReply` | The caller's token stops the callback; the binding stays with the connection | `invalid_params`, `callback` | +| `notify` | Send a notification to the calling connection, after its call's reply when it runs | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `undeclared`, `gone`, `too_large` | +| `progress` | Report progress for one call | `{connection_id, call_id, data}` | `{}` | None | `undeclared`, `gone`, `too_large` | +| `closed` | Wait until the calling connection is gone | `{connection_id}` | `{}` when it closes; an unknown id resolves at once | The caller's task ends; the wait ends | none | -`run`'s `call` is a callback by reference. The owner invokes it once with the binding open and removes the binding when the callback ends or the caller's future is dropped; no caller frees the binding on any path. `instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name. +`run`'s `call` is a callback parameter, not a request field. The owner invokes it once and keeps the binding until the connection closes or the registering row unloads; no caller frees the binding on any path. `instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name. ### Errors -| Kind | What the caller does next | -| --- | --- | -| `duplicate` | The call id is bound already; this is a programming error in the caller | -| `undeclared` | The registration did not declare the name; fix the declaration, nothing was written | -| `gone` | The call ended or the connection closed; stop notifying for the call | -| `too_large` | The notification exceeds the connection's frame budget; shorten it — the connection stays open | +| Kind | Wire code | What the caller does next | +| --- | --- | --- | +| `invalid_params` | `invalid_params` | The call id is bound to another connection or the request is malformed; a programming error | +| `undeclared` | `undeclared` | The registration did not declare the name; fix the declaration, nothing was written | +| `gone` | `gone` | The connection closed or the row unloaded; stop notifying for the call | +| `too_large` | `too_large` | The frame exceeds the connection's budget (a notification) or progress allowance; shorten it — the connection stays open | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `run` | Record the binding under the row instance and the connection, invoke the callback, remove the binding | The callback stops; the binding is removed; nothing else changes | The caller's future drops; a guard removes the binding | A connection close interrupts the call through its cancellation; the binding is removed | CallChannel: the binding; the caller: the callback's future | -| `notify` | Find the binding, check the declared name, ask Connection to write after the call | The provider's task ends before the write; nothing is written | The binding is gone; `gone` | Pending notifications are `gone` | Connection: the frame; CallChannel: the binding | +| `run` | Record the binding under the row instance and the connection (reuse one already bound for the same row and connection), invoke the callback, return its reply | The callback stops; the binding stays with the connection | The row's bindings are removed | A connection close removes every binding of that connection | CallChannel: the binding; the caller: the callback's future | +| `notify`, `progress` | Find the binding, check the declared name, ask Connection to write after the call (or directly, once the reply is written) | The provider's task ends; nothing is written | The binding is gone; `gone` | Pending frames end `gone` | Connection: the frame; CallChannel: the binding | | `closed` | Wait on Connection's `closed` for the connection | The provider stops waiting | The wait ends | The wait ends | Connection | ## Exceptions with reasons -- `run` takes the callback by reference, like SessionScope's `withHold`: the callback is never called inside a commit lock, and it may notify through this owner while it runs. -- A notification sent after the callback returned is `gone`: the binding is the call's, not the connection's, so a provider that wants to react to the caller leaving uses `closed`, which is addressed by the connection and needs no binding. +- `run` takes the callback by reference, like SessionScope's `withHold`: the callback is never called inside a commit lock, and it may notify and report progress through this owner while it runs. +- The binding outlives the call because the provider may keep notifying after it returned, as A.2 allows; the connection's close or the row's unload is the single settlement. + +## Supersedes + +- [Methods contract](../contracts/session-boundary.md) A.2's Rust binding paragraph (`Caller`, `Callers`, `CallSite`): the operations above replace it; the wire semantics of `notify`, `progress` and `closed` are unchanged. ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | CallChannel is one process part; it writes no Timeline fact and is not a Capability. | @@ -107,7 +121,7 @@ Connection's `write_after` and `closed`. | §3 orthogonality | No other owner's state is read; Connection is asked to write and to report its close. | | §4 rules 1–6, 9 | No event, handoff, before callback, business meaning, batch, model context or Timeline fact. | | §4 rule 7 | Callers use these operations; no caller sees the binding table. | -| §7 one operation | `run` binds, invokes and settles in one call; there is no `bind` or `finish` to pair or leak. | +| §7 one operation | `run` binds and invokes in one call; no `bind` or `finish` is paired or leaked. | | §7 no proxy | The binding, the declared-name answer and the connection's end are this owner's state; Connection writes the frame. | | §7 no handle | The binding is addressed by `{connection_id, call_id}`; no writer crosses. | | ADR 002 D1 | Process scope: calls span rows and connections. | @@ -123,17 +137,20 @@ None. The callback is the same binding rutis already gives `withHold` and FileSt ## Binding appendix ```rust +use crate::host::CancelledFn; +use rutis::Ctx; + pub type CallFn = Arc< - dyn Fn() -> BoxFuture<'static, Result> + Send + Sync, + dyn Fn() -> BoxFuture<'static, Result> + Send + Sync, >; -#[derive(Clone)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub struct RunRequest { pub connection_id: String, pub call_id: String, pub instance: String, - pub notifications: BTreeSet, - pub call: CallFn, + pub notifications: Vec, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -146,21 +163,52 @@ pub struct NotifyRequest { pub params: serde_json::Map, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ProgressRequest { + pub connection_id: String, + pub call_id: String, + pub data: serde_json::Value, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClosedRequest { pub connection_id: String } -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum NotifyError { Undeclared, Gone, TooLarge } +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum RunError { + #[error("{message}")] + InvalidParams { message: String }, + #[error("{code}: {message}")] + Callback { code: String, message: String }, +} + +impl From for RunError { + fn from(error: MethodError) -> Self { + Self::Callback { code: error.code, message: error.message } + } +} + +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum NotifyError { + #[error("The notification is not declared by the registering namespace")] + Undeclared, + #[error("The connection is closed or the row unloaded")] + Gone, + #[error("The frame exceeds the connection's budget")] + TooLarge, +} #[rutis::service(name = "callChannel")] impl CallChannel { - pub async fn run(&self, request: RunRequest, cancel: CancellationToken) - -> Result { /* ... */ } + pub async fn run(&self, caller: &Ctx, request: RunRequest, call: CallFn, cancelled: CancelledFn) + -> Result { /* ... */ } pub async fn notify(&self, request: NotifyRequest) -> Result<(), NotifyError> { /* ... */ } + pub async fn progress(&self, request: ProgressRequest) -> Result<(), NotifyError> { /* ... */ } pub async fn closed(&self, request: ClosedRequest) { /* waits */ } } ``` -`CallFn` is passed by reference; the owner invokes it once and removes the binding when it returns or the caller's future is dropped. The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same two operations. +`MethodReply` and `MethodError` are the [methods contract](../contracts/session-boundary.md) A.1 shapes; `MethodError` is `{code, message}`, defined in the [ManagementMethods](ManagementMethods.md) appendix. The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same operations. diff --git a/docs/design/plugins/Connection.md b/docs/design/plugins/Connection.md index e453be0316..3a2888992c 100644 --- a/docs/design/plugins/Connection.md +++ b/docs/design/plugins/Connection.md @@ -8,34 +8,38 @@ Connection owns the process's live client connections. This document is the owne Connection owns: -- **Admission.** Whether a client may join now: the hello/attach admission that races with the idle-close decision, and the connection limit inside a frame budget. +- **Admission.** Whether a client may join now: the hello/attach admission that races with the idle-close decision, and the connection's frame and reply budgets. - **Connections.** Each accepted client's reader, writer, outbound queue and reply ordering. A connection lives until its reader ends, its client closes, or the daemon closes. -- **Session attachments.** Which Sessions a connection is viewing, each holding one Session lease and one broadcast subscription. Detaching is not closing a Session. -- **Presence.** The live clients of one Session, as the value the model-facing branch reads. +- **Session attachments.** Which Sessions a connection is viewing, each holding one Agents lease and one broadcast subscription. Detaching is not closing a Session. +- **Presence.** The live clients of one Session, as the value the model-facing branch reads. The leaf attribution is folded from UiHost's event; Connection never reads the UI registry. - **The inbound handover.** Each frame is handed to Rpc's current generation; Connection never interprets a method. +- **The two facts and one notice.** `ClientsChanged` wakes the presence branch when a Session's audience changes; `uiExtensions/changed` carries the UI content revision; the `ui.extensions.changed` notification carries it to clients. Connection keeps no Timeline fact, no Session state and no protocol meaning. Callers keep: -- HTTP routing, authentication and the web entry's own routes: WebEntry decides which request becomes a connection upgrade. +- HTTP routing, authentication and the web entry's routes: WebEntry decides which request becomes a connection upgrade. - Protocol semantics: hello fields, built-in methods, Session routing and method errors are Rpc's. - Listener binding and endpoint cleanup: Transport owns the sockets that produce accepted streams. -- The UI registry: UiHost owns interface registrations; Connection tells UiHost that a connection ended. -- The model-facing client snapshot: EnvironmentClientsBranch owns the `` text; Connection gives the presence value. +- The UI registry: UiHost owns interface registrations and emits the attribution event; Connection folds it. +- The model-facing client snapshot: EnvironmentClientsBranch owns the `` text. - The decision to close the daemon: Rpc's `daemon.shutdown` reads the facts each owner publishes; Connection contributes the connection counts and commits the refusal. | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | Transport and WebEntry need an accepted stream to become a live connection | No: creating the record, admitting it against the idle-close decision and owning the read loop are the owner's; the stream is the one handover | `accept` | | A frame must reach the protocol generation that is current now | No: storing the handler in Connection makes a reload a stale object; the owner asks Rpc per frame | dependency on Rpc's `hello` and `request` | -| A provider or Rpc must write a frame after the reply of a call | No: the reply ordering is the connection's outbound queue | `write`, `write_after` | -| A client views a Session | No: the attachment holds one Session lease and one subscription, released on every path | `attach`, `detach` | +| Rpc must write a call's reply and release the notifications held behind it | No: the reply ordering and the reply's own budget are the connection's | `reply` | +| A provider or UiHost must write a notification, before or after a call's reply | No: the ordering and the notification budget are the connection's | `write`, `write_after` | +| A shutdown must answer the initiating client after the daemon settled | No: only the connection can write after its queues drain | `write_deferred` | +| A client views a Session | No: the attachment holds one Agents lease and one subscription, released on every path | `attach`, `detach` | | UiHost needs to know whether a connection views a Session | Yes: a read composes | `attached` | -| The model needs the live clients of a Session | No: the value must come from the owner's own records, not from another owner's registry | `presences` | +| The model needs the live clients of a Session, including which are UI leaves | No: the value must come from the owner's own records; the leaf attribution is folded from UiHost's event | `presences` | | An idle close needs connection counts and an atomic refusal | No: counting and refusing in two calls races with hello and attach | `counts`, `close_for_idle` | | The daemon closes every connection and waits for its tasks | No: the owner settles the writers and readers | `close_all` | -| A connection ends and its attachment and UI registration must go | No: one settlement releases the lease, the subscription and the UI registration | `settle` | +| A connection ends and its attachment and UI attribution must go | No: one settlement releases the lease and the subscription | `settle` | +| A part must wait for a specific connection to end | Yes: `closed` composes | `closed` | An operation or parameter exists only where the row says No. @@ -45,10 +49,7 @@ Transport accepts a stream and hands it over: ```rust // Refused only while the daemon is closing; nothing was created. -let connection = match connections.accept(stream, Entry::Local).await { - Ok(connection) => connection, - Err(AcceptError::Closing) => return, -}; +let Some(connection) = connections.accept(stream, Entry::Local) else { return }; ``` EnvironmentClientsBranch reads the presence value and writes its own input: @@ -59,35 +60,23 @@ let body = render(&presences); // the branch owns the text append_snapshot(&timeline, body)?; ``` -The idle-close handler reads the other owners' facts, then commits the refusal in one call: +The idle-close handler reads the other owner's count and commits the refusal in one call: ```rust let running = agents.sessions().await?.sessions.iter().filter(|s| s.running).count(); -let held = process_activity.holds().await?.count; // a count, not a guard -match connections.close_for_idle(CloseForIdle { - exclude_connection_id: caller.clone(), - running_sessions: running, - held_work: held, -}) { - Ok(counts) => { - // The refusal is committed; the assembly quiesces Agents and closes. - shutdown.request(ShutdownMode::Graceful); - } - Err(CloseForIdleError::Busy(busy)) => return Err(busy.into()), +match connections.close_for_idle(CloseForIdle { exclude_connection_id: caller.clone(), running }) { + Ok(counts) => shutdown.request(ShutdownMode::Graceful), + // The refusal is the protocol's `daemon_busy` with these three counts. + Err(CloseForIdleError::Busy(busy)) => return Err(daemon_busy(busy)), } -``` - -A provider that notifies the calling connection uses CallChannel, which calls `write_after`: - -```rust -channel.notify(NotifyRequest { connection_id, call_id, method, params }).await?; +// A process-work refusal is Rpc's own: it answers `daemon_busy` with an explanation and no counts. ``` ## Own contract ### Dependencies -Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach` and `release`; Agents' `acquire {sessionId} → {leaseId, generation}`, `release {leaseId}` and `sessions` ([Agents contract](Agents.md)). +Rpc's current generation (`hello`, `request`), read by name on each frame; UiHost's `detach`/`release` and its attribution event; Agents' `acquire {sessionId} → {leaseId, generation}` and `release {leaseId}` ([Agents contract, PR #2098](https://github.com/arcships/dim/pull/2098)); UiExtensions' revision event. ### Operations @@ -96,47 +85,50 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `accept` (crate-internal) | Turn an accepted stream into a live connection | `{stream, entry}` | `{connection_id, generation}` | None; the caller either accepts it or drops the stream | `closing` | -| `write` | Write one frame to a connection | `{connection_id, frame}` | `{}` | None; the frame is queued or refused | `unknown_connection`, `gone`, `too_large`, `slow` | -| `write_after` | Write one notification after the reply of one call | `{connection_id, call_id, frame}` | `{}` | None | `unknown_connection`, `gone`, `too_large`, `slow` | +| `reply` | Write a call's reply and release the notifications held behind it | `{connection_id, call_id, frame}` | `{}` | None | `unknown_connection`, `gone`, `too_large`, `slow` | +| `write` | Write one notification with no call ordering | `{connection_id, frame}` | `{}` | None; the frame is queued or refused | `unknown_connection`, `gone`, `too_large`, `slow` | +| `write_after` | Write one notification after a call's reply | `{connection_id, call_id, frame}` | `{}` | None | `unknown_connection`, `gone`, `too_large`, `slow` | | `write_deferred` | Write one frame when the connection settles, before its writer ends | `{connection_id, frame}` | `{}`; a connection that already settled drops the frame | None | none | -| `closed` | Wait until a connection ends | `{connection_id}` | `{}` when the connection ends; an unknown id resolves at once | The caller's task ends | none | -| `attach` | A connection views a Session | `{connection_id, session_id}` | `{generation}` | While the Session lease is acquired and the listener registered; nothing is attached | `unknown_connection`, `closed`, `session_unavailable`, `cancelled` | -| `detach` | A connection stops viewing a Session | `{connection_id, session_id}` | `{}` | None; the owner completes the release | none | +| `closed` | Wait until a connection ends | `{connection_id}` | `{}` when it ends; an unknown id resolves at once | The caller's task ends | none | +| `attach` | A connection views a Session | `{connection_id, session_id}` + `caller: &Ctx` | `{generation}` | The caller's cancellation: the lease is released and the listener disposed | `unknown_connection`, `closed`, `session_unavailable`, `cancelled`, `invalid_params` | +| `detach` | A connection stops viewing a Session | `{connection_id, session_id}` + `caller: &Ctx` | `{}` | None | `invalid_params` | | `attached` | Whether a connection views a Session now | `{connection_id, session_id}` | `{attached}` | None | none | | `presences` | The live clients of a Session | `{session_id}` | `{presences: [{channel, label?}]}` | None | none | | `counts` | Live connections and attached Sessions, excluding one connection | `{exclude_connection_id}` | `{connections, attached_sessions}` | None | none | -| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running_sessions, held_work}` | `{counts}` | None | `busy{connections, attached_sessions, running_sessions}` | +| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running}` | `{connections, attached_sessions, running}` | None | `busy {connections, attached_sessions, running}` | | `close_all` | Close every connection and wait for its tasks | `{}` | `{}` | None; the owner completes the close | none | -| `settle` (internal) | One connection ended: release its attachment, tell UiHost, end its writer | `{connection_id, reason}` | `{}` | None | none | +| `settle` (crate-internal) | One connection ended: release its attachment, tell UiHost, end its writer | `{connection_id, reason}` | `{}` | None | none | -`write` and `write_after` are one operation family: `write_after` exists because a notification sent while a call runs must follow that call's reply, and only the connection's outbound queue knows the reply has been written. `write` refuses a frame over the connection's frame budget with `too_large`, and closes a connection whose reliable allowance is exhausted, reporting `slow` to the writer of that frame. +`reply` writes the frame a call produced and releases the notifications `write_after` held behind it. `write` is for a notification with no call to follow (a UI close notice); `write_after` is for a notification sent while or after a call runs, ordered behind that call's reply. A notification over the frame budget is `too_large` and leaves the connection open; a notification or reply the reliable allowance cannot take is `slow` and closes the connection as a slow consumer. -`close_for_idle` reads the other owners' facts from its request: `running_sessions` from Agents' `sessions` value and `held_work` from `processActivity.holds`, both read immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. +`close_for_idle` takes `running` from Agents' `sessions` value, read immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. After the commit the assembly asks Agents to `quiesce` every Session. A `running` answer means a Session accepted work between the read and the pause; the refusal stands and the graceful close settles that work — admission is never reopened after the commit. ### Errors -| Kind | What the caller does next | -| --- | --- | -| `closing` | The daemon has refused new clients; stop accepting on this listener | -| `unknown_connection` | The connection is gone; drop the write or the attachment and read the current state | -| `gone` | The connection closed or its generation unloaded; nothing was written | -| `too_large` | The frame exceeds the connection's frame budget; the connection stays open — the provider must shorten its notification | -| `slow` | The connection's reliable allowance is exhausted; the connection is closed and the caller drops the frame | -| `session_unavailable` | The Session cannot be acquired now; report it to the client and retry the attach later | -| `cancelled` | Nothing was attached; the caller stopped waiting | -| `closed` | This generation is unloading; reconnect to the replacement generation | -| `busy` | Somebody is using the daemon; answer the client with the three counts and do not close | +| Kind | Wire code | What the caller does next | +| --- | --- | --- | +| `closing` | `daemon_busy` (no counts, with the explanation) | The daemon refused the stream before it was admitted; stop accepting on this listener | +| `busy` | `daemon_busy` with `connections`, `attachedSessions`, `running` | Answer the client with the three counts and do not close | +| `unknown_connection` | — (in-process) | The connection is gone; drop the write or the attachment and read the current state | +| `gone` | — (in-process) | The connection closed or its generation unloaded; nothing was written | +| `too_large` | — (in-process) | The frame exceeds the connection's frame budget; the connection stays open — shorten the notification | +| `slow` | — (in-process) | The connection's reliable allowance is exhausted; the connection is closed and the frame is dropped | +| `session_unavailable` | `session_closed` when the Session is closed, `service_unavailable` when it cannot be acquired | Report it to the client and retry the attach later | +| `cancelled` | — (in-process) | Nothing was attached; the caller stopped waiting | +| `closed` | `service_unavailable` | This generation is unloading; reconnect to the replacement generation | +| `invalid_params` | `invalid_params` | Fix the request: an unknown entry, a malformed id | + +Only the kinds with a wire code reach a client. The others are in-process outcomes of a caller that is itself a part. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `accept` | Admit under the lock, create the record and the writer, spawn the reader, count it | The stream is dropped before the record exists; nothing was admitted | The reader ends with the stream | New accepts are refused as `closing`; every connection is closed | Connection: the record, reader and writer | -| `write`, `write_after` | Encode once, admit into the outbound queue, write in order | None; a frame is queued or refused | A closed connection is `gone` | Pending writes end `gone` | Connection: the queue and writer | +| `reply`, `write`, `write_after` | Encode once, admit into the outbound queue, write in order | None; a frame is queued or refused | A closed connection is `gone` | Pending writes end `gone` | Connection: the queue and writer | | `write_deferred` | Hold the frame until the connection settles | — | — | `close_all` writes it after the queue drains and before the writer ends | Connection | -| `closed` | Resolve when the reader or the owner ends the connection | — | The waiter ends | Resolves for every waiter | Connection | | `attach` | Acquire the Session lease, register the subscription, attach under the connection lock | Before the reply: lease released, listener disposed, nothing attached | The attachment is released with the connection | Pending calls end `closed`; every attachment is released | Connection: the attachment; Agents: the lease | | `detach` | Remove the attachment and release its lease and listener | — | — | The attachment is already gone | Connection | | `close_for_idle` | Recheck counts under the lock, set the refusal, return the counts; the caller then asks Agents to quiesce | None | — | The refusal is the close; a `running` quiesce answer does not reopen it | Connection | @@ -145,16 +137,29 @@ After the commit the assembly asks Agents to `quiesce` every Session. A `running ## Exceptions with reasons - `accept` takes an accepted stream: a socket cannot be represented as data. The shared lifecycle is fixed here: Transport creates the stream by accepting on a listener it owns, calls `accept` once, and never reads or writes the stream afterwards; Connection owns it from the call boundary and settles it in `settle` or `close_all`; when Transport reloads, the listeners close and existing connections stay with Connection; when Connection reloads, every connection settles and Transport's accept calls are refused as `closing` until the new generation is installed. -- Attachment leases are agents' ids, not guards: the connection stores the lease id and releases it in one settlement path, so a connection that dies on any path leaves no lease. +- Attachment leases are Agents' ids, not guards: the connection stores the lease id and releases it in one settlement path, so a connection that dies on any path leaves no lease. - `presences` labels are self-declared and never identities; the value says so by naming the field `label`. +- The UI-leaf attribution is a fact UiHost publishes (`uiHost/attribution` with `{connection_id, session_id, kind}`, and `uiHost/attribution-ended` with `{connection_id}`), and Connection folds it into its own presence state. A read of UiHost's registry would be 代查 and a handle would cross. + +## Client-visible changes + +- `daemon.shutdown {ifIdle:true}` keeps the wire error `daemon_busy` with `connections`, `attachedSessions` and `running`; the field `running` counts Sessions with accepted work or an activity hold, as before. +- One narrow behaviour changes: when a Session accepts work between the caller's read and Agents' `quiesce`, the daemon now closes gracefully instead of answering `daemon_busy`, because Agents' pause is one-way and cannot be reverted. Accepted work still settles; the affected client is the CLI's `daemon stop --if-idle` and any start that stops an idle daemon. Maintaining the old refusal would need a revertable pause from Agents; this contract asks the maintainer to confirm the change. + +## Supersedes + +- [Service faces](../service-faces.md) §3.6 rows `connectionHub` and `serverControl`, and §4.9's `sessionClientsHost` shape: the object names are replaced by this face. +- [Process owner operations](../contracts/process-owner-operations.md) rows `Presence consumers → Connection`, `Activity consumers / daemon clients → ServerControl` and `UI clients → UiHost / UiExtensions`: the operations are those in this document, [ServerControl](ServerControl.md) and [UiHost](UiHost.md). ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | Connection is one process part. It writes no Timeline fact and folds no state, so it is not a Capability. | | §2 scopes | Process. A connection is shared by every Session it views; attachments are the Session-facing part of the same resource. | -| §3 orthogonality | No other owner's state is read. UiHost and Agents are asked through their operations; presence is Connection's own projection over its records. | +| §3 orthogonality | No other owner's state is read. UiHost and Agents are asked through their operations and events. | | §4 rule 1 | No command event: Connection writes no Timeline fact. | | §4 rule 2 | No Timeline handoff. | | §4 rule 3 | No before callback. | @@ -165,68 +170,106 @@ After the commit the assembly asks Agents to `quiesce` every Session. A `running | §4 rule 8 | No infrastructure change. | | §4 rule 9 | No Timeline fact. | | §7 object handover | `accept` is the only object handover; its lifecycle is the exception above. | -| §7 no proxy | Presence is computed from Connection's own records; the UI-leaf attribution arrives as UiHost's fact, not as a read of its registry. | +| §7 no proxy | Presence is computed from Connection's own records; the leaf attribution arrives as UiHost's event, not as a read of its registry. | | ADR 002 D1 | Process scope: connections outlive Sessions and are shared by them. | | ADR 002 D2 | No wiring plugin: the service is on the owner type. | -| ADR 002 D3 | Dependencies point to extensions: Rpc, Transport, UiHost and Agents are used as operations; none is stored as an object. | +| ADR 002 D3 | Dependencies point to extensions: Rpc, Transport, UiHost and Agents are used as operations. | | ADR 002 D4 | The listener configuration is structural; no business setting is involved. | | ADR 002 D5 | The contract is language-neutral except `accept`; the Rust binding is the appendix. | ## Requirements raised to mechanism owners -- **Agents (#2020)**: the operations are the ones in the Agents contract ([#2098](https://github.com/arcships/dim/pull/2098)): `acquire {sessionId} → {leaseId, generation}` and `release {leaseId}` for the attachment lease, `sessions` for the running count, and `quiesce` for the shutdown pause. No new operation is required; the caller passes the read values into `close_for_idle` and quiesces after the commit. -- **rutis (runtime)**: none. +- **Agents (#2020)**: the operations are the ones in the Agents contract ([PR #2098](https://github.com/arcships/dim/pull/2098)): `acquire {sessionId} → {leaseId, generation}` and `release {leaseId}` for the attachment lease, `sessions` for the running count, and `quiesce` for the shutdown pause. +- **UiHost (#2021)**: the attribution events `uiHost/attribution` and `uiHost/attribution-ended`, defined in [UiHost](UiHost.md). ## Binding appendix +`CancelledFn` is the crate's cancellation argument (`crate::host::CancelledFn`); a row-bound operation takes `caller: &Ctx` and registers its cleanup on that row. + ```rust -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +use crate::host::CancelledFn; +use rutis::Ctx; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct PresencesRequest { pub session_id: String } -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct PresencesReply { pub presences: Vec } -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CountsRequest { pub exclude_connection_id: String } + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Counts { pub connections: usize, pub attached_sessions: usize } -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CloseForIdle { pub exclude_connection_id: String, pub running: usize } + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Busy { pub connections: usize, pub attached_sessions: usize, - pub running_sessions: usize, + pub running: usize, } -#[derive(Debug, serde::Serialize, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum CloseForIdleError { #[error("The App Server is in use")] Busy(Busy), } +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ConnectionError { + #[error("The daemon is closing")] + Closing, + #[error("No such connection")] + UnknownConnection, + #[error("The connection is closed")] + Gone, + #[error("The frame exceeds the connection's budget")] + TooLarge, + #[error("The connection cannot keep up")] + Slow, + #[error("The Session cannot be acquired")] + SessionUnavailable, + #[error("The call was cancelled")] + Cancelled, + #[error("The service is unloading")] + Closed, + #[error("{message}")] + InvalidParams { message: String }, +} + #[rutis::service(name = "connection")] impl ConnectionHub { - pub async fn write(&self, request: WriteRequest) -> Result<(), WriteError> { /* ... */ } - pub async fn write_after(&self, request: WriteAfterRequest) -> Result<(), WriteError> { /* ... */ } + pub async fn reply(&self, request: ReplyRequest) -> Result<(), ConnectionError> { /* ... */ } + pub async fn write(&self, request: WriteRequest) -> Result<(), ConnectionError> { /* ... */ } + pub async fn write_after(&self, request: WriteAfterRequest) -> Result<(), ConnectionError> { /* ... */ } pub async fn write_deferred(&self, request: DeferredRequest) { /* ... */ } pub async fn closed(&self, request: ClosedRequest) { /* waits */ } - pub async fn attach(&self, request: AttachRequest) -> Result { /* ... */ } - pub async fn detach(&self, request: DetachRequest) { /* ... */ } + pub async fn attach(&self, caller: &Ctx, request: AttachRequest, cancelled: CancelledFn) + -> Result { /* ... */ } + pub async fn detach(&self, caller: &Ctx, request: DetachRequest) -> Result<(), ConnectionError> { /* ... */ } pub async fn attached(&self, request: AttachedRequest) -> AttachedReply { /* ... */ } pub async fn presences(&self, request: PresencesRequest) -> PresencesReply { /* ... */ } pub async fn counts(&self, request: CountsRequest) -> Counts { /* ... */ } - pub async fn close_for_idle(&self, request: CloseForIdleRequest) -> Result { /* ... */ } - pub async fn close_all(&self, request: Empty) { /* ... */ } + pub async fn close_for_idle(&self, request: CloseForIdle) -> Result { /* ... */ } + pub async fn close_all(&self) { /* ... */ } } impl ConnectionHub { /// Crate-internal: a socket cannot be data. See the exception in this contract. - pub(crate) async fn accept(&self, stream: ClientStream, entry: Entry) -> Result { /* ... */ } + pub(crate) async fn accept(&self, stream: ClientStream, entry: Entry) -> Result { /* ... */ } pub(crate) async fn settle(&self, connection_id: &str, reason: SettleReason) { /* ... */ } } ``` -`ClientStream` is the accepted socket (Unix stream, named pipe or WebSocket); it never crosses a language boundary. `Entry` is `local`, `bare` or `web`. +`ClientStream` is the accepted socket (Unix stream, named pipe or WebSocket); it never crosses a language boundary. `Entry` is `local`, `bare` or `web`. `ClientPresence` is `{channel, label?}` with the channel names `tui`, `cli`, `web`, `acp`, `remote`, `desktop`, `unknown`. diff --git a/docs/design/plugins/EnvironmentClients.md b/docs/design/plugins/EnvironmentClients.md index 22d4dd364a..2b7e4f2a02 100644 --- a/docs/design/plugins/EnvironmentClients.md +++ b/docs/design/plugins/EnvironmentClients.md @@ -2,7 +2,7 @@ Status: Draft. Parent: [agent environment awareness](../agent-environment.md). Issue: [#1019](https://github.com/arcships/dim/issues/1019). Rules: [design rules](../../architecture/rust-agent/principles.md) §1, §4 and §5, [ADR 002](../../adr/002-plugin-scope.md), [model-facing prompts](../model-prompts.md). Language: Rust. -EnvironmentClients tells the model which client connections are attached to its Session. It is a read projection of the App Server's connection and UI registries; it owns no connection state. The snapshot is appended directly to the branch input. It is not a Prompt source and has no version, keyed state or compaction replay. +EnvironmentClients tells the model which client connections are attached to its Session. It reads the App Server's `connection.presences` value and own the snapshot text; the branch does not read the connection or UI registries. The snapshot is appended directly to the branch input. It is not a Prompt source and has no version, keyed state or compaction replay. ## Use and scope: responsibility split @@ -10,7 +10,7 @@ EnvironmentClientsBranch is a pure consumer with no public face. It owns the mod - **Responsibilities.** Build one snapshot at branch open and one per observed change; compare it with the last appended body; append an `input/message` with one Append-mode Raw block. No Prompt source, no version, no replay. - **Left with callers.** Which clients exist and what they are: `connection.presences` is a value; the branch decides how to render it. -- **Not owned.** No connection, no registration, no presence state. The branch does not poll and does not read either registry. +- **Not owned.** No connection, no registration, no presence state. The branch does not poll and reads neither registry; it only calls `connection.presences` and listens for `ClientsChanged`. | Requirement (callers) | Can callers compose it from existing operations without breaking the owner's invariants? | Handling | | --- | --- | --- | @@ -133,7 +133,7 @@ A change that arrives during a turn is appended when it arrives. The input-order ## Plugin structure -- `ConnectionPlugin` provides `SessionClientsHost`. +- `Connection` provides the `connection` face; `presences` answers the value. - `ConnectionPlugin` emits `ClientsChanged` on attach, detach, UI attach/close/replace and connection finish. - `ConnectionPlugin` registers one branch part: `EnvironmentClientsBranch`. - There is no Session part for this projection. @@ -163,7 +163,7 @@ The in-memory presence read is infallible; it returns an empty list for an unkno | Dependency | Purpose | | --- | --- | -| `SessionClientsHost` | Read the current connections | +| `connection.presences` | Read the current connections | | The branch's input path | Append the snapshot | | `BranchLifecycle` | Wait for publication before appending; stop when the branch closes | | Process bus (`ClientsChanged`) | Wake on a connection change | @@ -178,16 +178,19 @@ None to the runtime or rutis. ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + + | Rule | How this design complies | | --- | --- | -| §1 Parts bounded; Capability | The connection registries stay with the App Server; `EnvironmentClientsBranch` is a Capability because it writes snapshot input facts through its branch Timeline. No new process part is added. | +| §1 Parts bounded; Capability | The connection and UI registries stay with their owners; `EnvironmentClientsBranch` is a Capability because it writes snapshot input facts through its branch Timeline. No new process part is added. | | §4 rule 1 Command events | Presence changes no state. | | §4 rule 2 Handover | No handover. | | §4 rule 3 Before callbacks | The branch part appends in its own task; the event handler only wakes it. | | §4 rule 4 Core carries no business meaning | The body is the App Server projection; no core branch. | | §4 rule 5 Batch | A snapshot is one branch input. | | §4 rule 6 Context from consumed events | The snapshot is an input; no second context path. | -| §4 rule 7 Public services | `SessionClientsHost` is the public read port. | +| §4 rule 7 Public services | `connection.presences` is the public read operation; this part publishes none. | | §4 rule 8 Infrastructure unchanged | No Timeline, Dispatcher, envelope, assembly or facade change. | | §4 rule 9 Timeline holds decision facts | The delivered snapshot is an input fact; live presence remains in the App Server registries. | | ADR 002 D1 | Connections stay with the App Server; the branch part only projects them. | diff --git a/docs/design/plugins/ManagementMethods.md b/docs/design/plugins/ManagementMethods.md index c8b7bd8888..0db57b7f4d 100644 --- a/docs/design/plugins/ManagementMethods.md +++ b/docs/design/plugins/ManagementMethods.md @@ -2,7 +2,7 @@ Scope: process. Issue: #2021. -ManagementMethods owns the process namespace table: which namespaces a process part registered, what each declared, and who answers a name now. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/methods.rs` and `crates/dim-agent-capabilities/src/methods.rs`. Rpc, the Session method table ([#2026](../contracts/session-boundary.md)) and the registering parts are separate owners. +ManagementMethods owns the process namespace table: which namespaces a process part registered, what each declared, and who answers a name now. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/methods.rs` and `crates/dim-agent-capabilities/src/methods.rs`. Rpc, the Session method table ([#2026](https://github.com/arcships/dim/issues/2026)) and the registering parts are separate owners. The method declarations, interruptions and reply/error shapes are the [methods contract](../contracts/session-boundary.md) A.1; this document states the owner's operations. ## Use and scope: responsibility split @@ -21,7 +21,7 @@ Callers keep: | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| A process part publishes its namespace for the row's lifetime | No: the registration's lifetime and the duplicate check are the owner's | `register` | +| A process part publishes its namespace for the row's lifetime | No: the registration's lifetime, the duplicate check and the row-bound cleanup are the owner's | `register` | | Rpc must dispatch one call to the namespace that holds the name now | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | An operation or parameter exists only where the row says No. @@ -31,22 +31,30 @@ An operation or parameter exists only where the row says No. A process part registers from `apply`: ```rust -table.register(RegisterRequest { - namespace: "settings".into(), +table.register( + ctx, + RegisterRequest { namespace: "settings".into() }, declarations, - call: handler, // a callback by reference; never called inside a commit lock -}).await?; + Arc::new(move |call: MethodCall| { + let owner = owner.clone(); + Box::pin(async move { owner.handle(call).await }) // Result + }), +).await?; ``` Rpc dispatches: ```rust -// `reloading` and `unavailable` are answered from the registering row's status. +// `service_reloading` and `service_unavailable` are answered from the registering row's status. let reply = table.call(CallRequest { method: method.into(), params, caller: Some(CallerRef { connection_id, call_id }), -}).await?; +}, cancelled).await?; +match reply { + MethodReply::Value { value } => answer_value(value), + MethodReply::Error { code, message } => answer_error(code, message), +} ``` ## Own contract @@ -59,39 +67,47 @@ The loader's row status (`rutis/loader`), read when a withdrawn namespace answer | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Publish a namespace for the registering row's lifetime | `{namespace, declarations, call}` | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | The calling connection closing ends the call as interrupted; an unload ends it by its declaration (`report` or `drain`) | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `invalid` | +| `register` | Publish a namespace for the registering row's lifetime | `{namespace, declarations, call}` + `caller: &Ctx` | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid_params` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `MethodReply`: a value, or the handler's own error | The caller's token stops the wait; a caller disconnect stops delivery only and does not cancel the accepted call | `unknown_method`, `service_reloading`, `service_unavailable`, `operation_interrupted`, `invalid_params` | -`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses. It is absent for an in-process call. The table passes it to the handler unchanged; a handler that notifies uses it with `callChannel` or the native binding. +`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses. It is absent for an in-process call. The table passes it to the handler unchanged; a handler that notifies uses it with `callChannel`. -A call's reply is `MethodReply` data: a value, or the handler's own error with its `code` and `message`. +`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock. ### Errors -| Kind | What the caller does next | -| --- | --- | -| `reserved` | The namespace or a name is the host's; pick another name | -| `duplicate` | The namespace is registered already; the registering row must not register twice | -| `invalid` | The namespace or declaration is outside the name grammar | -| `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | -| `reloading` | The registering row is starting or reloading; retry after it is Active | -| `unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | -| `interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | +The wire codes are the existing ones from the methods contract. + +| Kind | Wire code | What the caller does next | +| --- | --- | --- | +| `reserved` | — (registration, in-process) | The namespace or a name is the host's; pick another name | +| `duplicate` | — (registration, in-process) | The namespace is registered already; the registering row must not register twice | +| `invalid_params` | `invalid_params` | The namespace or declaration is outside the name grammar, or the request is malformed | +| `unknown_method` | `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | +| `service_reloading` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | +| `service_unavailable` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | +| `operation_interrupted` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the name and declarations, record them under the row, refuse a duplicate | — | The registration is withdrawn and the row recorded | New registrations are refused; the table reloads with the process | The registering row | -| `call` | Find the owner, admit the call, run the handler, return the reply; on unload, interrupt `report` and wait for `drain` | A closing connection ends the call as interrupted | The call ends and its commands settle | A withdrawn namespace answers from its row's status | The table for the call's settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return the reply; on unload, interrupt `report` and wait for `drain` | The caller stops waiting; the accepted call continues and settles by its declaration | The call ends and its commands settle | A withdrawn namespace answers from its row's status | The table for the call's settlement; the handler for its effects | ## Exceptions with reasons -- The table remembers the registering row per namespace: a withdrawn namespace must answer `reloading` or `unavailable` rather than fall through to a parent namespace. +- The table remembers the registering row per namespace: a withdrawn namespace must answer `service_reloading` or `service_unavailable` rather than fall through to a parent namespace. - `call` takes the caller as data, not as a connection handle: the reply ordering belongs to Connection, and the table never writes a socket. +## Supersedes + +None. The declarations, interruptions and reply/error shapes stay with the [methods contract](../contracts/session-boundary.md) A.1; this contract states the table owner's operations. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | ManagementMethods is one process part; it writes no Timeline fact and is not a Capability. | @@ -109,15 +125,22 @@ A call's reply is `MethodReply` data: a value, or the handler's own error with i ## Requirements raised to mechanism owners -- **Session registration (#2026)**: the Session method table takes the same `call` request and reply data, so Rpc has one call path for both tables. +- **Session registration (#2026)**: the Session method table takes the same `call` request and `MethodReply`, so Rpc has one call path for both tables. ## Binding appendix ```rust +use crate::host::CancelledFn; +use rutis::Ctx; + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct CallerRef { pub connection_id: String, pub call_id: String } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterRequest { pub namespace: String } + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct CallRequest { @@ -129,7 +152,14 @@ pub struct CallRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CallReply { pub reply: serde_json::Value } +pub struct MethodError { pub code: String, pub message: String } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum MethodReply { + Value { value: serde_json::Value }, + Error { code: String, message: String }, +} #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] @@ -147,7 +177,19 @@ pub struct MethodDecl { pub progress: bool, } -#[derive(Debug, serde::Serialize, thiserror::Error)] +pub type HandlerFn = Arc< + dyn Fn(MethodCall) -> BoxFuture<'static, Result> + Send + Sync, +>; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MethodCall { + pub method: String, + pub params: serde_json::Value, + pub caller: Option, +} + +#[derive(Debug, serde::Serialize, thiserror::Error, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum TableError { #[error("{message}")] @@ -155,22 +197,24 @@ pub enum TableError { #[error("{message}")] Duplicate { message: String }, #[error("{message}")] - Invalid { message: String }, + InvalidParams { message: String }, #[error("Unknown method")] UnknownMethod, #[error("Service is reloading; retry")] - Reloading, + ServiceReloading, #[error("Service is unavailable until it is fixed or restarted")] - Unavailable, + ServiceUnavailable, #[error("Service reloaded; the call may have committed")] - Interrupted, + OperationInterrupted, } #[rutis::service(name = "managementMethods")] impl MethodTable { - pub async fn register(&self, request: RegisterRequest) -> Result<(), TableError> { /* ... */ } - pub async fn call(&self, request: CallRequest) -> Result { /* ... */ } + pub async fn register(&self, caller: &Ctx, request: RegisterRequest, + declarations: Vec, call: HandlerFn) -> Result<(), TableError> { /* ... */ } + pub async fn call(&self, request: CallRequest, cancelled: CancelledFn) + -> Result { /* ... */ } } ``` -`RegisterRequest.call` is a callback by reference: the handler runs on the registering row's runtime and is never called inside a commit lock. +`MethodError` is the handler's own `{code, message}` data; the handler returns it inside `MethodReply::Error` and the table never rewrites it. diff --git a/docs/design/plugins/ProcessRoot.md b/docs/design/plugins/ProcessRoot.md index 642a32a7ea..ee9656bcab 100644 --- a/docs/design/plugins/ProcessRoot.md +++ b/docs/design/plugins/ProcessRoot.md @@ -82,8 +82,16 @@ None. The root reads the assembly's configuration and provides the values. - The root has no plugin row: the assembly is the provider, and a process-scope value needs no `apply`. It provides no resource, so no settlement path exists. - `credentialVariablesHost` covers the configured model catalog's names only; the managed provider's credentials are not environment variables and are not listed. +## Supersedes + +- [Service faces](../service-faces.md) §3.1 row `localId`: the face is retired by this contract. +- [Resource faces](../resource-faces.md) the `localId.get` example: the value stays a value; the face is retired. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + + | Rule | Application | | --- | --- | | §1 parts and Capabilities | The root is the assembly, not a part; it writes no Timeline fact and is not a Capability. | diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 9fb82b710c..86066880a1 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -60,6 +60,6 @@ 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) | +| Process parts | Connection, Transport, ServerControl, Rpc, ManagementMethods, ProcessRoot, CallChannel, UiHost, UiExtensions; 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 | UiResources; 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/Report.md b/docs/design/plugins/Report.md index e40756af03..009d981470 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -51,7 +51,7 @@ Home's error-only flow uses the same three calls in the process namespace with ` In both TUI modes, `/report` opens a report for the current Session, including while a turn is running. It needs no captured error. Users can report an unsatisfactory answer or a repeating turn without waiting for a failure or stopping the turn. The dialog keeps the Session selected when it opened, including when preparing again after expiry. Returning to the composer and running `/report` again selects the Session shown at that time. -Both modes show `Run /report to create a report.` below reportable errors. When a Session is shown, the hint points to the Session report and its recent activity excerpt (§3). On Home, the command can report a conversation-open failure from that view through the process entry. Leaving a Session clears its eligibility as an error source for Home. With neither a Session nor a conversation-open failure to report, the command shows `No session to report.` Desktop and Web error actions remain bound to the selected error. A failure of the report flow stays inside the dialog. +Both modes show `Run /report to create a report.` below reportable errors. When a Session is shown, the hint points to the Session report and its recent activity excerpt (see [Evidence and redaction](#evidence-and-redaction)). On Home, the command can report a conversation-open failure from that view through the process entry. Leaving a Session clears its eligibility as an error source for Home. With neither a Session nor a conversation-open failure to report, the command shows `No session to report.` Desktop and Web error actions remain bound to the selected error. A failure of the report flow stays inside the dialog. ```text > /report @@ -79,9 +79,9 @@ Both modes show `Run /report to create a report.` below reportable errors. When +--------------------------------------------------------------+ ``` -The error-only overlay uses `Report this error`. The Session overlay shows when the Timeline could not be read or the bounded excerpt has no reportable activity. Either state permits generation. Local generation is available on its own. Clients can expose a model picker once the one-shot operation in §7 is available. Its initial model is the adopted model of the referenced branch, or of the Session's main branch when there is no branch reference. It also offers models from the client's admitted catalog and **Generate locally**. Redaction starts checked on every new report: Generate then Save ZIP produces diagnostics only. Before generation, the Session dialog explains that turning redaction off may include sensitive text from recent user and assistant messages. An error-only report has no conversation to attach. Generating and saving never send a report to a feedback destination. Options accepts a short instruction about what to omit or keep. There are no required fields. With a model selected, the dialog exposes the exact model material and limits before Generate can send it. Local mode displays zero model requests. After a stale plan or a failed generation, the client offers to refresh the plan. When the draft expires, the client offers to prepare a report for the original target and reapplies the chosen options. +The error-only overlay uses `Report this error`. The Session overlay shows when the Timeline could not be read or the bounded excerpt has no reportable activity. Either state permits generation. Local generation is available on its own. Clients can expose a model picker once the Provider's one-shot operation is available (see [Requirements raised to mechanism owners](#requirements-raised-to-mechanism-owners)). Its initial model is the adopted model of the referenced branch, or of the Session's main branch when there is no branch reference. It also offers models from the client's admitted catalog and **Generate locally**. Redaction starts checked on every new report: Generate then Save ZIP produces diagnostics only. Before generation, the Session dialog explains that turning redaction off may include sensitive text from recent user and assistant messages. An error-only report has no conversation to attach. Generating and saving never send a report to a feedback destination. Options accepts a short instruction about what to omit or keep. There are no required fields. With a model selected, the dialog exposes the exact model material and limits before Generate can send it. Local mode displays zero model requests. After a stale plan or a failed generation, the client offers to refresh the plan. When the draft expires, the client offers to prepare a report for the original target and reapplies the chosen options. -The overlay follows the TUI's focus and list conventions. Up and Down move between controls, and Tab and Shift+Tab cycle focus. Enter activates the focused control. Esc closes a picker first, cancels generation while busy, or closes the report. Focus starts on Model. The TUI shortens the error and report title to fit the overlay and keeps the focused action visible. The result lists the archive contents and shows the saved path so users can inspect the files with their own tools. Place `/report` immediately before `/exit` in both curated menus with the description `report the current session`, following the existing exact-name, Enter and Tab behavior. The CLI command owner owns the menu (§7). [TUI design](Tui.md), [command menu contract](../cli-commands.md#command-menu). +The overlay follows the TUI's focus and list conventions. Up and Down move between controls, and Tab and Shift+Tab cycle focus. Enter activates the focused control. Esc closes a picker first, cancels generation while busy, or closes the report. Focus starts on Model. The TUI shortens the error and report title to fit the overlay and keeps the focused action visible. The result lists the archive contents and shows the saved path so users can inspect the files with their own tools. Place `/report` immediately before `/exit` in both curated menus with the description `report the current session`, following the existing exact-name, Enter and Tab behavior. The CLI command owner owns the menu. [TUI design](Tui.md), [command menu contract](../cli-commands.md#command-menu). ## Evidence and redaction @@ -112,26 +112,26 @@ TimelineTree's bounded branch read and branch summary ([#2024](https://github.co | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `prepare` | Capture a bounded snapshot and open a draft | `{error?}`; the process namespace requires `error` in the observed variant | `{reportId, defaultModel?, plan}` | Before the snapshot is captured; nothing is drafted | `caller_required`, `invalid`, `unavailable` | -| `plan` | Bind the exact material, generation and directives | `{reportId, generation, redact, instructions?}` | `{planId, generation, evidence, instructionsStatus}` | None; the plan is a value | `not_found`, `invalid`, `busy`, `model_unavailable` | -| `generate` | Consume the plan and produce the archive | `{reportId, planId}` | `{title, body, files, archive, sharing}` | The named plan stops; the evidence stays for a new plan | `not_found`, `stale`, `busy`, `generation_failed`, `cancelled` | -| `cancel` | Stop a generation or drop a draft | `{reportId, target: "generation", planId}` or `{reportId, target: "report"}` | `{cancelled}` | — | `not_found` | +| `prepare` | Capture a bounded snapshot and open a draft | `{error?}`; the process namespace requires `error` in the observed variant | `{reportId, defaultModel?, plan}` | Before the snapshot is captured; nothing is drafted | `caller_required`, `invalid_params`, `unavailable`, `report_cancelled` | +| `plan` | Bind the exact material, generation and directives | `{reportId, generation, redact, instructions?}` | `{planId, generation, evidence, instructionsStatus, material, maxOutputTokens, estimatedCost}` | None; the plan is a value | `report_not_found`, `invalid_params`, `report_busy`, `report_model_unavailable` | +| `generate` | Consume the plan and produce the archive | `{reportId, planId}` | `{title, body, files, archive, sharing}` | The named plan stops; the evidence stays for a new plan | `report_not_found`, `report_plan_stale`, `report_busy`, `report_generation_failed`, `report_cancelled` | +| `cancel` | Stop a generation or drop a draft | `{reportId, target: "generation", planId}` or `{reportId, target: "report"}` | `{cancelled}` | — | `report_not_found` | -The draft is keyed by the calling connection and the part instance; a missing, expired or foreign draft is `not_found`. A new `prepare` replaces an idle draft for that connection. At most 16 drafts per part instance; a seventeenth is `busy`. The observed input and instructions are bounded to 1 KiB each; the prepared model material to 8 KiB; the encoded ZIP to 64 KiB before the reply. +The draft is keyed by the calling connection and the part instance; a missing, expired or foreign draft is `report_not_found`. A new `prepare` replaces an idle draft for that connection. At most 16 drafts per part instance; a seventeenth is `report_busy`. The observed input and instructions are bounded to 1 KiB each; the prepared model material to 8 KiB; the encoded ZIP to 64 KiB before the reply. ### Errors | Kind | What the caller does next | | --- | --- | -| `caller_required` | The method needs a client connection; an in-process caller cannot prepare a report | +| `caller_required` | The method needs a client connection; an in-process caller cannot prepare a report. Never reaches a client | | `invalid` | Fix the request: a missing or malformed error reference, a model id outside the admitted catalog, an out-of-range field | | `unavailable` | No draft can be prepared now: the Session is closing or its evidence cannot be read; use the local template or retry later | -| `not_found` | The draft expired or belongs to another connection; prepare again | -| `stale` | The plan was replaced or consumed; review the new plan before generating | -| `busy` | A generation is running for this draft; cancel it or wait for it to settle | -| `model_unavailable` | The selected model cannot serve this request; choose another or generate locally | -| `generation_failed` | The generation failed; the draft keeps its evidence and the caller retries with a new plan or generates locally | -| `cancelled` | The generation stopped; the draft keeps its evidence | +| `report_not_found` | The draft expired or belongs to another connection; prepare again | +| `report_plan_stale` | The plan was replaced or consumed; review the new plan before generating | +| `report_busy` | A generation is running for this draft; cancel it or wait for it to settle | +| `report_model_unavailable` | The selected model cannot serve this request; choose another or generate locally | +| `report_generation_failed` | The generation failed; the draft keeps its evidence and the caller retries with a new plan or generates locally | +| `report_cancelled` | The generation stopped; the draft keeps its evidence | ### Flows @@ -153,7 +153,7 @@ The draft is keyed by the calling connection and the part instance; a missing, e Local generation renders a template from the approved snapshot and uses zero model calls. The optional short-lived report Agent performs one isolated drafting operation using only the reviewed material. Its input is the fixed system instruction, filtered snapshot and resolved redaction directives. It has no inherited Session, tools, workspace, credentials or publishing access. The Provider owner resolves and authenticates the request. The report plan shows the exact prompt material, the chosen provider/model, output limit and an estimate when the necessary price and token count are available. A plan cannot silently fall back to a different connection, model or request payload. -The Agent's operation uses the one-shot auxiliary model boundary, with the single-attempt policy requested in §7. It does not create a general-purpose chat Session. The model proposes the title template, body section order and evidence selections and omissions using a bounded schema of known fields. Report validates the selection and renders the actual text from approved values. Invalid output fails generation and offers the local template. Neither path includes reproduction steps unless approved evidence establishes them. +The Agent's operation uses the one-shot auxiliary model boundary, with the single-attempt policy requested from the Provider (see [Requirements raised to mechanism owners](#requirements-raised-to-mechanism-owners)). It does not create a general-purpose chat Session. The model proposes the title template, body section order and evidence selections and omissions using a bounded schema of known fields. Report validates the selection and renders the actual text from approved values. Invalid output fails generation and offers the local template. Neither path includes reproduction steps unless approved evidence establishes them. ## Preview and sharing @@ -179,8 +179,15 @@ The client keeps the completed preview and bytes when a share action fails. The | Provider ([#2019](https://github.com/arcships/dim/issues/2019)) | A one-shot completion with a caller-selected no-retry policy and the exact prepared material | Model-assisted generation is outside this contract until the owner offers that operation; the local template stays the default | | Web entry (App Server, this block) | Admit the process `report.*` namespace on the authenticated local Web entry | The error-only entry is served to the web client; the admission list is the entry's | +## Supersedes + +None. This document replaces its own previous ownership and methods sections in place; the client interaction, evidence and generation sections stay. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + + | Rule | Application | | --- | --- | | Principles §1 and ADR 002 D1 | Report has a Session part and a process part for their draft scopes; neither is a Capability. | @@ -229,6 +236,24 @@ pub struct PrepareReply { pub plan: Plan, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PlanReply { + pub plan_id: String, + pub generation: Generation, + pub evidence: Reviewed, + pub instructions_status: String, + /// The exact prompt material the user reviews before Generate; bounded to 8 KiB. + pub material: String, + pub max_output_tokens: u32, + /// `{amount, currency}` when the owner knows a price, else none. + pub estimated_cost: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Cost { pub amount: String, pub currency: String } + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct PlanRequest { @@ -255,21 +280,21 @@ pub enum ReportError { #[error("Report methods require a client connection")] CallerRequired, #[error("{message}")] - Invalid { message: String }, + InvalidParams { message: String }, #[error("The report cannot be prepared now")] Unavailable, #[error("The report draft is missing or expired")] - NotFound, + ReportNotFound, #[error("The plan was replaced or consumed")] - Stale, + ReportPlanStale, #[error("A generation is running for this report")] - Busy, + ReportBusy, #[error("The selected model is unavailable")] - ModelUnavailable, + ReportModelUnavailable, #[error("The generation failed")] - GenerationFailed, + ReportGenerationFailed, #[error("The generation was cancelled")] - Cancelled, + ReportCancelled, } ``` diff --git a/docs/design/plugins/Rpc.md b/docs/design/plugins/Rpc.md index b4ae5b2736..9b854e4af0 100644 --- a/docs/design/plugins/Rpc.md +++ b/docs/design/plugins/Rpc.md @@ -2,13 +2,13 @@ Scope: process. Issue: #2021. -Rpc owns the daemon's inbound protocol entry: the handshake, the built-in methods, the routing to method namespaces, and the settlement of accepted commands. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/connection.rs` (`RpcService`, `RpcPlugin`). Connection, ManagementMethods, CallChannel, Agents and ServerControl are separate owners with their own contracts. +Rpc owns the daemon's inbound protocol entry: the handshake, the built-in methods, the routing to method namespaces, and the settlement of accepted commands. This document is the owner's target contract; the current implementation is in `crates/dim-app-server/src/connection.rs` (`RpcService`, `RpcPlugin`). Connection, ManagementMethods, CallChannel, Agents and ServerControl are separate owners with their own contracts. The wire behaviour of methods — declarations, interruptions, `callChannel` — is the [methods contract](../contracts/session-boundary.md); this document states the owner's operations. ## Use and scope: responsibility split Rpc owns: -- **The handshake.** Which protocol versions a connection may greet with, what the greeting records, and what the greeting reply carries. +- **The handshake.** Which protocol versions a connection may greet with, what the greeting records, and the method list the greeting carries. - **Built-in methods.** `daemon.ping`, `daemon.shutdown`, `session.*` and the other methods the protocol reserves; each built-in's admission and reply. - **Routing.** For each call: the management table, the Session's table, or a built-in; the caller identity the table receives; the call id notifications are addressed by. - **Command settlement.** The commands a call starts, their drain on unload, and the interruption kinds their declarations name. @@ -19,7 +19,7 @@ Callers keep: - Reading frames and writing replies: Connection owns the socket, the outbound queue and the reply ordering. - The namespace table and the registered handlers: ManagementMethods and the Session's method table own them. -- Authorizing Session access: Agents decides whether a Session may be acquired; the built-in methods carry the decision. +- Authorizing Session access: Agents decides whether a Session may be acquired. - The shutdown sequence: ServerControl owns the intent; the assembly runs the sequence. | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | @@ -32,53 +32,64 @@ An operation or parameter exists only where the row says No. ## Caller example +Connection reads one frame and asks the current generation: + ```rust -// Connection reads one frame and asks the current generation. -let hello = rpc.hello(HelloRequest { connection_id: id.clone(), params }).await?; -connection.write(hello.reply); +let hello = rpc.hello(HelloRequest { connection_id: id.clone(), params }, cancelled.clone()).await?; +connection.reply(ReplyRequest { connection_id: id.clone(), call_id, frame: hello.reply }).await?; -let reply = rpc.request(RequestCall { connection_id: id, call_id, request }).await?; -connection.write_after(WriteAfter { connection_id: id, call_id, frame: reply.frame }).await?; +let reply = rpc.request(RequestCall { connection_id: id, call_id, request }, cancelled).await?; +connection.reply(ReplyRequest { connection_id: id, call_id, frame: reply.reply }).await?; ``` ## Own contract ### Dependencies -Connection's `write_after` and `attached`; ManagementMethods' `call`; the Session's method table (the same shape, per [ManagementMethods](ManagementMethods.md)); Agents' `acquire` and running/close operations; CallChannel's `run`; ServerControl's `shutdown`. +Connection's `reply` and `attached`; ManagementMethods' `call`; the Session's method table (the same shape, per [ManagementMethods](ManagementMethods.md)); Agents' `acquire` and `sessions` ([Agents contract, PR #2098](https://github.com/arcships/dim/pull/2098)); CallChannel's `run`; ServerControl's `shutdown`. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `hello` | Answer a client's greeting for this generation | `{connection_id, params}` | `{reply, records}` | None; the handshake is one step | `reloading` (no generation is serving), `invalid` (version, entry or hello fields), `closed` | -| `request` | Dispatch one call and settle what it starts | `{connection_id, call_id, request}` | `{reply}` | The calling connection closing ends the call as interrupted; an unload ends it by the method's declaration | `reloading`, `unknown_method`, `interrupted`, `invalid`, and the method's own error | +| `hello` | Answer a client's greeting for this generation | `{connection_id, params}` | `{reply, instance, methods}`: the frame, this generation's instance id and the management method names | The caller's token; the handshake stops before anything is recorded | `service_reloading`, `invalid_params`, `service_unavailable` | +| `request` | Dispatch one call and settle what it starts | `{connection_id, call_id, request}` | `{reply}`: the frame | The caller's token stops the wait; the provider's call is not cancelled by it (see below) | `service_reloading`, `service_unavailable`, `unknown_method`, `operation_interrupted`, `invalid_params`, and the method's own error | + +`request` mints nothing: the `call_id` comes from Connection, so the provider, CallChannel and the reply ordering name one call. The method's own error is the data the table returns; Rpc maps it to the protocol envelope and does not add kinds. -`request` mints nothing: the `call_id` comes from Connection, so the provider, CallChannel and the reply ordering name one call. The method's own errors are the data the table returns; Rpc maps them to the protocol envelope and does not add kinds. +A calling connection closing stops delivery only: the admitted call belongs to the provider generation and settles according to its declaration, as the [methods contract A.1 and A.2](../contracts/session-boundary.md) require. Rpc's `request` returns the reply frame; writing it is Connection's. ### Errors -| Kind | What the caller does next | -| --- | --- | -| `reloading` | Retry after the next generation is installed; the connection stays open | -| `unknown_method` | The name no namespace holds; the client sees the method error | -| `interrupted` | The call may have committed; read the current state before retrying | -| `invalid` | The frame or the greeting is malformed; answer the client with the protocol error | -| `closed` | The connection is gone; nothing was dispatched | +The wire codes are the existing ones from the methods contract; a client matches them unchanged. + +| Kind | Wire code | What the caller does next | +| --- | --- | --- | +| `service_reloading` | `service_reloading` | Retry after the next generation is installed; the connection stays open | +| `service_unavailable` | `service_unavailable` | The generation cannot run; reconnect or report the service as unavailable | +| `unknown_method` | `unknown_method` | The name no namespace holds; the client sees the method error | +| `operation_interrupted` | `operation_interrupted` | The call may have committed; read the current state before retrying | +| `invalid_params` | `invalid_params` | The frame or the greeting is malformed; answer the client with the protocol error | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `hello` | Check the version window and the entry, record the greeting, build the method list | — | — | New hellos are refused as `reloading`; open connections stay | Rpc | -| `request` | Route, admit through the table with the caller identity and `call_id`, return the reply; commands settle in Rpc's tracker | A closing connection ends the call as interrupted | The call ends and its commands settle | An unloading generation cancels its commands, answers pending waits as interrupted and drains before unload; connections stay open | Rpc: the commands | +| `hello` | Check the version window and the entry, record the greeting, build the method list | — | — | New hellos are refused as `service_reloading`; open connections stay | Rpc | +| `request` | Route, admit through the table with the caller identity and `call_id`, return the reply; commands settle in Rpc's tracker | A closing connection stops waiting for the frame; the accepted call continues and settles by its declaration | The call finishes and its commands settle | An unloading generation cancels its commands, answers pending waits as `operation_interrupted` and drains before unload; connections stay open | Rpc: the commands | ## Exceptions with reasons - The built-in methods are a closed set on the owner type, not registrations: they are the protocol's own methods and never appear in the management table. +## Supersedes + +None. The method declarations, interruptions and `callChannel` behaviour stay with the [methods contract](../contracts/session-boundary.md); this contract states the dispatcher owner's operations. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | Rpc is one process part; it writes no Timeline fact and is not a Capability. | @@ -96,20 +107,26 @@ Connection's `write_after` and `attached`; ManagementMethods' `call`; the Sessio ## Requirements raised to mechanism owners -- **Session registration (#2026)**: the Session method table's dispatch takes the same `{method, params, caller: {connectionId, callId}}` request and returns the same reply data, so one call path serves both tables. +- **Session registration (#2026)**: the Session method table's dispatch takes the same `{method, params, caller: {connectionId, callId}}` request and returns the same `MethodReply`, so one call path serves both tables. ## Binding appendix ```rust -#[derive(Debug, serde::Serialize, serde::Deserialize)] +use crate::host::CancelledFn; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct HelloRequest { pub connection_id: String, pub params: HelloParams } -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct HelloReply { pub reply: Frame, pub records: Vec } +pub struct HelloReply { + pub reply: Frame, + pub instance: String, + pub methods: Vec, +} -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct RequestCall { pub connection_id: String, @@ -117,30 +134,32 @@ pub struct RequestCall { pub request: Request, } -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RequestReply { pub reply: Reply } +pub struct RequestReply { pub reply: Frame } -#[derive(Debug, serde::Serialize, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum RpcError { #[error("Service is reloading; retry")] - Reloading, + ServiceReloading, + #[error("Service is unavailable until it is fixed or restarted")] + ServiceUnavailable, #[error("Unknown method")] UnknownMethod, #[error("Service reloaded; the call may have committed")] - Interrupted, + OperationInterrupted, #[error("{message}")] - Invalid { message: String }, - #[error("The connection is closed")] - Closed, + InvalidParams { message: String }, } #[rutis::service(name = "rpc")] impl RpcService { - pub async fn hello(&self, request: HelloRequest) -> Result { /* ... */ } - pub async fn request(&self, request: RequestCall) -> Result { /* ... */ } + pub async fn hello(&self, request: HelloRequest, cancelled: CancelledFn) + -> Result { /* ... */ } + pub async fn request(&self, request: RequestCall, cancelled: CancelledFn) + -> Result { /* ... */ } } ``` -`Connection` looks the `rpc` service up on each frame; a generation that is unloading refuses new frames as `reloading`. +`Frame` is the encoded protocol frame the client receives; `Request` is the decoded call. Connection looks the `rpc` service up on each frame; a generation that is unloading refuses new frames as `service_reloading`. diff --git a/docs/design/plugins/ServerControl.md b/docs/design/plugins/ServerControl.md index f361d098d7..54d1995df0 100644 --- a/docs/design/plugins/ServerControl.md +++ b/docs/design/plugins/ServerControl.md @@ -36,20 +36,22 @@ An operation or parameter exists only where the row says No. A process part that starts work before any Session exists: ```rust -if !activity.activated().await { +if !activity.activated().await.activated { return Err(WorkError::HostClosed); // startup failed or shutdown began } -let hold = activity.hold().ok_or(WorkError::HostClosed)?; +let hold = activity.hold(ctx).await?; // the id is bound to this row let result = run_work().await; -activity.release(hold); +activity.release(ReleaseRequest { hold_id: hold.hold_id }).await; ``` The `daemon.shutdown` handler: ```rust -match activity.shutdown(ShutdownMode::Graceful) { +match activity.shutdown(ShutdownRequest { mode: ShutdownMode::Graceful }).await { Ok(()) => { /* hold the reply until the assembly settles, then write it */ } - Err(ShutdownError::Conflict) => return Err(RpcError::invalid("Shutdown already requested")), + // Rpc maps this kind to the protocol's `invalid_params`: "Shutdown already requested". + Err(ActivityError::Conflict) => return Err(RpcError::invalid("Shutdown already requested")), + Err(error) => return Err(error.into()), } ``` @@ -73,16 +75,16 @@ None. The owner injects no service. | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `activated` | Whether the host has opened; a reload does not reset it | `{}` | `{activated}` | None | none | -| `closing` | Wait until the daemon starts closing | `{}` | `{}` when closing begins | The caller's token; the wait ends | none | -| `hold` | Keep a graceful close until the work settles | `{}` | `{hold_id}` | None; the id is settled by `release` or the row's unload | `closed` | +| `closing` | Wait until the daemon starts closing | `{}` | `{}` when closing begins | The caller's task ends; the wait ends | none | +| `hold` | Keep a graceful close until the work settles | `{}` + `caller: &Ctx` | `{hold_id}` | None; the id is settled by `release` or the row's unload | `closed` | | `release` | The work settled | `{hold_id}` | `{released}`; an already released id is `false` | None | none | | `holds` | Whether any accepted work is held now | `{}` | `{count}` | None | none | | `shutdown` | Ask the process to close | `{mode: graceful \| forced}` | `{}` accepted | None; the close cannot be cancelled | `conflict` | | `fault` | A listener exited; end the process | `{listener, message}` | `{}` | None | none | -`hold` and `release` are not a `withHold(work)` callback. The accepted work outlives the call that started it: a Workflow run spans several calls and several Sessions, and a Scheduler delivery settles after the launching call returned. No single function represents that work, and a callback form would make the owner keep the caller's future alive across those calls. The id lets the caller's business object own the hold while the owner only tracks it. +`hold` takes the calling row's context because the hold is settled at that row's unload: an id that outlives its row is released by the owner, and a later `release` answers `false`. A row that crashes without unloading keeps its hold until the process ends, and `shutdown(forced)` proceeds without it. -The pair is one id's acquire and release, not a multi-step session: `release` is idempotent, a lost id never corrupts owner state and only keeps a graceful close waiting, and the row's unload releases it. A hold released by the row's unload answers `false` to a later `release`. A row that crashes without unloading keeps its hold until the process ends, and `shutdown(forced)` proceeds without it. +`hold` and `release` are not a `withHold(work)` callback. The accepted work outlives the call that started it: a Workflow run spans several calls and several Sessions, and a Scheduler delivery settles after the launching call returned. No single function represents that work, and a callback form would make the owner keep the caller's future alive across those calls. The id lets the caller's business object own the hold while the owner only tracks it. `shutdown` does not run the sequence. It records the intent; `closing` resolves for every waiter; the assembly settles Agents, drains Rpc, closes connections and answers the initiating client. A second `shutdown` with any mode is `conflict`. @@ -90,10 +92,10 @@ The pair is one id's acquire and release, not a multi-step session: `release` is ### Errors -| Kind | What the caller does next | -| --- | --- | -| `closed` | The daemon is closing; stop starting work | -| `conflict` | A shutdown was already requested; answer the client as already requested | +| Kind | Wire code | What the caller does next | +| --- | --- | --- | +| `closed` | `service_unavailable` at `daemon.ping`/`daemon.shutdown` | The daemon is closing; stop starting work | +| `conflict` | `invalid_params` | A shutdown was already requested; answer the client as already requested | No other error exists: the owner has no "not found", "invalid input" or "too large" state. @@ -111,8 +113,15 @@ No other error exists: the owner has no "not found", "invalid input" or "too lar - `processActivity` is the single published name for a merged owner: the publication gate, the holds and the shutdown intent share one plugin and one lifecycle, and `serverControl` had no method of its own. Keeping the name avoids a wire rename for Workflow and Scheduler. - `hold`/`release` are two calls rather than `withHold(work)`: the accepted work outlives the call (a Workflow run, a Scheduler delivery), so no callback represents it. Settlement: the calling row's unload releases its holds; the owner refuses new holds once closing starts and waits for the released ones; a lost owner keeps the close graceful until the process ends, and a forced close does not wait. +## Supersedes + +- [Service faces](../service-faces.md) §3.6 row `serverControl`. +- [Process owner operations](../contracts/process-owner-operations.md) row `Activity consumers / daemon clients → ServerControl`: the operations are those in this document. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | ServerControl is one process part; it writes no Timeline fact and is not a Capability. | @@ -130,16 +139,46 @@ No other error exists: the owner has no "not found", "invalid input" or "too lar ## Requirements raised to mechanism owners -- **Agents (#2020)**: `quiesce` ([#2098](https://github.com/arcships/dim/pull/2098)) — the assembly calls it after `shutdown` is accepted; the pause lives in Agents until its generation unloads, so no guard crosses to this owner. +- **Agents (#2020)**: `quiesce` ([PR #2098](https://github.com/arcships/dim/pull/2098)) — the assembly calls it after `shutdown` is accepted; the pause lives in Agents until its generation unloads, so no guard crosses to this owner. ## Binding appendix ```rust -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +use rutis::Ctx; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ShutdownMode { Graceful, Forced } -#[derive(Debug, serde::Serialize, thiserror::Error)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ActivatedReply { pub activated: bool } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HoldReply { pub hold_id: u64 } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReleaseRequest { pub hold_id: u64 } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReleasedReply { pub released: bool } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HoldsReply { pub count: usize } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ShutdownRequest { pub mode: ShutdownMode } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FaultRequest { pub listener: String, pub message: String } + +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum ActivityError { #[error("The daemon is closing")] @@ -150,14 +189,14 @@ pub enum ActivityError { #[rutis::service(name = "processActivity")] impl ProcessActivity { - pub async fn activated(&self, request: Empty) -> ActivatedReply { /* ... */ } - pub async fn closing(&self, request: Empty) { /* waits */ } - pub async fn hold(&self, request: Empty) -> Result { /* ... */ } + pub async fn activated(&self) -> ActivatedReply { /* ... */ } + pub async fn closing(&self) { /* waits */ } + pub async fn hold(&self, caller: &Ctx) -> Result { /* ... */ } pub async fn release(&self, request: ReleaseRequest) -> ReleasedReply { /* ... */ } - pub async fn holds(&self, request: Empty) -> HoldsReply { /* ... */ } + pub async fn holds(&self) -> HoldsReply { /* ... */ } pub async fn shutdown(&self, request: ShutdownRequest) -> Result<(), ActivityError> { /* ... */ } pub async fn fault(&self, request: FaultRequest) { /* ... */ } } ``` -`HoldId` is a `u64`; the id is not authority — the owner releases it by id or by the calling row's unload. +`hold_id` is a `u64`; the id is not authority — the owner releases it by id or by the calling row's unload. diff --git a/docs/design/plugins/Transport.md b/docs/design/plugins/Transport.md index 4ff06e3f9b..7d5b832895 100644 --- a/docs/design/plugins/Transport.md +++ b/docs/design/plugins/Transport.md @@ -44,15 +44,15 @@ Connection's `accept`, called once per accepted stream; ServerControl's `activat | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `read` | The addresses this process bound | `{}` | `{unixPath?, pipeName?, websocketAddress?}` | None | `invalid` | +| `read` | The addresses this process bound | `{}` | `{unixPath?, pipeName?, websocketAddress?}` | None | `invalid_path` | -`read` converts the bound addresses to UTF-8 text; a Unix path that is not UTF-8 is `invalid`, and the rest of the reply is not sent. +`read` converts the bound addresses to UTF-8 text; a Unix path that is not UTF-8 is `invalid_path`, and the rest of the reply is not sent. ### Errors | Kind | What the caller does next | | --- | --- | -| `invalid` | The bound Unix path is not UTF-8; use another endpoint or start the daemon with a UTF-8 path | +| `invalid_path` | The bound Unix path is not UTF-8; use another endpoint or start the daemon with a UTF-8 path | ### Flows @@ -65,8 +65,15 @@ Connection's `accept`, called once per accepted stream; ServerControl's `activat - The accept loop is internal: a listener event is not data. Transport calls `Connection::accept` crate-internally; the stream's lifecycle is fixed in the [Connection contract](Connection.md). +## Supersedes + +- [Service faces](../service-faces.md) §4.9's `listenAddresses.read` line: the operation is the one in this contract. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + + | Rule | Application | | --- | --- | | §1 parts and Capabilities | Transport is one process part; it writes no Timeline fact and is not a Capability. | @@ -101,7 +108,7 @@ pub struct BoundAddresses { #[serde(tag = "code", rename_all = "snake_case")] pub enum ListenError { #[error("{message}")] - Invalid { message: String }, + InvalidPath { message: String }, } #[rutis::service(name = "listenAddresses")] diff --git a/docs/design/plugins/Tui.md b/docs/design/plugins/Tui.md index 7472045f01..86cd4bcb8f 100644 --- a/docs/design/plugins/Tui.md +++ b/docs/design/plugins/Tui.md @@ -255,6 +255,8 @@ or plugin. ### 3.6 UI registry and UI leaves +The registry's operations are the [UiHost contract](UiHost.md); this section describes the leaf lifecycle. + The daemon is the authority over which interfaces are alive, and can close or replace them. An attached terminal interface is a **UI leaf**: the interactive `dimcode` process is a rutis kernel in a rutis session with the daemon diff --git a/docs/design/plugins/UiExtensions.md b/docs/design/plugins/UiExtensions.md index 99d3ca2caf..7d095c21b1 100644 --- a/docs/design/plugins/UiExtensions.md +++ b/docs/design/plugins/UiExtensions.md @@ -57,12 +57,12 @@ FileStorage (`add_root`, `list`, `read`) for the declared roots and files; Manag | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Publish one package's UI content | `{plugin, manifest?}` | `{}`; a failed preparation is recorded as a refusal, not an error | While the files are copied; nothing is published | `invalid` (unknown plugin id, unsupported version, bad declaration) | +| `register` | Publish one package's UI content | `{plugin, manifest?}` | `{}`; a failed preparation is recorded as a refusal, not an error | While the files are copied; nothing is published | `invalid_params` (unknown plugin id, unsupported version, bad declaration) | | `withdraw` | Remove a package's content | `{plugin}` | `{}` | None; the owner settles admitted reads | none | | `plugins` | The packages with content now | `{}` | `{plugins: [id]}` | None | none | | `refusal` | Why a package's content was refused | `{plugin}` | `{message?}` | None | none | | `directory` | The published directory | `{}` | `{revision, extensions, errors}` | None | none | -| `read` | One page of a prepared file | `{generation, path, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The calling connection's task ends; the page stops | `unavailable` | +| `read` | One page of a prepared file | `{generation, path, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The calling connection's task ends; the page stops | `resource_unavailable` | `register` with no manifest withdraws the package's content, the same as `withdraw`. @@ -70,8 +70,8 @@ FileStorage (`add_root`, `list`, `read`) for the declared roots and files; Manag | Kind | What the caller does next | | --- | --- | -| `invalid` | The package id is unknown, the version unsupported or the declaration invalid; the reason is recorded as the package's refusal | -| `unavailable` | The file is gone or unreadable; the client shows the panel as unavailable | +| `invalid_params` | The package id is unknown, the version unsupported or the declaration invalid; the reason is recorded as the package's refusal | +| `resource_unavailable` | The file is gone or unreadable; the client shows the panel as unavailable | ### Flows @@ -81,13 +81,23 @@ FileStorage (`add_root`, `list`, `read`) for the declared roots and files; Manag | `withdraw` | Remove the entry, cancel admitted reads, wait for them, remove the directory, emit the change event | — | — | — | UiExtensions | | `read` | Resolve the generation and the path, read one bounded page under the read counter | The page stops; nothing changes | The read token is released | Admitted reads are cancelled and awaited before the directory goes | UiExtensions | +The `ui.extensions.read` client method is the same `read`, served to clients; WebEntry's HTTP route is its transport. Both stay. + ## Exceptions with reasons - `register` takes the declaration as an optional value: a package with no UI member withdraws, and the owner resolves the installation directory by plugin id through PluginManager, so no path or handle crosses. - The change event is the owner's fact, not a subscription: a subscriber reads `directory` when the revision differs, so no freshness state crosses. +## Supersedes + +- [Client UI extensions](../client-ui-extensions.md) service table row `uiExtensions`: the operations are those in this contract. +- [Service faces](../service-faces.md) §3.6 row `uiExtensions`. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + + | Rule | Application | | --- | --- | | §1 parts and Capabilities | UiExtensions is one process part; it writes no Timeline fact and is not a Capability. | @@ -138,7 +148,7 @@ pub struct ReadRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Page { +pub struct ContentPage { pub offset: u64, pub bytes: usize, pub total: u64, @@ -150,9 +160,9 @@ pub struct Page { #[serde(tag = "code", rename_all = "snake_case")] pub enum ContentError { #[error("{message}")] - Invalid { message: String }, + InvalidParams { message: String }, #[error("The UI content file is unavailable")] - Unavailable, + ResourceUnavailable, } #[rutis::service(name = "uiExtensions")] @@ -162,7 +172,7 @@ impl UiExtensions { pub async fn plugins(&self, request: Empty) -> PluginsReply { /* ... */ } pub async fn refusal(&self, request: PluginRef) -> RefusalReply { /* ... */ } pub async fn directory(&self, request: Empty) -> DirectoryReply { /* ... */ } - pub async fn read(&self, request: ReadRequest) -> Result { /* ... */ } + pub async fn read(&self, request: ReadRequest) -> Result { /* ... */ } } ``` diff --git a/docs/design/plugins/UiHost.md b/docs/design/plugins/UiHost.md index 789039dfa2..4a1160223a 100644 --- a/docs/design/plugins/UiHost.md +++ b/docs/design/plugins/UiHost.md @@ -12,6 +12,7 @@ UiHost owns: - **Leaves.** The rutis session mounted for an interactive leaf, its one-time token, its twenty-second start window, and its disposal when the session or the interface ends. - **Replacement.** Claiming the interface a replacement replaces, and closing it once the replacement attaches. - **Notices.** The advisory close notice on the interface's connection. +- **Attribution.** The fact `uiHost/attribution {connection_id, session_id, kind}` when a registration binds a connection, and `uiHost/attribution-ended {connection_id}` when it clears. Connection folds the fact into the presence value; UiHost's registry is never read by another owner. Callers keep: @@ -62,15 +63,15 @@ let attached = ui_host.attach(AttachRequest { ### Dependencies -Connection's `attached` and `write`; the process root for mounting a leaf session. +Connection's `attached` and `write`; rutis' `Ctx::plugin` on the owner's own process context, which mounts the leaf session inside this owner's subtree. No other owner provides a mount operation. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `open` | Reserve an interface and mount a leaf's session | `{connection_id, session_id, kind, peer, address, replace?, expected_generation?}` | `{ui_id, generation, token}` | While the leaf session is mounted; a failed start leaves nothing registered | `not_attached`, `invalid`, `ui_unknown`, `ui_generation`, `ui_leaf_failed` | -| `attach` | Register a connection as an interface of a Session | `{connection_id, session_id, kind, ui_id?, token?}` | `{ui_id, generation}` | None | `not_attached`, `invalid`, `ui_token`, `ui_in_use`, `ui_unknown` | -| `replace` | Replace an interface with a new registration | `{connection_id, session_id, kind, ui_id, expected_generation?}` | `{ui_id, generation}` | None | `not_attached`, `invalid`, `ui_unknown`, `ui_generation` | +| `open` | Reserve an interface and mount a leaf's session | `{connection_id, session_id, kind, peer, address, replace?, expected_generation?}` | `{ui_id, generation, token}` | While the leaf session is mounted; a failed start leaves nothing registered | `session_not_attached`, `invalid_params`, `ui_unknown`, `ui_generation`, `ui_leaf_failed` | +| `attach` | Register a connection as an interface of a Session | `{connection_id, session_id, kind, ui_id?, token?}` | `{ui_id, generation}` | None | `session_not_attached`, `invalid_params`, `ui_token`, `ui_in_use`, `ui_unknown` | +| `replace` | Replace an interface with a new registration | `{connection_id, session_id, kind, ui_id, expected_generation?}` | `{ui_id, generation}` | None | `session_not_attached`, `invalid_params`, `ui_unknown`, `ui_generation` | | `status` | The live interfaces and the count of web connections | `{}` | `{instances, web_connections}` | None | none | | `close` | Remove an interface; a leaf's session ends | `{ui_id, reason?}` | `{}` | None; the owner settles the notice and the leaf | `ui_unknown` | | `shutdown` | Advise an interface to leave, without closing it | `{ui_id, reason?}` | `{}` | None | `ui_unknown`, `ui_detached` | @@ -79,19 +80,24 @@ Connection's `attached` and `write`; the process root for mounting a leaf sessio `open` and `attach` require that `connection_id` views `session_id`; the owner asks Connection rather than reading its attachments. +The owner emits two process events: `uiHost/attribution {connection_id, session_id, kind}` when a registration binds a connection and `uiHost/attribution-ended {connection_id}` when it clears. Connection folds them into its presence value; no other owner reads the registry. + +The `ui.extensions.changed {revision}` notification is Connection's delivery of UiExtensions' event to clients; UiHost plays no part in it. + `expected_generation` is the generation the client read from `status` when it asked the user to confirm a replacement. It is a business version, not an owner-internal revision: the owner cannot decide it, because a client that saw interface A may have confirmed replacing A, and replacing whatever is current instead would close an interface the user never saw. The claim is atomic in `open`/`replace`; the attach token authorizes the leaf's attach and is a different value. ### Errors | Kind | What the caller does next | | --- | --- | -| `not_attached` | Attach to the Session before registering an interface | -| `invalid` | Fix the request: an unsupported kind, a missing address, a malformed peer, a token without an id | +| `session_not_attached` | Attach to the Session before registering an interface | +| `invalid_params` | Fix the request: an unsupported kind, a missing address, a malformed peer, a token without an id | | `ui_token` | The one-time token is wrong; the leaf cannot attach | | `ui_in_use` | Another connection already is this leaf; close it first or replace it | | `ui_unknown` | The interface is gone; list the live interfaces | | `ui_generation` | The interface changed since the caller looked; re-read `status` | | `ui_leaf_failed` | The leaf did not start; nothing is registered | +| `ui_detached` | The interface is between a detach and its reattach; it can reattach and receive a later notice | ### Flows @@ -108,8 +114,15 @@ Connection's `attached` and `write`; the process root for mounting a leaf sessio - The twenty-second start window is the owner's state: a leaf that does not attach is closed as `close` would. - `expected_generation` stays a request field: it is the version the client observed and confirmed, so the owner cannot choose it; a stale client is refused with `ui_generation` instead of silently replacing a newer interface. +## Supersedes + +- [Tui design](Tui.md#36-ui-registry-and-ui-leaves) §3.6: the registry's state and operations are those in this contract; the leaf lifecycle description stays. +- [Service faces](../service-faces.md) §3.6 row `uiHost`. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | UiHost is one process part; it writes no Timeline fact and is not a Capability. | @@ -168,9 +181,9 @@ pub struct StatusReply { pub instances: Vec, pub web_connections: usiz #[serde(tag = "code", rename_all = "snake_case")] pub enum UiError { #[error("Attach to the Session before registering an interface on it")] - NotAttached, + SessionNotAttached, #[error("{message}")] - Invalid { message: String }, + InvalidParams { message: String }, #[error("The UI leaf token is not valid")] UiToken, #[error("Another connection already is this UI leaf")] @@ -181,6 +194,8 @@ pub enum UiError { UiGeneration, #[error("{message}")] UiLeafFailed { message: String }, + #[error("This UI leaf is between a detach and its reattach")] + UiDetached, } #[rutis::service(name = "uiHost")] diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md index e9dbaea432..4e5d386345 100644 --- a/docs/design/plugins/UiResources.md +++ b/docs/design/plugins/UiResources.md @@ -54,9 +54,9 @@ FileStorage (`open_read`, `read_at`, `close_read`) for the file; SessionLifecycl | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While the file is opened; nothing is registered | `invalid`, `unavailable`, `closed` | -| `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `gone`, `invalid`, `closed` | -| `read` | One bounded page of a published file | `{reference, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The caller's token; the page stops, the reference stays | `gone`, `invalid` | +| `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While the file is opened; nothing is registered | `invalid_params`, `resource_unavailable`, `session_closed` | +| `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `resource_gone`, `invalid_params`, `session_closed` | +| `read` | One bounded page of a published file | `{reference, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params` | `publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. @@ -66,10 +66,10 @@ The media type decides inline display: a listed image, audio, video, text or PDF | Kind | What the caller does next | | --- | --- | -| `invalid` | The path is relative or outside every authorized root, the reference names another Session, or a page offset is beyond the file | -| `unavailable` | The file is gone or unreadable; publish again or show the caller that the resource is unavailable | -| `gone` | The reference was withdrawn or the Session is closing; stop reading | -| `closed` | The Session is closing; the reference is settled | +| `invalid_params` | The path is relative or outside every authorized root, the reference names another Session, or a page offset is beyond the file | +| `resource_unavailable` | The file is gone or unreadable; publish again or show the caller that the resource is unavailable | +| `resource_gone` | The reference was withdrawn; stop reading | +| `session_closed` | The Session is closing; the reference is settled | ### Flows @@ -79,13 +79,23 @@ The media type decides inline display: a listed image, audio, video, text or PDF | `withdraw` | Check the owner row, cancel and wait for admitted reads, remove the reference | — | Already removed | Already removed | UiResources | | `read` | Resolve the reference, take a read token, read one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference goes | UiResources | +The `session.ui.resources.read` client method is the same `read`, served to RPC clients; the web entry's HTTP route is its transport. Both stay. + ## Exceptions with reasons - `publish` takes `caller: &Ctx`: ownership and cleanup must bind the calling row, and only rutis knows which row is calling; a caller-supplied id would let one row publish a reference owned by another. The parameter is not a request field and no caller sends a row. - WebEntry's media route calls `read` directly: the browser needs an HTTP response with range handling, and the route is a transport over the same read, not a second business path. +## Supersedes + +- [Client UI extensions](../client-ui-extensions.md) service table row `uiResources`: the operations are those in this contract. +- [Service faces](../service-faces.md) §3.6's `uiResources` note. + ## Rule check +The checks below cite [design rules §7, PR #2029](https://github.com/arcships/dim/pull/2029) because the section is not yet on `main`. + + | Rule | Application | | --- | --- | | §1 parts and Capabilities | UiResources is one Session part; it writes no Timeline fact and is not a Capability. | @@ -127,7 +137,7 @@ pub struct ReadRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Page { +pub struct ResourcePage { pub offset: u64, pub bytes: usize, pub total: u64, @@ -138,21 +148,21 @@ pub struct Page { #[derive(Debug, serde::Serialize, thiserror::Error)] #[serde(tag = "code", rename_all = "snake_case")] pub enum ResourceError { - #[error("UI resource is unavailable")] - Gone, + #[error("UI resource is gone")] + ResourceGone, #[error("{message}")] - Invalid { message: String }, + InvalidParams { message: String }, #[error("{message}")] - Unavailable { message: String }, + ResourceUnavailable { message: String }, #[error("The Session is closing")] - Closed, + SessionClosed, } #[rutis::service(name = "uiResources")] impl UiResources { pub async fn publish(&self, caller: &rutis::Ctx, request: PublishRequest) -> Result { /* ... */ } pub async fn withdraw(&self, caller: &rutis::Ctx, request: ResourceRef) -> Result<(), ResourceError> { /* ... */ } - pub async fn read(&self, request: ReadRequest) -> Result { /* ... */ } + pub async fn read(&self, request: ReadRequest) -> Result { /* ... */ } } ``` diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 8f891133b6..a385cc7398 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -631,7 +631,7 @@ commits {sessionId} (async) notification {subscriptionId, batchId, branchId, through, result: "committed" | {code, message}} ``` -- `append` is a **sync** operation, like `localId.get`: it validates, assigns the batch its place +- `append` is a **sync** operation, like `toolchainSourceHost.list`: it validates, assigns the batch its place in the Session's single writer queue, and answers `{accepted}` without waiting for I/O. It is the one face operation a caller may issue inside its own commit lock, because it performs no I/O and returns nothing the caller must await. The Timeline's existing admission — one diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..379b51ed54 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -78,7 +78,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | 名字 | 处理 | | --- | --- | | `managementMethods` | 数据面,shared 名字与 dispatcher 一同注册。 | -| `localId` | 数据面,由 root 提供 `get`。 | +| `localId` | 已撤销:peer id 由 rutis-bridge 的 `LocalId` 值提供,不再有数据面([ProcessRoot 契约](plugins/ProcessRoot.md))。 | | `rutis/loader` | 插件管理数据面;`LoaderService` 是提供方的私有 Rust 类型,不是另一个服务名。 | | `PluginMounter` 类型键 | rutis-loader 与 rutis-bridge 内部挂载插件定义的装配键,不是公共服务目录项。 | @@ -188,16 +188,12 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow ### 3.6 入口、凭据与宿主资源 -按 #1292 逐批确定各项的公共操作,并按 §2.6 迁移登记。状态、资源和凭据留在各自的 owner。`managedSearch` 的搜索操作见 §4.6。`skillsCatalog` 的插件内容操作见 [Skills owner 契约](../architecture/rust-agent/plugins/Skills.md#plugin-content-data-face)。 +按 #1292 逐批确定各项的公共操作,并按 §2.6 迁移登记。连接、入口与 UI 板块的操作面见 [Connection](plugins/Connection.md)、[ServerControl](plugins/ServerControl.md)、[UiHost](plugins/UiHost.md)、[UiExtensions](plugins/UiExtensions.md)。状态、资源和凭据留在各自的 owner。`managedSearch` 的搜索操作见 §4.6。`skillsCatalog` 的插件内容操作见 [Skills owner 契约](../architecture/rust-agent/plugins/Skills.md#plugin-content-data-face)。 | 名字 | scope | provider | reason | | --- | --- | --- | --- | -| `serverControl` | process | ServerControl | control | -| `connectionHub` | process | Connection | control | | `grokOAuthService` | process | GrokOAuth | secret | | `openAICodexOAuthService` | process | OpenAICodexOAuth | secret | -| `uiHost` | process | UiHost | control | -| `uiExtensions` | process | UiExtensions | control | | `mentionIndex` | process | WorkspaceToolsOwner | host-resource | | `mcpService` | process | Mcp | host-resource | | `hooksService` | process | HooksSettings | host-resource | @@ -328,7 +324,7 @@ store.associateWorktree {sessionId, repository, root, subtree} -> {} ```text credentialVariablesHost.variables() -> {variables: [string]} -- 只给变量名,永不给凭据值 -sessionClientsHost.presences {sessionId} -> {presences: [{channel, label?}]} +connection.presences {sessionId} -> {presences: [{channel, label?}]} -- channel 是 tui/cli/web/acp/remote/desktop/unknown;label 是 hello.clientName,不是身份 listenAddresses.read() -> {unixPath?, pipeName?, websocketAddress?} -> error {code: invalid_path, message} From c9d3ef93078e062eccc07698f3c57f817306a0e0 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 21:34:24 +0800 Subject: [PATCH 07/12] docs(design): use FileStorage's offset read Refs #2021 Refs #2015 --- docs/design/plugins/UiExtensions.md | 4 ++-- docs/design/plugins/UiResources.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/design/plugins/UiExtensions.md b/docs/design/plugins/UiExtensions.md index 7d095c21b1..423933a15b 100644 --- a/docs/design/plugins/UiExtensions.md +++ b/docs/design/plugins/UiExtensions.md @@ -51,7 +51,7 @@ let page = ui.read(ReadRequest { generation, path, offset: 0, limit: None }).awa ### Dependencies -FileStorage (`add_root`, `list`, `read`) for the declared roots and files; ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). +FileStorage (`add_root`, `list`, `read`) for the declared roots and files, with `read`'s offset form for a page; ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). ### Operations @@ -114,7 +114,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. FileStorage's contract (#2016) supplies `add_root`, `list` and `read`. +None. FileStorage's contract (#2016) supplies `add_root`, `list` and the offset `read`. ## Binding appendix diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md index 4e5d386345..1fa65f658d 100644 --- a/docs/design/plugins/UiResources.md +++ b/docs/design/plugins/UiResources.md @@ -48,7 +48,7 @@ let page = resources.read(ReadRequest { reference: reference.clone(), offset: 0, ### Dependencies -FileStorage (`open_read`, `read_at`, `close_read`) for the file; SessionLifecycle's `closing` for the Session's end. +FileStorage's offset read `read {path, offset, length}` and its path resolution for the file; SessionLifecycle's `closing` for the Session's end. No pinned reader id crosses. ### Operations @@ -75,9 +75,9 @@ The media type decides inline display: a listed image, audio, video, text or PDF | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `publish` | Check the Session phase, resolve the path in FileStorage, open the file, register the reference and the row's cleanup | The file is closed, nothing is registered | The reference is removed by the row's cleanup | Every reference is closed and removed | UiResources: the reference and the file | +| `publish` | Check the Session phase, resolve the path in FileStorage and read its size, register the reference and the row's cleanup | Nothing is registered | The reference is removed by the row's cleanup | Every reference is removed | UiResources: the reference and its read counter | | `withdraw` | Check the owner row, cancel and wait for admitted reads, remove the reference | — | Already removed | Already removed | UiResources | -| `read` | Resolve the reference, take a read token, read one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference goes | UiResources | +| `read` | Resolve the reference, take a read token, call FileStorage's offset read for one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference goes | UiResources: the token; FileStorage: the page | The `session.ui.resources.read` client method is the same `read`, served to RPC clients; the web entry's HTTP route is its transport. Both stay. @@ -112,7 +112,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. FileStorage's contract (#2016) supplies `open_read`, `read_at` and `close_read`. +None. FileStorage's contract (#2016) supplies the offset read. ## Binding appendix From bc831185eebf3510be77d049b6ce09616ef3172c Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:25:39 +0800 Subject: [PATCH 08/12] docs(design): align the call binding with the methods contract Refs #2021 Refs #2015 --- docs/design/agent-environment.md | 2 +- docs/design/cli-commands.md | 2 +- .../contracts/process-owner-operations.md | 6 +- docs/design/contracts/session-boundary.md | 20 ++-- .../examples/timeline-capability-analysis.md | 2 +- docs/design/plugins/CallChannel.md | 100 ++++++++++-------- docs/design/plugins/ClientView.md | 2 +- docs/design/plugins/Connection.md | 6 +- docs/design/plugins/ManagementMethods.md | 44 +++++--- docs/design/plugins/README.md | 2 +- docs/design/plugins/Report.md | 5 +- docs/design/plugins/Rpc.md | 10 +- docs/design/plugins/ServerControl.md | 8 +- docs/design/plugins/UiExtensions.md | 4 +- docs/design/plugins/UiResources.md | 19 ++-- docs/design/web-workspace.md | 2 +- 16 files changed, 127 insertions(+), 107 deletions(-) diff --git a/docs/design/agent-environment.md b/docs/design/agent-environment.md index c8f8024259..5c190973f6 100644 --- a/docs/design/agent-environment.md +++ b/docs/design/agent-environment.md @@ -101,7 +101,7 @@ A Session can outlive every client. The presence snapshot says no connection is | §4 rule 4 Core carries no business meaning | Bodies are module projections; no core branch. | | §4 rule 5 Batch | A snapshot is one input; the settings tool performs no write. | | §4 rule 6 Context from consumed events | Snapshots are inputs; tool results are tool results; no second path. | -| §4 rule 7 Public services | `SessionClientsHost` and the setting modules' read ports are public. | +| §4 rule 7 Public services | `connection.presences` and the setting modules' read ports are public. | | §4 rule 8 Infrastructure unchanged | No Timeline, Dispatcher, envelope, assembly or facade change. | | §4 rule 9 Timeline holds decision facts | Only the delivered snapshot is an input fact; the live connection and settings stores remain outside the Timeline. | | ADR 002 D1 | Each fact stays with its producer; parts are placed in Session or branch. | diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 5e6a25bf98..efcafdba68 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -1901,7 +1901,7 @@ whole rule as one quoted argument, so global options stay unambiguous. | `dimcode account PROVIDER` | Print the described account's non-secret state. | | `dimcode logout PROVIDER` | Sign the described account out. | | `/connect` | List the Providers `provider.management` reports; a described account opens its sign-in or sign-out step, and any other Provider opens the connection form. | -| `/report` | Report the current Session, including during a turn or when no error occurred. Save the local report ZIP, see its path, or open a share destination after saving. [Report contract](plugins/Report.md#2-client-interaction). | +| `/report` | Report the current Session, including during a turn or when no error occurred. Save the local report ZIP, see its path, or open a share destination after saving. [Report contract](plugins/Report.md#client-interaction). | | `/exit` | Detach and exit from the idle interactive prompt. | | `!command` / `!!command` | Call the Session's existing `shell.run` in record/private mode, including during a model turn. | | `--permission read-only\|workspace-write\|full-access` | Select the preset of a new or resumed Session for `dimcode`, `tui`, `exec` and `exec resume` ([permission controls](#permission-controls)). | diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 7048b368ca..9e813bcd02 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -11,9 +11,9 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Management clients → Provider / Grok OAuth / OpenAI Codex OAuth | Existing [Provider management RPCs](../appserver/provider-management.md) and account status, begin, attempt status, cancel and logout RPCs. Codex also handles its browser callback. | | Session consumers → Agent directory | [`sessions` operations](../appserver/sessions-service.md). Agent administration and Session creation/fork retain the existing `agent.create/list/close` and `session.create/fork` client RPCs. RPC, Agent configuration, Collaboration and Provider lifecycle consumers use directory-owned admission, generation observation, close and rollback. The directory keeps the Session lease through each admitted operation. | | Plugin management → loader | `rutis/loader.create/reload/remove/status`. The loader owns native profile construction and group instantiation with the original parent and group. | -| Presence consumers → Connection | `connection.presences` ([Connection](../../plugins/Connection.md)). Connection serves this operation directly and handles broadcast, socket registration, writes, close and detach. | -| Activity consumers / daemon clients → ServerControl | `processActivity.activated/closing/hold/release/holds/shutdown/fault` ([ServerControl](../../plugins/ServerControl.md)); existing `daemon.ping/shutdown` RPCs. Shutdown settles the initiating reply before transport teardown. | -| UI clients → UiHost / UiExtensions | Existing `ui.open/attach/replace/status/shutdown/close` RPCs ([UiHost](../../plugins/UiHost.md)) and [extension listing, resources and notices](../client-ui-extensions.md) ([UiExtensions](../../plugins/UiExtensions.md), [UiResources](../../plugins/UiResources.md)). Transport supplies the authenticated connection identity. | +| Presence consumers → Connection | `connection.presences` ([Connection](../plugins/Connection.md)). Connection serves this operation directly and handles broadcast, socket registration, writes, close and detach. | +| Activity consumers / daemon clients → ServerControl | `processActivity.activated/closing/hold/release/holds/shutdown/fault` ([ServerControl](../plugins/ServerControl.md)); existing `daemon.ping/shutdown` RPCs. Shutdown settles the initiating reply before transport teardown. | +| UI clients → UiHost / UiExtensions | Existing `ui.open/attach/replace/status/shutdown/close` RPCs ([UiHost](../plugins/UiHost.md)) and [extension listing, resources and notices](../client-ui-extensions.md) ([UiExtensions](../plugins/UiExtensions.md), [UiResources](../plugins/UiResources.md)). Transport supplies the authenticated connection identity. | | Prompt, scenario and summary evaluation tools → active profile | Use `providerService` for their catalog/selection calls and `modelHost.invoke` for execution. | | Media execution and realtime → native adapter | Existing native connection binding and credential owner ([#1613](https://github.com/arcships/dim/issues/1613), [#1634](https://github.com/arcships/dim/issues/1634)). | | Transport, Web entry and Session subscriptions → Connection | Connection-owned attach, broadcast, close and detach using the authenticated connection identity. | diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 0bbd6f4f3c..3b710c62b7 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -282,7 +282,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 the [CallChannel contract](../plugins/CallChannel.md)'s `notify`/`progress`/`closed` with `{connectionId, callId}` (Appendix F). | Method | Mode | Request | Reply | | --- | --- | --- | --- | @@ -564,7 +564,7 @@ The neutral services map to the native owners below. Tools register with ToolReg | `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) | | 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`: `{connectionId, callId}` from the handler's `MethodCall.origin`, per call; for other languages the process service `callChannel` | — | Rpc gives each admitted call a sink to its calling connection; the CallChannel entry records the row instance and connection until the connection closes, the Rpc load unloads or the row unloads | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | ```rust // crates/dim-agent-capabilities/src/methods.rs (C1), shared by both services @@ -618,19 +618,15 @@ pub struct ManagementMethods(pub Arc); // Deref } -#[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; -} +pub struct Origin { pub caller: Option } +#[derive(Clone, Debug)] +pub struct CallerRef { pub connection_id: String, pub call_id: String } +// notify/progress/closed are the operations of the CallChannel contract. ``` -`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` and `Callers` are replaced by the [CallChannel contract](../plugins/CallChannel.md): the provider keeps `{connectionId, callId}` and calls `notify`, `progress` and `closed`, and `run` binds the call around the table dispatch. The delivery rules above — declared before gone, after-reply ordering, the held allowance, `unsupported`/`undeclared`/`gone`/`too_large` and the lifetime of the entry — are unchanged; the binding holds no connection handle. -`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` has no service catalog name; the public operation surface is `callChannel`. 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. diff --git a/docs/design/examples/timeline-capability-analysis.md b/docs/design/examples/timeline-capability-analysis.md index 061ca3288e..0810c81267 100644 --- a/docs/design/examples/timeline-capability-analysis.md +++ b/docs/design/examples/timeline-capability-analysis.md @@ -192,7 +192,7 @@ - **场景/状态**:当前客户端 presence 的字符串快照和本代 last;输入只是声称的客户端环境,不授予信任或权限。 - **转换**:先注册 ClientsChanged listener,再在 activation 后读当前值;变化才 append 自己的 input/message,成功后更新 last;关闭/代取消结束任务。 -- **恢复**:重新读 SessionClientsHost 当前状态,不恢复已断开的客户端;last 清空允许本代再次报告当前值。 +- **恢复**:重新读 `connection.presences` 当前状态,不恢复已断开的客户端;last 清空允许本代再次报告当前值。 - **性质/论证**:先监听再初读避免丢初值期间的改变,notify 合并后重读当前值而不是逐个回放连接通知。失败 append 不更新 last,但这里没有定时 retry,直到下次唤醒才再试;不能承诺无新信号时必然重试成功。 - **对应**:[environment_clients.rs](../../../crates/dim-agent-capabilities/src/environment_clients.rs);environment_clients。它只写采用输入,按现有行为更接近输入发布部件,不为它增加恢复状态机。 diff --git a/docs/design/plugins/CallChannel.md b/docs/design/plugins/CallChannel.md index f977a8babf..037877b3df 100644 --- a/docs/design/plugins/CallChannel.md +++ b/docs/design/plugins/CallChannel.md @@ -2,16 +2,16 @@ Scope: process. Issue: #2021. -CallChannel owns the binding between an admitted table call and the connection it arrived on: which notifications the provider may send, whether a notification is declared, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. The notification, progress and closed semantics are the [methods contract](../contracts/session-boundary.md) A.2; this document states the owner's operations. +CallChannel owns the binding between an admitted table call and the connection it arrived on: which notifications the provider may send, whether a notification is declared, and when the connection is gone. This document is the owner's target contract; the current implementation is `CallChannelPlugin` in `crates/dim-app-server/src/connection.rs` and `Caller`/`Callers` in `crates/dim-agent-capabilities/src/methods.rs`. Connection, Rpc and the method tables are separate owners. The notification, progress and closed semantics — modes, refusal order and lifetime — are the [methods contract](../contracts/session-boundary.md) A.2; this document states the owner's operations and keeps A.2's wire behaviour. ## Use and scope: responsibility split CallChannel owns: -- **The call binding.** One per admitted table call: the connection id, the call id, the registering row instance and the notification names that namespace declared. The binding lives until the connection closes or the registering row unloads; a notification sent after the call returned still finds it. +- **The call binding.** One entry per registering row instance and connection: the notification names that row's namespace declared, and that connection's unfinished calls by `call_id`. The entry lives until the connection closes, the admitting Rpc load unloads or the row unloads; a call leaves it when its reply is written. - **The declared-name answer.** A name the registration did not declare is refused before anything is written. -- **The connection's end.** `closed` resolves when the binding's connection closes. -- **Routing the write.** A notification is written by Connection: `write_after` while the call runs, `write` after it returned. Progress is written under the call's own allowance. +- **The connection's end.** `closed` resolves, and later `notify` answers `gone`, once the connection closes or the Rpc load that admitted the call unloads. +- **Routing the write.** A notification is written by Connection: `write_after` while the call runs, `write` once its reply is written. Progress is a best-effort notice the connection drops when the method did not declare it. CallChannel writes no socket and holds no connection state. @@ -20,22 +20,23 @@ Callers keep: - What a notification means: the provider chooses the name and the payload. - The reply: the callback produces it; Rpc writes it. - The declarations: the registering part declared them; the table admitted the call with them. +- Interruption: an admitted call is interrupted by the unload of its provider generation or of the Rpc load that admitted it (A.1). A caller's disconnect cancels nothing. | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | Rpc must run one admitted table call with the caller's notifications enabled | No: the binding, the declared-name answer and the write ordering are the owner's; a `bind`/`finish` pair would make Rpc drive three owners and could leave the binding behind on an error path | `run` | | A provider must send a notification while or after the call runs, in order after its reply | No: the declared-name check, the binding lookup and the ordering are the owner's | `notify` | | A provider must report progress under the call's own allowance | No: progress is bounded by the connection's progress budget and the declaration | `progress` | -| A provider must stop when the connection closes | Yes: `closed` composes | `closed` | +| A provider must stop when the connection closes or the admitting load unloads | Yes: `closed` composes | `closed` | An operation or parameter exists only where the row says No. ## Caller example -Rpc runs the call once; the owner binds, invokes, and leaves the binding until the connection closes: +Rpc runs the call once; the owner binds, invokes, and keeps the entry until the connection, the Rpc load or the row ends: ```rust -let reply = channel.run( +let outcome = channel.run( ctx, RunRequest { connection_id: caller.connection_id.clone(), @@ -45,13 +46,19 @@ let reply = channel.run( }, Arc::new(move || { let table = table.clone(); + let caller = Some(CallerRef { + connection_id: caller.connection_id.clone(), + call_id: caller.call_id.clone(), + }); let (method, params) = (method.clone(), params.clone()); - Box::pin(async move { table.call(CallRequest { method, params, caller: None }, cancelled).await }) + Box::pin(async move { + // The token is the Rpc load's, never the connection's: a disconnect stops delivery only. + table.call(CallRequest { method, params, caller }, rpc_unload).await + .map_err(|error| rutis::Error::from(error.into_call_error())) + }) }), - cancelled, ) .await?; -// The provider may notify after this returned; the binding ends with the connection or the row. ``` A provider inside the callback notifies, reports progress, and waits for the caller to leave: @@ -61,9 +68,9 @@ match channel.notify(NotifyRequest { connection_id, call_id, method, params }).a Ok(()) => {} Err(NotifyError::Undeclared) => return Err(ProviderError::Programming), Err(NotifyError::Gone) => return Ok(()), // the caller left; nothing to do - Err(NotifyError::TooLarge) => return Err(ProviderError::TooLarge), + Err(NotifyError::TooLarge | NotifyError::Unsupported) => return Err(ProviderError::Rejected), } -channel.progress(ProgressRequest { connection_id, call_id, data }).await; +channel.progress(ProgressRequest { call_id, data }); // best effort; dropped unless declared channel.closed(ClosedRequest { connection_id }).await; // also usable after the call returned ``` @@ -77,38 +84,41 @@ Connection's `write_after`, `write` and `closed`. | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `run` | Run one admitted table call with its caller's notifications enabled | `{connection_id, call_id, instance, notifications}` + `caller: &Ctx` + `call` | the callback's `MethodReply` | The caller's token stops the callback; the binding stays with the connection | `invalid_params`, `callback` | -| `notify` | Send a notification to the calling connection, after its call's reply when it runs | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `undeclared`, `gone`, `too_large` | -| `progress` | Report progress for one call | `{connection_id, call_id, data}` | `{}` | None | `undeclared`, `gone`, `too_large` | -| `closed` | Wait until the calling connection is gone | `{connection_id}` | `{}` when it closes; an unknown id resolves at once | The caller's task ends; the wait ends | none | +| `run` | Run one admitted table call with its caller's notifications enabled | `{connection_id, call_id, instance, notifications}` + `caller: &Ctx` + `call` | `CallOutcome`: the callback's reply or its own error | None; the admitted call is interrupted only by its provider or Rpc unloading (A.1) | `invalid_params` | +| `notify` | Send a notification to the calling connection, after its call's reply when it runs | `{connection_id, call_id, method, params}` | `{}` | None; the frame is queued or refused | `unsupported`, `undeclared`, `gone`, `too_large` | +| `progress` | Report progress for one call | `{call_id, data}` | none | None | none | +| `closed` | Wait until the calling connection is gone | `{connection_id}` | `{}` when the connection closes or the admitting Rpc load unloads; an unknown id resolves at once | The caller's task ends; the wait ends | none | -`run`'s `call` is a callback parameter, not a request field. The owner invokes it once and keeps the binding until the connection closes or the registering row unloads; no caller frees the binding on any path. `instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name. +`run`'s `call` is a callback parameter, not a request field. The owner invokes it once and keeps the entry until the connection closes, the Rpc load unloads or the row unloads; no caller frees the entry on any path. `instance` is the registering row's instance id: two rows of the same language runtime may declare different notifications for the same namespace name. + +`progress` is sync and best effort: the connection drops it unless the method declared `progress`. It is the same notice A.2 defines, sent as `management.progress {id, method, data}` for Session and management methods. ### Errors | Kind | Wire code | What the caller does next | | --- | --- | --- | -| `invalid_params` | `invalid_params` | The call id is bound to another connection or the request is malformed; a programming error | -| `undeclared` | `undeclared` | The registration did not declare the name; fix the declaration, nothing was written | -| `gone` | `gone` | The connection closed or the row unloaded; stop notifying for the call | -| `too_large` | `too_large` | The frame exceeds the connection's budget (a notification) or progress allowance; shorten it — the connection stays open | +| `invalid_params` | `invalid_params` | The call id is bound to another connection or the request is malformed; a programming error, do not retry | +| `unsupported` | `unsupported` | The notification names a link this binding does not carry; drop the notification, nothing was written | +| `undeclared` | `undeclared` | The registration did not declare the name; fix the declaration, nothing was written. Decided before the connection's state | +| `gone` | `gone` | The connection closed, the Rpc load unloaded or the row unloaded; stop notifying for the call | +| `too_large` | `too_large` | The notification exceeds the connection's frame budget; shorten it — the connection stays open | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `run` | Record the binding under the row instance and the connection (reuse one already bound for the same row and connection), invoke the callback, return its reply | The callback stops; the binding stays with the connection | The row's bindings are removed | A connection close removes every binding of that connection | CallChannel: the binding; the caller: the callback's future | -| `notify`, `progress` | Find the binding, check the declared name, ask Connection to write after the call (or directly, once the reply is written) | The provider's task ends; nothing is written | The binding is gone; `gone` | Pending frames end `gone` | Connection: the frame; CallChannel: the binding | -| `closed` | Wait on Connection's `closed` for the connection | The provider stops waiting | The wait ends | The wait ends | Connection | +| `run` | Record the entry for the row and connection (reuse one already bound), invoke the callback, return its outcome | No caller cancellation exists; a disconnect stops delivery only | The row's entries are removed | A connection close or the Rpc load's unload removes the connection's entries; an unloading row answers `gone` | CallChannel: the entry; the caller: the callback's future | +| `notify`, `progress` | Find the entry, check the declared name (before the connection's state), ask Connection to write after the call or directly | — | The entry is gone; `gone` | Pending frames end `gone`; a generation that unloaded answers `gone` for every name | Connection: the frame; CallChannel: the entry | +| `closed` | Wait on Connection's `closed` for the connection, or the Rpc load's unload | The provider stops waiting | The wait ends | The wait ends | Connection: the connection; Rpc: the load | ## Exceptions with reasons -- `run` takes the callback by reference, like SessionScope's `withHold`: the callback is never called inside a commit lock, and it may notify and report progress through this owner while it runs. -- The binding outlives the call because the provider may keep notifying after it returned, as A.2 allows; the connection's close or the row's unload is the single settlement. +- `run` takes the callback as a direct method parameter (`impl Fn`, not a field or an alias): the callback is never called inside a commit lock, and it may notify and report progress through this owner while it runs. It returns `Result` with `RunError: From`, the form rutis accepts for a callback parameter; a handler's own failure is `MethodError` data inside the outcome, never a callback error code. +- The entry outlives the call because the provider may keep notifying after it returned, as A.2 allows; the connection's close, the Rpc load's unload or the row's unload is the single settlement. ## Supersedes -- [Methods contract](../contracts/session-boundary.md) A.2's Rust binding paragraph (`Caller`, `Callers`, `CallSite`): the operations above replace it; the wire semantics of `notify`, `progress` and `closed` are unchanged. +- [Methods contract](../contracts/session-boundary.md) A.2's Rust binding paragraph (`Caller`, `Callers`, `CallSite`): the operations above replace it; the wire semantics of `progress`, `notify` and `closed` are unchanged. ## Rule check @@ -132,18 +142,16 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. The callback is the same binding rutis already gives `withHold` and FileStorage's `write` source; no runtime change is needed. +None. The callback is the form `crates/dim-agent-capabilities/src/host.rs` already gives existing callback parameters; no runtime change is needed. ## Binding appendix +`CallOutcome`, `MethodReply` and `MethodError` are the [methods contract](../contracts/session-boundary.md) A.1 shapes, defined in the [ManagementMethods](ManagementMethods.md) appendix. + ```rust use crate::host::CancelledFn; use rutis::Ctx; -pub type CallFn = Arc< - dyn Fn() -> BoxFuture<'static, Result> + Send + Sync, ->; - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct RunRequest { @@ -165,11 +173,7 @@ pub struct NotifyRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ProgressRequest { - pub connection_id: String, - pub call_id: String, - pub data: serde_json::Value, -} +pub struct ProgressRequest { pub call_id: String, pub data: serde_json::Value } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -180,19 +184,19 @@ pub struct ClosedRequest { pub connection_id: String } pub enum RunError { #[error("{message}")] InvalidParams { message: String }, - #[error("{code}: {message}")] - Callback { code: String, message: String }, } -impl From for RunError { - fn from(error: MethodError) -> Self { - Self::Callback { code: error.code, message: error.message } +impl From for RunError { + fn from(error: rutis::host::CallError) -> Self { + Self::InvalidParams { message: error.message().to_owned() } } } #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "code", rename_all = "snake_case")] pub enum NotifyError { + #[error("The notification needs a link this binding does not carry")] + Unsupported, #[error("The notification is not declared by the registering namespace")] Undeclared, #[error("The connection is closed or the row unloaded")] @@ -203,12 +207,16 @@ pub enum NotifyError { #[rutis::service(name = "callChannel")] impl CallChannel { - pub async fn run(&self, caller: &Ctx, request: RunRequest, call: CallFn, cancelled: CancelledFn) - -> Result { /* ... */ } + pub async fn run( + &self, + caller: &Ctx, + request: RunRequest, + call: impl Fn() -> BoxFuture<'static, Result> + Send + Sync, + ) -> Result { /* ... */ } pub async fn notify(&self, request: NotifyRequest) -> Result<(), NotifyError> { /* ... */ } - pub async fn progress(&self, request: ProgressRequest) -> Result<(), NotifyError> { /* ... */ } + pub fn progress(&self, request: ProgressRequest) { /* best effort */ } pub async fn closed(&self, request: ClosedRequest) { /* waits */ } } ``` -`MethodReply` and `MethodError` are the [methods contract](../contracts/session-boundary.md) A.1 shapes; `MethodError` is `{code, message}`, defined in the [ManagementMethods](ManagementMethods.md) appendix. The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same operations. +The native `Caller` type no longer exists: Rust providers keep `{connection_id, call_id}` and call the same operations. `CancelledFn` is not a `run` parameter: the admitted call's interruption comes from its provider or Rpc unloading, never from the connection. diff --git a/docs/design/plugins/ClientView.md b/docs/design/plugins/ClientView.md index 92705ad2ab..1c96e56149 100644 --- a/docs/design/plugins/ClientView.md +++ b/docs/design/plugins/ClientView.md @@ -47,7 +47,7 @@ The App Server supplies `connectionId` from the calling connection's process-loc ### 2.3 Read -The proposed management/UI read returns these per-connection records and their viewed branch. It is separate from `SessionClientsHost::presences`, whose model-facing projection contains only `channel` and `label`; no connection handle enters that projection or the model body. The App Server uses the same connection identity to clear the record on detach or close. +The proposed management/UI read returns these per-connection records and their viewed branch. It is separate from `connection.presences`, whose model-facing projection contains only `channel` and `label`; no connection handle enters that projection or the model body. The App Server uses the same connection identity to clear the record on detach or close. ## 3. Model visibility diff --git a/docs/design/plugins/Connection.md b/docs/design/plugins/Connection.md index 3a2888992c..e4b7366dba 100644 --- a/docs/design/plugins/Connection.md +++ b/docs/design/plugins/Connection.md @@ -95,7 +95,7 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c | `attached` | Whether a connection views a Session now | `{connection_id, session_id}` | `{attached}` | None | none | | `presences` | The live clients of a Session | `{session_id}` | `{presences: [{channel, label?}]}` | None | none | | `counts` | Live connections and attached Sessions, excluding one connection | `{exclude_connection_id}` | `{connections, attached_sessions}` | None | none | -| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running}` | `{connections, attached_sessions, running}` | None | `busy {connections, attached_sessions, running}` | +| `close_for_idle` | Commit the daemon's refusal of new clients when nothing uses it | `{exclude_connection_id, running}` | `Counts` | None | `busy {connections, attached_sessions, running}` | | `close_all` | Close every connection and wait for its tasks | `{}` | `{}` | None; the owner completes the close | none | | `settle` (crate-internal) | One connection ended: release its attachment, tell UiHost, end its writer | `{connection_id, reason}` | `{}` | None | none | @@ -103,7 +103,7 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c `close_for_idle` takes `running` from Agents' `sessions` value, read immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. -After the commit the assembly asks Agents to `quiesce` every Session. A `running` answer means a Session accepted work between the read and the pause; the refusal stands and the graceful close settles that work — admission is never reopened after the commit. +The caller's sequence is Rpc's: read Agents' `sessions`, then `close_for_idle`; on `Busy` answer `daemon_busy` with the counts; the assembly then asks Agents to `quiesce`. Quiesce runs after the commit because Agents' pause is one-way; [#2098](https://github.com/arcships/dim/pull/2098)'s `Busy { running }` answer belongs to its own call site, and at this one a `running` answer is settled by the graceful close — admission is never reopened after the commit. ### Errors @@ -144,7 +144,7 @@ Only the kinds with a wire code reach a client. The others are in-process outcom ## Client-visible changes - `daemon.shutdown {ifIdle:true}` keeps the wire error `daemon_busy` with `connections`, `attachedSessions` and `running`; the field `running` counts Sessions with accepted work or an activity hold, as before. -- One narrow behaviour changes: when a Session accepts work between the caller's read and Agents' `quiesce`, the daemon now closes gracefully instead of answering `daemon_busy`, because Agents' pause is one-way and cannot be reverted. Accepted work still settles; the affected client is the CLI's `daemon stop --if-idle` and any start that stops an idle daemon. Maintaining the old refusal would need a revertable pause from Agents; this contract asks the maintainer to confirm the change. +- One narrow behaviour changes: when a Session accepts work between the caller's read and Agents' `quiesce`, the daemon closes gracefully instead of answering `daemon_busy`, because Agents' pause is one-way and cannot be reverted; the alternative order (quiesce before the commit) would leave a paused daemon running when the commit is refused. Accepted work still settles; the affected client is the CLI's `daemon stop --if-idle` and any start that stops an idle daemon. Maintaining the old refusal would need a revertable pause from Agents; this contract asks the maintainer to confirm the change. ## Supersedes diff --git a/docs/design/plugins/ManagementMethods.md b/docs/design/plugins/ManagementMethods.md index 0db57b7f4d..fb2bead2e5 100644 --- a/docs/design/plugins/ManagementMethods.md +++ b/docs/design/plugins/ManagementMethods.md @@ -68,11 +68,13 @@ The loader's row status (`rutis/loader`), read when a withdrawn namespace answer | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a namespace for the registering row's lifetime | `{namespace, declarations, call}` + `caller: &Ctx` | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid_params` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `MethodReply`: a value, or the handler's own error | The caller's token stops the wait; a caller disconnect stops delivery only and does not cancel the accepted call | `unknown_method`, `service_reloading`, `service_unavailable`, `operation_interrupted`, `invalid_params` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `CallOutcome`: the handler's `MethodReply` or its own `MethodError` | The calling load's token (A.1); a caller disconnect stops delivery only and does not cancel the accepted call | `unknown_method`, `service_reloading`, `service_unavailable`, `operation_interrupted`, `invalid_params` | `caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses. It is absent for an in-process call. The table passes it to the handler unchanged; a handler that notifies uses it with `callChannel`. -`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock. +The handler's own failure is `MethodError` data inside `CallOutcome::Error` (A.1's `{code, appError, message}`), never a table error; the table returns only its routing failures. + +`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock; it returns `Result` with `TableError: From`, the form rutis accepts for a callback parameter. ### Errors @@ -93,7 +95,7 @@ The wire codes are the existing ones from the methods contract. | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the name and declarations, record them under the row, refuse a duplicate | — | The registration is withdrawn and the row recorded | New registrations are refused; the table reloads with the process | The registering row | -| `call` | Find the owner, admit the call, run the handler, return the reply; on unload, interrupt `report` and wait for `drain` | The caller stops waiting; the accepted call continues and settles by its declaration | The call ends and its commands settle | A withdrawn namespace answers from its row's status | The table for the call's settlement; the handler for its effects | +| `call` | Find the owner, admit the call, run the handler, return its outcome; on unload, interrupt `report` and wait for `drain` | The caller stops waiting; the accepted call continues and settles by its declaration | The call ends and its commands settle | A withdrawn namespace answers from its row's status | The table for the call's settlement; the handler for its effects | ## Exceptions with reasons @@ -125,7 +127,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -- **Session registration (#2026)**: the Session method table takes the same `call` request and `MethodReply`, so Rpc has one call path for both tables. +- **Session registration (#2026)**: the Session method table's shape is [SessionMethods](https://github.com/arcships/dim/pull/2103) (#2103), the owner's latest head; Rpc calls each table by its own contract. This contract covers only the management table. ## Binding appendix @@ -152,13 +154,24 @@ pub struct CallRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct MethodError { pub code: String, pub message: String } +pub struct MethodError { + pub code: i32, + pub app_error: String, + pub message: String, +} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] +#[serde(tag = "kind", rename_all = "camelCase")] pub enum MethodReply { Value { value: serde_json::Value }, - Error { code: String, message: String }, + HandedOff, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CallOutcome { + Reply { reply: MethodReply }, + Error { error: MethodError }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -177,10 +190,6 @@ pub struct MethodDecl { pub progress: bool, } -pub type HandlerFn = Arc< - dyn Fn(MethodCall) -> BoxFuture<'static, Result> + Send + Sync, ->; - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct MethodCall { @@ -210,11 +219,16 @@ pub enum TableError { #[rutis::service(name = "managementMethods")] impl MethodTable { - pub async fn register(&self, caller: &Ctx, request: RegisterRequest, - declarations: Vec, call: HandlerFn) -> Result<(), TableError> { /* ... */ } + pub async fn register( + &self, + caller: &Ctx, + request: RegisterRequest, + declarations: Vec, + call: impl Fn(MethodCall) -> BoxFuture<'static, Result> + Send + Sync, + ) -> Result<(), TableError> { /* ... */ } pub async fn call(&self, request: CallRequest, cancelled: CancelledFn) - -> Result { /* ... */ } + -> Result { /* ... */ } } ``` -`MethodError` is the handler's own `{code, message}` data; the handler returns it inside `MethodReply::Error` and the table never rewrites it. +`MethodError` is A.1's `{code, appError, message}` data; the handler returns it inside `CallOutcome::Error` and the table never rewrites it. `HandedOff` is A.1's reply kind for a call whose final answer is written later by the provider. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 86066880a1..567f06f3e7 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -60,6 +60,6 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | -| Process parts | Connection, Transport, ServerControl, Rpc, ManagementMethods, ProcessRoot, CallChannel, UiHost, UiExtensions; 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) | +| Process parts | Connection, Transport, ServerControl, Rpc, ManagementMethods, CallChannel, UiHost, UiExtensions; 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 | UiResources; 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/Report.md b/docs/design/plugins/Report.md index 009d981470..f27c981f61 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -112,7 +112,7 @@ TimelineTree's bounded branch read and branch summary ([#2024](https://github.co | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `prepare` | Capture a bounded snapshot and open a draft | `{error?}`; the process namespace requires `error` in the observed variant | `{reportId, defaultModel?, plan}` | Before the snapshot is captured; nothing is drafted | `caller_required`, `invalid_params`, `unavailable`, `report_cancelled` | +| `prepare` | Capture a bounded snapshot and open a draft | `{error?}`; the process namespace requires `error` in the observed variant | `{reportId, defaultModel?, plan}` | Before the snapshot is captured; nothing is drafted | `caller_required`, `invalid_params`, `report_cancelled` | | `plan` | Bind the exact material, generation and directives | `{reportId, generation, redact, instructions?}` | `{planId, generation, evidence, instructionsStatus, material, maxOutputTokens, estimatedCost}` | None; the plan is a value | `report_not_found`, `invalid_params`, `report_busy`, `report_model_unavailable` | | `generate` | Consume the plan and produce the archive | `{reportId, planId}` | `{title, body, files, archive, sharing}` | The named plan stops; the evidence stays for a new plan | `report_not_found`, `report_plan_stale`, `report_busy`, `report_generation_failed`, `report_cancelled` | | `cancel` | Stop a generation or drop a draft | `{reportId, target: "generation", planId}` or `{reportId, target: "report"}` | `{cancelled}` | — | `report_not_found` | @@ -124,8 +124,7 @@ The draft is keyed by the calling connection and the part instance; a missing, e | Kind | What the caller does next | | --- | --- | | `caller_required` | The method needs a client connection; an in-process caller cannot prepare a report. Never reaches a client | -| `invalid` | Fix the request: a missing or malformed error reference, a model id outside the admitted catalog, an out-of-range field | -| `unavailable` | No draft can be prepared now: the Session is closing or its evidence cannot be read; use the local template or retry later | +| `invalid_params` | Fix the request: a missing or malformed error reference, a model id outside the admitted catalog, an out-of-range field | | `report_not_found` | The draft expired or belongs to another connection; prepare again | | `report_plan_stale` | The plan was replaced or consumed; review the new plan before generating | | `report_busy` | A generation is running for this draft; cancel it or wait for it to settle | diff --git a/docs/design/plugins/Rpc.md b/docs/design/plugins/Rpc.md index 9b854e4af0..e9e3431e7c 100644 --- a/docs/design/plugins/Rpc.md +++ b/docs/design/plugins/Rpc.md @@ -46,18 +46,20 @@ connection.reply(ReplyRequest { connection_id: id, call_id, frame: reply.reply } ### Dependencies -Connection's `reply` and `attached`; ManagementMethods' `call`; the Session's method table (the same shape, per [ManagementMethods](ManagementMethods.md)); Agents' `acquire` and `sessions` ([Agents contract, PR #2098](https://github.com/arcships/dim/pull/2098)); CallChannel's `run`; ServerControl's `shutdown`. +Connection's `reply` and `attached`; ManagementMethods' `call`; the Session's method table by its own contract ([SessionMethods, PR #2103](https://github.com/arcships/dim/pull/2103)); Agents' `acquire` and `sessions` ([Agents contract, PR #2098](https://github.com/arcships/dim/pull/2098)); CallChannel's `run`; ServerControl's `shutdown`. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `hello` | Answer a client's greeting for this generation | `{connection_id, params}` | `{reply, instance, methods}`: the frame, this generation's instance id and the management method names | The caller's token; the handshake stops before anything is recorded | `service_reloading`, `invalid_params`, `service_unavailable` | -| `request` | Dispatch one call and settle what it starts | `{connection_id, call_id, request}` | `{reply}`: the frame | The caller's token stops the wait; the provider's call is not cancelled by it (see below) | `service_reloading`, `service_unavailable`, `unknown_method`, `operation_interrupted`, `invalid_params`, and the method's own error | +| `request` | Dispatch one call and settle what it starts | `{connection_id, call_id, request}` | `{reply}`: the frame, built from the table's `CallOutcome` | The calling load's token (A.1); the provider's call is not cancelled by the connection closing (see below) | `service_reloading`, `service_unavailable`, `unknown_method`, `operation_interrupted`, `invalid_params`, and the method's own error | `request` mints nothing: the `call_id` comes from Connection, so the provider, CallChannel and the reply ordering name one call. The method's own error is the data the table returns; Rpc maps it to the protocol envelope and does not add kinds. -A calling connection closing stops delivery only: the admitted call belongs to the provider generation and settles according to its declaration, as the [methods contract A.1 and A.2](../contracts/session-boundary.md) require. Rpc's `request` returns the reply frame; writing it is Connection's. +A calling connection closing stops delivery only: the admitted call belongs to the provider generation and settles according to its declaration, as the [methods contract A.1 and A.2](../contracts/session-boundary.md) require. The token `request` receives is the admitting Rpc load's, never the connection's. Rpc's `request` returns the reply frame; writing it is Connection's. + +An idle close reads Agents' `sessions` value and calls `connection.close_for_idle`; on `Busy` it answers `daemon_busy` with the three counts. After the refusal is committed the assembly quiesces Agents and settles. Agents' `quiesce` answer is [#2098](https://github.com/arcships/dim/pull/2098)'s; at this call site it runs after the commit, so a `Busy { running }` answer is settled by the graceful close and cannot reopen admission — Agents' pause is one-way and cannot be reverted. ### Errors @@ -107,7 +109,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -- **Session registration (#2026)**: the Session method table's dispatch takes the same `{method, params, caller: {connectionId, callId}}` request and returns the same `MethodReply`, so one call path serves both tables. +- **Session registration (#2026)**: none. The Session table's shape is [#2103](https://github.com/arcships/dim/pull/2103)'s latest head; Rpc calls each table by its own contract. ## Binding appendix diff --git a/docs/design/plugins/ServerControl.md b/docs/design/plugins/ServerControl.md index 54d1995df0..447e5f79ac 100644 --- a/docs/design/plugins/ServerControl.md +++ b/docs/design/plugins/ServerControl.md @@ -39,7 +39,7 @@ A process part that starts work before any Session exists: if !activity.activated().await.activated { return Err(WorkError::HostClosed); // startup failed or shutdown began } -let hold = activity.hold(ctx).await?; // the id is bound to this row +let hold = activity.hold(ctx).await?; // the id is bound to this row; WorkError: From let result = run_work().await; activity.release(ReleaseRequest { hold_id: hold.hold_id }).await; ``` @@ -49,9 +49,9 @@ The `daemon.shutdown` handler: ```rust match activity.shutdown(ShutdownRequest { mode: ShutdownMode::Graceful }).await { Ok(()) => { /* hold the reply until the assembly settles, then write it */ } - // Rpc maps this kind to the protocol's `invalid_params`: "Shutdown already requested". - Err(ActivityError::Conflict) => return Err(RpcError::invalid("Shutdown already requested")), - Err(error) => return Err(error.into()), + // Rpc maps these kinds: Conflict -> invalid_params ("Shutdown already requested"), Closed -> service_unavailable. + Err(ActivityError::Conflict) => { /* answer invalid_params */ } + Err(ActivityError::Closed) => { /* answer service_unavailable */ } } ``` diff --git a/docs/design/plugins/UiExtensions.md b/docs/design/plugins/UiExtensions.md index 423933a15b..1d5b4a4e9c 100644 --- a/docs/design/plugins/UiExtensions.md +++ b/docs/design/plugins/UiExtensions.md @@ -51,7 +51,7 @@ let page = ui.read(ReadRequest { generation, path, offset: 0, limit: None }).awa ### Dependencies -FileStorage (`add_root`, `list`, `read`) for the declared roots and files, with `read`'s offset form for a page; ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). +FileStorage (`add_root`, `list`, `read`, and `open_read`/`read_at`/`close_read` for a page of a prepared file; the reader id stays inside this owner); ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). ### Operations @@ -114,7 +114,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. FileStorage's contract (#2016) supplies `add_root`, `list` and the offset `read`. +None. FileStorage's contract (#2016) supplies `add_root`, `list`, `read`, `open_read`, `read_at` and `close_read`. ## Binding appendix diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md index 1fa65f658d..44b2048ed4 100644 --- a/docs/design/plugins/UiResources.md +++ b/docs/design/plugins/UiResources.md @@ -41,14 +41,14 @@ let reference = resources.publish(PublishRequest { An interface reads it in pages: ```rust -let page = resources.read(ReadRequest { reference: reference.clone(), offset: 0, limit: None }).await?; +let page = resources.read(ReadRequest { session_id, id: reference.id.clone(), offset: 0, limit: None }).await?; ``` ## Own contract ### Dependencies -FileStorage's offset read `read {path, offset, length}` and its path resolution for the file; SessionLifecycle's `closing` for the Session's end. No pinned reader id crosses. +FileStorage's `open_read` (`{path} → {read_id, size}`), `read_at {read_id, offset}` and `close_read {read_id}`; SessionLifecycle's `closing`. The reader id stays inside UiResources: no client and no other owner sees it. ### Operations @@ -56,9 +56,9 @@ FileStorage's offset read `read {path, offset, length}` and its path resolution | --- | --- | --- | --- | --- | --- | | `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While the file is opened; nothing is registered | `invalid_params`, `resource_unavailable`, `session_closed` | | `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `resource_gone`, `invalid_params`, `session_closed` | -| `read` | One bounded page of a published file | `{reference, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params` | +| `read` | One bounded page of a published file | `{sessionId, id, offset?, limit?}` (the client method's flat shape) | `{offset, bytes, total, media_type, data}` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params`, `session_closed` | -`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. +`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. The FileStorage reader opened at `publish` is owned by UiResources and closed with the reference; its id never crosses. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. The media type decides inline display: a listed image, audio, video, text or PDF type is served as declared; any other type is served as `application/octet-stream` and marked as an attachment. @@ -69,15 +69,15 @@ The media type decides inline display: a listed image, audio, video, text or PDF | `invalid_params` | The path is relative or outside every authorized root, the reference names another Session, or a page offset is beyond the file | | `resource_unavailable` | The file is gone or unreadable; publish again or show the caller that the resource is unavailable | | `resource_gone` | The reference was withdrawn; stop reading | -| `session_closed` | The Session is closing; the reference is settled | +| `session_closed` | The Session is closing or is gone; the reference is settled | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `publish` | Check the Session phase, resolve the path in FileStorage and read its size, register the reference and the row's cleanup | Nothing is registered | The reference is removed by the row's cleanup | Every reference is removed | UiResources: the reference and its read counter | +| `publish` | Check the Session phase, `open_read` the path in FileStorage, register the reference (with its read id and size) and the row's cleanup | The reader is closed, nothing is registered | The reference and its reader are removed by the row's cleanup | Every reference and reader is closed and removed | UiResources: the reference and the reader | | `withdraw` | Check the owner row, cancel and wait for admitted reads, remove the reference | — | Already removed | Already removed | UiResources | -| `read` | Resolve the reference, take a read token, call FileStorage's offset read for one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference goes | UiResources: the token; FileStorage: the page | +| `read` | Resolve the reference, take a read token, call FileStorage's `read_at` for one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference and its reader go | UiResources: the token and the reader; FileStorage: the page | The `session.ui.resources.read` client method is the same `read`, served to RPC clients; the web entry's HTTP route is its transport. Both stay. @@ -112,7 +112,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. FileStorage's contract (#2016) supplies the offset read. +None. FileStorage's contract (#2016) supplies `open_read`, `read_at` and `close_read`. ## Binding appendix @@ -128,7 +128,8 @@ pub struct ResourceRef { pub session_id: String, pub id: String } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReadRequest { - pub reference: ResourceRef, + pub session_id: String, + pub id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub offset: Option, #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/docs/design/web-workspace.md b/docs/design/web-workspace.md index 9ad35687cb..33864ece56 100644 --- a/docs/design/web-workspace.md +++ b/docs/design/web-workspace.md @@ -108,7 +108,7 @@ For development against the repository checkout, and for a build that must carry | Model list | The read-only management methods `provider.list`, `provider.catalog`, `provider.selection` and `account.providers` are also served (decision Q1); their replies carry no credentials (`provider.list` reports only `credentialConfigured` and header names). Managed Provider discovery follows §4.2. Switching uses the Session method `session.model.update` | | New Session model | `session.model.preview` is served and advertised with the authority the entry's own `session.create` already implies ([model preview](model-configuration.md#model-preview-before-creation)): `{cwd, agentId?, model?, modelPreferences?}` resolves the model a new Session would adopt, creates no Session, saves no selection and returns no credential. `startup` is refused `local_transport_required`, because [model startup](model-startup.md) is a protected-local launch channel. The bare `/ws` serves neither | | UI directory | UiExtensions contributes `ui.extensions.list`, which is explicitly allowlisted and advertised in `hello.features` while available. Connection forwards `ui.extensions.changed` over the reliable control channel; clients refetch the directory on this notice | -| Error-only reports | Report contributes `report.prepare`, `report.plan`, `report.generate` and `report.cancel`. The authenticated local Web entry explicitly admits these four methods and advertises them in `hello.features` while available. They take no Session or branch ID and use no Session data. [Report contract](plugins/Report.md#4-report-methods) | +| Error-only reports | Report contributes `report.prepare`, `report.plan`, `report.generate` and `report.cancel`. The authenticated local Web entry explicitly admits these four methods and advertises them in `hello.features` while available. They take no Session or branch ID and use no Session data. [Report contract](plugins/Report.md#own-contract) | Compatibility: the bare `/ws` keeps today's rules (`hello` and `daemon.ping` only in protected profiles). Execution Session methods become reachable from the web entry; this is the same widening RemoteGateway records as E3, limited here to loopback connections authenticated by the local user's token. From d505f3e3dee9781c6424d1266877a3fbc63bd2e2 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:26:14 +0800 Subject: [PATCH 09/12] docs(zh): follow the report contract's heading Refs #2021 --- docs/zh/design/cli-commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/design/cli-commands.md b/docs/zh/design/cli-commands.md index 32263c0763..460dc62c01 100644 --- a/docs/zh/design/cli-commands.md +++ b/docs/zh/design/cli-commands.md @@ -1068,7 +1068,7 @@ Remove 先在提示栏询问,`Remove deny prefix git push? Enter confirm · Es | `dimcode account PROVIDER` | 打印被描述账号的非机密状态。 | | `dimcode logout PROVIDER` | 让被描述的账号退出。 | | `/connect` | 列出 `provider.management` 报告的提供方;被描述的账号打开签到或退出步骤,其他提供方打开连接表单。 | -| `/report` | 上报当前 Session。回合进行中或没有错误时均可使用。可将报告保存为 ZIP,查看保存路径,并在保存后打开分享页面。参见[报告契约](../../design/plugins/Report.md#2-client-interaction)。 | +| `/report` | 上报当前 Session。回合进行中或没有错误时均可使用。可将报告保存为 ZIP,查看保存路径,并在保存后打开分享页面。参见[报告契约](../../design/plugins/Report.md#client-interaction)。 | | `/exit` | 在空闲的交互提示符处断开并退出。 | | `!command` / `!!command` | 以 record/private 模式调用 Session 现有的 `shell.run`,模型回合进行中也可用。 | | `--permission read-only\|workspace-write\|full-access` | 为 `dimcode`、`tui`、`exec` 和 `exec resume` 选择新建或恢复的 Session 的预设([权限控制](#权限控制))。 | From 82c6f8e0c316483697c3e214ff0d7d072aa79874 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:44:45 +0800 Subject: [PATCH 10/12] docs(design): page UI resources with FileStorage's stateless read Refs #2021 Refs #2015 --- docs/design/plugins/UiExtensions.md | 6 +++--- docs/design/plugins/UiResources.md | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/design/plugins/UiExtensions.md b/docs/design/plugins/UiExtensions.md index 1d5b4a4e9c..2099363673 100644 --- a/docs/design/plugins/UiExtensions.md +++ b/docs/design/plugins/UiExtensions.md @@ -51,7 +51,7 @@ let page = ui.read(ReadRequest { generation, path, offset: 0, limit: None }).awa ### Dependencies -FileStorage (`add_root`, `list`, `read`, and `open_read`/`read_at`/`close_read` for a page of a prepared file; the reader id stays inside this owner); ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). +FileStorage (`add_root`, `list`, `read`; a page of a prepared file is `read {path, offset, length}` with the owner's 64 KiB page size, and the reply's `size`/`eof` give the end); ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). ### Operations @@ -79,7 +79,7 @@ FileStorage (`add_root`, `list`, `read`, and `open_read`/`read_at`/`close_read` | --- | --- | --- | --- | --- | --- | | `register` | Validate, copy into a new generation directory, swap the catalog entry, bump the revision, emit the change event | The generation directory is removed, the old entry stays | The registration is dropped with the process row | Sources are retained and restored on the next generation | UiExtensions: the generation directory and its reads | | `withdraw` | Remove the entry, cancel admitted reads, wait for them, remove the directory, emit the change event | — | — | — | UiExtensions | -| `read` | Resolve the generation and the path, read one bounded page under the read counter | The page stops; nothing changes | The read token is released | Admitted reads are cancelled and awaited before the directory goes | UiExtensions | +| `read` | Resolve the generation and the path, read one page with FileStorage's offset read (64 KiB at most) | The page stops; nothing changes | The read ends with the row | Admitted reads are cancelled and awaited before the directory goes | UiExtensions | The `ui.extensions.read` client method is the same `read`, served to clients; WebEntry's HTTP route is its transport. Both stay. @@ -114,7 +114,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. FileStorage's contract (#2016) supplies `add_root`, `list`, `read`, `open_read`, `read_at` and `close_read`. +None. FileStorage's contract ([PR #2080](https://github.com/arcships/dim/pull/2080)) supplies `add_root`, `list` and the offset `read`. ## Binding appendix diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md index 44b2048ed4..73c0ef233c 100644 --- a/docs/design/plugins/UiResources.md +++ b/docs/design/plugins/UiResources.md @@ -48,7 +48,7 @@ let page = resources.read(ReadRequest { session_id, id: reference.id.clone(), of ### Dependencies -FileStorage's `open_read` (`{path} → {read_id, size}`), `read_at {read_id, offset}` and `close_read {read_id}`; SessionLifecycle's `closing`. The reader id stays inside UiResources: no client and no other owner sees it. +FileStorage's stateless `read {path, offset?, length?} → ReadReply {data, eof, size} | none` and `stat {path}`; SessionLifecycle's `closing`. No reader id exists: each page is one read, the owner reports the file's `size` as the page total and `eof` as the end. ### Operations @@ -56,9 +56,9 @@ FileStorage's `open_read` (`{path} → {read_id, size}`), `read_at {read_id, off | --- | --- | --- | --- | --- | --- | | `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While the file is opened; nothing is registered | `invalid_params`, `resource_unavailable`, `session_closed` | | `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `resource_gone`, `invalid_params`, `session_closed` | -| `read` | One bounded page of a published file | `{sessionId, id, offset?, limit?}` (the client method's flat shape) | `{offset, bytes, total, media_type, data}` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params`, `session_closed` | +| `read` | One bounded page of a published file | `{sessionId, id, offset?, limit?}` (the client method's flat shape) | `{offset, bytes, total, media_type, data}`; `total` is FileStorage's `size`, and `eof` is `offset + bytes == total` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params`, `session_closed` | -`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. The FileStorage reader opened at `publish` is owned by UiResources and closed with the reference; its id never crosses. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. +`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. `publish` records the resolved path and the file's `size` from FileStorage; it opens no reader. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. The media type decides inline display: a listed image, audio, video, text or PDF type is served as declared; any other type is served as `application/octet-stream` and marked as an attachment. @@ -75,9 +75,9 @@ The media type decides inline display: a listed image, audio, video, text or PDF | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `publish` | Check the Session phase, `open_read` the path in FileStorage, register the reference (with its read id and size) and the row's cleanup | The reader is closed, nothing is registered | The reference and its reader are removed by the row's cleanup | Every reference and reader is closed and removed | UiResources: the reference and the reader | +| `publish` | Check the Session phase, `read` the path's facts in FileStorage (`size`), register the reference (path and size) and the row's cleanup | Nothing is registered | The reference is removed by the row's cleanup | Every reference is removed | UiResources: the reference | | `withdraw` | Check the owner row, cancel and wait for admitted reads, remove the reference | — | Already removed | Already removed | UiResources | -| `read` | Resolve the reference, take a read token, call FileStorage's `read_at` for one page, release the token | The page stops; the token is released | The read ends with the row | Admitted reads are cancelled before the reference and its reader go | UiResources: the token and the reader; FileStorage: the page | +| `read` | Resolve the reference, call FileStorage's `read {path, offset, length}` for one page (64 KiB at most, the client's `limit` clamped to it), map `size` to `total` and `eof` to the page end | The page stops; nothing changes | The read ends with the row | Admitted reads are counted and awaited before the reference goes | UiResources: the reference and the read count; FileStorage: the page | The `session.ui.resources.read` client method is the same `read`, served to RPC clients; the web entry's HTTP route is its transport. Both stay. @@ -112,7 +112,7 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Requirements raised to mechanism owners -None. FileStorage's contract (#2016) supplies `open_read`, `read_at` and `close_read`. +None. FileStorage's contract ([PR #2080](https://github.com/arcships/dim/pull/2080)) supplies `read` and `stat`. ## Binding appendix From 1e78ce316a91169f1c6a02ef244098e9c23018b3 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 13:31:07 +0800 Subject: [PATCH 11/12] docs(design): compile the table binding and bound the pages Refs #2021 Refs #2015 --- docs/design/plugins/CallChannel.md | 11 +++++- docs/design/plugins/Connection.md | 4 +-- docs/design/plugins/ManagementMethods.md | 43 +++++++++++++++++------- docs/design/plugins/README.md | 2 +- docs/design/plugins/Report.md | 2 -- docs/design/plugins/UiExtensions.md | 7 ++-- docs/design/plugins/UiResources.md | 12 +++---- 7 files changed, 53 insertions(+), 28 deletions(-) diff --git a/docs/design/plugins/CallChannel.md b/docs/design/plugins/CallChannel.md index 037877b3df..15ceb9cd6f 100644 --- a/docs/design/plugins/CallChannel.md +++ b/docs/design/plugins/CallChannel.md @@ -54,7 +54,7 @@ let outcome = channel.run( Box::pin(async move { // The token is the Rpc load's, never the connection's: a disconnect stops delivery only. table.call(CallRequest { method, params, caller }, rpc_unload).await - .map_err(|error| rutis::Error::from(error.into_call_error())) + .map_err(RunError::from) }) }), ) @@ -98,6 +98,7 @@ Connection's `write_after`, `write` and `closed`. | Kind | Wire code | What the caller does next | | --- | --- | --- | | `invalid_params` | `invalid_params` | The call id is bound to another connection or the request is malformed; a programming error, do not retry | +| `table` | `table` with the table's own code inside | The table refused the call (`service_reloading`, `service_unavailable`, `unknown_method`, `operation_interrupted`); Rpc answers with the table's code | | `unsupported` | `unsupported` | The notification names a link this binding does not carry; drop the notification, nothing was written | | `undeclared` | `undeclared` | The registration did not declare the name; fix the declaration, nothing was written. Decided before the connection's state | | `gone` | `gone` | The connection closed, the Rpc load unloaded or the row unloaded; stop notifying for the call | @@ -184,6 +185,14 @@ pub struct ClosedRequest { pub connection_id: String } pub enum RunError { #[error("{message}")] InvalidParams { message: String }, + #[error("the table refused the call")] + Table { error: TableError }, +} + +impl From for RunError { + fn from(error: TableError) -> Self { + Self::Table { error } + } } impl From for RunError { diff --git a/docs/design/plugins/Connection.md b/docs/design/plugins/Connection.md index e4b7366dba..2ce3932910 100644 --- a/docs/design/plugins/Connection.md +++ b/docs/design/plugins/Connection.md @@ -99,7 +99,7 @@ The owner type is `ConnectionHub`. `accept` is crate-internal because a socket c | `close_all` | Close every connection and wait for its tasks | `{}` | `{}` | None; the owner completes the close | none | | `settle` (crate-internal) | One connection ended: release its attachment, tell UiHost, end its writer | `{connection_id, reason}` | `{}` | None | none | -`reply` writes the frame a call produced and releases the notifications `write_after` held behind it. `write` is for a notification with no call to follow (a UI close notice); `write_after` is for a notification sent while or after a call runs, ordered behind that call's reply. A notification over the frame budget is `too_large` and leaves the connection open; a notification or reply the reliable allowance cannot take is `slow` and closes the connection as a slow consumer. +`reply` writes the frame a call produced and releases the notifications `write_after` held behind it. `write` is for a notification with no call to follow (a UI close notice); `write_after` is for a notification sent while or after a call runs, ordered behind that call's reply. A notification over the frame budget is `too_large` and leaves the connection open; a notification or reply the reliable allowance cannot take is `slow` and closes the connection as a slow consumer. A reply over the frame budget is also `too_large`, but the call cannot stay unanswered: the connection closes, the caller's wait ends `gone`, and the client reconnects and reads the current state. `close_for_idle` takes `running` from Agents' `sessions` value, read immediately before. The owner rechecks only its own counts under the admission lock and commits the refusal in the same step, so no hello or attach joins after the decision. @@ -113,7 +113,7 @@ The caller's sequence is Rpc's: read Agents' `sessions`, then `close_for_idle`; | `busy` | `daemon_busy` with `connections`, `attachedSessions`, `running` | Answer the client with the three counts and do not close | | `unknown_connection` | — (in-process) | The connection is gone; drop the write or the attachment and read the current state | | `gone` | — (in-process) | The connection closed or its generation unloaded; nothing was written | -| `too_large` | — (in-process) | The frame exceeds the connection's frame budget; the connection stays open — shorten the notification | +| `too_large` | — (in-process) | A notification over the budget: nothing written, the connection stays open — shorten it. A reply over the budget: the connection closes and the call ends unanswered; the client reconnects | | `slow` | — (in-process) | The connection's reliable allowance is exhausted; the connection is closed and the frame is dropped | | `session_unavailable` | `session_closed` when the Session is closed, `service_unavailable` when it cannot be acquired | Report it to the client and retry the attach later | | `cancelled` | — (in-process) | Nothing was attached; the caller stopped waiting | diff --git a/docs/design/plugins/ManagementMethods.md b/docs/design/plugins/ManagementMethods.md index fb2bead2e5..6ce0e92536 100644 --- a/docs/design/plugins/ManagementMethods.md +++ b/docs/design/plugins/ManagementMethods.md @@ -35,9 +35,10 @@ table.register( ctx, RegisterRequest { namespace: "settings".into() }, declarations, - Arc::new(move |call: MethodCall| { + Arc::new(move |call: MethodCall, cancelled: CancellationToken, progress: Progress| { let owner = owner.clone(); - Box::pin(async move { owner.handle(call).await }) // Result + // The token fires on the provider's or the admitting Rpc load's unload (A.1). + Box::pin(async move { owner.handle(call, cancelled, progress).await }) // Result }), ).await?; ``` @@ -52,8 +53,8 @@ let reply = table.call(CallRequest { caller: Some(CallerRef { connection_id, call_id }), }, cancelled).await?; match reply { - MethodReply::Value { value } => answer_value(value), - MethodReply::Error { code, message } => answer_error(code, message), + CallOutcome::Reply { reply } => answer_reply(reply), + CallOutcome::Error { error } => answer_error(error.code, error.app_error, error.message), } ``` @@ -74,7 +75,7 @@ The loader's row status (`rutis/loader`), read when a withdrawn namespace answer The handler's own failure is `MethodError` data inside `CallOutcome::Error` (A.1's `{code, appError, message}`), never a table error; the table returns only its routing failures. -`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock; it returns `Result` with `TableError: From`, the form rutis accepts for a callback parameter. +`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock. Its handler signature is A.1's `(MethodCall, CancellationToken, Progress)`, so the token fires on either unload, `drain` calls included; `CancellationToken` is the runtime's cancellation token and `Progress` is A.1's per-call progress sink (Appendix F). The handler returns `CallOutcome` with `TableError: From`. ### Errors @@ -217,18 +218,34 @@ pub enum TableError { OperationInterrupted, } -#[rutis::service(name = "managementMethods")] -impl MethodTable { - pub async fn register( +impl From for TableError { + fn from(error: rutis::host::CallError) -> Self { + Self::InvalidParams { message: error.message().to_owned() } + } +} + +pub type HandlerFn = Arc< + dyn Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> + + Send + Sync, +>; + +/// The process table's native binding. `managementMethods` is a shared catalog name +/// with a hand-written `HostDispatch` at `host_key("managementMethods")`: the handler +/// carries a cancellation token and a progress sink, which are not serde data, so the +/// marked-service macro cannot bind `register`. Rust callers use this trait directly; +/// other languages register through the dispatch, as the current `ForeignMethods` does. +pub trait ManagementTable { + fn register( &self, caller: &Ctx, request: RegisterRequest, declarations: Vec, - call: impl Fn(MethodCall) -> BoxFuture<'static, Result> + Send + Sync, - ) -> Result<(), TableError> { /* ... */ } - pub async fn call(&self, request: CallRequest, cancelled: CancelledFn) - -> Result { /* ... */ } + call: HandlerFn, + ) -> BoxFuture<'static, Result<(), TableError>>; + + fn call(&self, request: CallRequest, cancelled: CancelledFn) + -> BoxFuture<'static, Result>; } ``` -`MethodError` is A.1's `{code, appError, message}` data; the handler returns it inside `CallOutcome::Error` and the table never rewrites it. `HandedOff` is A.1's reply kind for a call whose final answer is written later by the provider. +`ManagementTable` is the native spelling; the catalog name is `managementMethods` and the foreign registration uses the hand-written dispatch, because a handler's token and progress sink are not data. A native part implements the trait; the same table serves `call` in process and on the wire. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 567f06f3e7..e4b0fb740f 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -18,7 +18,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [ServerControl](ServerControl.md) | publication gate, shutdown intent and accepted-work holds; `processActivity` | — | — | #2021 | | [Rpc](Rpc.md) | handshake, built-in methods and dispatch of one call; `rpc` | — | — | #2021 | | [ManagementMethods](ManagementMethods.md) | the process namespace table; `managementMethods` | — | — | #2021 | -| [ProcessRoot](ProcessRoot.md) | process values: reserved names and credential variable names | — | — | #2021 | +| [ProcessRoot](ProcessRoot.md) | process values: reserved names and credential variable names; the assembly supplies them, there is no plugin row | — | — | #2021 | | [CallChannel](CallChannel.md) | call bindings for connection-bound notifications; `callChannel` | — | — | #2021 | | [UiHost](UiHost.md) | interface registrations and UI leaves; `uiHost` | — | — | #2021 | | [UiExtensions](UiExtensions.md) | the UI content catalog; `uiExtensions` | UiResources | — | #2021 | diff --git a/docs/design/plugins/Report.md b/docs/design/plugins/Report.md index f27c981f61..e4d4e271c6 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -280,8 +280,6 @@ pub enum ReportError { CallerRequired, #[error("{message}")] InvalidParams { message: String }, - #[error("The report cannot be prepared now")] - Unavailable, #[error("The report draft is missing or expired")] ReportNotFound, #[error("The plan was replaced or consumed")] diff --git a/docs/design/plugins/UiExtensions.md b/docs/design/plugins/UiExtensions.md index 2099363673..ec63054e62 100644 --- a/docs/design/plugins/UiExtensions.md +++ b/docs/design/plugins/UiExtensions.md @@ -51,7 +51,7 @@ let page = ui.read(ReadRequest { generation, path, offset: 0, limit: None }).awa ### Dependencies -FileStorage (`add_root`, `list`, `read`; a page of a prepared file is `read {path, offset, length}` with the owner's 64 KiB page size, and the reply's `size`/`eof` give the end); ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). +FileStorage (`add_root`, `list`, `read`; one client page is served by looping FileStorage's 64 KiB offset reads up to the client's bound, 1 MiB by default and 4 MiB at most, with `size`/`eof` giving the end); ManagementMethods' `register` for the `ui.extensions` namespace; PartRegistry to mount the UiResources Session part (defined in the [UiResources contract](UiResources.md)). ### Operations @@ -62,7 +62,7 @@ FileStorage (`add_root`, `list`, `read`; a page of a prepared file is `read {pat | `plugins` | The packages with content now | `{}` | `{plugins: [id]}` | None | none | | `refusal` | Why a package's content was refused | `{plugin}` | `{message?}` | None | none | | `directory` | The published directory | `{}` | `{revision, extensions, errors}` | None | none | -| `read` | One page of a prepared file | `{generation, path, offset?, limit?}` | `{offset, bytes, total, media_type, data}` | The calling connection's task ends; the page stops | `resource_unavailable` | +| `read` | One page of a prepared file | `{generation, path, offset?, limit?}` (default 1 MiB, at most 4 MiB) | `{offset, bytes, total, media_type, data}` | The calling connection's task ends; the page stops | `resource_unavailable`, `invalid_params` | `register` with no manifest withdraws the package's content, the same as `withdraw`. @@ -72,6 +72,7 @@ FileStorage (`add_root`, `list`, `read`; a page of a prepared file is `read {pat | --- | --- | | `invalid_params` | The package id is unknown, the version unsupported or the declaration invalid; the reason is recorded as the package's refusal | | `resource_unavailable` | The file is gone or unreadable; the client shows the panel as unavailable | +| `invalid_params` | A page offset is past the file's end or the limit is zero; the client asks inside the file and at least one byte | ### Flows @@ -79,7 +80,7 @@ FileStorage (`add_root`, `list`, `read`; a page of a prepared file is `read {pat | --- | --- | --- | --- | --- | --- | | `register` | Validate, copy into a new generation directory, swap the catalog entry, bump the revision, emit the change event | The generation directory is removed, the old entry stays | The registration is dropped with the process row | Sources are retained and restored on the next generation | UiExtensions: the generation directory and its reads | | `withdraw` | Remove the entry, cancel admitted reads, wait for them, remove the directory, emit the change event | — | — | — | UiExtensions | -| `read` | Resolve the generation and the path, read one page with FileStorage's offset read (64 KiB at most) | The page stops; nothing changes | The read ends with the row | Admitted reads are cancelled and awaited before the directory goes | UiExtensions | +| `read` | Resolve the generation and the path, loop FileStorage's 64 KiB offset reads up to the client's bound (1 MiB default, 4 MiB max), then answer one page | The page stops; nothing changes | The read ends with the row | Admitted reads are cancelled and awaited before the directory goes | UiExtensions: the page; FileStorage: the 64 KiB reads | The `ui.extensions.read` client method is the same `read`, served to clients; WebEntry's HTTP route is its transport. Both stay. diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md index 73c0ef233c..8e4c0cb27c 100644 --- a/docs/design/plugins/UiResources.md +++ b/docs/design/plugins/UiResources.md @@ -54,11 +54,11 @@ FileStorage's stateless `read {path, offset?, length?} → ReadReply {data, eof, | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While the file is opened; nothing is registered | `invalid_params`, `resource_unavailable`, `session_closed` | +| `publish` | Publish a finalized regular file for interfaces | `{path, media_type}` | `{session_id, id}` | While `stat` runs; nothing is registered | `invalid_params`, `resource_unavailable`, `session_closed` | | `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `resource_gone`, `invalid_params`, `session_closed` | -| `read` | One bounded page of a published file | `{sessionId, id, offset?, limit?}` (the client method's flat shape) | `{offset, bytes, total, media_type, data}`; `total` is FileStorage's `size`, and `eof` is `offset + bytes == total` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params`, `session_closed` | +| `read` | One bounded page of a published file | `{sessionId, id, offset?, limit?}` (the client method's flat shape) | `{offset, bytes, total, media_type, data}`; `total` is the size recorded at publish, and `eof` is `offset + bytes == total` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params`, `resource_unavailable`, `session_closed` | -`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. `publish` records the resolved path and the file's `size` from FileStorage; it opens no reader. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. +`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. `publish` records the resolved path and the file's `size` from FileStorage's `stat`; it opens no reader. The recorded size is the page total, so the client's paging bounds stay stable across pages. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. The media type decides inline display: a listed image, audio, video, text or PDF type is served as declared; any other type is served as `application/octet-stream` and marked as an attachment. @@ -67,7 +67,7 @@ The media type decides inline display: a listed image, audio, video, text or PDF | Kind | What the caller does next | | --- | --- | | `invalid_params` | The path is relative or outside every authorized root, the reference names another Session, or a page offset is beyond the file | -| `resource_unavailable` | The file is gone or unreadable; publish again or show the caller that the resource is unavailable | +| `resource_unavailable` | The file is gone, unreadable, or replaced after publish (its size changed); the client shows the resource as unavailable and the row publishes again. An absent file is this kind, not `resource_gone` | | `resource_gone` | The reference was withdrawn; stop reading | | `session_closed` | The Session is closing or is gone; the reference is settled | @@ -75,9 +75,9 @@ The media type decides inline display: a listed image, audio, video, text or PDF | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `publish` | Check the Session phase, `read` the path's facts in FileStorage (`size`), register the reference (path and size) and the row's cleanup | Nothing is registered | The reference is removed by the row's cleanup | Every reference is removed | UiResources: the reference | +| `publish` | Check the Session phase, `stat` the path in FileStorage (kind and `size`), register the reference (path and size) and the row's cleanup | Nothing is registered | The reference is removed by the row's cleanup | Every reference is removed | UiResources: the reference | | `withdraw` | Check the owner row, cancel and wait for admitted reads, remove the reference | — | Already removed | Already removed | UiResources | -| `read` | Resolve the reference, call FileStorage's `read {path, offset, length}` for one page (64 KiB at most, the client's `limit` clamped to it), map `size` to `total` and `eof` to the page end | The page stops; nothing changes | The read ends with the row | Admitted reads are counted and awaited before the reference goes | UiResources: the reference and the read count; FileStorage: the page | +| `read` | Resolve the reference, call FileStorage's `read {path, offset, length}` for one page (64 KiB at most, the client's `limit` clamped to it); `total` is the recorded publish size and `eof` is the page end; a `none` reply, or a reply whose `size` differs from the recorded size, is `resource_unavailable` | The page stops; nothing changes | The read ends with the row | Admitted reads are counted and awaited before the reference goes | UiResources: the reference and the read count; FileStorage: the page | The `session.ui.resources.read` client method is the same `read`, served to RPC clients; the web entry's HTTP route is its transport. Both stay. From fa2eea2c764225e0c05ac9655634dff9fe51f8f3 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:10:23 +0800 Subject: [PATCH 12/12] docs(connection): share one method-table shape and state the published-path rule --- docs/design/plugins/ManagementMethods.md | 149 ++++++----------------- docs/design/plugins/UiResources.md | 2 +- 2 files changed, 36 insertions(+), 115 deletions(-) diff --git a/docs/design/plugins/ManagementMethods.md b/docs/design/plugins/ManagementMethods.md index 6ce0e92536..b5001483fc 100644 --- a/docs/design/plugins/ManagementMethods.md +++ b/docs/design/plugins/ManagementMethods.md @@ -33,12 +33,12 @@ A process part registers from `apply`: ```rust table.register( ctx, - RegisterRequest { namespace: "settings".into() }, + "settings".into(), declarations, Arc::new(move |call: MethodCall, cancelled: CancellationToken, progress: Progress| { let owner = owner.clone(); // The token fires on the provider's or the admitting Rpc load's unload (A.1). - Box::pin(async move { owner.handle(call, cancelled, progress).await }) // Result + Box::pin(async move { owner.handle(call, cancelled, progress).await }) // Result }), ).await?; ``` @@ -47,15 +47,13 @@ Rpc dispatches: ```rust // `service_reloading` and `service_unavailable` are answered from the registering row's status. -let reply = table.call(CallRequest { - method: method.into(), +let reply = table.call( + method.into(), params, - caller: Some(CallerRef { connection_id, call_id }), -}, cancelled).await?; -match reply { - CallOutcome::Reply { reply } => answer_reply(reply), - CallOutcome::Error { error } => answer_error(error.code, error.app_error, error.message), -} + Some(CallerRef { connection_id, call_id }), + cancelled, +).await?; +answer_reply(reply) // MethodReply: the handler's value or its own {code, message} ``` ## Own contract @@ -68,14 +66,14 @@ The loader's row status (`rutis/loader`), read when a withdrawn namespace answer | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Publish a namespace for the registering row's lifetime | `{namespace, declarations, call}` + `caller: &Ctx` | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid_params` | -| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `CallOutcome`: the handler's `MethodReply` or its own `MethodError` | The calling load's token (A.1); a caller disconnect stops delivery only and does not cancel the accepted call | `unknown_method`, `service_reloading`, `service_unavailable`, `operation_interrupted`, `invalid_params` | +| `register` | Publish a namespace for the registering row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`: the handler's `MethodReply` | The calling load's token (A.1); a caller disconnect stops delivery only and does not cancel the accepted call | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `invalid`, `closed` | `caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses. It is absent for an in-process call. The table passes it to the handler unchanged; a handler that notifies uses it with `callChannel`. -The handler's own failure is `MethodError` data inside `CallOutcome::Error` (A.1's `{code, appError, message}`), never a table error; the table returns only its routing failures. +The handler's own failure is `MethodReply`'s error data (A.1's `{code, appError, message}`), never a table error; the table returns only its routing failures. The operations, `MethodCall`, `MethodReply` and `MethodError` are the [SessionMethods](https://github.com/arcships/dim/pull/2103#own-contract) contract's (#2103), the same shape both tables serve. -`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock. Its handler signature is A.1's `(MethodCall, CancellationToken, Progress)`, so the token fires on either unload, `drain` calls included; `CancellationToken` is the runtime's cancellation token and `Progress` is A.1's per-call progress sink (Appendix F). The handler returns `CallOutcome` with `TableError: From`. +`register`'s `call` is a callback parameter, not a request field, and the registration is bound to `caller`'s row: the table removes it when that row unloads. The callback runs on the registering row and is never called inside a commit lock. Its handler signature is A.1's `(MethodCall, CancellationToken, Progress)`, so the token fires on either unload, `drain` calls included; `CancellationToken` is the runtime's cancellation token and `Progress` is A.1's per-call progress sink (Appendix F). The handler returns `MethodReply` with `MethodCallbackError: From`. ### Errors @@ -85,11 +83,12 @@ The wire codes are the existing ones from the methods contract. | --- | --- | --- | | `reserved` | — (registration, in-process) | The namespace or a name is the host's; pick another name | | `duplicate` | — (registration, in-process) | The namespace is registered already; the registering row must not register twice | -| `invalid_params` | `invalid_params` | The namespace or declaration is outside the name grammar, or the request is malformed | +| `invalid` | `invalid_params` | The namespace or declaration is outside the name grammar, or the request is malformed | | `unknown_method` | `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | -| `service_reloading` | `service_reloading` | The registering row is starting or reloading; retry after it is Active | -| `service_unavailable` | `service_unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | -| `operation_interrupted` | `operation_interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | +| `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` | — | This generation is unloading; the next generation serves the call | ### Flows @@ -100,7 +99,7 @@ The wire codes are the existing ones from the methods contract. ## Exceptions with reasons -- The table remembers the registering row per namespace: a withdrawn namespace must answer `service_reloading` or `service_unavailable` rather than fall through to a parent namespace. +- The table remembers the registering row per namespace: a withdrawn namespace must answer `reloading` or `unavailable` rather than fall through to a parent namespace. - `call` takes the caller as data, not as a connection handle: the reply ordering belongs to Connection, and the table never writes a socket. ## Supersedes @@ -132,100 +131,17 @@ The checks below cite [design rules §7, PR #2029](https://github.com/arcships/d ## Binding appendix +The operation shapes and their data types are the [SessionMethods](https://github.com/arcships/dim/pull/2103#own-contract) contract's (#2103): `MethodDecl`, `MethodCall`, `MethodReply`, `MethodCallbackError`, `MethodError`, `CallerRef` and `Interruption`. `Progress` is the per-call sink in the methods contract's Appendix F. This contract adds only the process table's binding; it declares no second copy of those types. + ```rust use crate::host::CancelledFn; +use crate::methods::{ + CallerRef, MethodCall, MethodCallbackError, MethodDecl, MethodError, MethodReply, Progress, +}; use rutis::Ctx; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CallerRef { pub connection_id: String, pub call_id: String } - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct RegisterRequest { pub namespace: String } - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CallRequest { - pub method: String, - pub params: serde_json::Value, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub caller: Option, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MethodError { - pub code: i32, - pub app_error: String, - pub message: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase")] -pub enum MethodReply { - Value { value: serde_json::Value }, - HandedOff, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase")] -pub enum CallOutcome { - Reply { reply: MethodReply }, - Error { error: MethodError }, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Interruption { Report, Drain } - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MethodDecl { - pub name: String, - pub mutating: bool, - pub interruption: Interruption, - #[serde(default)] - pub notifications: Vec, - #[serde(default)] - pub progress: bool, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MethodCall { - pub method: String, - pub params: serde_json::Value, - pub caller: Option, -} - -#[derive(Debug, serde::Serialize, thiserror::Error, serde::Deserialize)] -#[serde(tag = "code", rename_all = "snake_case")] -pub enum TableError { - #[error("{message}")] - Reserved { message: String }, - #[error("{message}")] - Duplicate { message: String }, - #[error("{message}")] - InvalidParams { message: String }, - #[error("Unknown method")] - UnknownMethod, - #[error("Service is reloading; retry")] - ServiceReloading, - #[error("Service is unavailable until it is fixed or restarted")] - ServiceUnavailable, - #[error("Service reloaded; the call may have committed")] - OperationInterrupted, -} - -impl From for TableError { - fn from(error: rutis::host::CallError) -> Self { - Self::InvalidParams { message: error.message().to_owned() } - } -} - pub type HandlerFn = Arc< - dyn Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> + dyn Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> + Send + Sync, >; @@ -233,19 +149,24 @@ pub type HandlerFn = Arc< /// with a hand-written `HostDispatch` at `host_key("managementMethods")`: the handler /// carries a cancellation token and a progress sink, which are not serde data, so the /// marked-service macro cannot bind `register`. Rust callers use this trait directly; -/// other languages register through the dispatch, as the current `ForeignMethods` does. +/// other languages register through the same dispatch. pub trait ManagementTable { fn register( &self, caller: &Ctx, - request: RegisterRequest, + namespace: String, declarations: Vec, call: HandlerFn, - ) -> BoxFuture<'static, Result<(), TableError>>; + ) -> BoxFuture<'static, Result<(), MethodError>>; - fn call(&self, request: CallRequest, cancelled: CancelledFn) - -> BoxFuture<'static, Result>; + fn call( + &self, + method: String, + params: serde_json::Value, + caller: Option, + cancelled: CancelledFn, + ) -> BoxFuture<'static, Result>; } ``` -`ManagementTable` is the native spelling; the catalog name is `managementMethods` and the foreign registration uses the hand-written dispatch, because a handler's token and progress sink are not data. A native part implements the trait; the same table serves `call` in process and on the wire. +`ManagementTable` is the native spelling; the catalog name is `managementMethods`. The same table serves `call` in process and on the wire. diff --git a/docs/design/plugins/UiResources.md b/docs/design/plugins/UiResources.md index 8e4c0cb27c..9efbd300d9 100644 --- a/docs/design/plugins/UiResources.md +++ b/docs/design/plugins/UiResources.md @@ -58,7 +58,7 @@ FileStorage's stateless `read {path, offset?, length?} → ReadReply {data, eof, | `withdraw` | Withdraw a reference this row published | `{reference}` | `{}` | None; the owner waits for admitted reads | `resource_gone`, `invalid_params`, `session_closed` | | `read` | One bounded page of a published file | `{sessionId, id, offset?, limit?}` (the client method's flat shape) | `{offset, bytes, total, media_type, data}`; `total` is the size recorded at publish, and `eof` is `offset + bytes == total` | The caller's token; the page stops, the reference stays | `resource_gone`, `invalid_params`, `resource_unavailable`, `session_closed` | -`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. `publish` records the resolved path and the file's `size` from FileStorage's `stat`; it opens no reader. The recorded size is the page total, so the client's paging bounds stay stable across pages. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. +`publish` takes the calling row's context as the binding's caller parameter, not as a request field: the reference belongs to the row that calls, and the owner registers the cleanup on that row. `publish` records the resolved path and the file's `size` from FileStorage's `stat`; it opens no reader. The recorded size is the page total, so the client's paging bounds stay stable across pages. A published path must not be replaced while the reference is published: each page is read by path, so a replacement the size check cannot see would mix two versions under one reference, which the [client contract](../client-ui-extensions.md) forbids. A size change is detected and answers `resource_unavailable`; a same-size replacement is the publisher's violation, and it publishes a new reference instead. The Rust binding and the wire call the same method; rutis supplies the calling row's context on the wire. The media type decides inline display: a listed image, audio, video, text or PDF type is served as declared; any other type is served as `application/octet-stream` and marked as an attachment.