diff --git a/docs/architecture/rust-agent/plugins/SessionMethods.md b/docs/architecture/rust-agent/plugins/SessionMethods.md index 0c3d4a4523..fae3f6eaa6 100644 --- a/docs/architecture/rust-agent/plugins/SessionMethods.md +++ b/docs/architecture/rust-agent/plugins/SessionMethods.md @@ -4,7 +4,7 @@ Owner: [methods.rs](../../../../crates/dim-agent-capabilities/src/methods.rs). Keeps the Session's method table, `sessionMethods`: the method namespaces the Session's parts register with it, which Rpc reads on each call to dispatch a Session method through the Session. Contract: -[methods contract A.1](../../../design/contracts/session-boundary.md#a1-method-contributions). +[SessionMethods](../../../design/plugins/SessionMethods.md). ## Dependencies @@ -17,24 +17,33 @@ accepted. The value is also the data face `reservedMethods`: a row of another language asks `check {namespace, declarations}` the same question ([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个)). +The contract also answers a withdrawn namespace from the row that registered it. +Rpc reads that row today (`session_provider` in +[dim-app-server/src/methods.rs](../../../../crates/dim-app-server/src/methods.rs)); +the table itself has no readable face for it, and the read is raised in the +contract ([SessionMethods §4 rule 8](../../../design/plugins/SessionMethods.md#requirements-raised-to-mechanism-owners)). + ## Events and lifetime -No Timeline events, worker tasks or I/O. A part depends on `sessionMethods` and -calls `register(ctx, namespace, declarations, handler)` from its own `apply`; -the registration is withdrawn when that part unloads, and a namespace registered -already fails +No Timeline events or I/O. Each registration tracks the calls it accepted, so +its unload can interrupt them and wait. A part depends on `sessionMethods` and +calls `register(ctx, namespace, declarations, call)` from its own `apply`, with +the part's own function as `call`; the registration is withdrawn when that part +unloads, and a namespace registered already fails ([rutis usage R6](../../../design/rutis-usage.md#r6-contributions-register-with-their-owner)). A refused registration fails the part. A part of another language calls `sessionMethods.register(namespace, declarations, call)` through the bridge; the registration belongs to the calling row, and `call` is the row's function, -called back through the bridge. The table provides that entry itself, at its -dispatcher key, with the native service. +called back through the bridge. Today `ForeignMethods` provides that entry; +the target removes it, and the table serves the entry itself at its dispatcher +key. A name belongs to the longest namespace that holds it. When a namespace is -withdrawn, the table keeps the row that registered it, so Rpc answers a call -into it from that row's status (`service_reloading` or `service_unavailable`) -rather than `unknown_method`. Each registration owns the calls it admitted: its -part's unload interrupts `report` calls and waits for every admitted call. +withdrawn, the table keeps the row that registered it, so a call into it answers +`service_reloading` or `service_unavailable` from that row's status. Today a +withdrawn namespace whose row is absent from the loader answers +`service_reloading`; the target contract answers `unknown_method` there, as it +already does for a disabled row and for a name no namespace ever held. `session.methods` lists the methods of the namespaces registered now that no management namespace holds. diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 0bbd6f4f3c..b87d0821e7 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ Status: Draft. Overall design: [overview §3 integration](../overview.md#3-integration-by-existing-mechanisms), [Appendix B Rpc and ToolRegistry](../overview.md#appendix-b-supplements-to-existing-plugins); rules: [ADR 002](../../adr/002-plugin-scope.md) D2, D3, D5. Phase: P0. Language: neutral contracts; Rust binding in [Appendix F](#appendix-f-rust-binding). The [C4 binding](../session-typescript.md) implements a non-Rust Session tool/method subset; Session broadcast uses the separate C4 leaf observation contract. -This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope; its methods take and return serializable data; errors are data; cancellation is a protocol action. A part of any language depends on the service of its scope and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc reads the two method tables on each call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). +This contract defines three registration services in the language-neutral form of ADR 002 D5: the Session's `sessionMethods` and `toolRegistry`, and the process's `managementMethods`. Each is identified by a service name and a scope. A method registration takes the namespace and its declarations as data and the caller's function as a callback; a tool registration takes its declaration and its execute function. The Session table's `call` is the owner's in-process operation ([SessionMethods](../plugins/SessionMethods.md#own-contract)); errors are data; cancellation is a protocol action. A part of any language depends on its scope's service (a method table or a registry) and registers from its own `apply`: a method namespace with `sessionMethods` or `managementMethods`, a tool with `toolRegistry`. A registration belongs to the part that made it and is withdrawn when that part unloads. Rpc dispatches each table's `call` on every call and depends on no provider. They are built on mechanisms the runtime already has: named services per scope, Rpc's existing dispatch through the Session, as `approval.respond` does today, and registrations that are effects of their caller. Implementation status: method namespaces (#14, C1, #382) and tools (#382) register through the Rust bindings in Appendix F and the owners' contracts, and parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)); of `callChannel`, per-call `progress` (C1) and connection-bound notifications `notify` and `closed` (#1158) are implemented; `takeFinalReply` and general plugin installation are not, nor are `ConnectionEntry {name, deviceId}`, routing by `deviceId` and exported rutis links (proposed for P3, with RemoteGateway). | Service | Scope | Registers | Registered by | Read by | | --- | --- | --- | --- | --- | @@ -54,11 +54,11 @@ flowchart LR | Service | Absent | | --- | --- | -| `sessionMethods` | `unknown_method` when no namespace of the Session ever held the name; when the namespace that holds it is withdrawn, `service_reloading` while the part that registered it starts or reloads and `service_unavailable` once it failed or cannot run (A.1) | +| `sessionMethods` | `unknown_method` when no namespace of the Session ever held the name, or when the row that registered its withdrawn namespace is disabled or absent; when the namespace that holds it is withdrawn, `service_reloading` while the part that registered it starts or reloads or has no copy in the Session, and `service_unavailable` once it failed or cannot run (A.1) | | `managementMethods` | `unknown_method` when no namespace ever held the name, or the row that registered it is disabled or absent; a withdrawn namespace otherwise answers from that row's status (§3.2) | | Tool registration | A tool the Session's mount list names that no part has registered is not declared and is reported in diagnostics; it is declared from the next request once a part registers it (A.5) | -Contracts defined here: the two method tables and their registration, tool registration, `MethodDecl`, `MethodCall`, `MethodReply`, `MethodError`, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. +Contracts defined here: method registration for both tables, tool registration, the `session.methods` listing method, the `callChannel` companion service (`progress`, `notify` and `closed` implemented), `ToolDeclaration`, `ToolCall`, `ToolResult`, its effect declaration, what each entry is served, naming, reserved names, the migration of existing management methods and the compatibility table. A declaration's wire fields are A.1's declaration block below; the call-data types it names — `MethodDecl`, `MethodCall`, `MethodReply` and `MethodError` — are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s. Contracts used: `SessionConfig` ([session-access](session-access.md#a3-sessionconfig-fields)), source input conventions ([session-access A.2](session-access.md#a2-source-input-conventions)), the Rpc command envelope and `appError` codes. ## 2. Data and state @@ -81,15 +81,15 @@ sequenceDiagram Rpc->>Rpc: not a built-in, no management namespace holds it, sessionId in params, authorize Session access Rpc->>AI: acquire(sessionId), restoring if unloaded AI-->>Rpc: Session lease - Rpc->>S: owner of session.question.respond - S-->>Rpc: provider of namespace session.question - Rpc->>Q: call(MethodCall) + Rpc->>S: call {method, params, caller?} + S->>Q: the handler of the longest namespace holding the name Q->>H: hand the answer to the waiting call (branchId, requestId, callId) - Q-->>Rpc: MethodReply + Q-->>S: MethodReply + S-->>Rpc: MethodReply Rpc-->>CL: result ``` -The name belongs to the longest namespace registered in that Session that holds it (A.1). If no namespace of the Session ever held the name, for example because its plugin is not enabled for the Session, the result is `unknown_method`; if the namespace that holds it is withdrawn, the result is `service_reloading` while the part that registered it starts or reloads, and `service_unavailable` once that part failed or cannot run (A.1). Session methods carry no level: every connection that is served Session methods is served all of them, including `shell.*`. +The name belongs to the longest namespace registered in that Session that holds it (A.1). If no namespace of the Session ever held the name, for example because its plugin is not enabled for the Session, the result is `unknown_method`; if the namespace that holds it is withdrawn, the result is `service_reloading` while the part that registered it starts or reloads or has no copy in the Session, and `service_unavailable` once that part failed or cannot run; a registering row that is disabled or absent is `unknown_method` (A.1). Session methods carry no level: every connection that is served Session methods is served all of them, including `shell.*`. ### 3.2 Management method @@ -116,9 +116,9 @@ Each process part that serves management methods depends on `managementMethods` | Scenario | Order | Outcome | Owner | | --- | --- | --- | --- | | Session-scoped provider reloads mid-call | call < reload | `report`: `operation_interrupted`; `drain`: the call's own result; the provider's unload waits for every admitted call (AGENTS.md rule 8) | Provider | -| Session method while the Session's capabilities reload | — | `service_reloading` | Rpc | -| Session method whose namespace is withdrawn and whose registering part failed or cannot run | — | `service_unavailable` until the part is fixed (A.1) | Rpc | -| Session method that no namespace of the Session ever held | — | `unknown_method` | Rpc | +| Session method while the Session's capabilities reload | — | `service_reloading` | Session method table | +| Session method whose namespace is withdrawn and whose registering part failed or cannot run | — | `service_unavailable` until the part is fixed (A.1) | Session method table | +| Session method that no namespace of the Session ever held | — | `unknown_method` | Session method table | | Management owner reloads | — | Calls into its withdrawn namespace return `service_reloading` until the new generation registers it again; a Failed, Unresolved, Stopped or Disposed owner returns `service_unavailable` (§3.2); admitted calls belong to the provider and follow their `interruption`; Rpc does not reload and connections stay open | Rpc | | Management method or `daemon.shutdown` on a connection with a `deviceId` | — | `unknown_method` | Rpc | | Two parts register one namespace in one table | registration | The second registration is refused (` is registered already`) and the part that made it fails | Method table | @@ -138,11 +138,13 @@ Methods have no model-visible effect. A method that changes model context does s | Service and method | Mode | Purpose | | --- | --- | --- | -| `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads | +| `sessionMethods.register(namespace, MethodDecl[], call)` | async | Register a Session method namespace until the calling part unloads; the registering row is the binding's `&Ctx`, not a request field, and the shape is [SessionMethods](../plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | Register a management namespace until the calling part unloads | | `call(MethodCall, cancelled, progress) -> MethodReply` (the registering part's function) | async | Execute a method of the namespace | +| `sessionMethods.call {method, params, caller?}` | in-process | Dispatch one Session method; the table answers `closed` once the Session is closing, else `unknown_method`, `reloading` or `unavailable`, and an interruption answers in its reply ([SessionMethods](../plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.methods {}` | sync | The declarations of the namespaces the Session registered now | | `session.methods {sessionId}` (wire, Rpc built-in) | async | List a Session's methods (protocol v3) | -| `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented, Appendix F) | +| `callChannel.progress / notify / closed` (App Server) | sync / async | Per-call progress and connection-bound notifications (implemented; `Progress` and `Caller` are [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s) | | `toolRegistry.register(ToolDeclaration, execute)` | async | Register a tool until the calling part unloads | | `execute(ToolCall, cancelled) -> ToolResult` (the registering part's function) | async | Tool execution | @@ -157,7 +159,7 @@ Proposed (P3, with RemoteGateway; not implemented): the connection's `Connection | §4 rule 1 (command events) | Not applicable: the services write no Timeline event themselves; a method that changes branch state calls its owner, which writes (for example InputQueue's `input/deleted` for `session.input.withdraw`). | | §4 rule 2 (handover) | Not applicable: methods and tool contributions hand nothing over; a tool call is handed to ToolExecutor by the existing `step/tool-call` contract. | | §4 rule 3 (before callbacks only) | Rpc validates only param shape and `sessionId` authorization; feature checks belong to the method's owner, and acting before a commit is left to Timeline before callbacks. | -| §4 rule 4 (no business meaning in core) | The method tables and ToolRegistry keep what parts register, and Rpc reads the tables; none names a provider or interprets a method. The effect declaration is carried on the result unchanged, and no part of the core names one of its kinds (A.6). | +| §4 rule 4 (no business meaning in core) | The method tables and ToolRegistry keep what parts register, and Rpc calls their operations; none names a provider or interprets a method. The effect declaration is carried on the result unchanged, and no part of the core names one of its kinds (A.6). | | §4 rule 5 (batch) | Not applicable: no decision here is taken on a Timeline event; owners decide from their own facts. | | §4 rule 6 (model context) | Methods have no model-visible effect, and a registered tool reaches the model only through its declaration and `ToolResult` (§5). | | §4 rule 7 (public events and services) | Providers reach branches only through the branch's public services, and Rpc dispatches only through the Session's `sessionMethods`. | @@ -168,7 +170,7 @@ Proposed (P3, with RemoteGateway; not implemented): the connection's `Connection | ADR 002 D2 | No port or Management plugin; method namespaces register with the method table of their scope and tools with ToolRegistry, which owns the Session's tools. | | ADR 002 D3 | Providers depend on their own or an enclosing scope, including the method table they register with. The method tables and ToolRegistry follow registration and withdrawal and do not depend on the parts that register (A.1, A.5); Rpc depends neither on management providers (§3.2) nor on Session method providers (A.1), so their reloads stay within their namespace. | | ADR 002 D4 | A link's management export is structural host-local configuration; no business configuration is defined here. | -| ADR 002 D5 | Every service is named with scope and data-only methods, and a part of any language registers a method namespace or a tool with the same data and its own function (`call`, `execute`); Rust types appear only in Appendix F. The implemented binding is a subset of these shapes (A.1, Appendix F). | +| ADR 002 D5 | Every service is named with scope and data-only methods, and a part of any language registers a method namespace or a tool with the same data and its own function (`call`, `execute`); Rust types appear only in each owner's binding: [SessionMethods](../plugins/SessionMethods.md#binding-appendix) for the Session table, the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) for it, and ToolRegistry's for tools. The implemented binding is a subset of these shapes (A.1). | ## 9. Requirements raised to mechanism owners @@ -188,26 +190,30 @@ Withdrawn: rutis is an external dependency, so no requirement is raised to it. R | Item | Content | | --- | --- | -| Blocked by | Rpc answers a withdrawn Session namespace from the copy, in that Session's instance, of the row that registered it (A.1). Rpc holds the `Session` handle, which does not say which instance its rows run in. | +| Blocked by | Rpc answered a withdrawn Session namespace from the copy, in that Session's instance, of the row that registered it (A.1). Rpc holds the `Session` handle, which does not say which instance its rows run in. The answer moved to the Session table, which reads its own instance from its names ([SessionMethods](../plugins/SessionMethods.md#own-contract)); the capability below stays implemented and remains available to other callers. | | Existing mechanisms considered | `Session::diagnostics` walks the Session's plugin tree on every such call. A Session part that provides its own scope as a public service adds a part to every Session only to republish what the facade already holds. | | Generic capability | `Session::instance()`, the Session's `InstanceId`, the instance its parts' names resolve in (`Names::instance`). Keys under it stay readable only from inside the Session (rutis refuses an instance key outside its instance), so it opens no service beyond `PublicService`. | | Effect on sequence, batch, interrupt, reload | None. The Session scope plugin refuses to reload, so the instance does not change while the Session is loaded; on a closed Session the read fails with `Closed`, as the other facade reads do. | | Owner and issue | Runtime (Session facade); implemented for [#207](https://github.com/arcships/dim/issues/207). | +The table's own row-status read is the §4 rule 8 request in [SessionMethods](../plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) ([#2021](https://github.com/arcships/dim/issues/2021)). + The implemented foreign Session subset is [C4](../session-typescript.md); general plugin installation remains separate work. ## Appendix A. Interface details -Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). Every error is `MethodError` data. +Shapes are JSON with camelCase fields; a `?` after a field name marks it optional and `|` separates alternatives. These shapes are canonical: plugin documents use these field names (Rust bindings map them to snake_case). The call data and the table's error kinds are the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; a handler answers its own `{code, message, ...owner fields}` failure, and the client receives every error in the Rpc envelope `{code, message, data: {appError, ...owner fields}}`. A handler of another language receives its call as `{method, params, origin?: {caller: {connectionId, callId}}}`, the bridge's encoding of `MethodCall`; `callId` is present exactly when the call arrived on a connection, and `origin` is absent for a call that did not. ### A.1 Method contributions -`sessionMethods` (Session) and `managementMethods` (process) are method tables with the same method, `register`. A part registers each namespace it serves with the table of its scope, and the table calls back the part's own `call`. Parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)) and reach the native call admission of Appendix F. +The call data of both tables — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) contract's; this appendix keeps the client error, interruption and routing behavior that the redesign does not change. + +`sessionMethods` (Session) and `managementMethods` (process) are method tables with the same method, `register`. A part registers each namespace it serves with the table of its scope, and the table calls back the part's own `call`. Parts of other languages register through the same services ([C4](../session-typescript.md), [process rows](../process-typescript.md)) and reach the owning table's binding: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), and the process table's is its contract's ([#2021](https://github.com/arcships/dim/issues/2021)). | Method | Mode | Request | Reply | | --- | --- | --- | --- | | `register` (the table's) | async | `namespace`, `MethodDecl[]`, `call` | Nothing once registered; an error when refused | -| `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply`, or `MethodError` | +| `call` (the registering part's function) | async | `MethodCall`, `cancelled`, `progress` | `MethodReply` data: the handler's value, or its own `{code, message, ...owner fields}` error | ```text // MethodDecl @@ -215,37 +221,29 @@ Shapes are JSON with camelCase fields; a `?` after a field name marks it optiona "mutating": true, "interruption": "report" | "drain", // the provider replies on unload: report → operation_interrupted; drain → the call's own result "progress": false, - "notifications?": ["session.goal.changed"], // inside the namespace - "reply": "direct" | "handoff" } // handoff: daemon.shutdown -// MethodCall -{ "callId": "string", "method": "session.goal.set", - "params": {}, // as sent; Session methods keep sessionId (and branchId) here - "origin": { "entry?": { "name": "string", "deviceId?": "string" }, // the connection's ConnectionEntry - "connectionId?": "string", "peer?": "string" } } // peer: rutis link; diagnostics only -// MethodReply -{ "kind": "value", "value": {} } | { "kind": "handedOff" } -// MethodError -{ "code": -32000, "appError": "string", "message": "string" } + "notifications?": ["session.goal.changed"], // equal to or inside the namespace + "reply?": "direct" | "handoff" } // handoff: daemon.shutdown; accepted and ignored until handoff exists +// MethodCall, MethodReply and the table's errors: [SessionMethods](../plugins/SessionMethods.md#binding-appendix). ``` -Implemented today (Appendix F): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (`origin.connectionId` on the wire); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply`, `handedOff`, `origin.entry` and `origin.peer` are not implemented. +Implemented today ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)): `MethodDecl.name`, `MethodDecl.mutating`, `interruption`, `progress` and `notifications`, and `MethodCall.method`, `params` and `origin.caller` (a native handler receives A.2's `Caller`; today's wire carries a top-level `callId` and a flat `origin.connectionId`, and the target nests them as `origin.caller`); the foreign `register` decodes these fields from a foreign part's declarations, supplies a fresh `callId` to each call, and adds `origin.connectionId` when the call came from a connection. `reply` is the target's field: today's `MethodDecl` has none, and the target accepts and ignores it until handoff exists; reply handoff is not implemented, and the target removes `origin.entry` and `origin.peer`. Cancellation and interruption: the provider replies to its own calls, not Rpc. Two events interrupt an admitted call: the unload of the provider's generation and the unload of the Rpc load that admitted it. On either, the handler's cancellation token fires, for `drain` calls too. A `report` call then replies `operation_interrupted` at once (the operation may already have committed) and settles afterwards; a `drain` call replies with its own result. The provider's unload waits for every call it accepted, `report` calls included. A caller's disconnect cancels nothing. | Rule | Content | | --- | --- | | Namespace | `(.)*`, segments `[a-z][a-z0-9_]*`, at most 128 bytes, owned by the part that registers it; a namespace may itself be a method (`session.rename`). A namespace outside this grammar is refused when it registers, and a called name outside it is `unknown_method` without any lookup | -| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations (at least one method, each unique and inside the namespace) and its `call`. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | +| Registration | A part registers a namespace with the table of its scope from its `apply`, with its declarations and its `call`. The declaration rules — at least one method; names unique and equal to or inside the namespace; notifications equal to or inside it, unique and never a method's name — are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. In Rust the part passes its ctx; from another language the bridge ties the registration to the calling row, and `call` is that row's function, called back through the bridge. The registration belongs to that part and is withdrawn when it unloads. A second registration of the same namespace in one table fails (` is registered already`). The table checks the namespace and declarations when they are registered (Reserved names below); a refused registration fails the registering part | | Ownership | A name belongs to the longest namespace registered in that table that prefixes or equals it. A withdrawn namespace keeps holding its names: the table remembers the row that registered it, and a call answers from that row's status (§3.2; Session-scoped call below). A name no namespace of the table ever held has no owner | -| Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | +| Reserved names | Checked when a namespace registers. Exact built-ins are the names `is_builtin_method` accepts ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs)). The declaration and notification rules are the [SessionMethods](../plugins/SessionMethods.md#own-contract) contract's. A declared notification may not take a built-in notification's wire name, the `Notification` variants' names: a provider cannot impersonate a notification its connection already reads. Management: the namespace follows the grammar, does not lie in a reserved root (`hello`, `daemon`, `agent`, `approval`, `session`), has no prefix equal to an exact built-in, and declares no method equal to one ("Invalid management namespace", "Invalid management contribution"); no exact built-in lies inside a management namespace, because every exact built-in lies under a reserved root. Session: App Server provides the process value `ReservedMethods`, which each Session's table consults; a namespace outside the grammar, in the roots `hello`, `daemon`, `agent` or `approval`, or that equals, contains or lies inside an exact built-in is refused ("invalid Session namespace "). For example `session.mcp` is an exact built-in, so `session.mcp`, `session.mcp.extra` and the bare `session` root, which contains it, are refused. A Session namespace may lie under `session` (`session.goal`, `session.input`). `session.input` is not reserved: InputQueue registers it with `sessionMethods`, so Rpc names no owning service | | Precedence and routing | A built-in method; else a name a management namespace holds, registered or withdrawn, goes to management (§3.2); else, for protocol v3+, a name in the grammar whose params object has a `sessionId` field is a Session method candidate (Session-scoped call below); else management, where a name no namespace holds is `unknown_method`. One wire name space. A name whose params have no `sessionId` is never a Session method candidate: Rpc cannot know a Session's namespaces without the Session, so a name only a Session namespace holds is `unknown_method` without one | | Namespace collisions | No assembly check: routing precedence decides. A Session namespace that equals, contains or lies inside a management namespace registers, but the names a management namespace holds route to management and never reach the Session | -| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then reads the name's owner in that Session's `sessionMethods`: a registered namespace → its provider; a withdrawn namespace → the status of the registering row's copy in this Session (§9.4), read with the management table (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held → `unknown_method`. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | -| Call ownership | The Session-scoped provider generation owns the calls it admitted, as a management provider does: it replies to them, its unload interrupts them per `interruption` and waits for them (Cancellation above) | -| Shared types | `MethodDecl`, `Interruption`, `Handler`, `Progress`, `RpcError` and `MethodTable`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. They sit beside the Session table `SessionMethods` (Appendix F), as `ToolContribution` and `ToolHandler`, which also takes a `CancellationToken`, live beside ToolRegistry. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | +| Session-scoped call | Rpc reads `sessionId` from a candidate's raw params; one that is not a non-empty string is `-32602` (an empty one is `invalid_params`, "sessionId must not be empty"). Rpc authorizes it and acquires the Session through `index.acquire`, which restores an unloaded Session (unlike `approval.respond`, which returns `session_closed` for a Session that is not loaded); a non-empty Session id that names no Session is `session_closed`. Rpc then calls that Session's `sessionMethods.call {method, params, caller?}` ([SessionMethods](../plugins/SessionMethods.md#own-contract)): the table finds the name's owner and answers its own errors. A registered namespace's handler replies; a withdrawn namespace answers `service_reloading` or `service_unavailable` from the status of the registering row's copy in this Session (§3.2): `service_reloading` while that copy is not started, Pending, Loading or between generations, `service_unavailable` while it is Failed, Unresolved, Disposed or Stopped, and `service_reloading` when the copy is Active (a child plugin of the row reloads) or there is no copy (a part between generations); a name no namespace of this Session ever held, and a name whose registering row is disabled or absent → `unknown_method`; while `loaderRows` is not installed, a withdrawn namespace answers `service_reloading` instead. Rpc holds the Session use until the call's operation settles. `sessionId` and `branchId` stay inside `params`; Rpc reads `sessionId` only to authorize and resolve. The provider reaches a branch through that branch's services. A name a management namespace holds, or whose params have no `sessionId`, never restores a Session | +| Call ownership | Each registration owns the calls it admitted, as a management registration does: it replies to them, its row's unload interrupts them per `interruption` and waits for them (Cancellation above) | +| Shared types | `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError`, with the call admission both tables share, live in a `methods` module of dim-agent-capabilities, because Session capabilities there cannot depend on dim-app-server. Their one definition is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding. Not dim-agent-types: it admits only serde and serde_json (`xtask check`; [architecture](../../architecture/README.md): no Tokio or rutis), while `Handler` takes tokio-util's `CancellationToken` and returns a rutis `BoxFuture`; and with `RpcError` there, `From for RpcError` could be implemented only in dim-agent-runtime (orphan rule). In dim-agent-capabilities that conversion lives with `RpcError`, so Rpc and Session providers keep `?` on runtime errors | | Not dispatched | No namespace of the table ever held the name, the row that registered its withdrawn namespace is disabled or absent (or, for management, Active without registering it again), the provider does not declare the name, a name only a Session namespace holds called without `sessionId` in its params, a management method on a connection with a `deviceId`, an unexported link or the bare WebSocket, or v1/v2 → `-32601 unknown_method`. Session reloading, or a withdrawn namespace whose registering row (for a Session namespace, that row's copy in the Session) is not started, Pending, Loading or between generations, or a withdrawn Session namespace whose copy is Active or absent → `-32000 service_reloading` (retryable). A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped → `-32000 service_unavailable` (not retryable). A Session id that names no Session → `session_closed`. A started `report` call interrupted → `operation_interrupted` | | `hello.features` (v3) | Built-ins, plus, when the connection is served management methods (local v3), the methods of the management namespaces registered at that call, each listed only under the namespace that owns it. Session-scoped methods are not listed here; `session.methods` lists them per Session | -| `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. v3 `hello.features` lists it where Session operations are served | +| `session.methods` | Public surface, an Rpc built-in for protocol v3, like the methods it lists: `session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`, the declared methods of the namespaces registered in that Session now, except the names a management namespace holds, which routing sends to management even when the call names a Session. It is authorized and resolved like other Session-scoped built-ins (restoring an unloaded Session), lists each method under the namespace that owns it, sorted by name, and adds one exact built-in name. It answers `service_unavailable` while the process is closing, because it cannot read the names a management namespace holds. v3 `hello.features` lists it where Session operations are served | | Ready latch | The native binding waits for its required process providers before the first `hello`. The [TS process binding](../process-typescript.md#21-startup-and-availability) excludes optional extension rows from host startup/restart readiness; `hello.features` lists only the namespaces registered at that call, with later ones visible at the next `hello`. | How Rpc routes a call once the connection's entry admits it: @@ -267,22 +265,23 @@ call authorize; index.acquire (restores an unloaded Session; | an unknown id -> session_closed) | - owner in the Session's sessionMethods? -------- none ------> -32601 unknown_method + sessionMethods.call {method, params, caller?} -> the table finds the owner + | none ------> -32601 unknown_method | withdrawn -> the registering row's copy - | in this Session (§9.4, §3.2): + | in this Session (§3.2): | starting or reloading, Active or no copy | -> -32000 service_reloading | Failed, Unresolved, Disposed or Stopped | -> -32000 service_unavailable | registered - provider call --> reply (an undeclared name: -32601 unknown_method) + the handler -> CallReply (an undeclared name: -32601 unknown_method) ``` Session namespaces registered today: `session.question` (Questions), `session.goal` (Goal), `session.rename` (SessionTitle), `session.input` (InputQueue), `session.context` (ContextCompaction), `session.exec.output` (WorkspaceTools, [background task output](../background-task-output.md)), `session.agent` ([model configuration](../model-configuration.md)), `session.language` (App Server, [PromptSources §3](../plugins/PromptSources.md#3-the-agent-prompt-language-state-source)), `attachment` (Attachments), `shell` (ShellInput), `session.wakeup` (Scheduler, [Scheduler §10](../plugins/Scheduler.md#10-session-scoped-wakeup)), `session.collaboration` (Collaboration, [Collaboration §6.7](../plugins/Collaboration.md#67-stopping-a-member-from-the-client)). `approval.respond` is a built-in Session method, not a part registration. The branch methods — `session.branch_create`, `session.branch_end`, `session.branch_set_default`, `session.branches` and `session.branch.get` — are built-ins too, and their contract is [timeline branches §9, §10 and §14](../timeline-branches.md#14-clients): each `branchId` they take names one line, and one that is omitted names the Session's default branch, not its root. `session.branch_set_default` accepts the root as a target whenever it is not the default branch and refuses only a target that is already the default branch; `session.branch_end` refuses the default branch for every caller, so ending it takes a move of the default branch first. Hooks registers no Session namespace: its `hooks.*` methods are management methods ([Hooks A.7](../plugins/Hooks.md#a7-management-methods)). Each plugin document is authoritative for its methods. ### A.2 Call channel -`progress`, `notify` and `closed` are implemented (C1, #1158); `takeFinalReply` is not. App Server provides the process service `callChannel` to method providers, from its own `CallChannel` row so that a row naming it does not reload with Rpc; the Rust binding is the handler's per-call `Progress` and `Caller` (Appendix F). +`progress`, `notify` and `closed` are implemented (C1, #1158); `takeFinalReply` is not. App Server provides the process service `callChannel` to method providers, from its own `CallChannel` row so that a row naming it does not reload with Rpc; the Rust binding is the handler's per-call `Progress` and `Caller` ([SessionMethods](../plugins/SessionMethods.md#binding-appendix)). | Method | Mode | Request | Reply | | --- | --- | --- | --- | @@ -298,7 +297,7 @@ How progress of one call reaches its caller: ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., sink of A) ---->|-- handler(.., progress) -->| + | |-- call(.., sink of A) ------>|-- handler(.., progress) -->| | | | (sink only if declared) | |<-- management.progress {id: 7, method: "x.run", data} ------- progress.send -->| | | |<-- result -----------------| @@ -320,14 +319,14 @@ reply ----------> reply and notice allowance ----+ full: a slow consumer, the connection closes ``` -A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the `callId` of the `MethodCall` the provider received. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. +A notification is the JSON-RPC notification `{"jsonrpc":"2.0","method":"","params":{...}}`, written to the calling connection only; other clients of the Session do not receive it. `params` is a JSON object. `callId` is required and names the call whose work the notification reports: it is the id minted for a call served by a registration of another language, which its `origin.caller.callId` carries. A native handler has no such id: it notifies through its `Caller`. While that call's reply is not written its notifications are held and written right after it, in order; once the reply is written, or the id is not in flight, they are written directly. `connectionId` is the address: a row that received no call from it answers `gone`. Only a name a generation that served the connection declared, equal to or inside its namespace, may be sent; any other name answers `undeclared` and nothing is written. How a notification of one call reaches its caller: ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., caller) ->|-- handler(.., caller) -->| + | |-- call(.., site) ----->|-- handler(.., caller) -->| | | | notify(callId, ..) | | | | held: after the reply | | | |<-- result ---------------| @@ -340,7 +339,7 @@ Client A Rpc call admission provider han Delivery differs from progress: - **Reliable.** A notification is encoded once when the provider sends it. One sent while its call's reply is not written is admitted against the connection's held allowance: the same limits as the reply-and-notice allowance (1024 frames, 32 MiB), separate from it, so held notifications never take the room a reply needs. A call that holds past the held allowance is disconnected like a slow consumer, and later `notify` calls answer `gone`. The reply is admitted against the reply-and-notice allowance only. After the reply, the held frames are queued in order with the room they already hold, which is freed as each is written; the connection's queued frames are therefore bounded by the two allowances together, at most 2048 frames and 64 MiB. A notification over the frame limit is refused with `too_large`: nothing is written and the connection stays open. -- **After the reply.** A notification is written after the reply of the call named by its `callId`, which is the `callId` of the `MethodCall` that reported the work. One sent while that call is still running is held in order and written right after its reply, so a client never sees an event that names something the reply has not told it yet (for example an id the reply returns). Once that reply is written, or the id is not in flight, it is written straight to the outbound queue; another unfinished call on the same connection neither holds it nor reorders it. The reply is written on every path, including an interrupted call and a call whose connection is gone. +- **After the reply.** A notification is written after the reply of the call named by its `callId`, which is the id minted for a call served by a registration of another language, carried as `origin.caller.callId`. A native handler has no id: its `Caller` holds the notification until that call's reply is written. One sent while that call is still running is held in order and written right after its reply, so a client never sees an event that names something the reply has not told it yet (for example an id the reply returns). Once that reply is written, or the id is not in flight, it is written straight to the outbound queue; another unfinished call on the same connection neither holds it nor reorders it. The reply is written on every path, including an interrupted call and a call whose connection is gone. - **Lifetime.** `closed` resolves, and later `notify` calls answer `gone`, once the connection has closed or the Rpc load that admitted the call has unloaded. A notification after the provider's generation unloads answers `gone` in both bindings: a native caller holds the generation's stopping signal, and the foreign index removes the instance's entries on the same unload. A caller's disconnect cancels no call. `notify` and `closed` answer `gone` for a connection the row received no call from. The service holds one entry per row instance and connection, with that connection's unfinished calls by `callId`; the entry is removed when the connection closes, when the admitting Rpc load unloads and when the row's generation unloads, and a call leaves it when its reply is written. - **Refusal order.** While the generation is loaded, `undeclared` is decided before the connection's state in both bindings: a closed connection does not hide a name the generation did not declare. A generation that has unloaded answers `gone` for every name, declared or not. @@ -527,9 +526,9 @@ carry the native event whole, and the frozen fixtures stay unchanged. | Session reloading, or a withdrawn namespace whose registering row (or its copy in the Session) is not running and has not failed (not started yet, Pending, Loading, or between generations), or a withdrawn Session namespace whose copy is Active or absent | `-32000`, `service_reloading` (retryable) | | A withdrawn namespace whose registering row, or that row's copy in the Session, is Failed, Unresolved, Disposed or Stopped | `-32000`, `service_unavailable` (not retryable) | | `report` call interrupted | `-32000`, `operation_interrupted` | -| Provider error | `-32000`, provider's `appError` | +| Handler error | the JSON-RPC code the handler's failure carries, when it carries one, otherwise the code Rpc gives a service error (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000), with the handler's `appError` and its owner fields | -Native method errors may include owner-defined JSON fields beside `data.appError`. +A handler's failure may carry owner-defined JSON fields in `data` beside `data.appError`. The method owner defines and supplies their safe public shape; the method table and Rpc preserve them without interpreting them. These fields must not shadow `appError` or built-in error fields. An error without additional fields keeps its @@ -537,7 +536,7 @@ existing wire shape. ## Appendix D. Acceptance -1. A Session-scoped method dispatches through the Session it names. A name no namespace of that Session ever held returns `unknown_method`; a withdrawn namespace returns `service_reloading` while the part that registered it starts or reloads and `service_unavailable` once that part is Failed or Unresolved; Rpc never names the provider. A Session namespace that overlaps a built-in or lies in a reserved root is refused when it registers, and one inside a management namespace never receives the names that namespace holds. +1. A Session-scoped method dispatches through the Session it names. A name no namespace of that Session ever held returns `unknown_method`, and so does one whose registering row is disabled or absent; a withdrawn namespace returns `service_reloading` while the part that registered it starts or reloads or has no copy in the Session, and `service_unavailable` once that part is Failed or Unresolved; Rpc never names the provider. A Session namespace that overlaps a built-in or lies in a reserved root is refused when it registers, and one inside a management namespace never receives the names that namespace holds. 2. A management method is reachable on the local entry, returns `unknown_method` on RemoteGateway, and is reachable over a link only when exported. A `shell.*` Session method is reachable on RemoteGateway like every Session method. 3. A recorded transcript of every migrated management method matches the pre-migration transcript, and `hello.features` is unchanged for v3 local profiles. 4. On a RemoteGateway test entry, `session.permission.update` and `session.exec.stop` succeed. @@ -557,81 +556,27 @@ existing wire shape. ## Appendix F. Rust binding -The neutral services map to the native owners below. Tools register with ToolRegistry (A.5). Each method table also serves other languages through its own dispatcher: the `SessionMethods` part at `host_key_in("sessionMethods", session_instance)` and App Server's `ManagementMethods` row at `host_key("managementMethods")`. A Session part of another language ([C4](../session-typescript.md)) or a process row ([TypeScript process binding](../process-typescript.md)) injects the table and calls `register(namespace, declarations, call)`, which returns a Promise. The registration belongs to its caller (the bridge's caller row), and `call` is called back through the bridge with C1 admission, progress and `report`/`drain`; admitted calls drain before the caller's cleanup runs. No service lookup by name is added to the Session facade, and entry admission is unchanged. Session parts read Session identity, configuration and closing from the `sessionIdentity`, `sessionConfig` and `sessionLifecycle` services; each listens to its Session's `session/{sessionId}` channel itself. It adds no public facade lookup or critical branch input path. Connection notifications (`notify` and `closed`) are implemented for both bindings; handoff (`takeFinalReply`) remains outside the implemented subset. +The neutral services map to the native owners below. Tools register with ToolRegistry (A.5). Each method table's Rust binding and wire form are its owner's contract: [SessionMethods](../plugins/SessionMethods.md#binding-appendix) for `sessionMethods`, and the process table's contract ([#2021](https://github.com/arcships/dim/issues/2021)) for `managementMethods`. No service lookup by name is added to the Session facade, and entry admission is unchanged. Session parts read Session identity, configuration and closing from the `sessionIdentity`, `sessionConfig` and `sessionLifecycle` services; each listens to its Session's `session/{sessionId}` channel itself. It adds no public facade lookup or critical branch input path. Connection notifications (`notify` and `closed`) are implemented for both bindings; handoff (`takeFinalReply`) remains outside the implemented subset. | Neutral service | Rust type | Registration in Rust | Collection | Status | | --- | --- | --- | --- | --- | | `managementMethods` | `ManagementMethods`, a process service holding a `MethodTable`, provided by App Server's `ManagementMethodsPlugin` row | A process part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Rpc depends on the table and reads it per call (`management_provider`, §3.2), with row status from `loader.get(row)`; no provider is in Rpc's `Deps` | Implemented (#14, #382) | -| `sessionMethods` | `SessionMethods`, a Session service holding a `MethodTable`, provided by the `SessionMethodsPlugin` Session part; its check is the process value `ReservedMethods` App Server provides | A Session part depends on `Keyed` and calls `methods.register(ctx, ns, Vec, Handler)` in its `apply` | Per call: `Session::session_service::()` on the Session `sessionId` names, after `index.acquire`, then `session_provider` (A.1); no provider is in Rpc's `Deps` | Implemented (C1, #382) | +| `sessionMethods` | `SessionMethods`, the Session service from the `SessionMethodsPlugin` part; its check is the process value `ReservedMethods` App Server provides | A Session part calls `register(ctx, namespace, declarations, call)` in its `apply`; the operations, values and wire form are [SessionMethods](../plugins/SessionMethods.md#binding-appendix) | Rpc calls `call` for the Session `sessionId` after `index.acquire`, and `methods` for `session.methods`; no provider is in Rpc's `Deps` | Implemented (C1, #382); the target operations are [SessionMethods](../plugins/SessionMethods.md#binding-appendix) | | Tool registration | `ToolContribution {definition, handler}`, registered with the Session's `ToolRegistry` (`Keyed`) | `tools.register(ctx, ToolContribution)` in the part's `apply`; a dynamic source uses `tools.register_source(ctx, name, provider)` | Every read takes in what is registered; a name the mount list gives that nothing has registered is omitted and reported in diagnostics; each registration is a registry-owned versioned set (A.5, #241) | Implemented (#382) | -| `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel` | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | - -```rust -// crates/dim-agent-capabilities/src/methods.rs (C1), shared by both services -pub type Handler = Arc< - dyn Fn(MethodCall, CancellationToken, Progress) - -> BoxFuture<'static, Result> + Send + Sync, ->; // (call, cancellation token, progress) -impl Progress { - pub fn send(&self, data: Value); // best effort; dropped unless declared, or once the reply is handed over -} -pub enum Interruption { Report, Drain } -pub struct MethodDecl { - pub name: String, - pub mutating: bool, - #[serde(skip_serializing)] - pub interruption: Interruption, // required in foreign declarations - #[serde(skip_serializing)] - pub progress: bool, // required in foreign declarations - #[serde(default, skip_serializing)] - pub notifications: Vec, // inside the namespace, unique across the set -} -impl MethodProvider { // one provider generation: declarations, handler, admitted calls - pub fn new(ctx: &Ctx, namespace: &str, declarations: Vec, handler: Handler, - foreign: bool) // a part of another language: its calls are recorded until the reply - -> Result, CordisError>; - pub fn accept(self: &Arc, method: String, params: Value, site: Option, - entry_stopping: CancellationToken, progress: impl Fn(Value) + Send + Sync + 'static) - -> Result; -} -// A table's check of a namespace and its declarations before they register. -pub type Check = Arc Result<(), CordisError> + Send + Sync>; -pub enum Owner { Active(Arc), Left { row: Option }, None } -impl MethodTable { // the namespaces registered, and those withdrawn with their last row - pub fn new(check: Check) -> Self; - pub fn register(&self, ctx: &Ctx, namespace: &str, declarations: Vec, - handler: Handler) -> Result<(), CordisError>; // until the part that owns ctx unloads - pub fn owner(&self, name: &str) -> Owner; // the longest namespace holding name - pub fn listed(&self) -> Vec; // the registered namespaces' methods -} -pub struct SessionMethods(pub Arc); // Deref -pub struct ReservedMethods(Check); // process value: the Session table's check -// and the data face `reservedMethods`; `check {namespace, declarations}` asks it -// crates/dim-app-server/src/methods.rs -pub struct ManagementMethods(pub Arc); // Deref -``` +| `callChannel` | `progress`: the handler's `Progress` argument, one per call; `notify` and `closed`: the `Caller` of the handler's `MethodCall.origin`, one per call; for other languages the process service `callChannel`. The call data is [SessionMethods](../plugins/SessionMethods.md#binding-appendix)'s | — | Rpc gives each admitted call a sink to its calling connection; the index records a foreign call by its `callId` until its reply is written, and removes the connection's entries on close or unload | `progress`, `notify` and `closed` implemented (C1, #1158); `takeFinalReply` not implemented | -`MethodProvider::new` rejects invalid declarations (the A.1 grammar; at least one method, each unique and inside the namespace; and each declared notification: grammar, inside the namespace, unique across the declaration set and never a method's name) and ties the provider to the generation of the part that registers it: when that generation is cancelled, the first step of its unload and before any of its effects runs, the provider stops admitting and interrupts its admitted `Report` calls, and its unload effect waits for every admitted call, so the two tables cannot diverge. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls are told to settle while the plugin still runs. `MethodTable::register` runs the table's `Check`, builds the provider and registers the namespace on behalf of the part that owns `ctx`; a namespace registered already fails. When that part unloads, the table records its row with the namespace, so a later call answers from that row (`Owner::Left`). The `ManagementMethods` check is the management rule of A.1 Reserved names; the Session table's is App Server's `ReservedMethods`, which the table depends on when the assembly names it; a host that names none reserves nothing, and only the grammar applies. `ReservedMethods` is a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and a Rust table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)). The handler receives the `MethodCall` -- the name, the raw params and its `Origin` -- a cancellation token that fires on either unload (A.1) and the call's `Progress`. `origin.caller` is present when a client connection made the call, through either table, and absent otherwise. `RpcError`, with its `From`, lives in the same module (A.1 Shared types); dim-app-server keeps `ManagementMethods`, the reserved-name checks and Rpc's lookups (`management_provider`, `session_provider`). - -`Progress` binds A.2 `progress` per call rather than through a `callChannel` process service: Rpc passes each admitted call a sink that writes `management.progress {id, method, data}` to the calling connection, and the admission hands it to the handler only when the method declares `progress` and closes it before it hands over the reply. The sink queues progress under its own allowance on the connection, so progress never takes room from the reply or durable notifications. Management methods use the same path; `runtime.watch` and `schedule.watch` declare `progress` ([RuntimeManager §10](../plugins/RuntimeManager.md#10-client-change-notices); [Scheduler §11.2](../plugins/Scheduler.md#112-jobs-and-runs)). - -```rust -// crates/dim-agent-capabilities/src/methods.rs, shared by both services -pub struct MethodCall { pub method: String, pub params: Value, pub origin: Origin } -pub struct Origin { pub caller: Option } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum NotifyError { Undeclared, Gone, TooLarge } // code(): "undeclared", "gone", "too_large" -impl Caller { - 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; -} -``` +The call data — `MethodDecl`, `Interruption`, `MethodCall`, `Origin`, `Caller`, `CallerConnection`, `CallSite`, `MethodReply`, `MethodCallbackError`, `MethodError`, `Handler`, `Progress` and `NotifyError` — with the call admission both tables share, is the [SessionMethods](../plugins/SessionMethods.md#binding-appendix) binding's, in the `methods` module of dim-agent-capabilities. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s, and it lives in the same module for its conversions. The target removes the deref: the Session table holds its own storage and does not deref to `MethodTable`. `RpcError` keeps its `From` there, so Rpc and Session providers keep `?` on runtime errors. The Session table's check is App Server's `ReservedMethods`, a data face: `reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` refuses a namespace the host keeps, and the table consults the same operation in process ([service faces §4.9](../service-faces.md#49-旧主机端口credentialvariableshost-等六个)); a host that names none reserves only the grammar. + +A refused registration fails the registering part: the namespace and its declarations are checked against the name grammar and the reserved names, a namespace registered already in one table fails, and a registration lasts until the row that made it unloads (A.1 Registration). + +`Progress` binds A.2 `progress` per call rather than through a `callChannel` process service: Rpc passes each admitted call a sink that writes `management.progress {id, method, data}` to the calling connection, and the table's `call` hands it to the handler only when the method declares `progress` and closes it before the reply is written. The sink queues progress under its own allowance on the connection, so progress never takes room from the reply or durable notifications. Management methods use the same path; `runtime.watch` and `schedule.watch` declare `progress` ([RuntimeManager §10](../plugins/RuntimeManager.md#10-client-change-notices); [Scheduler §11.2](../plugins/Scheduler.md#112-jobs-and-runs)). + +`Caller`, `CallerConnection`, `CallSite`, `Progress` and `NotifyError` live in the module's binding, stated by [SessionMethods](../plugins/SessionMethods.md#binding-appendix); this appendix states what CallChannel does with them, not their shape. -`Caller` binds A.2 `notify` and `closed` per call, like `Progress`: `MethodProvider::accept` builds it only when the call arrived on a client connection, bound to the notifications its declaration set declared, so a name outside that set is `Undeclared` before anything is written, and a generation that has unloaded is `Gone` first. It holds the connection through a trait object (`CallerConnection`) that keeps no strong reference to it, so a provider that keeps a `Caller` does not keep a closed connection alive. Rpc writes each notification after the reply of the call that produced the caller: one sent while the call runs is encoded once, admitted under the connection's held allowance, held in order and flushed right after the reply; one over the frame limit is `TooLarge` and the connection stays open, and one the held allowance cannot take closes the connection as a slow consumer. The caller resolves `closed` when the connection closes or the admitting Rpc load unloads. +`Caller` binds A.2 `notify` and `closed` per call, like `Progress`: the table's `call` builds it only when the call arrived on a client connection, bound to the notifications its declaration set declared, so a name outside that set is `Undeclared` before anything is written, and a generation that has unloaded is `Gone` first. It holds the connection through a trait object (`CallerConnection`) that keeps no strong reference to it, so a provider that keeps a `Caller` does not keep a closed connection alive. Rpc writes each notification after the reply of the call that produced the caller: one sent while the call runs is encoded once, admitted under the connection's held allowance, held in order and flushed right after the reply; one over the frame limit is `TooLarge` and the connection stays open, and one the held allowance cannot take closes the connection as a slow consumer. The caller resolves `closed` when the connection closes or the admitting Rpc load unloads. -`Callers` is private transport wiring shared by the CallChannel and Rpc rows at its Rust type key; it has no service catalog name. The public operation surface remains `callChannel`. `Callers` is the process's only caller index: per row instance it holds the notification names its generation declared, kept after a connection of that instance closes so `Undeclared` is decided before `Gone`, and per row instance and connection the connection's direct writer and the row's unfinished calls by `callId`. `MethodProvider::accept` mints a foreign call's `callId` where the call's sink, the instance and the provider's declarations meet, and records the call; `Connection::answer` removes it after the reply is written. The entries of a connection are removed when it closes, when the admitting Rpc load unloads and when the row's generation unloads; the declared names go with the instance's generation. A native provider keeps its own `Caller` and records nothing. App Server provides A.2 `callChannel` for other languages as the process service `callChannel` (`ForeignCallChannel`, at `host_key("callChannel")`, from the `CallChannel` row that has no dependencies): its `notify` and `closed` read the calling row's instance with `rutis_bridge::session::caller_row()` and end in the same call's sink the Rust binding uses, so both bindings share one delivery path. +`Callers` is private transport wiring shared by the CallChannel and Rpc rows at its Rust type key; it has no service catalog name. The public operation surface remains `callChannel`. `Callers` is the process's only caller index: per row instance it holds the notification names its generation declared, kept after a connection of that instance closes so `Undeclared` is decided before `Gone`, and per row instance and connection the connection's direct writer and the row's unfinished calls by `callId`. The table's admission mints a foreign call's `callId` where the call's sink, the instance and the provider's declarations meet, and records the call; `Connection::answer` removes it after the reply is written. The entries of a connection are removed when it closes, when the admitting Rpc load unloads and when the row's generation unloads; the declared names go with the instance's generation. A native provider keeps its own `Caller` and records nothing. App Server provides A.2 `callChannel` for other languages as the process service `callChannel` (`ForeignCallChannel`, at `host_key("callChannel")`, from the `CallChannel` row that has no dependencies): its `notify` and `closed` read the calling row's instance with `rutis_bridge::session::caller_row()` and end in the same call's sink the Rust binding uses, so both bindings share one delivery path. -The foreign `register` (`ForeignMethods`, shared by both tables) decodes the declarations once, with the required fields above. It calls `call` with `{callId, method, params}` and, when the call came from a connection, `origin: {connectionId}`, a cancellation Promise and a per-call progress callback, and decodes `{kind:"value", value}` or a `{code, message}` error, whose `code` is the `appError`; an omitted `value`, including JavaScript `undefined` omitted by JSON serialization, becomes JSON `null`. A method may instead rethrow a service error it received. Unsupported declaration/reply fields and malformed data fail at this boundary. Not implemented: final-reply handoff, `origin.entry` and `origin.peer`, and the `reply` declaration field. +Another language registers through the owning table's dispatch: the Session table's is [SessionMethods](../plugins/SessionMethods.md#binding-appendix), the process table's is its own contract ([#2021](https://github.com/arcships/dim/issues/2021)). Each decodes the declarations once and calls the same `register` with the caller's function; `ForeignMethods` leaves. Not implemented in either binding: final-reply handoff. A declaration's `reply` field is accepted and ignored. `ToolContribution` and `ToolHandler` are the native types in `dim-agent-capabilities/src/tool_registry.rs`. `ToolRegistry::register(ctx, ToolContribution)` registers on behalf of the part that owns `ctx`, until that part unloads; it refuses a name outside `[A-Za-z0-9_-]{1,64}`, a host tool's name and a name registered already. Other languages reach `toolRegistry` through ToolRegistry's dispatcher: `register(declaration, execute, options?)` decodes the declaration as `ToolDefinition` once, requires a nonempty `risk`, and registers, on behalf of the calling row (the bridge's `caller_row`), a `ToolHandler` that calls `execute` back through the bridge. `options.concurrency` is `'concurrent'` or absent; it is not part of the declaration, because the class is an execution property of the bound handler, so the persisted `ToolDefinition` keeps its shape. Absent means the tool's calls run alone, in call order. That handler holds the calling row's generation token: once the row starts unloading, a call through a retained handler is not made, and a call in flight ends with an error warning that it may already have taken effect, without rebinding to a replacement generation; the foreign owner still settles its JavaScript work. Each execution derives a child cancellation token so completing one call cannot cancel other tools in the same batch. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..7e4cf2baec 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [SessionMethods](SessionMethods.md) (owner contract) | — | `sessionMethods`: the Session's method namespaces, their admission and the method list | — | [#2026](https://github.com/arcships/dim/issues/2026) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md new file mode 100644 index 0000000000..d41cd02ad9 --- /dev/null +++ b/docs/design/plugins/SessionMethods.md @@ -0,0 +1,653 @@ +# SessionMethods + +Scope: session. Issue: #2026. + +SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The call data both method tables serve — `MethodCall`, `MethodReply`, the handler's own error and the table's error kinds — has one definition, in the `methods` module of `dim-agent-capabilities`; this contract states it. ManagementMethods (#2021) is the process table; Rpc, the registering parts and WebEntry's upload entry are callers. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). + +## Use and scope: responsibility split + +SessionMethods owns: + +- **Registrations.** One namespace per registration, its declarations and its call callback; a row may register several namespaces, and a registration ends when its row unloads. +- **Admission.** One call: the name's owner, the interruption kind its declaration names, the caller identity, and the settlement of the calls a registration accepted. +- **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers `reloading` or `unavailable` from that row instead of falling through to a parent namespace; a row that is disabled or absent is `unknown_method`. +- **Reserved names.** The host's own roots, built-ins and their notification names are refused at registration; a management namespace does not stop a Session namespace from registering (A.1 namespace collisions). The host supplies the check as a process face. +- **The method list.** The declarations of the namespaces registered now, each under its owning namespace. + +Callers keep: + +- What a method means: the registering part declares and implements its namespace. +- Routing: Rpc decides which table a wire name reaches and reads `sessionId` from the params. +- Client methods: Rpc serves `session.methods` and the built-ins; this table answers its own registrations. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the host's refusal are the owner's | `register` | +| Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | +| `session.methods` lists what a Session serves | No: the declarations and the namespace that owns each are the owner's | `methods` | +| The caller learns why a registration was refused | Yes: `register` answers `duplicate`, `invalid` or, in the process table, `reserved`; a separate check would race the next registration | Business | +| Rpc routes a name between management and Session | Yes: the process table answers its own `call` and `heldNamespaces`; Rpc reads `sessionId` | Business | +| A provider notifies its caller | Yes: a native handler has the call's `Caller`, and a handler of another language has `{connectionId, callId}` for `callChannel` (#2021) | Business | +| A process-side caller holding a Session asks the table in process, as WebEntry's upload entry does | Yes: the same `call` without a site | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +A part registers from its `apply`; the registration belongs to that part's row. A refused registration fails the part, so the part turns the `MethodError` into its own `rutis::Error`: + +```rust +methods.register( + ctx, + "session.input".into(), + declarations, + |call, cancelled, _progress| Box::pin(withdraw(call, cancelled)), +) +.await +.map_err(|error| rutis::Error::from(rutis::host::ErrorKind::PluginFailed(error.to_string().into())))?; +``` + +Rpc dispatches one wire call; the caller is the admission's site for this call, `progress` is Rpc's sink for it, and the reply is `MethodReply` data: + +```rust +let reply = match methods.call( + method.into(), + params, + Some(site), + cancelled.clone(), + progress, +).await { + Ok(reply) => reply, + Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), + Err(MethodError::Reloading) => return Err(RpcError::reloading()), + Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), + Err(MethodError::Closed) => return Err(RpcError::closed()), + Err(MethodError::Interrupted) => unreachable!("an interruption answers in the reply"), + Err(MethodError::Invalid { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) => unreachable!("a Session call answers none of these"), +}; +let CallReply { + reply, + registration, + settled, +} = reply; +// Write the reply on every path: the handler's value, its own failure, or an +// interrupted call's `interrupted`. +let written = match reply { + Ok(MethodReply::Value(ValueReply::Value { value })) => Ok(value), + Ok(MethodReply::Error(error)) => Err(RpcError::from(error)), + Err(MethodError::Interrupted) => Err(RpcError::interrupted()), + Err(_) => Err(RpcError::closed()), +}; +``` + +Rpc writes `written` on the calling connection and releases the call's held notifications, then: + +```rust +// The reply is written: end the foreign call's index entry and wait for the +// call to settle, whichever answer went out. +if let Some(registration) = registration { + registration.finish(); +} +settled.await; +``` + +A process-side caller holding a Session, such as WebEntry's upload entry, calls the table without a site and writes its own answer: + +```rust +// An admission failure fails this caller's own operation. +let admitted = match methods.call(method.into(), params, None, cancelled, |_| {}).await { + Ok(reply) => reply, + Err(MethodError::UnknownMethod { .. }) => return Err(RpcError::unknown_method()), + Err(MethodError::Reloading) => return Err(RpcError::reloading()), + Err(MethodError::Unavailable) => return Err(RpcError::app(-32000, "service_unavailable", "The service is unavailable")), + Err(MethodError::Closed) => return Err(RpcError::closed()), + Err(MethodError::Invalid { .. }) | Err(MethodError::Duplicate { .. }) | Err(MethodError::Reserved { .. }) => unreachable!("a Session call answers none of these"), + Err(MethodError::Interrupted) => unreachable!("an interruption answers in reply.reply, not as the outer error"), +}; +let CallReply { reply, settled, .. } = admitted; +// No connection wrote a reply here: `reply` is the handler's answer, or the +// table's interruption, and this caller writes its own answer. +let answer = reply; +write_answer(&answer); +settled.await; +answer +``` + +`session.methods` composes the value with the process table's held namespaces: + +```rust +// A.1's routing precedence: a declaration whose name equals or lies inside a +// held management namespace is routed to management, never listed for the Session. +// The process closing is not the Session's close: Rpc answers +// `service_unavailable` rather than list names it cannot filter. +let Ok(held) = management.held_namespaces() else { + return Err(RpcError::service("service_unavailable", "The process is closing")); +}; +// `methods` fails only `closed`, which the client sees as `session_closed`. +let Ok(declarations) = methods.methods() else { + return Err(RpcError::closed()); +}; +let listed = declarations.into_iter().filter(|decl| { + let covered = |ns: &str| decl.name == ns || decl.name.strip_prefix(ns).is_some_and(|rest| rest.starts_with('.')); + !held.iter().any(|namespace| covered(&namespace.namespace)) +}).collect::>(); +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:reservedMethods` (optional) | The host's reserved names, consulted at registration. It is an `Option>` the factory fills only when the assembly names it; a host that names none reserves only the name grammar. | +| `sessionLifecycle` (the Session's own lifecycle service) | The Session's publication and close. The table reads `phase()`: `SessionPhase::Closing` is a synchronous check, and once it reads closing — before any row unloads — `register` and `call` answer `closed` and no handler runs. | +| `P:loaderRows` (proposed dim-owned process face; optional) | The loader row that registered a withdrawn namespace: `status {row}` answers `{found, status?, copies?}`. `found: false` when no row has that id, and a disabled row answers so too, both of which the table answers as `unknown_method`. When `found` is true, `status` and `copies` are present: `status` is the row's own state, and `copies: [{instance, status}]` gives each copy's state with its instance, from which the table picks this Session's copy before answering `reloading` or `unavailable`. The face does not exist yet; §4 rule 8 raises it, and App Server's loader row is its provider. It is an `Option>`: while the assembly names none, a withdrawn namespace answers `reloading`, as today; once it is installed, the rules above apply. | + +The process table (#2021) answers `heldNamespaces` (Rust `held_namespaces`), so Rpc routes a name and filters `session.methods` by A.1's routing precedence. Its own contract states its operations, data and kinds. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations}` and a call callback | `{}` | None; it awaits nothing, so it completes at its first poll | `invalid`, `reserved` (process table only), `duplicate`, `closed` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}`, in Rust a `CallReply`; an interruption answers in `reply.reply`, not as an outer error | `cancelled` settles when the caller's load unloads (Rpc's, or the process part's for an in-process call); the table then interrupts the call: `report` answers `interrupted` and settles, `drain` replies with its own result. The provider's generation unload interrupts the same way. A caller that stops waiting drops the future and the accepted call continues; a disconnect cancels nothing. The progress sink is a binding parameter too | `closed` once the Session is closing, else `unknown_method`, `reloading`, `unavailable`; an interruption answers in `reply.reply`. The process table's `call` kinds are its contract's | +| `methods` | The declarations registered now, sorted by name | `{}` | `{methods}` | None | `closed` | + +`register`'s declarations follow A.1's Registration row: at least one method; each name equal to or inside the namespace and unique; each declared notification equal to or inside the namespace, unique across the set, never a method's name. The table checks these first — a set that breaks them, or that cannot be decoded from another language's request, is `invalid` — and then consults the host's reserved names through `reservedMethods`. The Session table answers `invalid` for a name or notification the host keeps; the process table's registration answers those as `reserved`. + +`register` is data plus the caller's function on the wire, `methods` is data, and `call` is the owner's in-process operation. The dispatch calls the table's private `register_foreign(caller: &Ctx, namespace, declarations, call)`: the bridge hands it the calling row's `&Ctx`, so the registration is bound to that row's generation and unload exactly as a native one is, and the table records it as foreign so its `call` mints a call id. `register` is the native entry with the same body minus that record. Neither entry records a caller-index entry — that belongs to a call, and `call` derives it from the site it is given. In Rust each reply is a `Result`: `register` is `Result<(), MethodError>`, `call` is `Result`, and `methods` is `Result, MethodError>`. `{}` is the empty reply, `{methods}` the declaration vector, and `{reply}` the `MethodReply` the caller writes. `CallReply` carries what the caller that writes the reply needs beyond it: `{reply, registration, settled}`. `registration` is the call's caller-index entry for a call from another language, which the caller finishes once the reply is written so a later notification is direct; `settled` resolves once the call has settled, which may follow an interrupted reply. Rpc writes `reply`, finishes `registration` and awaits `settled`, so its load's unload waits for the call. Rpc wraps a `MethodError` in its envelope; `MethodReply`'s own error is the handler's data and is not a table failure. + +`caller` is `{connectionId}`: the connection the call arrived on, absent when no client connection made the call. In Rust Rpc passes the admission's site (`CallSite`, below), which holds the connection and that connection's close signal. The handler receives the caller as `MethodCall.origin.caller`, A.2's `Caller`. The table reads its own instance from its names (`Names::instance`) to pick this Session's copy. It writes no socket. It mints a call id for a call served by a registration of another language, and that id is what its `origin.caller.callId` and its notifications carry; a native call has none, because `Caller::notify` needs no id. Progress is the sink Rpc passes, which addresses the call by Rpc's own request id. It hands the handler a `Progress` over the call's sink; Rpc passes its connection's sink, and an in-process call passes one whose sends are dropped. The handler runs outside the table's lock: the table serializes only its own state changes, and two calls run concurrently. The call callback is a direct parameter; it never runs inside the Timeline's commit lock; the handler's token fires on the provider's generation unload and on the admitting Rpc load's unload, which `cancelled` reports. + +A handler's reply is `MethodReply` data: `{kind: "value", value}` or its own error as `{code, message, ...owner fields}`. The table adds no meaning. The client sees the handler's failure in the Rpc envelope's error: `appError` is the handler's `code`, the message is the handler's `message`, and the handler's `data` fields sit beside `appError` — the table and Rpc preserve them without interpreting them ([Appendix C](../contracts/session-boundary.md#appendix-c-errors-and-recovery)). The JSON-RPC code is the handler's `wire` code when it carries one, and otherwise the service-error rule (`invalid_params` → -32602, `unknown_method` → -32601, otherwise -32000); a handler of another language's own reply data carries no wire code, so its errors take the rule; an error it rethrows from a nested call keeps the code Rpc gives it. + +### Errors + +| Kind | Operation | Client `appError` | What the caller does next | +| --- | --- | --- | --- | +| `invalid` | `register` | — | The namespace or a declaration is outside the name grammar, malformed or repeated, or the request cannot be decoded — the table checks these. The host's names follow: the Session table's check answers `invalid`, the process table's registration `reserved`. A name outside the grammar on `call` is `unknown_method` in both tables. Fix the name or the declaration and register again | +| `reserved` | `register` (process table) | — | The namespace or a name is the host's; the process table's registration answers this where the Session table maps the same input to `invalid`. Pick another name | +| `duplicate` | `register` | — | The namespace is registered already; the row may register another namespace instead | +| `unknown_method` | `call` | `unknown_method` | No namespace, registered or withdrawn, holds the name, the name is outside the grammar, the owning namespace's provider does not declare it, the row that registered its withdrawn namespace is disabled or absent (when `loaderRows` is installed), or, for the process table, its row is Active without registering the namespace again. While `loaderRows` is absent a withdrawn namespace answers `reloading`, never this kind. Check the name and the namespace's declarations; an absent row is a configuration problem | +| `reloading` | `call` | `service_reloading` | The registering row is starting or reloading; for the Session table, its copy in this Session is Active because a child plugin reloads, or the row has no copy in this Session because its part is between generations. While `loaderRows` is absent, every withdrawn namespace answers this. The process table's own contract states its answer. Retry after the row is Active and registered the namespace again | +| `unavailable` | `call` | `service_unavailable` | The registering row failed or cannot run; for the Session table, its copy in this Session failed, and a missing copy is `reloading` instead. The process table's own contract states its answer. Retrying fails the same way until that row is fixed or restarted | +| `interrupted` | `call` | `operation_interrupted` | A `report` call's provider generation or admitting Rpc load unloaded while it ran; the call may have committed, so read the current state before retrying. A `drain` call answers with its own result instead | +| `closed` | `register`, `call`, `methods`; `heldNamespaces` on the process table | `session_closed` (Session table) | The table is closing or has ended. A Session table: `phase()` reads `Closing`, before any row unloads, and no handler runs; re-acquire the Session by id (Rpc restores an unloaded Session) and call again. A process table: the process ended, so a later process serves the next call. Do not retry against the closed one | + +`invalid`, `reserved`, `duplicate` and a registration's `closed` answer a registration only, so no client sees them. For `call` and `methods`, `closed` is one kind for both tables: the Session table's reaches a client as `session_closed`, and the process table's ends the process and the connection with it, so it needs no code of its own. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Refuse as soon as `phase()` reads closing (`closed`), then check the namespace grammar and the declarations (A.1) — `invalid` — then the table's host refusal (`invalid` for the Session table, `reserved` for the process table), reject a namespace registered already (`duplicate`), and record the declarations and the callback under the row | — | Its last row is recorded before the registration is withdrawn — the record's effect was registered last, so it runs first — and the registration ends with the row | New registrations are refused; the table ends with its Session or process, and the next one builds a new table (the process table's own contract states its answers) | The registering row | +| `call` | Refuse as soon as `phase()` reads closing (`closed`, and no handler runs), else find the owner, admit the call, run the handler, return its `CallReply` — the reply, the caller-index entry and the settlement — and on unload interrupt `report` calls and wait for every accepted call. A withdrawn Session namespace answers from its row and that row's copy in this Session: a missing copy is `reloading` | A caller that stops waiting drops its future; the accepted call continues and settles by its declaration, and a disconnect cancels nothing | The admitting load's unload fires `cancelled`; a `report` call answers `interrupted` and settles later, a `drain` call with its own result | The last row is recorded before the namespace stops being registered — its effect was registered last, so it runs first — and a withdrawn Session namespace answers from that row's status; the table ends with its Session and interrupts its calls by their declarations, waiting for them | The registration's unload effect for settlement; the table for admission | +| `methods` | Read the registered namespaces' declarations, sorted by name; the read observes the state at the call | — | Nothing to release | A table that closes answers no further read; the next Session or process builds a new one; a read already answered is unaffected | SessionMethods | + +## Exceptions with reasons + +- Four hand-outs cross this owner: Rpc passes the admission's `CallSite` to `call`, the table hands the handler the `Caller` it builds from it, and the `CallReply` gives the caller a `CallRegistration` for the call's caller-index entry, which it finishes once the reply is written, plus the `settled` future that resolves when the call has settled. No id alone can address a native row's connection, and a handler needs it to notify and to observe its close. [A.2](../contracts/session-boundary.md#a2-call-channel) fixes the behaviour, and the [binding appendix below](#binding-appendix) states all four: Rpc builds the site for one call and hands it to `call`; the table holds it, binds its serving generation's declared notifications to the `Caller`, and drops it when the call settles; the handler may keep the `Caller` after the reply, it answers `undeclared`, `gone` or `too_large` per A.2, and its `closed` resolves when the connection closes or the admitting Rpc load unloads. No handle keeps a strong reference to the connection. A handler of another language receives `{connectionId, callId}` instead, because `callChannel` addresses the call by those ids. + +## Verification + +Flow tests on the owner: + +- A registration lives until its row unloads; a duplicate namespace is `duplicate`, while a reserved name or a malformed declaration is `invalid`; a refused registration fails the registering part. +- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts, while its copy in this Session is Active or missing, and `unavailable` once it failed; a name no namespace ever held, and a name whose registering row is disabled or absent, are `unknown_method`. +- A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result; a caller that disconnects while the call runs receives nothing further and the call still settles. +- A native handler receives the call's `Caller` and notifies through it; a handler of another language receives the same caller encoded by the bridge as `{connectionId, callId}` and notifies through `callChannel` with that id. An in-process call has no caller. The handler's `closed` resolves when the connection closes or the admitting Rpc load unloads. +- A value reply and an error reply reach the client unchanged: the error's `appError` is the handler's `code`, its owner fields sit beside it, and its JSON-RPC code is the handler's own when it carries one and otherwise follows the service-error rule. +- A handler of another language that returns `{code, message}` reaches the client with that `appError`. A handler that fails with an `AgentError` reaches it with the code Rpc maps for that error. A runtime error converted from a `CallError` keeps its `code()`, else a remote's variant name under the service-error rule; a bridge error without a code is `failed` under the rule, and a call that crossed nothing is `failed` with `-32603`. +- `methods` lists the registered declarations sorted by name; Rpc's filter removes the names a held management namespace owns. That filter is Rpc's, so the listing's `service_unavailable` while the process closes belongs to `session.methods`, not this table. +- Once `phase()` reads closing and before any row unloads, `register` and `call` answer `closed` and no handler runs. +- While `loaderRows` is not installed, a withdrawn namespace answers `reloading`; installed, a missing row or a disabled one is `unknown_method`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the Session's lifecycle, the host's reserved names when the assembly names them and, once it exists, `loaderRows`. | +| §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | +| §3 orthogonality | No other business owner's state is read or changed; `sessionLifecycle`, `reservedMethods` and `loaderRows` are the mechanism's services. | +| §4 rule 1 | No command event: a registration is the calling row's effect. | +| §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | Core and assembly carry no method-specific meaning; a namespace's contents are its part's. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | +| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the registered namespaces, a provider or a channel through the owner. Rpc calls the operations and passes the call's site; a handler receives the `Caller`, the stated exception. | +| §4 rule 8 | The infrastructure requests are `loaderRows`, a dim-owned process face for one loader row, and the shared call shape the process table serves; both are raised below with their five fields. Nothing else changes. | +| §4 rule 9 | No Timeline fact. | +| §7 values, ids and callbacks | The caller is data on the wire; the site, the `Caller`, the `CallRegistration` and the settlement future are the stated objects, each with its shared design; the call callback, `cancelled` and the progress sink cross by reference; a registration lives with its row. | +| §7 no proxy | The table answers its own registrations; `loaderRows` is the runtime's read, raised below. | +| §7 one interface | One name, `sessionMethods`, on the owner type; `register` and `methods` are its wire operations, `call` is its in-process operation, and the two entries record one registration: the wire's `register` reaches `register_foreign` and the Rust one `register`. | +| §7 cross-language | `register` crosses as data plus the caller's callback through the table's dispatch, `methods` as data; `call` stays in process because it takes the admission's site, an object the wire cannot carry; `cancelled` and the progress sink are closures the binding already serves. The site's type is below. | +| §7.1 resources and lifecycle | The table owns no I/O and no resource: the namespaces, their declarations, their last rows and the calls they admitted are memory. The Session closing ends admission first: `phase()` reading `Closing` answers `closed` for `register` and `call` before any row unloads, and no handler runs. A registration lives until its row unloads: at the first step of that unload, before any of the row's effects runs, it stops admitting and interrupts its admitted `report` calls, and its unload effect waits for every admitted call. A row of another language unloads its plugin in an effect that runs before those registered during its apply, so its accepted calls settle while the plugin still runs. The table ends with its Session. | +| §7.1 operations | `register` is one state migration, `call` one call's admission and settlement, `methods` one read; each states its cancellation and its error kinds above, and no operation exposes a step another could be composed from. | +| §7.2 review checks | No cross-owner call is left unmapped; no object crosses except the stated site, `Caller`, `CallRegistration` and settlement future; the table does not answer for another owner; one interface; every operation names its errors; the delivery removes the old surface in one change. | +| §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | +| ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | +| ADR 002 D3 | No dependency on providers; a failed row affects only its namespaces. | +| ADR 002 D4 | The namespace set is structural: parts bring their namespaces. | +| ADR 002 D5 | The wire operations and their data are language-neutral; `call` is the owner's in-process operation with the same reply data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +| Field | Value | +| --- | --- | +| Which feature is blocked, by which rule | The table answers `reloading` and `unavailable` for a withdrawn namespace, as [A.1](../contracts/session-boundary.md#a1-method-contributions) requires, from the status of the row that registered it and of that row's copy in this Session. §7 forbids reading another owner's state, and the process's loader is `rutis-loader`'s own business state; the table has no dim-owned face for it. | +| Existing mechanisms considered | Rpc answering the two kinds instead of the table: rejected, the reviewed `call` answers them. Depending on `rutis/loader` as it is: blocked, it is `rutis-loader`'s own service (`create`, `reload`, `remove`, `status` over the whole process), it is not a dim face, and `dim-agent-capabilities` does not depend on that crate. `Loader::get(row)` answers one row's `EntryInfo` but lives on the crate's value, not on the face. The table subscribing to loader changes and recording row status itself: a plugin-layer port, which §4 rule 8 forbids. | +| Generic capability needed | A dim-owned process face `loaderRows` over one loader row: `status {row}` → `{found, status?, copies?}`, each copy naming its instance and its state, and `found: false` for a row id nothing has or a row that is disabled. No business meaning. | +| Effect on sequence, batches, interruption, reload | None on sequence or batches. A read, so it interrupts nothing. During a reload it answers the transitional status, which is its purpose. | +| Who implements it, which issue | The dim runtime: App Server's loader row (`crates/dim-app-server/src/lib.rs:1476-1482` creates the loader (`LoaderPlugin`); the per-row read Rpc does today is at `crates/dim-app-server/src/methods.rs:220-250`) provides the face, tracked in [#2021](https://github.com/arcships/dim/issues/2021). | + +The process table (#2021) must serve the same shared shape, because Rpc dispatches both tables on one path: + +| Field | Value | +| --- | --- | +| Which feature is blocked, by which rule | Rpc dispatches both tables on every call and depends on no provider (§3.2); a shared `MethodCall`, `MethodReply` and `MethodError` that only one table serves would leave Rpc with two paths. | +| Existing mechanisms considered | Rpc adapting each table's own shapes: rejected, §7 one interface requires one reply per table. Leaving the process table's `call` returning `MethodReply`: blocked by A.2, which needs the caller-index entry and the settlement the reply carries. | +| Generic capability needed | The process table's `call` returns `CallReply { reply, registration, settled }` and takes `Option` like this one, and its `MethodCall.origin` carries the `Caller`. No business meaning. | +| Effect on sequence, batches, interruption, reload | None: the same reply, entry and settlement it serves today, named once. | +| Who implements it, which issue | ManagementMethods' owner, tracked in [#2021](https://github.com/arcships/dim/issues/2021); its PR is not open yet, and the link is added when it is. | + +## Supersedes + +- [session boundary A.1](../contracts/session-boundary.md#a1-method-contributions): its Session-scoped call paragraph is replaced by `register`, `call` and `methods`, and the call data A.1's interface block names — `MethodCall`, `MethodReply`, `MethodError` — are the binding below, which A.1 links to. +- [session boundary Appendix F](../contracts/session-boundary.md#appendix-f-rust-binding): its paragraphs for the Session table's shapes and the shared call data — `MethodProvider`, `Accepted`, `Check`, `Owner`, the Session table's `MethodTable` storage, its `owner`/`provider`/`holds`/`listed` readers, the `SessionMethods` deref, `Handler`, `MethodCall`/`Origin` and the foreign `register` decode — are replaced by the [binding below](#binding-appendix), and Appendix F links here. Its `managementMethods` row keeps its own storage and read, and its `CallChannel`/`ToolRegistry` rows and the `Callers` wiring stay. +- [session boundary A.2](../contracts/session-boundary.md#a2-call-channel): its `Caller`/`CallerConnection` paragraphs are this contract's [binding below](#binding-appendix); A.2 keeps the behaviour. + +No existing client method changes and no error kind is removed. The table adds one wire read, `sessionMethods.methods`; the shared error kinds keep `reserved` for the process table's registration; new `appError` values appear inside existing kinds. A handler's `code` is the client's `appError` today and stays so, a native handler's owner fields already reach the client, and an error a handler rethrows from a nested call keeps the code Rpc gives it. Eight client-visible changes: + +- A Session that is closing answers `closed` for `call` from `phase()`, before any row unloads, and no handler runs; today the table keeps admitting until its rows unload. +- A withdrawn Session namespace whose registering row is absent from the loader answers `unknown_method`; today `session_provider` falls through to `service_reloading` (`crates/dim-app-server/src/methods.rs:240-249`), which retrying could not fix. A disabled row already answers `unknown_method`. +- A native handler's failure without an application code keeps `-32603` and gains `appError: "failed"`; today it carries no `appError` (`crates/dim-agent-capabilities/src/methods.rs:153`). +- A malformed foreign reply carries `appError: "bad-value"`, and another bridge failure its own code (`peer-gone`, a `Binding` code), with `-32000`; today each is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:917`). +- A foreign handler that throws an error without an application code now carries that error's name as `appError` with `-32000`; today it is `-32603` "Method binding failed" with none (`crates/dim-agent-capabilities/src/methods.rs:843-853`). +- A callback failure whose error never reached the bridge keeps `-32603` and gains `appError: "failed"` (`crates/dim-agent-capabilities/src/methods.rs:905-918`). +- A bridge error that carries no code of its own is `failed` under the service rule (`-32000`), where today it is `-32603` "Method binding failed" (`crates/dim-agent-capabilities/src/methods.rs:912-918`). + +`session.methods` gains one failure: while the process is closing, it cannot filter the names a management namespace holds and answers `service_unavailable`; a registration's `closed` reaches no client, and a registration of another language whose declarations cannot be decoded now fails as `invalid` where the bridge's `bad-value` named the decode, which no client sees either. Three shapes change for a part of another language: its `call` request nests the caller as `origin.caller` where today it sends a top-level `callId` and a flat `origin.connectionId`, and its handler's owner fields now reach the client, where today the `{code, message}` decode rejects a reply that carries them. The third is a declaration's `reply` field: accepted and ignored, so it is not client-visible. + +## Binding appendix + +One definition, in the `methods` module of `dim-agent-capabilities`: the call data below — the declarations, the interruption, the reply, the errors, the progress sink and the admission's site. [A.2](../contracts/session-boundary.md#a2-call-channel) states the behaviour of `Caller`, `Progress` and the connection; this block states their shape and lifecycle, `Caller` and `CallerConnection` included. `NotifyError` is A.2's too, stated below. `Callers` is the process's caller index, A.2's own private wiring at its Rust type key, and `CallSite` only references it. `RpcError` is Rpc's wire error, whose contract is [#2021](https://github.com/arcships/dim/issues/2021)'s; this module keeps it beside the types that convert to it. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave the Session table; its storage is private. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. + +```rust +// crates/dim-agent-capabilities/src/methods.rs: the call data both tables serve. +use dim_agent_runtime::AgentError; +use rutis::host::{BoxFuture, CallError}; +use tokio_util::sync::CancellationToken; + +/// One declared method of a namespace. A declaration from another language +/// carries `name`, `mutating`, `interruption` and `progress`, may carry its +/// `notifications`, and may carry an ignored `reply`; the listing another +/// language reads is `{name, mutating}`. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MethodDecl { + pub name: String, + pub mutating: bool, + #[serde(skip_serializing)] + pub interruption: Interruption, + #[serde(skip_serializing)] + pub progress: bool, + #[serde(default, skip_serializing)] + pub notifications: Vec, + #[serde(default, skip_serializing)] + pub reply: Option, +} + +/// A method's reply mode (A.1). The table accepts the field and ignores it: +/// reply handoff is not implemented, so a `handoff` declaration registers and +/// its replies are direct. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReplyMode { + #[default] + Direct, + Handoff, +} + +/// How a provider answers an admitted call that an unload interrupts: `report` +/// answers `interrupted` and settles, `drain` answers with its own result. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Interruption { + Report, + Drain, +} + +/// The call's progress sink (A.2). The table hands it to a handler whose +/// declaration declares `progress`; one whose declaration does not receives a +/// sink whose sends are dropped. It closes before the reply is written. +#[derive(Clone)] +pub struct Progress(/* the calling connection's sink */); + +impl Progress { + /// Sends one progress value; best effort, and dropped once the reply is + /// handed over. + pub fn send(&self, data: serde_json::Value) { /* ... */ } +} + +/// Why a connection-bound notification was not written (A.2). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NotifyError { + /// A name the provider generation did not declare. + Undeclared, + /// The connection closed, or the generation or load that admitted the call unloaded. + Gone, + /// An encoded notification over the frame limit. + TooLarge, +} + +impl NotifyError { + /// The code a bridge error carries: `undeclared`, `gone` or `too_large`. + pub fn code(self) -> &'static str { /* ... */ } +} + +/// The calling connection of one admitted call (A.2), bound to the serving +/// generation's declared notifications. Opaque: its methods are its whole +/// surface. It keeps the connection through `Arc`, +/// which holds no strong reference, so a retained `Caller` does not keep a +/// closed connection alive. +#[derive(Clone)] +pub struct Caller(/* the connection, its declared names and the generation */); + +impl Caller { + /// The contract's `connectionId`. + pub fn id(&self) -> &str { /* ... */ } + /// The call id a notification addresses, minted for a call served by a + /// registration of another language; `None` for a native provider's call, + /// which needs none. The + /// module's own binding: a part never reads it. + pub(crate) fn call_id(&self) -> Option<&str> { /* ... */ } + /// Sends a connection-bound notification (A.2): `undeclared` for a name + /// this generation did not declare, `gone` once it unloaded or the + /// connection closed, `too_large` over the frame limit. + pub fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError> { /* ... */ } + /// Resolves when the connection closes or the admitting Rpc load unloads. + pub fn closed(&self) -> impl std::future::Future + Send + 'static { /* ... */ } +} + +/// A connection as the `methods` module uses it: its id, a write to it and its +/// close signal. Rpc implements it; `Caller` and `CallSite` hold it through an +/// `Arc` that keeps no strong reference to the connection. +pub trait CallerConnection: Send + Sync + 'static { + fn id(&self) -> &str; + fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError>; + fn closed(&self) -> BoxFuture<'static, ()>; +} + +/// One admitted call's connection, as Rpc passes it to `call`: the call's +/// channel, the connection's direct writer, the process's caller index (A.2) +/// and the connection's close signal. Rpc builds it for one call; the table +/// binds it to the serving generation's declarations. +#[derive(Clone)] +pub struct CallSite { + pub connection: std::sync::Arc, + pub direct: std::sync::Arc, + pub callers: std::sync::Arc, + pub closed: CancellationToken, +} + +/// One admitted call as its handler receives it: the declared name, the raw +/// params and who called. +#[derive(Clone)] +pub struct MethodCall { + pub method: String, + pub params: serde_json::Value, + pub origin: Origin, +} + +/// Who called: the call's `Caller` (A.2) for a native handler, built by the +/// admission from the calling connection and this generation's declared +/// notifications; its type and lifecycle are below and in A.2. +#[derive(Clone)] +pub struct Origin { + pub caller: Option, +} + +/// A handler's own failure: its application code, message and any owner-defined +/// fields the client receives beside `data.appError`. +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{code}: {message}")] +pub struct MethodCallbackError { + pub code: String, + pub message: String, + /// The JSON-RPC code the handler's failure carries; the service-error rule + /// applies + /// when it is absent. Another language's handler sends none. + #[serde(skip, default)] + pub wire: Option, + /// Owner-defined wire fields, preserved by the table and Rpc; they must + /// not shadow `appError` or a built-in field. + #[serde(flatten, default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub data: std::collections::BTreeMap, +} + +impl MethodCallbackError { + /// The client code, message and owner fields Rpc gives a runtime error. + fn from_wire(wire: RpcError) -> Self { + let data = wire.data.as_ref(); + Self { + code: data.map(|data| data.app_error.clone()).unwrap_or_else(|| "failed".into()), + message: wire.message, + wire: Some(wire.code), + data: data.map(|data| data.details.clone()).unwrap_or_default(), + } + } +} + +impl From for MethodCallbackError { + fn from(error: AgentError) -> Self { + Self::from_wire(RpcError::from(error)) + } +} + +/// A handler's own `params(..)?` or `reply(..)?` failure keeps its client +/// code, message and owner fields. +impl From for MethodCallbackError { + fn from(wire: RpcError) -> Self { + Self::from_wire(wire) + } +} + +impl From for MethodCallbackError { + fn from(error: CallError) -> Self { + let remote = error.raw().and_then(|raw| raw.downcast_ref::()); + // An error a nested call rethrew keeps the client code Rpc gives it, + // `AgentError`'s mapping included. `rethrown` is this module's + // existing conversion: `fn rethrown(&session::Error) -> Option`. + if let Some(wire) = remote.and_then(rethrown) { + return Self::from_wire(wire); + } + // Otherwise, by case: a remote error keeps its own application code, + // or its variant name when it has none; a bridge error (`bad-value`, + // `peer-gone`, a `Binding` code) keeps its code; both take the + // service-error rule. A bridge error without a code is `failed`. A + // `CallError` that is not a session error is the binding's own failure: + // `failed`, keeping today's `-32603`. + let (code, wire) = match remote { + Some(error) => ( + error.code().map(str::to_owned).or_else(|| match error { + rutis_bridge::session::Error::Remote { name, .. } => Some(name.clone()), + _ => None, + }) + .unwrap_or_else(|| "failed".into()), + None, + ), + None => ("failed".into(), Some(-32603)), + }; + Self { code, message: error.message().into(), wire, data: Default::default() } + } +} + +/// One admitted call's answer, for the caller that writes its reply. +pub struct CallReply { + /// The handler's reply, or the table's own kind for an interrupted call. + pub reply: Result, + /// The foreign call's caller-index entry, finished once the reply is + /// written; `None` for a native call. + pub registration: Option, + /// Resolves once the call has settled, which may follow an interrupted reply. + pub settled: BoxFuture<'static, ()>, +} + +/// The caller-index entry one call from another language holds until its reply +/// is written (A.2). +pub struct CallRegistration(/* the index, the row instance, the connection and the call id */); + +impl CallRegistration { + /// The call's reply is written: a later notification with its `callId` is + /// written directly, and the index no longer holds the call. + pub fn finish(self) { /* ... */ } +} + +/// The handler both tables store: the call, a token that fires on either +/// unload, and the call's progress sink. +pub type Handler = std::sync::Arc< + dyn Fn(MethodCall, CancellationToken, Progress) + -> BoxFuture<'static, Result> + + Send + + Sync, +>; + +/// The handler's reply: its value, or its own failure as data. The bridge +/// writes a value as `{kind: "value", value}` and a failure as +/// `{code, message, ...owner fields}`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum MethodReply { + Value(ValueReply), + Error(MethodCallbackError), +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum ValueReply { + Value { + #[serde(default)] + value: serde_json::Value, + }, +} + +impl From for MethodReply { + fn from(value: serde_json::Value) -> Self { + Self::Value(ValueReply::Value { value }) + } +} + +impl From for MethodReply { + fn from(error: MethodCallbackError) -> Self { + Self::Error(error) + } +} + +/// Rpc's wrapping of a handler's failure: the handler's wire code, else the +/// service-error rule, with `appError` and its owner fields in `data`. +impl From for RpcError { + fn from(error: MethodCallbackError) -> Self { + let code = error.wire.unwrap_or(match error.code.as_str() { + "invalid_params" => -32602, + "unknown_method" => -32601, + _ => -32000, + }); + Self { + code, + message: error.message, + data: Some(ErrorData { + app_error: error.code, + details: error.data, + daemon_busy: None, + }), + } + } +} + +/// The table's own failures, by kind. One kind set serves both tables; +/// `closed` reaches a client as `session_closed` for the Session table, and +/// the process table has no client code of its own. `reserved` answers the +/// process table's registration only: the Session table maps the same input +/// to `invalid`. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum MethodError { + #[error("{message}")] + Reserved { message: String }, + #[error("{message}")] + Duplicate { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("no namespace answers {method}")] + UnknownMethod { method: String }, + #[error("the registering row is reloading")] + Reloading, + #[error("the registering row is unavailable")] + Unavailable, + #[error("the provider's generation or the admitting Rpc load unloaded during the call")] + Interrupted, + #[error("the table is closing")] + Closed, +} +``` + +```rust +// crates/dim-agent-capabilities/src/methods.rs: the owner, in the same module. +use crate::host::CancelledFn; +use rutis::Ctx; +use rutis_bridge::session::{HostDispatch, Reply, Value as BridgeValue}; +use tokio_util::sync::CancellationToken; + +/// The owner type; the namespaces, their declarations and their last rows +/// stay private. +pub struct SessionMethods { /* ... */ } + +impl SessionMethods { + /// Publishes `namespace` for the lifetime of the row that owns `caller`. + /// Another language's wire form is `register {namespace, declarations, call}` + /// through the dispatch below, because the callback's arguments are not + /// data. + pub async fn register( + &self, + caller: &Ctx, + namespace: String, + declarations: Vec, + call: impl Fn(MethodCall, CancellationToken, Progress) -> BoxFuture<'static, Result> + Send + Sync + 'static, + ) -> Result<(), MethodError> { /* ... */ } + + /// The declarations registered now. + pub fn methods(&self) -> Result, MethodError> { /* ... */ } + + /// One call, in process: the caller's site (`CallSite`, below), the + /// cancellation and the progress sink are parameters, and the reply is the + /// `CallReply` above. + pub async fn call( + &self, + method: String, + params: serde_json::Value, + site: Option, + cancelled: CancelledFn, + progress: impl Fn(serde_json::Value) + Send + Sync + 'static, + ) -> Result { /* ... */ } +} + +/// The catalog name `sessionMethods` in the Session group, served to other +/// languages at its dispatcher key: `register {namespace, declarations, call}` +/// and `methods {}`. One dispatcher, hand-written: `#[rutis::service]` cannot +/// bind `register`'s callback, and a marked service beside this dispatch would +/// claim the same name twice. +impl HostDispatch for SessionMethods { + /// The dispatch's method list, not the owner's read: `invoke` forwards + /// `methods` to the inherent `SessionMethods::methods`. + fn methods(&self) -> Option { + Some(serde_json::json!({ "register": "async", "methods": "sync" })) + } + + fn invoke(&self, method: &str, args: BridgeValue) -> Reply { /* ... */ } +} +``` + +`register` and `methods` are the wire face, both through the dispatch above: it decodes the declarations and the caller's function for the bridge's calling row, and answers `methods` as data. `call` is the owner's in-process operation: it takes the admission's site, the cancellation and the progress sink, so none of them crosses a wire; the handler's caller is the `Caller`, and only the bridge encodes it as `{connectionId, callId}` for another language. `MethodCall` carries A.2's `Caller` to a native handler and `{connectionId, callId}` to a handler of another language. `MethodReply::Value` wraps `ValueReply::Value` so the wire keeps its `kind` tag; `MethodReply::Error` is the handler's `{code, message, ...owner fields}` unchanged, and `From` produces it. `MethodError` serializes with `#[serde(tag = "code", rename_all = "snake_case")]`, so each variant's kind is its snake-case name; the dispatch hands that kind to the bridge as the error's code, and Rpc maps the kind to the client's `appError` and JSON-RPC code. `MethodCall` carries the `Caller`; a handler of another language receives it as the bridge's JSON shape. A handler's failure carries a `code`, or Rpc's mapping supplies one for an `AgentError` or a rethrown nested error; that code becomes the client's `appError`. diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 4b4af3095b..9b916d815a 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -2,7 +2,7 @@ 状态:草案。总体设计:[总览 §3 集成](../overview.md#3-基于现有机制的集成)、[附录 B Rpc 与 ToolRegistry](../overview.md#附录-b-现有插件的补充);规则:[ADR 002](../../adr/002-plugin-scope.md) D2、D3、D5。阶段:P0。语言:语言中立合同;Rust 绑定见[附录 F](#附录-f-rust-绑定)。[C4 绑定](../../../design/session-typescript.md) 已实现非 Rust Session 工具和方法子集;原生广播仍待定。 -本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;其方法接收并返回可序列化数据;错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务,并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时读取这两张方法表,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 +本合同以 ADR 002 D5 的语言中立形式定义三种注册服务:Session 的 `sessionMethods` 与 `toolRegistry`,以及进程的 `managementMethods`。每个服务由服务名和作用域标识;注册接收命名空间及其声明的数据,以及调用方的函数回调;Session 方法表的 `call` 是所有者进程内的操作([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));错误是数据;取消是一个协议动作。任何语言的部件都依赖其作用域的服务(方法表或注册表),并在自己的 `apply` 中注册:方法命名空间注册到 `sessionMethods` 或 `managementMethods`,工具注册到 `toolRegistry`。注册属于发起它的部件,在该部件卸载时撤回。Rpc 在每次调用时分发各张方法表的 `call`,不依赖任何提供方。它们建立在运行时已有的机制之上:按作用域的具名服务、Rpc 现有的经 Session 分发(与如今的 `approval.respond` 相同),以及作为调用方 effect 的注册。实现状态:方法命名空间(#14、C1、#382)与工具(#382)通过附录 F 与各所有者契约的 Rust 绑定注册,其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md));`callChannel` 已实现逐次调用的 `progress`(C1)以及绑定连接的通知 `notify` 与 `closed`(#1158);`takeFinalReply` 及通用插件安装尚未实现,`ConnectionEntry {name, deviceId}`、按 `deviceId` 路由和导出的 rutis 链接也未实现(提议在 P3 随 RemoteGateway 实现)。 | 服务 | 作用域 | 注册什么 | 注册方 | 读取方 | | --- | --- | --- | --- | --- | @@ -54,11 +54,11 @@ flowchart LR | 服务 | 缺失时 | | --- | --- | -| `sessionMethods` | 该 Session 从没有命名空间持有过此名称时返回 `unknown_method`;持有它的命名空间已撤回时,注册它的部件正在启动或重载则返回 `service_reloading`,已失败或无法运行则返回 `service_unavailable`(A.1) | +| `sessionMethods` | 该 Session 从没有命名空间持有过此名称时返回 `unknown_method`;注册其已撤回命名空间的行已禁用或不存在时同样返回 `unknown_method`;持有它的命名空间已撤回时,注册它的部件正在启动或重载、或其在本 Session 中没有副本则返回 `service_reloading`,已失败或无法运行则返回 `service_unavailable`(A.1) | | `managementMethods` | 从没有命名空间持有过该名称,或注册它的行已禁用或不存在时返回 `unknown_method`;其他情况下,已撤回的命名空间按该行的状态作答(§3.2) | | 工具注册 | Session 挂载列表列出但没有部件注册的工具不声明,并在诊断中报告;有部件注册后从下一个请求起声明(A.5) | -本文定义的合同:这两张方法表及其注册、工具注册、`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 +本文定义的合同:两张方法表共用的注册、工具注册、列出方法的 `session.methods`、配套服务 `callChannel`(`progress`、`notify` 与 `closed` 已实现)、`ToolDeclaration`、`ToolCall`、`ToolResult` 及其效果声明、各入口获得的服务范围、命名、保留名、现有管理方法的迁移以及兼容性表。调用数据——`MethodDecl`、`MethodCall`、`MethodReply`、`MethodError`——归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)。使用的合同:`SessionConfig`([session-access](session-access.md#a3-sessionconfig-字段))、来源输入约定([session-access A.2](session-access.md#a2-来源输入约定))、Rpc 命令信封以及 `appError` 码。 ## 2. 数据与状态 @@ -81,15 +81,15 @@ sequenceDiagram Rpc->>Rpc: 非内建方法,没有管理命名空间持有它,params 中带 sessionId,授权 Session 访问 Rpc->>AI: acquire(sessionId),未装载时恢复 AI-->>Rpc: Session 租约 - Rpc->>S: session.question.respond 的所有者 - S-->>Rpc: 命名空间 session.question 的提供方 - Rpc->>Q: call(MethodCall) + Rpc->>S: call {method, params, caller?} + S->>Q: 持有该名称的最长命名空间的处理函数 Q->>H: 把回答交给等待中的调用 (branchId, requestId, callId) - Q-->>Rpc: MethodReply + Q-->>S: MethodReply + S-->>Rpc: MethodReply Rpc-->>CL: 结果 ``` -名称属于该 Session 中持有它的最长已注册命名空间(A.1)。如果该 Session 从没有命名空间持有过此名称(例如其插件未对该 Session 启用),结果为 `unknown_method`;如果持有它的命名空间已撤回,注册它的部件正在启动或重载时结果为 `service_reloading`,该部件已失败或无法运行时结果为 `service_unavailable`(A.1)。Session 方法没有级别:获得 Session 方法的连接获得全部 Session 方法,包括 `shell.*`。 +名称属于该 Session 中持有它的最长已注册命名空间(A.1)。如果该 Session 从没有命名空间持有过此名称(例如其插件未对该 Session 启用),结果为 `unknown_method`;如果持有它的命名空间已撤回,注册它的部件正在启动或重载、或其在本 Session 中没有副本时结果为 `service_reloading`,该部件已失败或无法运行时结果为 `service_unavailable`;注册它的行已禁用或不存在时结果为 `unknown_method`(A.1)。Session 方法没有级别:获得 Session 方法的连接获得全部 Session 方法,包括 `shell.*`。 ### 3.2 管理方法 @@ -116,9 +116,9 @@ sequenceDiagram | 场景 | 顺序 | 结果 | 所有者 | | --- | --- | --- | --- | | Session 级提供方在调用中途重载 | call < reload | `report`:`operation_interrupted`;`drain`:调用自己的结果;提供方的卸载等待每个已受理的调用(AGENTS.md 规则 8) | 提供方 | -| Session 的 Capability 重载期间调用 Session 方法 | — | `service_reloading` | Rpc | -| 命名空间已撤回、且注册它的部件已失败或无法运行时调用 Session 方法 | — | 该部件修复前返回 `service_unavailable`(A.1) | Rpc | -| 调用该 Session 从没有命名空间持有过的 Session 方法 | — | `unknown_method` | Rpc | +| Session 的 Capability 重载期间调用 Session 方法 | — | `service_reloading` | Session 方法表 | +| 命名空间已撤回、且注册它的部件已失败或无法运行时调用 Session 方法 | — | 该部件修复前返回 `service_unavailable`(A.1) | Session 方法表 | +| 调用该 Session 从没有命名空间持有过的 Session 方法 | — | `unknown_method` | Session 方法表 | | 管理方法所有者重载 | — | 新一代重新注册前,调用其已撤回的命名空间返回 `service_reloading`;处于 Failed、Unresolved、Stopped 或 Disposed 的所有者返回 `service_unavailable`(§3.2);已受理的调用属于提供方,按 `interruption` 处理;Rpc 不重载,连接保持打开 | Rpc | | 在带 `deviceId` 的连接上调用管理方法或 `daemon.shutdown` | — | `unknown_method` | Rpc | | 两个部件在同一张表中注册同一命名空间 | 注册 | 第二次注册被拒绝(` is registered already`),发起它的部件失败 | 方法表 | @@ -138,11 +138,13 @@ sequenceDiagram | 服务与方法 | 模式 | 用途 | | --- | --- | --- | -| `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载 | +| `sessionMethods.register(namespace, MethodDecl[], call)` | async | 注册一个 Session 方法命名空间,直到调用方部件卸载;注册行是绑定的 `&Ctx`,不是请求字段,形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) | | `managementMethods.register(namespace, MethodDecl[], call)` | async | 注册一个管理命名空间,直到调用方部件卸载 | | `call(MethodCall, cancelled, progress) -> MethodReply`(注册部件自己的函数) | async | 执行该命名空间的方法 | +| `sessionMethods.call {method, params, caller?}` | 进程内 | 分发一个 Session 方法;Session 一开始 closing 就答 `closed`,否则为 `unknown_method`、`reloading` 或 `unavailable`,中断在其回复里作答([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)) | +| `sessionMethods.methods {}` | sync | 该 Session 现在注册的命名空间的声明 | | `session.methods {sessionId}`(线上方法,Rpc 内建) | async | 列出某个 Session 的方法(协议 v3) | -| `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现,附录 F) | +| `callChannel.progress / notify / closed`(App Server) | sync / async | 逐次调用的进度与绑定连接的通知(已实现;`Progress` 与 `Caller` 归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)) | | `toolRegistry.register(ToolDeclaration, execute)` | async | 注册一个工具,直到调用方部件卸载 | | `execute(ToolCall, cancelled) -> ToolResult`(注册部件自己的函数) | async | 工具执行 | @@ -157,7 +159,7 @@ sequenceDiagram | §4 第 1 条(指令事件) | 不适用:这些服务自身不写 Timeline 事件;改变分支状态的方法调用状态所有者,由所有者写入(例如 InputQueue 为 `session.input.withdraw` 写入的 `input/deleted`)。 | | §4 第 2 条(交接) | 不适用:方法与工具贡献不交接任何对象;工具调用按现有 `step/tool-call` 合同交给 ToolExecutor。 | | §4 第 3 条(只用 before 回调) | Rpc 只校验参数格式和 `sessionId` 授权;功能检查归方法所有者,提交前的处理只用 Timeline before 回调。 | -| §4 第 4 条(核心不带业务含义) | 方法表与 ToolRegistry 保存部件注册的内容,Rpc 读取方法表;它们都不点名提供方,也不解释方法。效果声明随结果原样携带,核心没有任何部分认识它的类型(A.6)。 | +| §4 第 4 条(核心不带业务含义) | 方法表与 ToolRegistry 保存部件注册的内容,Rpc 调用它们的操作;它们都不点名提供方,也不解释方法。效果声明随结果原样携带,核心没有任何部分认识它的类型(A.6)。 | | §4 第 5 条(批次) | 不适用:本文没有依据 Timeline 事件做的决定;所有者依据自己的事实决定。 | | §4 第 6 条(模型上下文) | 方法对模型不可见,注册的工具只通过其声明和 `ToolResult` 到达模型(§5)。 | | §4 第 7 条(公开事件与服务) | 提供方只通过分支的公开服务到达分支,Rpc 只经 Session 的 `sessionMethods` 分发。 | @@ -168,7 +170,7 @@ sequenceDiagram | ADR 002 D2 | 不新增端口或 Management 插件;方法命名空间注册到其作用域的方法表,工具注册到拥有本 Session 工具的 ToolRegistry。 | | ADR 002 D3 | 提供方只依赖自身或外层作用域,包括它注册时用的方法表。方法表与 ToolRegistry 跟随注册与撤回,不依赖注册的部件(A.1、A.5);Rpc 既不依赖管理方法提供方(§3.2),也不依赖 Session 方法提供方(A.1),因此它们的重载只影响自己的命名空间。 | | ADR 002 D4 | 链接的管理方法导出是宿主本地的结构性配置;本文不定义业务配置。 | -| ADR 002 D5 | 每个服务都有名称、作用域和纯数据方法,任何语言的部件都用同样的数据和自己的函数(`call`、`execute`)注册方法命名空间或工具;Rust 类型只出现在附录 F。已实现的绑定是这些结构的一个子集(A.1、附录 F)。 | +| ADR 002 D5 | 每个服务都有名称、作用域和纯数据方法,任何语言的部件都用同样的数据和自己的函数(`call`、`execute`)注册方法命名空间或工具;Rust 类型只出现在各所有者自己的绑定里:Session 表见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表见其契约([#2021](https://github.com/arcships/dim/issues/2021)),工具见 ToolRegistry 的绑定。已实现的绑定是这些结构的一个子集(A.1)。 | ## 9. 向机制所有者提出的需求 @@ -188,26 +190,30 @@ sequenceDiagram | 项 | 内容 | | --- | --- | -| 被什么挡住 | Session 命名空间已撤回时,Rpc 按注册它的行在该 Session 实例中的副本作答(A.1)。Rpc 手里只有 `Session` 句柄,它不说明自己的行运行在哪个实例中。 | +| 被什么挡住 | 已撤回的 Session 命名空间原本由 Rpc 按注册它的行在该 Session 实例中的副本作答(A.1)。Rpc 手里只有 `Session` 句柄,它不说明自己的行运行在哪个实例中。该作答已移到 Session 方法表:方法表从自己的名字得到所在实例([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract));下面这项能力仍然实现,其他调用方仍可用。 | | 考虑过的现有机制 | `Session::diagnostics` 每次这样的调用都要遍历 Session 的插件树。由一个 Session 部分把自己的作用域作为公开服务提供,会给每个 Session 增加一个部分,只为重新发布门面已经持有的信息。 | | 需要的通用能力 | `Session::instance()`,即 Session 的 `InstanceId`,也就是它的部件解析名字时所在的实例(`Names::instance`)。其下的 key 只能在该 Session 内部读取(rutis 拒绝在实例之外读取实例 key),因此它不会开放 `PublicService` 之外的任何服务。 | | 对序号、批次、中断、重载的影响 | 无。Session 作用域插件拒绝重载,因此 Session 装载期间实例不变;对已关闭的 Session,读取像其他门面读取一样以 `Closed` 失败。 | | 由谁实现、对应 issue | 运行时(Session 门面);为 [#207](https://github.com/arcships/dim/issues/207) 实现。 | +方法表自己的行状态读取是 [SessionMethods](../../../design/plugins/SessionMethods.md#requirements-raised-to-mechanism-owners) 的 §4 第 8 条请求([#2021](https://github.com/arcships/dim/issues/2021))。 + 外来 Session 服务的已实现子集见 [C4](../../../design/session-typescript.md);通用插件安装仍由其所有者推进。 ## 附录 A. 接口细节 -结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。每个错误都是 `MethodError` 数据。 +结构为 camelCase 字段的 JSON;字段名后的 `?` 表示可选,`|` 分隔备选项。这些结构是规范形式:插件文档使用这些字段名(Rust 绑定把它们映射为 snake_case)。调用数据与方法表的错误种类归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 契约;处理函数以自己的 `{code, message, ...所有者字段}` 作答,客户端收到的每个错误都是 Rpc 信封 `{code, message, data: {appError, ...所有者字段}}`。另一种语言的处理函数收到的调用是 `{method, params, origin?: {caller: {connectionId, callId}}}`,即 `MethodCall` 的桥接编码;`callId` 只在调用来自连接时出现,未来自连接的调用没有 `origin`。 ### A.1 方法贡献 -`sessionMethods`(Session)与 `managementMethods`(进程)是方法表,具有同一个方法 `register`。部件把它提供的每个命名空间注册到其作用域的方法表,方法表回调该部件自己的 `call`。其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md)),并进入附录 F 的原生调用受理。 +两张表的调用数据——`MethodCall`、`MethodReply`、处理函数自己的错误与方法表的错误种类——归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 契约定义;本附录保留重构不改的客户端错误、中断与路由行为。 + +`sessionMethods`(Session)与 `managementMethods`(进程)是方法表,具有同一个方法 `register`。部件把它提供的每个命名空间注册到其作用域的方法表,方法表回调该部件自己的 `call`。其他语言的部件通过同样的服务注册([C4](../../../design/session-typescript.md)、[进程行](../../../design/process-typescript.md)),并进入各表自己的绑定:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | | `register`(方法表的) | async | `namespace`、`MethodDecl[]`、`call` | 注册完成时无返回值;被拒绝时返回错误 | -| `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply`,或 `MethodError` | +| `call`(注册部件自己的函数) | async | `MethodCall`、`cancelled`、`progress` | `MethodReply` 数据:处理函数的值,或它自己的 `{code, message, ...所有者字段}` 错误 | ```text // MethodDecl @@ -215,37 +221,29 @@ sequenceDiagram "mutating": true, "interruption": "report" | "drain", // 卸载时由提供方回复:report → operation_interrupted;drain → 调用自己的结果 "progress": false, - "notifications?": ["session.goal.changed"], // 位于命名空间内 - "reply": "direct" | "handoff" } // handoff:daemon.shutdown -// MethodCall -{ "callId": "string", "method": "session.goal.set", - "params": {}, // 原样传入;Session 方法的 sessionId(以及 branchId)留在这里 - "origin": { "entry?": { "name": "string", "deviceId?": "string" }, // 连接的 ConnectionEntry - "connectionId?": "string", "peer?": "string" } } // peer:rutis 链接;仅用于诊断 -// MethodReply -{ "kind": "value", "value": {} } | { "kind": "handedOff" } -// MethodError -{ "code": -32000, "appError": "string", "message": "string" } + "notifications?": ["session.goal.changed"], // 等于或位于命名空间内 + "reply?": "direct" | "handoff" } // handoff:daemon.shutdown;交接落地前接受并忽略 +// MethodCall、MethodReply 与方法表的错误:见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)。 ``` -目前已实现(附录 F):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(线上为 `origin.connectionId`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply`、`handedOff`、`origin.entry` 与 `origin.peer` 未实现。 +目前已实现([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix)):`MethodDecl.name`、`MethodDecl.mutating`、`interruption`、`progress` 与 `notifications`,以及 `MethodCall.method`、`params` 与 `origin.caller`(原生处理函数收到 A.2 的 `Caller`;当前线上是顶层 `callId` 与扁平的 `origin.connectionId`,目标把它们嵌套为 `origin.caller`);外来 `register` 从外来部件的声明解码这些字段,为每次调用提供新的 `callId`,并在调用来自连接时加上 `origin.connectionId`。`reply` 是目标中的字段:今天的 `MethodDecl` 没有它,目标在交接落地前接受并忽略;回复交接未实现,目标删除 `origin.entry` 与 `origin.peer`。 取消与中断:调用由提供方自己回复,不由 Rpc 回复。有两种情况会中断已受理的调用:提供方这一代卸载,以及受理该调用的 Rpc 装载卸载。任一发生时,处理函数的取消令牌都会触发,`drain` 调用也不例外。随后 `report` 调用立即回复 `operation_interrupted`(操作可能已经提交),之后再结算;`drain` 调用回复自己的结果。提供方的卸载等待它受理的每个调用,包括 `report` 调用。调用方断开不会取消任何东西。 | 规则 | 内容 | | --- | --- | | 命名空间 | `(.)*`,段为 `[a-z][a-z0-9_]*`,最多 128 字节,由注册它的部件拥有;命名空间本身可以是一个方法(`session.rename`)。不符合该语法的命名空间在注册时被拒绝,被调用的名称不符合该语法时不做任何查找,直接为 `unknown_method` | -| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明(至少一个方法,每个方法唯一且位于命名空间内)和它的 `call` 注册到其作用域的方法表。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | +| 注册 | 部件在自己的 `apply` 中把命名空间连同其声明和它的 `call` 注册到其作用域的方法表。声明规则——至少一个方法;方法名唯一且等于或位于命名空间内;通知等于或位于其命名空间内、在集合内唯一且不等于任何方法名——归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约。Rust 部件传入自己的 ctx;其他语言由桥把注册绑定到调用方行,`call` 是该行的函数,经桥回调。注册属于该部件,在它卸载时撤回。在同一张表中再次注册同一命名空间会失败(` is registered already`)。方法表在注册时检查命名空间与声明(见下文保留名);被拒绝的注册使发起注册的部件失败 | | 所有权 | 名称属于该表中作为其前缀或与其相等的最长已注册命名空间。已撤回的命名空间仍持有它的名称:方法表记住注册它的行,调用按该行的状态作答(§3.2;见下文 Session 级调用)。该表从没有命名空间持有过的名称没有所有者 | -| 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | +| 保留名 | 在命名空间注册时检查。精确内建名是 `is_builtin_method` 接受的名称([protocol.rs](../../../../crates/dim-app-server/src/protocol.rs))。声明与通知的规则归 [SessionMethods](../../../design/plugins/SessionMethods.md#own-contract) 契约。声明的通知不能取内建通知的线上名称,即 `Notification` 各变体的名称:提供方不能冒充其连接已经在读取的通知。管理方法:命名空间须符合语法,不能位于保留根(`hello`、`daemon`、`agent`、`approval`、`session`)之内,任何前缀都不能等于精确内建名,声明的方法也不能等于精确内建名("Invalid management namespace"、"Invalid management contribution");精确内建名不会落在管理命名空间之内,因为每个精确内建名都位于某个保留根之下。Session:App Server 提供进程值 `ReservedMethods`,每个 Session 的方法表都用它检查;不符合语法、位于根 `hello`、`daemon`、`agent` 或 `approval` 之内,或者与精确内建名相等、包含它或位于它之内的命名空间被拒绝("invalid Session namespace ")。例如 `session.mcp` 是精确内建名,因此 `session.mcp`、`session.mcp.extra` 以及包含它的单独 `session` 根都被拒绝。Session 命名空间可以位于 `session` 之下(`session.goal`、`session.input`)。`session.input` 不保留:InputQueue 把它注册到 `sessionMethods`,因此 Rpc 不点名任何所属服务 | | 优先级与路由 | 内建方法;否则,管理命名空间(已注册或已撤回)持有的名称交给管理方法(§3.2);否则,对协议 v3+,符合语法且 params 对象带 `sessionId` 字段的名称是 Session 方法候选(见下文 Session 级调用);否则交给管理方法,没有命名空间持有的名称为 `unknown_method`。共用一个线上名称空间。params 中没有 `sessionId` 的名称从不是 Session 方法候选:没有 Session,Rpc 就不知道它的命名空间,因此只有 Session 命名空间持有的名称在没有 `sessionId` 时为 `unknown_method` | | 命名空间冲突 | 没有装配检查,由路由优先级决定。与某个管理命名空间相等、包含它或位于它之内的 Session 命名空间照常注册,但管理命名空间持有的名称路由到管理方法,从不到达该 Session | -| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 在该 Session 的 `sessionMethods` 中读取该名称的所有者:已注册的命名空间 → 其提供方;已撤回的命名空间 → 读取注册它的行在本 Session 中的副本状态(§9.4),按管理方法的对照表作答(§3.2):该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称 → `unknown_method`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | +| Session 级调用 | Rpc 从候选的原始 params 读取 `sessionId`;不是非空字符串时结果为 `-32602`(空字符串为 `invalid_params`,"sessionId must not be empty")。Rpc 对其授权,并通过 `index.acquire` 获取该 Session,未装载的 Session 会被恢复(不同于 `approval.respond`:对未装载的 Session 它返回 `session_closed`);非空但不对应任何 Session 的 id 为 `session_closed`。然后 Rpc 调用该 Session 的 `sessionMethods.call {method, params, caller?}`([SessionMethods](../../../design/plugins/SessionMethods.md#own-contract)):方法表找到该名称的所有者并作答自己的错误。已注册命名空间的处理函数回复;已撤回的命名空间按注册它的行在本 Session 中的副本状态(§3.2)作答:该副本尚未启动、处于 Pending、Loading 或新旧两代之间时返回 `service_reloading`,处于 Failed、Unresolved、Disposed 或 Stopped 时返回 `service_unavailable`,副本处于 Active(该行的子插件正在重载)或没有副本(部件处于新旧两代之间)时返回 `service_reloading`;本 Session 从没有命名空间持有过的名称,以及注册它的行已禁用或不存在的名称 → `unknown_method`;未安装 `loaderRows` 时,已撤回的命名空间答 `service_reloading`。Rpc 一直持有该 Session 的使用权,直到调用的操作结算。`sessionId` 与 `branchId` 留在 `params` 中;Rpc 读取 `sessionId` 只为授权和解析。提供方通过该分支的服务到达某个分支。管理命名空间持有的名称,或 params 中没有 `sessionId` 的名称,从不恢复 Session | | 调用归属 | Session 级提供方这一代拥有它受理的调用,与管理方法提供方相同:由它回复,它的卸载按 `interruption` 中断这些调用并等待它们(见上文取消与中断) | -| 共享类型 | `MethodDecl`、`Interruption`、`Handler`、`Progress`、`RpcError` 与 `MethodTable`,连同两张方法表共用的调用受理逻辑,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session Capability 不能依赖 dim-app-server。它们与 Session 方法表 `SessionMethods` 放在一起(附录 F),如同 `ToolContribution` 与同样接收 `CancellationToken` 的 `ToolHandler` 和 ToolRegistry 放在一起。不放在 dim-agent-types:它只允许依赖 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不依赖 Tokio 或 rutis),而 `Handler` 接收 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 放在那里时,`From for RpcError` 只能在 dim-agent-runtime 中实现(孤儿规则)。放在 dim-agent-capabilities 时,这个转换与 `RpcError` 放在一起,Rpc 与 Session 提供方仍可对运行时错误使用 `?` | +| 共享类型 | `MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`,连同两张方法表共用的调用受理,位于 dim-agent-capabilities 的 `methods` 模块,因为那里的 Session 能力不能依赖 dim-app-server。它们的唯一定义是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定。不放在 dim-agent-types:它只接受 serde 与 serde_json(`xtask check`;[架构](../../../architecture/README.md):不用 Tokio 或 rutis),而 `Handler` 持有 tokio-util 的 `CancellationToken` 并返回 rutis 的 `BoxFuture`;并且 `RpcError` 在那里时,`From for RpcError` 只能在 dim-agent-runtime 实现(孤儿规则)。在 dim-agent-capabilities 中该转换与 `RpcError` 同处,因此 Rpc 与 Session 提供方都对运行时错误保留 `?` | | 不分发 | 该表从没有命名空间持有过该名称、注册其已撤回命名空间的行已禁用或不存在(对管理方法,还包括处于 Active 但没有重新注册的行)、提供方未声明该名称、只有 Session 命名空间持有的名称在 params 中没有 `sessionId`、在带 `deviceId` 的连接、未导出的链接或裸 WebSocket 上调用管理方法,或 v1/v2 → `-32601 unknown_method`。Session 正在重载,或已撤回命名空间的注册行(对 Session 命名空间,是该行在该 Session 中的副本)尚未启动、处于 Pending、Loading 或新旧两代之间,或已撤回 Session 命名空间的副本处于 Active 或不存在 → `-32000 service_reloading`(可重试)。已撤回命名空间的注册行或其在该 Session 中的副本处于 Failed、Unresolved、Disposed 或 Stopped → `-32000 service_unavailable`(不可重试)。不对应任何 Session 的 Session id → `session_closed`。已开始的 `report` 调用被中断 → `operation_interrupted` | | `hello.features`(v3) | 内建方法;连接获得管理方法时(本地 v3),再加上调用时已注册的管理命名空间的方法,每个方法只列在拥有它的命名空间下。Session 级方法不在这里列出,由 `session.methods` 按 Session 列出 | -| `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | +| `session.methods` | 公开接口,Rpc 内建方法,与它列出的方法一样仅限协议 v3:`session.methods {sessionId}` → `{ "methods": [ { "name": "string", "mutating": true } ] }`,即该 Session 中此刻已注册的命名空间所声明的方法,但不含管理命名空间持有的名字:这些名字即使调用中带有 Session 也会路由到管理。它与其他 Session 级内建方法一样授权和解析(未装载的 Session 会被恢复),每个方法只列在拥有它的命名空间下并按名称排序,并增加一个精确内建名。进程正在关闭时它答 `service_unavailable`,因为它读不到管理命名空间持有的名字。在提供 Session 操作的连接上,v3 的 `hello.features` 列出它 | | 就绪闩 | 原生绑定在首个 `hello` 前等待必需进程提供方;[TS 进程绑定](../../../design/process-typescript.md#21-startup-and-availability) 不把可选扩展行纳入宿主启动/重启就绪条件。`hello.features` 只列出调用时已注册的命名空间,后来注册的在下次 `hello` 出现。 | 连接的入口接纳调用后,Rpc 如何路由: @@ -266,22 +264,23 @@ sequenceDiagram 授权;index.acquire(恢复未装载的 Session; | 未知 id -> session_closed) | - 该 Session 的 sessionMethods 中的所有者? ---- 没有 -----> -32601 unknown_method + sessionMethods.call {method, params, caller?} -> 方法表查找所有者 + | 没有 -----> -32601 unknown_method | 已撤回 ---> 注册它的行在本 Session 中的副本 - | (§9.4、§3.2): + | (§3.2): | 启动中或重载中、Active 或没有副本 | -> -32000 service_reloading | Failed、Unresolved、Disposed 或 Stopped | -> -32000 service_unavailable | 已注册 - 提供方调用 --> 回复(未声明的名称:-32601 unknown_method) + 处理函数 --> CallReply(未声明的名称:-32601 unknown_method) ``` 目前注册的 Session 命名空间:`session.question`(Questions)、`session.goal`(Goal)、`session.rename`(SessionTitle)、`session.input`(InputQueue)、`session.context`(ContextCompaction)、`session.exec.output`(WorkspaceTools,[后台任务输出](../../../design/background-task-output.md))、`session.agent`([模型配置](../../../design/model-configuration.md))、`attachment`(Attachments)、`shell`(ShellInput)、`session.wakeup`(Scheduler,[Scheduler §10](../plugins/Scheduler.md#10-session-作用域的一次性唤醒))、`session.collaboration`(Collaboration,[Collaboration §6.7](../plugins/Collaboration.md#67-从客户端停止成员))。`approval.respond` 是内建的 Session 方法,不是部件注册。分支方法——`session.branch_create`、`session.branch_end`、`session.branch_set_default`、`session.branches` 与 `session.branch.get`——同样都是内建方法,它们的契约见[timeline branches §9、§10 与 §14](../timeline-branches.md#14-客户端):它们接受的每个 `branchId` 各指名一条线,省略的那个指名Session 的主线,而不是它的根。`session.branch_set_default` 在根不是主线时接受根作为目标,只拒绝已经是主线的目标;`session.branch_end` 对任何调用方都拒绝当前主线,所以要结束它,先移动主线。Hooks 不注册 Session 命名空间:它的 `hooks.*` 方法是管理方法([Hooks A.7](../plugins/Hooks.md#a7-管理方法))。各插件文档对其方法具有权威性。 ### A.2 调用通道 -`progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现。App Server 以自己的 `CallChannel` 行向方法提供方提供进程服务 `callChannel`,因此声明该名字的行不会随 Rpc 重载;Rust 绑定是处理函数按调用获得的 `Progress` 与 `Caller`(附录 F)。 +`progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现。App Server 以自己的 `CallChannel` 行向方法提供方提供进程服务 `callChannel`,因此声明该名字的行不会随 Rpc 重载;Rust 绑定是处理函数按调用获得的 `Progress` 与 `Caller`([SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix))。 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | @@ -297,7 +296,7 @@ sequenceDiagram ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., sink of A) ---->|-- handler(.., progress) -->| + | |-- call(.., sink of A) ------>|-- handler(.., progress) -->| | | | (sink only if declared) | |<-- management.progress {id: 7, method: "x.run", data} ------- progress.send -->| | | |<-- result -----------------| @@ -319,14 +318,14 @@ reply ----------> 回复与通知额度 ----------------+ 已满:慢消费者,关闭连接 ``` -通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即提供方收到的 `MethodCall` 的 `callId`。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 +通知是 JSON-RPC 通知 `{"jsonrpc":"2.0","method":"<声明的名称>","params":{...}}`,只写到发起调用的连接;该 Session 的其他客户端收不到。`params` 是 JSON 对象。`callId` 必填,指通知所报告工作所属的调用:即另一种语言注册所提供的调用被铸出的 id,由 `origin.caller.callId` 携带。原生处理函数没有这个 id:它经自己的 `Caller` 通知。该调用的回复尚未写出时,它的通知按序暂存并在回复之后写出;回复写出后,或该 id 不在途时,直接写出。`connectionId` 是地址:未从该连接收到过调用的行返回 `gone`。只能发送服务过该连接的代际声明过、且等于或位于其命名空间内的名称;其他名称返回 `undeclared`,不写任何内容。 一次调用的通知如何到达调用方: ```text Client A Rpc call admission provider handler | x.run {..} id 7 -->| | | - | |-- accept(.., caller) ->|-- handler(.., caller) -->| + | |-- call(.., site) ----->|-- handler(.., caller) -->| | | | notify(callId, ..) | | | | 暂存:等回复之后 | | | |<-- result ---------------| @@ -339,7 +338,7 @@ Client A Rpc call admission provider han 送达方式与进度不同: - **可靠。** 提供方发送通知时只编码一次。调用的回复尚未写出时发出的通知经连接的暂存额度受理:其上限与回复与通知额度相同(1024 帧、32 MiB)但彼此独立,因此暂存的通知不会占用回复所需的空间。一次调用暂存的通知超过暂存额度时,该客户端像慢消费者一样被断开,之后的 `notify` 返回 `gone`。回复只经回复与通知额度受理。回复写出后,暂存的通知按序连同它们已占用的额度进入发送队列,并在各自写出后释放;因此连接的排队帧由两个额度共同界定,至多 2048 帧、64 MiB。超过帧上限的通知返回 `too_large`:不写任何内容,连接保持。 -- **回复之后。** 通知写在它 `callId` 所指调用的回复之后,该 `callId` 即报告该工作的 `MethodCall` 的 `callId`。调用仍进行时发出的通知按序暂存,紧接回复之后写出,因此客户端不会先看到回复尚未告知的对象的通知(例如回复才返回的 id)。该回复写出后,或该 id 不在途时,通知直接进入发送队列;同一连接上另一个未完成的调用既不会暂存它,也不会改变它的顺序。每条路径都会写出回复,包括被中断的调用和连接已消失的调用。 +- **回复之后。** 通知写在它 `callId` 所指调用的回复之后,该 `callId` 即另一种语言注册所提供的调用被铸出的 id,由 `origin.caller.callId` 携带。原生处理函数没有这个 id:它的 `Caller` 把通知暂存到该调用的回复写出为止。调用仍进行时发出的通知按序暂存,紧接回复之后写出,因此客户端不会先看到回复尚未告知的对象的通知(例如回复才返回的 id)。该回复写出后,或该 id 不在途时,通知直接进入发送队列;同一连接上另一个未完成的调用既不会暂存它,也不会改变它的顺序。每条路径都会写出回复,包括被中断的调用和连接已消失的调用。 - **生命周期。** 连接关闭,或受理该调用的 Rpc 代际卸载后,`closed` 完成,之后的 `notify` 返回 `gone`。提供方代际卸载后发出的通知在两种绑定中都返回 `gone`:原生调用方持有该代际的停止信号,外来索引在同一次卸载时删除该实例的条目。调用方断开不取消任何调用。未从某连接收到过调用的行,其 `notify` 与 `closed` 对该连接返回 `gone`。服务按行实例与连接保存一个条目,内含该连接按 `callId` 记录的未完成调用;连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除条目,调用在回复写出后从条目中移除。 - **拒绝顺序。** 代际已装载时,两种绑定都先判定 `undeclared`,再看连接状态:连接已关闭也不会掩盖该代际未声明的名称。已卸载的代际对任何名称都返回 `gone`,无论是否声明过。 @@ -496,11 +495,11 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 | Session 正在重载,或已撤回命名空间的注册行(或其在该 Session 中的副本)未运行且未失败(尚未启动、Pending、Loading,或新旧两代之间),或已撤回 Session 命名空间的副本处于 Active 或不存在 | `-32000`,`service_reloading`(可重试) | | 已撤回命名空间的注册行,或该行在该 Session 中的副本,处于 Failed、Unresolved、Disposed 或 Stopped | `-32000`,`service_unavailable`(不可重试) | | `report` 调用被中断 | `-32000`,`operation_interrupted` | -| 提供方错误 | `-32000`,提供方的 `appError` | +| 处理函数错误 | 处理函数自选的 JSON-RPC 码,未选则为 Rpc 为服务错误给出的码(`invalid_params` → -32602、`unknown_method` → -32601,其他为 -32000),并带处理函数的 `appError` 与其所有者字段 | ## 附录 D. 验收 -1. Session 级方法经其指定的 Session 分发。该 Session 从没有命名空间持有过的名称返回 `unknown_method`;命名空间已撤回时,注册它的部件正在启动或重载则返回 `service_reloading`,该部件处于 Failed 或 Unresolved 则返回 `service_unavailable`;Rpc 从不点名提供方。与内建方法重叠或位于保留根之内的 Session 命名空间在注册时被拒绝,位于管理命名空间之内的 Session 命名空间从收不到该管理命名空间持有的名称。 +1. Session 级方法经其指定的 Session 分发。该 Session 从没有命名空间持有过的名称返回 `unknown_method`,注册它的行已禁用或不存在的名称同样返回 `unknown_method`;命名空间已撤回时,注册它的部件正在启动、重载或在本 Session 中没有副本则返回 `service_reloading`,该部件处于 Failed 或 Unresolved 则返回 `service_unavailable`;Rpc 从不点名提供方。与内建方法重叠或位于保留根之内的 Session 命名空间在注册时被拒绝,位于管理命名空间之内的 Session 命名空间从收不到该管理命名空间持有的名称。 2. 管理方法在本地入口上可达,在 RemoteGateway 上返回 `unknown_method`,只在导出时经链接可达。`shell.*` Session 方法与所有 Session 方法一样可在 RemoteGateway 上调用。 3. 每个迁移后的管理方法的录制记录与迁移前的记录一致,且 v3 本地 profile 的 `hello.features` 不变。 4. 在 RemoteGateway 测试入口上,`session.permission.update` 与 `session.exec.stop` 成功。 @@ -520,81 +519,27 @@ ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采 ## 附录 F. Rust 绑定 -上述服务映射到下列原生所有者。工具注册到 ToolRegistry(A.5)。每张方法表也经自己的分发器服务其他语言:`SessionMethods` 部件在 `host_key_in("sessionMethods", session_instance)`,App Server 的 `ManagementMethods` 行在 `host_key("managementMethods")`。其他语言的 Session 部件([C4](../../../design/session-typescript.md))或进程行([TypeScript 进程绑定](../../../design/process-typescript.md))注入方法表并调用 `register(namespace, declarations, call)`,它返回一个 Promise。注册属于调用方(桥的调用方行),`call` 经桥回调,并使用 C1 的受理、进度与 `report`/`drain`;已受理的调用在调用方清理之前结束。不向 Session facade 增加按名称的服务查找,入口准入不变。Session 部件从 `sessionIdentity`、`sessionConfig` 与 `sessionLifecycle` 服务读取 Session 标识、配置与 closing;每个部件自己监听其 Session 的 `session/{sessionId}` 通道。它不增加公开 facade 查找或关键分支输入路径。连接通知(`notify` 与 `closed`)在两种绑定中均已实现;交接(`takeFinalReply`)不在已实现的子集内。 +上述服务映射到下列原生所有者。工具注册到 ToolRegistry(A.5)。每张方法表的 Rust 绑定与线上形状归其所有者契约:`sessionMethods` 见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),`managementMethods` 见进程表的契约([#2021](https://github.com/arcships/dim/issues/2021))。不向 Session facade 增加按名称的服务查找,入口准入不变。Session 部件从 `sessionIdentity`、`sessionConfig` 与 `sessionLifecycle` 服务读取 Session 标识、配置与 closing;每个部件自己监听其 Session 的 `session/{sessionId}` 通道。它不增加公开 facade 查找或关键分支输入路径。连接通知(`notify` 与 `closed`)在两种绑定中均已实现;交接(`takeFinalReply`)不在已实现的子集内。 | 语言中立服务 | Rust 类型 | Rust 中的注册 | 收集 | 状态 | | --- | --- | --- | --- | --- | | `managementMethods` | `ManagementMethods`,持有一个 `MethodTable` 的进程服务,由 App Server 的 `ManagementMethodsPlugin` 行提供 | 进程部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | Rpc 依赖这张表并按调用读取(`management_provider`,§3.2),行状态来自 `loader.get(row)`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(#14、#382) | -| `sessionMethods` | `SessionMethods`,持有一个 `MethodTable` 的 Session 服务,由 `SessionMethodsPlugin` Session 部件提供;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件依赖 `Keyed`,在其 `apply` 中调用 `methods.register(ctx, ns, Vec, Handler)` | 每次调用:在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `Session::session_service::()`,再经 `session_provider`(A.1);没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382) | +| `sessionMethods` | `SessionMethods`,由 `SessionMethodsPlugin` 部件提供的 Session 服务;其检查是 App Server 提供的进程值 `ReservedMethods` | Session 部件在其 `apply` 中调用 `register(ctx, namespace, declarations, call)`;操作、值与线上形状见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | Rpc 在 `sessionId` 指定、经 `index.acquire` 获取的 Session 上调用 `call`,并为 `session.methods` 调用 `methods`;没有提供方在 Rpc 的 `Deps` 中 | 已实现(C1、#382);目标操作见 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | | 工具注册 | `ToolContribution {definition, handler}`,注册到本 Session 的 `ToolRegistry`(`Keyed`) | 在部件的 `apply` 中调用 `tools.register(ctx, ToolContribution)`;动态来源用 `tools.register_source(ctx, name, provider)` | 每次读取纳入已注册的内容;挂载列表中没有注册的名称被省略并记录诊断;每次注册是注册表自有的带版本集合(A.5,#241) | 已实现(#382) | -| `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel` | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | - -```rust -// crates/dim-agent-capabilities/src/methods.rs(C1),两个服务共用 -pub type Handler = Arc< - dyn Fn(MethodCall, CancellationToken, Progress) - -> BoxFuture<'static, Result> + Send + Sync, ->; // (call, 取消令牌, 进度) -impl Progress { - pub fn send(&self, data: Value); // 尽力送达;未声明时、或回复交出之后丢弃 -} -pub enum Interruption { Report, Drain } -pub struct MethodDecl { - pub name: String, - pub mutating: bool, - #[serde(skip_serializing)] - pub interruption: Interruption, // 外来声明必填 - #[serde(skip_serializing)] - pub progress: bool, // 外来声明必填 - #[serde(default, skip_serializing)] - pub notifications: Vec, // 位于命名空间内,整个声明集内唯一 -} -impl MethodProvider { // 一代提供方:声明、处理函数、已受理的调用 - pub fn new(ctx: &Ctx, namespace: &str, declarations: Vec, handler: Handler, - foreign: bool) // 其他语言的部件:其调用被记录到回复写出 - -> Result, CordisError>; - pub fn accept(self: &Arc, method: String, params: Value, site: Option, - entry_stopping: CancellationToken, progress: impl Fn(Value) + Send + Sync + 'static) - -> Result; -} -// 方法表在命名空间及其声明注册之前对它们的检查。 -pub type Check = Arc Result<(), CordisError> + Send + Sync>; -pub enum Owner { Active(Arc), Left { row: Option }, None } -impl MethodTable { // 已注册的命名空间,以及已撤回的命名空间与其最后的行 - pub fn new(check: Check) -> Self; - pub fn register(&self, ctx: &Ctx, namespace: &str, declarations: Vec, - handler: Handler) -> Result<(), CordisError>; // 直到拥有 ctx 的部件卸载 - pub fn owner(&self, name: &str) -> Owner; // 持有 name 的最长命名空间 - pub fn listed(&self) -> Vec; // 已注册命名空间的方法 -} -pub struct SessionMethods(pub Arc); // Deref -pub struct ReservedMethods(Check); // 进程值:Session 方法表的检查, -// 也是数据面 `reservedMethods`;`check {namespace, declarations}` 就是这个问题 -// crates/dim-app-server/src/methods.rs -pub struct ManagementMethods(pub Arc); // Deref -``` +| `callChannel` | `progress`:处理函数的 `Progress` 参数,每次调用一个;`notify` 与 `closed`:处理函数 `MethodCall.origin` 上的 `Caller`,每次调用一个;其他语言使用进程服务 `callChannel`。调用数据归 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) | — | Rpc 为每个已受理调用提供一个通向发起调用连接的 sink;索引按 `callId` 记录其他语言的调用直到其回复写出,并在连接关闭或卸载时删除该连接的条目 | `progress`、`notify` 与 `closed` 已实现(C1、#1158);`takeFinalReply` 未实现 | -`MethodProvider::new` 拒绝无效的声明(A.1 的语法;至少一个方法,每个方法唯一且位于命名空间内;以及每个声明的通知:符合语法、位于命名空间内、整个声明集内不重复,且不等于任何方法名),并把提供方绑定到注册它的部件的这一代:这一代被取消时(这是卸载的第一步,早于它的任何 effect),提供方停止受理,并中断已受理的 `Report` 调用;它的卸载 effect 等待每个已受理调用,因此两张方法表不会分叉。其他语言的行在其 apply 返回的 effect 里卸载插件,这个 effect 先于 apply 期间注册的 effect 运行,所以它已受理的调用在插件仍在运行时就收到结束信号。`MethodTable::register` 先运行方法表的 `Check`,再构造提供方,并代表拥有 `ctx` 的部件注册该命名空间;已被注册的命名空间会失败。该部件卸载时,方法表把它的行与命名空间一起记下,之后的调用按该行作答(`Owner::Left`)。`ManagementMethods` 的检查是 A.1 保留名中的管理规则;Session 方法表的检查是 App Server 的 `ReservedMethods`,装配登记了这个名字时方法表依赖它;宿主不登记它时不保留任何名字,只检查语法。`ReservedMethods` 是数据面:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个))。处理函数接收 `MethodCall`——方法名、原始 params 与其 `Origin`——在任一卸载时触发的取消令牌(A.1),以及该调用的 `Progress`。调用由客户端连接发出时(无论经哪张表)`origin.caller` 存在,否则不存在。`RpcError`(连同它的 `From`)位于同一模块(A.1 共享类型);`ManagementMethods`、保留名检查与 Rpc 的查找(`management_provider`、`session_provider`)留在 dim-app-server。 - -`Progress` 按调用绑定 A.2 的 `progress`,而不是通过 `callChannel` 进程服务:Rpc 给每个已受理调用一个 sink,把 `management.progress {id, method, data}` 写到发起调用的连接;受理逻辑只在方法声明了 `progress` 时把它交给处理函数,并在交出回复之前关闭它。sink 在连接上按进度自己的额度排队,所以进度不会占用回复和持久通知的空间。管理方法走同一路径;`runtime.watch` 与 `schedule.watch` 声明了 `progress`([RuntimeManager §10](../plugins/RuntimeManager.md#10-客户端变更通知);[Scheduler §11.2](../plugins/Scheduler.md#112-任务与运行))。 - -```rust -// crates/dim-agent-capabilities/src/methods.rs,两个服务共用 -pub struct MethodCall { pub method: String, pub params: Value, pub origin: Origin } -pub struct Origin { pub caller: Option } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum NotifyError { Undeclared, Gone, TooLarge } // code():"undeclared"、"gone"、"too_large" -impl Caller { - pub fn id(&self) -> &str; // 合同中的 connectionId - pub fn notify(&self, method: &str, params: serde_json::Map) -> Result<(), NotifyError>; - pub fn closed(&self) -> impl Future + Send + 'static; -} -``` +调用数据——`MethodDecl`、`Interruption`、`MethodCall`、`Origin`、`Caller`、`CallerConnection`、`CallSite`、`MethodReply`、`MethodCallbackError`、`MethodError`、`Handler`、`Progress` 与 `NotifyError`——连同两张方法表共用的调用受理,是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 的绑定,位于 dim-agent-capabilities 的 `methods` 模块。`RpcError` 是 Rpc 的线上错误,其契约归 [#2021](https://github.com/arcships/dim/issues/2021),与这些类型同处一个模块以便转换。目标去掉这一 `Deref`:Session 表持有自己的存储,不对 `MethodTable` `Deref`。`RpcError` 在同一处保留 `From`,因此 Rpc 与 Session 提供方都对运行时错误保留 `?`。Session 方法表的检查是 App Server 的数据面 `ReservedMethods`:`reservedMethods.check {namespace, declarations: [{name, mutating, notifications}]} -> {}` 拒绝宿主保留的命名空间,Rust 方法表在进程内调用同一个操作([service faces §4.9](../../../design/service-faces.md#49-旧主机端口credentialvariableshost-等六个));宿主不登记它时只检查语法。 + +注册被拒绝会使注册它的部件失败:命名空间及其声明按名称语法与保留名检查,同一张表内已被注册的命名空间失败,注册持续到发起它的行卸载(A.1 注册)。 + +`Progress` 按调用绑定 A.2 的 `progress`,而不是通过 `callChannel` 进程服务:Rpc 给每个已受理调用一个 sink,把 `management.progress {id, method, data}` 写到发起调用的连接;方法表的 `call` 只在方法声明了 `progress` 时把它交给处理函数,并在回复写出之前关闭它。sink 在连接上按进度自己的额度排队,所以进度不会占用回复和持久通知的空间。管理方法走同一路径;`runtime.watch` 与 `schedule.watch` 声明了 `progress`([RuntimeManager §10](../plugins/RuntimeManager.md#10-客户端变更通知);[Scheduler §11.2](../plugins/Scheduler.md#112-任务与运行))。 + +`Caller`、`CallerConnection`、`CallSite`、`Progress` 与 `NotifyError` 位于模块的绑定里,形状由 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix) 给出;本附录说明 CallChannel 如何用它们,不说明其形状。 -`Caller` 与 `Progress` 一样按调用绑定 A.2 的 `notify` 与 `closed`:只有调用来自客户端连接时 `MethodProvider::accept` 才构造它,并绑定到该声明集声明的通知,因此集合外的名称在写入任何内容之前就是 `Undeclared`,已卸载的代际则先返回 `Gone`。它通过 `CallerConnection` 这个 trait 对象持有连接,而该对象不强引用连接,所以保留 `Caller` 的提供方不会让已关闭的连接存活。Rpc 在产生该 `Caller` 的调用回复之后写出每条通知:调用进行中发出的通知只编码一次,经连接的暂存额度受理,按序暂存,紧接回复之后写出;超过帧上限的通知是 `TooLarge`,连接保持;暂存额度收不下的通知作为慢消费者关闭连接。连接关闭或受理该调用的 Rpc 代际卸载时,`closed` 完成。 +`Caller` 与 `Progress` 一样按调用绑定 A.2 的 `notify` 与 `closed`:只有调用来自客户端连接时方法表的 `call` 才构造它,并绑定到该声明集声明的通知,因此集合外的名称在写入任何内容之前就是 `Undeclared`,已卸载的代际则先返回 `Gone`。它通过 `CallerConnection` 这个 trait 对象持有连接,而该对象不强引用连接,所以保留 `Caller` 的提供方不会让已关闭的连接存活。Rpc 在产生该 `Caller` 的调用回复之后写出每条通知:调用进行中发出的通知只编码一次,经连接的暂存额度受理,按序暂存,紧接回复之后写出;超过帧上限的通知是 `TooLarge`,连接保持;暂存额度收不下的通知作为慢消费者关闭连接。连接关闭或受理该调用的 Rpc 代际卸载时,`closed` 完成。 -`Callers` 是 CallChannel 和 Rpc 行通过 Rust 类型键共享的私有传输装配,不登记服务目录名称;公开操作面仍是 `callChannel`。`Callers` 是进程内唯一的调用方索引:按行实例保存该代际声明的通知名称,该实例的连接关闭后仍保留,因此先判定 `Undeclared` 再看连接状态;并按行实例与连接保存该连接的直接写入端与该行按 `callId` 记录的未完成调用。`MethodProvider::accept` 在调用的 sink、实例与提供方声明都可用的位置生成其他语言调用的 `callId` 并记录该调用;`Connection::answer` 在回复写出后移除它。连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除该连接的条目;声明的名称随该实例的代际一起删除。原生提供方保留自己的 `Caller`,不记录任何内容。App Server 以进程服务 `callChannel`(`ForeignCallChannel`,位于 `host_key("callChannel")`,由无依赖的 `CallChannel` 行提供)向其他语言提供 A.2 的 `callChannel`:其 `notify` 与 `closed` 用 `rutis_bridge::session::caller_row()` 读取调用行的实例,并最终落在 Rust 绑定所用同一次调用的 sink 上,两种绑定共用一条送达路径。 +`Callers` 是 CallChannel 和 Rpc 行通过 Rust 类型键共享的私有传输装配,不登记服务目录名称;公开操作面仍是 `callChannel`。`Callers` 是进程内唯一的调用方索引:按行实例保存该代际声明的通知名称,该实例的连接关闭后仍保留,因此先判定 `Undeclared` 再看连接状态;并按行实例与连接保存该连接的直接写入端与该行按 `callId` 记录的未完成调用。方法表的受理在调用的 sink、实例与提供方声明都可用的位置生成其他语言调用的 `callId` 并记录该调用;`Connection::answer` 在回复写出后移除它。连接关闭、受理该调用的 Rpc 代际卸载或该行代际卸载时删除该连接的条目;声明的名称随该实例的代际一起删除。原生提供方保留自己的 `Caller`,不记录任何内容。App Server 以进程服务 `callChannel`(`ForeignCallChannel`,位于 `host_key("callChannel")`,由无依赖的 `CallChannel` 行提供)向其他语言提供 A.2 的 `callChannel`:其 `notify` 与 `closed` 用 `rutis_bridge::session::caller_row()` 读取调用行的实例,并最终落在 Rust 绑定所用同一次调用的 sink 上,两种绑定共用一条送达路径。 -外来 `register`(`ForeignMethods`,两张方法表共用)一次性解码声明,要求上列必填字段。它在调用来自连接时以 `{callId, method, params, origin: {connectionId}}`、否则以 `{callId, method, params}`、取消 Promise 及逐次调用的进度回调调用 `call`,并解码 `{kind:"value", value}` 或 `{code, message}` 错误,其中 `code` 即 `appError`;省略的 `value`(包括 JSON 序列化时省略的 JavaScript `undefined`)成为 JSON `null`。方法也可以重新抛出它收到的服务错误。不支持的声明/回复字段及损坏数据在此边界失败。尚未实现:最终回复交接、`origin.entry` 与 `origin.peer`,以及 `reply` 声明字段。 +外来注册经各自表的分发器:Session 表的是 [SessionMethods](../../../design/plugins/SessionMethods.md#binding-appendix),进程表的是它自己的契约([#2021](https://github.com/arcships/dim/issues/2021))。两者都一次性解码声明,并以调用方的函数调用同一个 `register`;`ForeignMethods` 离开。两种绑定都未实现:最终回复交接。声明的 `reply` 字段接受并忽略。 `ToolContribution` 与 `ToolHandler` 是 `dim-agent-capabilities/src/tool_registry.rs` 中的原生类型。`ToolRegistry::register(ctx, ToolContribution)` 代表拥有 `ctx` 的部件注册,直到该部件卸载;它拒绝不满足 `[A-Za-z0-9_-]{1,64}` 的名称、宿主工具名和已被注册的名称。其他语言经 ToolRegistry 的分发器访问 `toolRegistry`:`register(declaration, execute, options?)` 把声明解码为 `ToolDefinition` 一次,要求 `risk` 非空,并代表调用方行(桥的 `caller_row`)注册一个经桥回调 `execute` 的 `ToolHandler`。`options.concurrency` 取 `'concurrent'` 或缺省;它不属于声明,因为这个类别是绑定后处理器的执行属性,所以落盘的 `ToolDefinition` 形状不变。缺省表示该工具的调用单独执行,按调用顺序。该处理器持有调用方行的代次令牌:行开始卸载后,经保留的处理器发起的调用不会发出,在途调用以错误结束,错误提示它可能已经生效,不会改绑到新的代次;外部所有者仍负责结算其 JavaScript 工作。每次执行派生自己的子取消令牌,单个工具正常完成不会取消同批其他工具。 diff --git a/docs/zh/design/plugins/README.md b/docs/zh/design/plugins/README.md index 266a344e16..259484f5e4 100644 --- a/docs/zh/design/plugins/README.md +++ b/docs/zh/design/plugins/README.md @@ -8,6 +8,7 @@ | 插件 | 进程部件 | Session 部件 | 分支部件 | 阶段 / issue | | --- | --- | --- | --- | --- | +| [SessionMethods](../../../design/plugins/SessionMethods.md)(所有者契约) | — | `sessionMethods`:本 Session 的方法命名空间、调用准入与方法清单 | — | [#2026](https://github.com/arcships/dim/issues/2026) | | [Migration](../../../design/plugins/Migration.md) | 按需加载的导入任务、来源映射、进度与重试记录;结算后卸载 | — | — | [实施计划](../../../plan/analysis/legacy-migration.md) | | [Provider 管理](../appserver/provider-management.md) | 现有 Provider:配置、目录、客户端偏好与管理方法 | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` 工具、`session.question.respond`、运行中 `ask_user` 调用的等待者;没有事件 | — | M2;#262 |