From 4a29c15aa14649ac66ff80a0ba11631ab538f3c6 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:32:55 +0800 Subject: [PATCH 1/9] design(provider): target contracts for the model and provider owners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Write the owner contracts for the model and provider board under design rules §7: the responsibility split, the caller compositions, the operations with their cancellation and error kinds, the flows that settle each resource, the exceptions, the rule check and the Rust bindings. Provider becomes the single model owner of the product profile: resolution, preference application, selection listing, temporary startup admissions, request execution, media routes and one-attempt credentials. It owns the driver, so credentials never leave the owner and no connection crosses. ConfiguredModels answers the same `providerService` operations from the model file. Account owners share one contract: availability and its subscription, the account catalog, and one `with_lease` operation that hands the lease to the caller's attempt, recovers once and settles the lease itself, so no caller holds a lease id. DimOAuth adds relay search and title. The ChatGPT account remains; the ManagedProviders host binding and the `managedSearch` face are retired, so no owner returns another owner's data. ModelLog and the provider document stay with the Settings board (#2094); the driver reads ModelLog's recording value. Refs #2019 · Refs #2015 --- docs/design/plugins/ConfiguredModels.md | 103 +++++++ docs/design/plugins/DimOAuth.md | 133 +++++++++ docs/design/plugins/ManagedAccount.md | 201 +++++++++++++ docs/design/plugins/ManagedOAuth.md | 112 ++++++++ docs/design/plugins/ManagedProviders.md | 111 ++++++++ docs/design/plugins/Provider.md | 358 ++++++++++++++++++++++++ docs/design/plugins/README.md | 6 + 7 files changed, 1024 insertions(+) create mode 100644 docs/design/plugins/ConfiguredModels.md create mode 100644 docs/design/plugins/DimOAuth.md create mode 100644 docs/design/plugins/ManagedAccount.md create mode 100644 docs/design/plugins/ManagedOAuth.md create mode 100644 docs/design/plugins/ManagedProviders.md create mode 100644 docs/design/plugins/Provider.md diff --git a/docs/design/plugins/ConfiguredModels.md b/docs/design/plugins/ConfiguredModels.md new file mode 100644 index 0000000000..d6d47eedbc --- /dev/null +++ b/docs/design/plugins/ConfiguredModels.md @@ -0,0 +1,103 @@ +# ConfiguredModels + +Scope: process. Issue: [#2019](https://github.com/arcships/dim/issues/2019). + +ConfiguredModels is the model owner of the API-key profile: the model file passed with `--model-config` is its catalog, the environment variables the file names are its credentials, and the same operations [Provider](Provider.md) provides answer the same callers. This document records what the profile changes; the operations, caller intents, cancellation and error kinds are [Provider](Provider.md)'s. + +## Use and scope: responsibility split + +ConfiguredModels owns: + +- **The model file.** Its providers and models, their endpoints, protocols, limits and `apiKeyEnv` names. The file is validated at load: both limits are required, and no modality operation is declared. +- **Selection.** The default model is the file's first model; an explicit target must be in the file. There is no workspace or global selection, no preferences and no account. +- **Credentials.** The environment variable the file names for a provider; no record and no secret store. +- **Execution.** One model request through the same driver, retry and recovery path as Provider. + +Callers keep everything they keep with Provider: the Session's adopted model and configuration, the request, the output handling and the summary budget. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Choose a model for a Session | No: the file's default and its validation are this owner's | `resolve` | +| List the models a use can run | No: the file and its limits are this owner's | `selectable` | +| Run one model request | No: credentials, retries and streaming are the owner's | `invoke` | +| A media model's route and credential | No: the file declares no modality operation | `media_route` answers `unavailable` for every operation | +| Run one exchange with a model's environment credential (the media executor) | No: the credential is this owner's resource | `with_lease` | +| Apply a preference patch | No: the file declares no effort or tier | `preferences` is absent in this profile; the client protocol rejects preferences | +| Admit a temporary connection | No: the file is the only connection source | `prepare_startup` is absent; the client protocol rejects startup | +| Learn where the recorder writes | Yes: read ModelLog's `recording` value | Business | + +## Caller example + +The Rpc entry and Agents call `providerService` exactly as in [Provider](Provider.md); the profile decides which owner answers: + +```rust +let selection = provider + .resolve(ResolveRequest { target: explicit, cwd: Some(cwd) }, cancelled.clone()) + .await?; +``` + +ModelProvider runs a turn through the same operation: + +```rust +let outcome = provider + .invoke(InvokeRequest { request, mode: Mode::Dialogue { chain }, consume, admit: None }, cancelled) + .await?; +``` + +## Own contract + +### Face and operations + +Face `providerService`, marked on `ConfiguredModels`; operations `resolve`, `selectable`, `invoke`, `media_route` and `with_lease`, with [Provider](Provider.md)'s request and reply types. `media_route` answers `unavailable`: a model file declares no `.`, so no media call resolves. `with_lease` hands the environment credential to the caller's attempt for one exchange and drops it when the attempt ends. `preferences`, `prepare_startup`, `retain_startup` and `release_startup` do not exist in this profile; the recorder reads ModelLog's `recording` value. + +The file's entries declare both limits; a selection always carries them, so `resolve` and `selectable` cannot fail for an undeclared limit. `selectable(chat)` returns every entry in file order; `selectable(modality)` returns none. + +### Errors + +[Provider](Provider.md)'s kinds, minus `invalid_connection`, `invalid_path` and `output_limit`'s startup variants: `invalid` for a malformed request, `not_found` for a target missing from the file, `unavailable` for a media operation or a missing environment variable, `cancelled`, `closed`, `failed` and `provider_failed {retryable}`; `with_lease` has `not_found`, `unavailable`, `cancelled` and `closed`. + +### Flows + +[Provider](Provider.md)'s `resolve`, `selectable`, `invoke` and `with_lease` flows. The file is loaded at `apply`; a reload re-reads it. No record, selection or lease is persisted. + +## Exceptions with reasons + +- `with_lease` hands the environment credential to the caller's attempt for one exchange; the same prohibition as [ManagedAccount](ManagedAccount.md) applies. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part; no Timeline facts. | +| §2 scopes | Process: the file and its credentials are shared across the assembly. | +| §3 orthogonality | No other owner's state is read; the file is this owner's configuration. | +| §4 rules 1–6, 9 | No events, handoffs, callbacks, batches, context or Timeline state. | +| §4 rule 7 | Callers use the face; none reads the file or the environment directly. | +| §4 rule 8 | No infrastructure change. | +| §7 one change | The delivery part deletes the `ModelHost`, selection, selectable and auxiliary names in this profile together with Provider's. | +| ADR 002 D1 | Process scope. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Depends on nothing but its file; callers depend on `providerService`. | +| ADR 002 D4 | The model file is structural configuration; there is no business state. | +| ADR 002 D5 | The face is language-neutral. | + +## Requirements raised to mechanism owners + +None. The model file and its validation are this owner's; no other owner's operation is needed. + +## Binding appendix + +`providerService` is [Provider](Provider.md)'s name; this profile registers the same name from `ConfiguredModels`. The types are shared; only the operations listed above exist. + +```rust +impl PublicService for ConfiguredModels {} + +#[rutis::service(name = "providerService")] +impl ConfiguredModels { + pub async fn resolve(&self, request: ResolveRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn selectable(&self, request: SelectableRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result<(), ProviderError> { /* ... */ } +} +``` diff --git a/docs/design/plugins/DimOAuth.md b/docs/design/plugins/DimOAuth.md new file mode 100644 index 0000000000..ae243d2b7d --- /dev/null +++ b/docs/design/plugins/DimOAuth.md @@ -0,0 +1,133 @@ +# DimOAuth + +Scope: process. Issue: [#2019](https://github.com/arcships/dim/issues/2019). Source: [`crates/dim-oauth`](../../../crates/dim-oauth/README.md). + +DimOAuth is the account owner for the Dim relay. The account operations, errors and flows are [ManagedAccount](ManagedAccount.md)'s; this document records what DimOAuth adds and what it keeps in the owner's vocabulary. + +## Use and scope: responsibility split + +DimOAuth owns: + +- **The account record.** `/auth.json` with `nextApiOauth` and `dimAccountState` schema 1 (`credentialEpoch`, `generation`, `credentialRevision`, `state`, and when authenticated `identity` and `tokenDigest`). Writes go through FileStorage's `update`; the record's revision is the business compare-and-set inside the change. +- **Login.** Browser PKCE and device flows, the directory discovery from the email or the host default, the localhost callback listener's browser opening, and the token exchange. +- **Tokens.** The 30-second freshness window, one serialized refresh under the account lock, rotation persisted before release, and the background renewal. +- **The relay catalog.** The provider ids and models the plan serves, projected as the account catalog the model owner reads. +- **Request leases.** One request's relay base URL, headers and bearer, with the lease id, capacity and expiry [ManagedAccount](ManagedAccount.md) defines. +- **Search and title.** The relay's `POST {relay}/web-search` and `POST {issuer}/v1/session/rename`. +- **The client namespace `account.*`.** Status, recover, login begin/browser/device, login status/cancel, logout, usage, referral, reset batches and reset apply. + +Callers keep: + +- Which provider uses the account: the record's credential authority. +- The search query and how results are shown: Web. +- The title prompt and the fallback when the relay is unavailable: SessionTitle. +- The login UI and when a sign-in starts: the client. + +| Requirement (callers) | Compose from [ManagedAccount](ManagedAccount.md)'s operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Sign in, sign out, read usage and resets | No: the flow, the record and the plan are DimOAuth's | Client namespace `account.*` | +| Run one relay request with the account's credential, recovering once on a rejection | No: the grant and the lease table are DimOAuth's | `with_lease` | +| Search through the relay | No: the server-side model and the grant are DimOAuth's | `search` | +| Generate a session title through the relay | No: the server model, quota and prompt are the relay's | `title` | +| Learn whether the relay is signed in | No: state and its changes are DimOAuth's | `availability`, `subscribe` | + +## Caller example + +Web declares its search tool only while the relay account is signed in: + +```rust +let AccountAvailability { signed_in, .. } = dim_account.availability(cancelled.clone()).await?; +if signed_in { + let mut changes = dim_account.subscribe(SubscriptionRequest {}, cancelled.clone()).await?; + // declare web_search; withdraw it when changes report signed_out +} +``` + +Web searches: + +```rust +let SearchReply { results } = dim_account + .search(SearchRequest { query, count }, cancelled.clone()) + .await?; +``` + +SessionTitle asks for a title when the Session's model belongs to the relay: + +```rust +match dim_account.title(TitleRequest { provider: adopted.provider_id.clone(), text }, cancel.clone()).await { + Ok(TitleReply { title }) => use_title(title), + Err(TitleError::UnsupportedProvider | TitleError::Unavailable { .. }) => fallback_title(), + Err(error) => return Err(error), +} +``` + +## Own contract + +### Face and operations + +Face `dimAccount`, marked on `DimOAuth`. The operations are [ManagedAccount](ManagedAccount.md)'s table, with these DimOAuth facts: + +| Operation | DimOAuth's request and reply | Errors | +| --- | --- | --- | +| `availability`, `subscribe` | `{}` → `{signed_in, identity?}`; the identity is the grant's issuer and subject, never a token | `cancelled`, `closed`, `failed` | +| `catalog` | `{}` → `{account, models}`; the models are the relay's, each with its declared capabilities | `unavailable`, `cancelled`, `closed`, `failed` | +| `with_lease` | `{provider, model}` plus the attempt callback → `{recovered}`; `provider` must be one of the relay's; one serialized refresh on a rejection | `not_found`, `unavailable`, `cancelled`, `closed`, `rejected`, `failed` | +| `search` | `{query, count}` → `{results: [{title, url, snippet, publishedAt?}]}` | `unavailable`, `failed`, `cancelled`, `closed` | +| `title` | `{provider, text}` → `{title}`; `provider` must be the relay's | `unsupported_provider`, `unavailable`, `cancelled`, `closed`, `failed` | + +The `account.*` namespace keeps its published methods; handlers call the same owner operations. A failed login attempt reports only `Login failed`; account-service error bodies are never returned. + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `with_lease` | Read the grant atomically when fresh; inside the 30-second window take the lock and refresh; record the lease id; call the attempt; on `rejected` one recovery under the account lock; release the lease | The token ends the attempt; the lease is released and the call ends `cancelled` | The callback is revoked; the lease is released | The attempt ends; leases and callbacks are released; a persisted grant stays | DimOAuth: grant, lease id, expiry and recovery; the calling row: its attempt | +| `search` / `title` | Send the relay request with the current bearer; a 401 follows the same one-recovery rule as `lease` | The request is cancelled | Pending requests end `closed` | DimOAuth | +| `account.*` | Run the login flow or the account read; write the record through FileStorage; publish the result | The attempt is cancelled | Attempts end with the generation; a completed token rotation settles before unload | DimOAuth | + +## Exceptions with reasons + +- `Lease` carries the bearer to the caller's attempt for one request; [ManagedAccount](ManagedAccount.md) states the rule and the prohibition on storing, logging or returning it. +- The account file is shared with the TypeScript subscriber under the published `auth.json.lock` marker protocol; FileStorage's contract records the marker exception, and DimOAuth keeps the file format. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part; no Timeline facts, no Capability. | +| §2 scopes | Process: the grant and leases outlive Sessions. | +| §3 orthogonality | No other owner's state is read; FileStorage provides the file operations. | +| §4 rules 1–6, 9 | No command events, handoffs, before callbacks, batches, context or Timeline state. | +| §4 rule 7 | Web, SessionTitle and the model owner call the face; none reads `auth.json`, the lock or the token. | +| §4 rule 8 | No infrastructure change; FileStorage's operations are the contract. | +| §7 ids, values, callbacks | The lease is a value with an id; availability and its changes are a read-only view. | +| §7 no proxy | DimOAuth returns its own account data; no host binding stands between the caller and this owner. | +| §7 one change | The delivery part deletes the account forwarding methods and migrates Web, SessionTitle and the model owner together. | +| ADR 002 D1 | Process: the account is shared across Sessions. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Depends on FileStorage only; the model owner depends on this face. | +| ADR 002 D4 | The directory and account record are business state in the owner's store. | +| ADR 002 D5 | The face is language-neutral; the lease value is data. | + +## Requirements raised to mechanism owners + +- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for `auth.json` and its backup; the `auth.json.lock` marker exception is already recorded there. +- **Settings, storage, session directory.** None. + +## Binding appendix + +`DimOAuth` is the owner type; `dimAccount` is the wire name. The request and reply types are the [ManagedAccount](ManagedAccount.md) types plus the search and title types this crate already exports. + +```rust +impl PublicService for DimOAuth {} + +#[rutis::service(name = "dimAccount")] +impl DimOAuth { + pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn search(&self, request: SearchRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn title(&self, request: TitleRequest, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ManagedAccount.md b/docs/design/plugins/ManagedAccount.md new file mode 100644 index 0000000000..61b7889f6a --- /dev/null +++ b/docs/design/plugins/ManagedAccount.md @@ -0,0 +1,201 @@ +# Managed account owners + +Scope: process. Issue: [#2019](https://github.com/arcships/dim/issues/2019). + +This document is the contract of the account owner role. Its implementations are DimOAuth, OpenAI Codex, Grok and the ChatGPT account; an account plugin built outside this repository implements the same role. Each implementation is its own owner with its own face name; the operations and errors below are the same for all. Per-owner facts, login flows and extra operations are in [DimOAuth](DimOAuth.md), [ManagedOAuth](ManagedOAuth.md) and [ManagedProviders](ManagedProviders.md). + +## Use and scope: responsibility split + +An account owner owns: + +- **The account record.** The persisted grant and account state under the product home, written through FileStorage's operations with the account's own revision and lease. +- **Login and tokens.** Login attempts, the pending exchange, token refresh, rotation and revocation. +- **Model availability.** Whether the account is signed in and which models its plan serves; the catalog the plan projects. +- **Request leases.** One request's connection facts, their expiry and capacity, recovery after a rejection, and the final settlement. +- **Its client namespace.** `account.*`, `account.codex.*`, `account.grok.*` or `account.chatgpt.*`, served to protected-local clients; handlers call the owner's operations. + +Callers keep: + +- Which account a provider uses: the Provider record's credential authority names the owner. +- The request itself: the model owner or the media executor performs the attempt with the lease the owner hands to its callback, and the owner settles the lease after the callback. +- What a login flow shows and when it starts: the client protocol. +- The search query and its presentation: Web, through DimOAuth's search operation when its settings name the relay. +- The title prompt and its fallback: SessionTitle, through DimOAuth's title operation. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Learn whether the account can serve, and follow changes | No: sign-in state and its changes are the owner's state | `availability`, `subscribe` | +| Project the models the plan serves | No: the plan, the grant and the catalog are the owner's | `catalog` | +| Run one request with the account's credential, recovering once when the provider rejects it | No: the grant, the refresh and the lease's capacity are the owner's; a caller holding a lease id would have to release it on every error, cancel and unload path | `with_lease` | +| Search through the relay (Dim) | No: the grant and the server-side model are the owner's | `search` | +| Generate a title through the relay (Dim) | No: the server model and quota are the owner's | `title` | +| Show login, logout, usage and resets | No: the flows, records and plan are the owner's | The client namespace | +| Decide which account to sign into | Yes: the client chooses from `provider.management`'s account namespaces | Business | + +An operation exists only where the row says No. + +## Caller example + +The model owner runs one attempt inside the owner's operation; the account owner hands over the lease, recovers once when the attempt reports a rejection, and settles the lease afterwards. No lease id appears here: + +```rust +let WithLeaseReply { recovered } = account + .with_lease( + LeaseRequest { provider: record.provider_id.clone(), model: model.clone() }, + Arc::new(move |lease: Lease, cancelled: CancellationToken| { + Box::pin(async move { + // One exchange with `lease`. `Rejected` only when the provider rejected the credential. + match send_once(&lease, cancelled).await { + Err(CredentialRejected) => AttemptReply { rejected: true }, + _ => AttemptReply { rejected: false }, + } + }) + }), + cancelled.clone(), + ) + .await?; +``` + +Web follows the Dim account's availability: + +```rust +let AccountAvailability { signed_in, .. } = account.availability(cancelled.clone()).await?; +let mut changes = account.subscribe(SubscriptionRequest {}, cancelled.clone()).await?; +while let Some(available) = changes.next().await { /* declare or withdraw web_search */ } +``` + +The client namespace is the same owner's operations behind the client protocol; no part calls it. + +## Own contract + +### Face names + +| Owner | Face name | Provider ids | Login | Extra operations | +| --- | --- | --- | --- | --- | +| DimOAuth | `dimAccount` | the relay providers its catalog projects | browser PKCE, device | `search`, `title` | +| OpenAI Codex | `codexAccount` | `openai-codex` | browser PKCE | — | +| Grok | `grokAccount` | `grok-build` | device | — | +| ChatGPT account | `chatgptAccount` | `openai-chatgpt` | browser PKCE | — | +| External account plugin | configured by its row | whatever its descriptor lists | its own | its own | + +### Operations + +All operations are marked on the owner type and provided under the owner's face name. `cancelled` is the caller's cancellation argument. + +| Operation | Intent | Request | Reply | Cancellation, timeout | Errors | +| --- | --- | --- | --- | --- | --- | +| `availability` | Whether the account is signed in | `{}` | `{signed_in, identity?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | +| `subscribe` | Follow availability changes | `{}` | `{subscription}` | The subscription ends with the caller's row | `closed` | +| `catalog` | The models the plan serves | `{}` | `{account, models}` | The caller cancels; a catalog read may wait on the account's own refresh | `unavailable`, `cancelled`, `closed`, `failed` | +| `with_lease` | Run the caller's attempt with one request's connection facts, recovering once when the attempt reports a rejection | `{provider, model}` plus `attempt(lease) -> {rejected}` | `{recovered}` | The caller cancels; the attempt stops and the owner settles the lease | `not_found`, `unavailable`, `cancelled`, `closed`, `rejected`, `failed` | +| `search` (Dim) | Search through the relay | `{query, count}` | `{results}` | The caller cancels; the provider request is cancelled | `unavailable`, `failed`, `cancelled`, `closed` | +| `title` (Dim) | Generate a title through the relay | `{provider, text}` | `{title}` | The caller cancels; an HTTP exchange is bounded at 10 s | `unsupported_provider`, `unavailable`, `cancelled`, `closed`, `failed` | + +`Lease` is a value handed to the attempt callback: `{lease_id, expires_at, protocol, base_url, headers, bearer}`. The owner records the id for capacity (1024) and expiry (30 minutes) and settles it when the callback returns, the caller drops the call, the lease expires, or the owner closes or reloads; `lease_id` lets a caller release early, and settling is otherwise the owner's. One `with_lease` call performs at most one controlled recovery: it adopts a newer persisted grant or performs one serialized refresh, then calls the callback once more with the new lease. A second rejection settles the lease and applies the sign-out rule only when the rejected grant still owns the account. + +`attempt` runs inside the account owner's call, not inside a lock: the owner holds no grant or file lock while the callback runs, and the callback must not call back into the same account owner. The callback may perform the network exchange for the request; `cancelled` is the call's token, which ends the attempt when the caller drops the call or the owner closes. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `not_found` | The provider is not this owner's; re-read the record | +| `unavailable` | Sign in, renew the plan or wait for the account; the message names the reason | +| `unsupported_provider` | This owner does not serve that provider; use the owner the record names | +| `cancelled` | Nothing changed; the attempt stopped and the lease is settled | +| `closed` | This generation is unloading; call the next generation | +| `rejected` | Both attempts were rejected; the owner settled the lease and applied the sign-out rule; the caller reports the failure | +| `failed` | The account store or the provider request failed; retry the business step | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `availability`, `subscribe` | Read the account state; publish the value and its changes | The read stops; a subscription ends | The subscription ends | The watch is rebuilt from the store; subscribers end | The owner | +| `catalog` | Read the grant, refresh if inside the window, project the plan's models | The wait ends; the owner's refresh continues | The call ends `cancelled` | Pending calls end `closed`; the next generation re-reads | The owner's refresh task | +| `with_lease` | Read the grant, refresh if needed, record the lease id, call `attempt`; on `rejected`, one controlled recovery, then `attempt` again; release the lease | The token ends the attempt; the lease is released and the call ends `cancelled` | The callback is revoked; the call ends `cancelled`; the lease is released | The attempt ends; every lease id and the callback are released; a persisted grant stays | The owner: lease id, expiry, capacity and recovery; the calling row: its attempt state | +| `search` / `title` | Send the relay request with the grant's bearer | The request is cancelled | The call ends `cancelled` | Pending requests end `closed` | The owner | +| Client namespace | Run the login flow, write the record through FileStorage and publish the result | The attempt is cancelled | The attempt stays queryable until its deadline | Attempts end with the generation | The owner | + +## Exceptions with reasons + +- `Lease` carries the bearer into the callback: the model owner or the media executor performs the exchange, the account owner holds the grant, and the value lives only for one attempt; the contract forbids storing, logging or returning the bearer to a client. +- The external account plugin's face name is configured by its row because the plugin is built outside this repository; the host records the name in the Provider record's authority. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part per account owner; no Timeline facts, no Capability. | +| §2 scopes | Process: grants, tokens and leases outlive Sessions. | +| §3 orthogonality | The account owner reads no other owner's state; FileStorage provides file operations, Settings the directory list. | +| §4 rules 1–6, 9 | No command events, handoffs, before callbacks, batches, context or Timeline state. | +| §4 rule 7 | Callers use these operations; no caller reads the grant, the token or the attempt table. | +| §4 rule 8 | FileStorage's operations are the only infrastructure dependency; no requirement beyond [#2080](https://github.com/arcships/dim/pull/2080). | +| §7 ids, values, callbacks | The lease is a value inside the owner's callback; the availability subscription is a read-only view; no object or lease id crosses. | +| §7 no proxy | The account owner returns its own account data; the model owner calls the owner the record names. | +| §7 one change | The delivery part migrates Provider, Web and the client namespace together. | +| ADR 002 D1 | Process: the account and its tokens are shared across Sessions. | +| ADR 002 D2 | No wiring plugin: the operations are on each owner type. | +| ADR 002 D3 | Account owners depend on the core FileStorage service; Provider depends on the account faces. | +| ADR 002 D4 | The account record and the directory are business configuration in the owner's store; the face name is structural. | +| ADR 002 D5 | The face is language-neutral; the Rust binding is each owner's appendix. | + +## Requirements raised to mechanism owners + +- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for the account record; `write` for the pre-reset backup. The account record keeps its file name and revision semantics. +- **Settings ([#2017](https://github.com/arcships/dim/issues/2017)).** The account directory default is read from the host entry, not a Settings document; no requirement. +- **Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)).** None: accounts persist through FileStorage, not the Session store. + +## Binding appendix + +Shared request, reply and error types; each owner's `#[rutis::service]` block is in its own document. `CancelledFn` is the binding's cancellation argument. + +```rust +use dim_agent_capabilities::host::CancelledFn; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountAvailability { pub signed_in: bool, pub identity: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LeaseRequest { pub provider: String, pub model: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Lease { + pub lease_id: String, + pub expires_at: u64, + pub protocol: ModelProtocol, + pub base_url: String, + pub headers: BTreeMap, + pub bearer: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttemptReply { pub rejected: bool } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WithLeaseReply { pub recovered: bool } + +/// The caller's attempt; `cancelled` ends it when the call or the owner ends. +pub type AttemptFn = + Arc BoxFuture<'static, AttemptReply> + Send + Sync>; + +#[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum AccountError { + #[error("{0}")] NotFound(String), + #[error("{reason}")] Unavailable { reason: String }, + #[error("{0}")] UnsupportedProvider(String), + #[error("cancelled")] Cancelled, + #[error("the account owner is unloading")] Closed, + #[error("the provider rejected the recovered credential")] Rejected, + #[error("{0}")] Failed(String), +} +``` + +`Subscription` is the owner's replayable watch over availability; it ends when the calling row unloads or the owner closes. diff --git a/docs/design/plugins/ManagedOAuth.md b/docs/design/plugins/ManagedOAuth.md new file mode 100644 index 0000000000..2e644ec276 --- /dev/null +++ b/docs/design/plugins/ManagedOAuth.md @@ -0,0 +1,112 @@ +# Managed OAuth accounts (OpenAI Codex, Grok) + +Scope: process. Issue: [#2019](https://github.com/arcships/dim/issues/2019). + +This document covers two owners that share one implementation: **OpenAI Codex** and **Grok**. The account operations, errors and flows are [ManagedAccount](ManagedAccount.md)'s; the two owners differ in provider id, issuer, login method and record namespace. + +## Use and scope: responsibility split + +Each owner holds: + +- **The account record** for its provider under the product home, written through FileStorage's `update`. +- **Login.** Browser PKCE for Codex, device flow for Grok, the pending attempt and its deadline. +- **Tokens.** Refresh, rotation and the one-controlled-recovery rule. +- **The account's model availability.** The models the subscription serves, as the account catalog. +- **Request leases.** The lease ids, capacity and expiry [ManagedAccount](ManagedAccount.md) defines. +- **The client namespace** `account.codex.*` or `account.grok.*`. + +Callers keep the same responsibilities as [ManagedAccount](ManagedAccount.md): the model owner chooses the provider by its record, the client owns login UX, no caller reads the record. + +| Requirement (callers) | Compose from [ManagedAccount](ManagedAccount.md)'s operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Sign in, cancel, sign out | No: the OAuth attempt and record are the owner's | Client namespace `account.codex.*` / `account.grok.*` | +| Read account status for the provider list | No: the sign-in state is the owner's | `availability` | +| Run one request with the account's credential, recovering once on a rejection | No: the grant and the lease table are the owner's | `with_lease` | +| Project the plan's models | No: the plan and the grant are the owner's | `catalog` | + +## Caller example + +The model owner runs one Codex request inside the owner's operation: + +```rust +codex_account + .with_lease( + LeaseRequest { provider: "openai-codex".into(), model: model.clone() }, + attempt, // one exchange with the lease; rejected on the provider's 401 + cancelled, + ) + .await?; +``` + +The client reads the provider list's account state through the client namespace, not the face: + +```text +account.codex.status {} -> { authenticated, identity? } +``` + +## Own contract + +### Faces + +| Owner | Face | Provider id | Login | Namespace | +| --- | --- | --- | --- | --- | +| OpenAI Codex | `codexAccount` | `openai-codex` | browser PKCE, callback at `http://localhost:1455/auth/callback` | `account.codex.*` | +| Grok | `grokAccount` | `grok-build` | device | `account.grok.*` | + +Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subscribe`, `catalog` and `with_lease`. The account record keeps its existing file, revision and `credentialEpoch`/`generation` fields; the catalog keeps the plan's models and their declared capabilities. + +### Errors + +[ManagedAccount](ManagedAccount.md)'s kinds. A failed login attempt reports only `Login failed`; a rejected refresh signs out only the grant that holds the lock. + +### Flows + +[ManagedAccount](ManagedAccount.md)'s flows. Codex additionally opens the browser and receives the localhost callback; Grok polls the device authorization. A completed token rotation remains the owner's work and settles before unload. + +## Exceptions with reasons + +- `Lease` carries the bearer to the caller's attempt for one request; [ManagedAccount](ManagedAccount.md) states the rule. +- The legacy `openai-codex` record keeps its legacy fields; the hidden state shared with the ChatGPT account and the migration between the two accounts stay the owners' business and are described in the [Codex sign-in design](../../../crates/dim-oauth/docs/design.md). + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Two process parts, one implementation; no Timeline facts, no Capability. | +| §2 scopes | Process: grants and leases are shared across Sessions. | +| §3 orthogonality | No other owner's state is read. | +| §4 rules 1–6, 9 | No events, handoffs, callbacks, batches, context or Timeline state. | +| §4 rule 7 | Callers use the faces; none reads the record or the attempt table. | +| §4 rule 8 | No infrastructure change. | +| §7 ids, values, callbacks | The lease is a value with an id; availability is a read-only view. | +| §7 no proxy | Each owner returns its own account data. | +| §7 one change | The delivery part deletes the forwarding shell and the object port together. | +| ADR 002 D1 | Process scope. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Depends on FileStorage; the model owner depends on the faces. | +| ADR 002 D4 | The issuer and client configuration are structural; the record is the owner's business state. | +| ADR 002 D5 | The faces are language-neutral. | + +## Requirements raised to mechanism owners + +- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read` and `update` for the account record. +- **Others.** None. + +## Binding appendix + +```rust +impl PublicService for OpenAICodexOAuthService {} + +#[rutis::service(name = "codexAccount")] +impl OpenAICodexOAuthService { + pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result { /* ... */ } +} + +impl PublicService for GrokOAuthService {} + +#[rutis::service(name = "grokAccount")] +impl GrokOAuthService { /* the same operations */ } +``` diff --git a/docs/design/plugins/ManagedProviders.md b/docs/design/plugins/ManagedProviders.md new file mode 100644 index 0000000000..64f413fc78 --- /dev/null +++ b/docs/design/plugins/ManagedProviders.md @@ -0,0 +1,111 @@ +# ManagedProviders (ChatGPT account; host binding retired) + +Scope: process. Issue: [#2019](https://github.com/arcships/dim/issues/2019). + +This document covers the plugin at its target shape. The host binding and the `managedSearch` face are removed; the in-tree ChatGPT account remains as the `chatgptAccount` owner and implements [ManagedAccount](ManagedAccount.md). An account plugin built outside this repository provides its own face under the name its row configures. + +## Use and scope: responsibility split + +The remaining owner, the ChatGPT account, holds: + +- **The account record** for `openai-chatgpt`, written through FileStorage's `update` with the record's revision. +- **Login.** Browser PKCE, the discovery document, the profile read and the pending attempt. +- **Tokens.** The access token's 30-second freshness window, one serialized refresh, rotation and the sign-out rule. +- **The plan catalog.** The models the ChatGPT plan serves, as the account catalog. +- **Request leases.** Lease ids, capacity and expiry [ManagedAccount](ManagedAccount.md) defines. +- **The client namespace** `account.chatgpt.*`. + +Removed with the host binding: + +- The `dyn ManagedProvider` object port and the binding slot, generation and validation around it. An external account plugin is a normal process row: it provides its account face and owns its lifecycle, including quiesce before RPC settlement. +- The account data forwarding: `providers`, `status`, `recover`, `begin_browser`, `complete_browser`, `begin_device`, `attempt_status`, `cancel_attempt`, `logout`, `usage`, `referral`, `reset_batches`, `apply_reset`, `catalog`, `credential`, `recover_rejected`, `finish_rejected`. Callers request the account owner the Provider record names. +- The `managedSearch` face and its `search`, `usable`, `subscribe_usable` and `refresh_usable` methods. Web reads the Dim account's `availability` and calls its `search`; no host layer returns account data. + +Callers keep the same responsibilities as [ManagedAccount](ManagedAccount.md): the model owner selects the account by the record's credential authority, Web owns the search tool and its declaration, and the client owns the login UI. + +| Requirement (callers) | Compose from the account owners' operations without breaking their invariants? | Handling | +| --- | --- | --- | +| Read the ChatGPT account's status, catalog and one-attempt credential | No: the grant, plan and lease table are this owner's | `availability`, `catalog`, `with_lease` | +| Search through the Dim relay | No: the Dim account's grant is DimOAuth's | DimOAuth's `availability`, `subscribe`, `search` | +| List the accounts a user can sign into | Yes: `provider.management` reports each record's account namespace | Business | +| Sign in, cancel, sign out | No: the attempt and record are this owner's | `account.chatgpt.*` | + +## Caller example + +Web reads the Dim account, not a host layer: + +```rust +let AccountAvailability { signed_in, .. } = dim_account.availability(cancelled.clone()).await?; +let SearchReply { results } = dim_account.search(SearchRequest { query, count }, cancelled).await?; +``` + +The model owner runs a ChatGPT request inside the owner's operation: + +```rust +chatgpt_account + .with_lease(LeaseRequest { provider: "openai-chatgpt".into(), model: model.clone() }, attempt, cancelled) + .await?; +// The request itself is Provider's; the lease is handed to `attempt` for one exchange. +``` + +A client signs in through the namespace; no part calls it: + +```text +account.chatgpt.login.browser.begin {} -> { attemptId, authorizationUrl, expiresAt } +account.chatgpt.login.status { attemptId } -> { state } +``` + +## Own contract + +### Face + +`chatgptAccount`, marked on `ChatGptAccount`, implements [ManagedAccount](ManagedAccount.md)'s `availability`, `subscribe`, `catalog` and `with_lease`. The provider id is `openai-chatgpt`; login is browser PKCE; the record keeps its existing file and revision fields; the catalog keeps the plan's models and capabilities. + +The client namespace `account.chatgpt.*` keeps its published methods. The existing rule that a ChatGPT plan request needs an interactive client Session stays in Provider: Provider reads the Session's creation record and refuses a non-client Session with `invalid`. + +### Errors and flows + +[ManagedAccount](ManagedAccount.md)'s kinds and flows. The account record's write, the one-recovery rule and the sign-out condition are unchanged. + +## Exceptions with reasons + +- The external account plugin's face name comes from its row: the plugin is built outside this repository, so the assembly supplies the name the Provider record's authority uses. +- `Lease` carries the bearer to the caller's attempt for one request; [ManagedAccount](ManagedAccount.md) states the rule. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part; ChatGPT is an account owner, not a Capability. | +| §2 scopes | Process: the grant and leases are shared across Sessions. | +| §3 orthogonality | No other owner's state is read; the host binding and its account forwarding are gone. | +| §4 rules 1–6, 9 | No events, handoffs, callbacks, batches, context or Timeline state. | +| §4 rule 7 | Callers use the account faces; no caller reads the binding or the account record. | +| §4 rule 8 | No infrastructure change. | +| §7 no proxy | Account data is returned by its owner; the host binding that returned it for every account is deleted. | +| §7 objects | The `dyn ManagedProvider` object port and the binding slot are deleted; the external plugin provides a face. | +| §7 one change | The delivery part deletes the binding, the forwarding methods and `managedSearch` and migrates Web, Provider and the client together. | +| ADR 002 D1 | Process scope. | +| ADR 002 D2 | No wiring plugin; the binding was one and is removed. | +| ADR 002 D3 | Depends on FileStorage; the model owner depends on the account faces. | +| ADR 002 D4 | The plan and the record are business state; the face name is structural for an external plugin. | +| ADR 002 D5 | The account face is language-neutral. | + +## Requirements raised to mechanism owners + +- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for the ChatGPT account record. +- **Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)).** Provider reads a Session's creation record through `store.creationRecord` to require an interactive client Session for this provider; the requirement is stated in [Provider](Provider.md)'s requirements. + +## Binding appendix + +```rust +impl PublicService for ChatGptAccount {} + +#[rutis::service(name = "chatgptAccount")] +impl ChatGptAccount { + pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md new file mode 100644 index 0000000000..25d8e2a89c --- /dev/null +++ b/docs/design/plugins/Provider.md @@ -0,0 +1,358 @@ +# Provider + +Scope: process. Issue: [#2019](https://github.com/arcships/dim/issues/2019). + +Provider is the model owner of the product profile: it decides which model a request uses, resolves the credential that model needs, and runs the request. This document is the owner's target contract. The client protocol and the existing management behavior stay in [Provider management](../appserver/provider-management.md); this document replaces the object surfaces that document describes as the pre-migration state. The API-key profile has the same operations from [ConfiguredModels](ConfiguredModels.md). + +## Use and scope: responsibility split + +Provider owns: + +- **Records.** Provider, model and selection records: static and imported records, descriptor overrides, user models, enables, per-model preferences, workspace and global selections, source generations and per-provider adoption. Records are read and written through the storage owner's operations; Provider keeps no SQL. +- **Selection.** The precedence among an explicit target, the workspace and global selections, the configured default and account-backed candidates; the availability rule execution applies; the adopted capability snapshot and configuration a selection carries. +- **Credentials.** Static credentials read from the record or an external secret store, managed-account leases, and temporary startup connections. A credential is used for one request and never leaves Provider except as the one-attempt lease a media call needs. +- **Execution.** One model request from the adopted selection through adaptation, transport, retries, credential recovery, streaming and settlement. Provider owns the driver that performs the request and its connection pool, request identity, stream set and tasks. +- **Temporary connections.** A startup connection admitted for one Session creation, the admission id that names it, and its settlement. +- **Client management.** The reads and writes the `provider` client namespace serves, with their transactions and versions. +- **The wire recorder.** The recorder its driver starts from ModelLog's `recording` value; the file, its redaction and its lifetime are Provider's. + +Callers keep: + +- Which model a Session adopts and when it changes; Provider answers the selection and the caller writes the Session's configuration. +- The request's messages, system prompt, tools and metadata; Provider adapts and sends what the caller built. +- What the output means: ModelProvider commits the stream to the Timeline and decides the turn's end; a one-shot caller collects the text. +- The summary budget and the retry display: the caller passes an admission callback and observes progress. +- Account login, logout and usage: the account owners' client namespaces, not Provider. +- Which search service a tool uses: Web's own settings, with the account owner's availability read. + +| Requirement (callers) | Compose from the operations below without breaking Provider's invariants? | Handling | +| --- | --- | --- | +| Choose the model for a Session creation or a model change | No: the precedence and the availability rule are Provider's state and decisions | `resolve` | +| Apply a preference patch to an adopted selection | No: the patch is validated against the model's declarations | `preferences` | +| List the models that can run a use, and the current default | No: the list is the execution rule, one snapshot | `selectable` | +| Admit a temporary connection for a Session creation | No: the credential is a resource bound to the calling row; expiring or releasing it is Provider's | `prepare_startup`, `retain_startup`, `release_startup` | +| Run one model request with retries, recovery and streaming | No: credentials, retry budgets, failure chains and output adaptation stay with the owner | `invoke` | +| Learn a media model's route and where its credential comes from (the media executor) | No: the route is catalog state; the credential owner is the record's authority | `media_route` | +| Run one media exchange with a static model's credential (the media executor) | No: the credential is Provider's resource, and a caller holding it would release it on every error path | `with_lease` | +| Read or write a Provider's management record | No: records, versions and transactions are Provider's | The `provider` client namespace; handlers call the same operations | +| Show a retry countdown | Yes: the `invoke` progress callback | Business | +| Learn where the recorder writes | Yes: read ModelLog's `recording` value | Business | +| Decide the prompt, tools or output handling | Yes | Business | +| Decide whether a search is offered | Yes: read the account owner's availability | Business | + +An operation exists only where the row says No. + +## Caller example + +The Rpc entry chooses a model while creating a Session: + +```rust +let selection = provider + .resolve(ResolveRequest { target: requested, cwd: Some(cwd) }, cancelled.clone()) + .await?; +session.configure(ConfigureUpdate { model: Some(selection), ..Default::default() }, &branch).await?; +``` + +The Rpc entry changes only the preferences of the model already adopted: + +```rust +let next = provider + .preferences(PreferencesRequest { selection: current, update: patch }, cancelled.clone()) + .await?; +session.configure(ConfigureUpdate { model: Some(next), ..Default::default() }, &branch).await?; +``` + +Modality lists the options for an operation: + +```rust +let SelectableReply { models, default } = provider + .selectable(SelectableRequest { use_: Use::Modality { operation: "image.generate".into() } }, cancelled.clone()) + .await?; +``` + +The media executor (the adapter that owns the protocol) resolves the route and then the credential owner it names; Modality passes the model target and holds no lease: + +```rust +let route = provider + .media_route(MediaRouteRequest { target, operation: "image.generate".into() }, cancelled.clone()) + .await?; +// `with_lease` resolves the face named by `route.credential` and runs the exchange inside it. +with_lease(&self.ctx, &route.credential, target, |lease| send_media(&lease), cancelled.clone()).await?; +``` + +ModelProvider runs a turn; `consume` is the branch part's own callback that writes `step/*` events and reports how the stream ended: + +```rust +let outcome = provider + .invoke( + InvokeRequest { + request, + mode: Mode::Dialogue { chain: failure_chain }, + consume: consumer, + admit: None, + }, + cancelled.clone(), + ) + .await?; +``` + +The summary strategy runs with its own budget: + +```rust +provider + .invoke( + InvokeRequest { request, mode: Mode::Dialogue { chain: None }, consume, admit: Some(budget) }, + cancelled, + ) + .await?; +``` + +SessionTitle and ImageUnderstanding run one request and keep the text: + +```rust +let selection = provider.resolve(ResolveRequest { target: Some(model), cwd: None }, cancel.clone()).await?; +let reply = provider + .invoke( + InvokeRequest { request: ModelRequest::from(selection, messages), mode: Mode::Once, consume: collect_text, admit: None }, + cancel, + ) + .await?; +``` + +The driver reads ModelLog's value when a request starts: + +```rust +let destination = model_log.recording().await.ok().flatten(); +// The recorder owns the file under this directory for the request it starts. +``` + +A Session creation with a temporary connection: + +```rust +let Started { selection, admission } = provider.prepare_startup(request, cancelled.clone()).await?; +let session = sessions.create(/* with selection */).await?; +provider.retain_startup(RetainRequest { session: session.id().into(), model: selection }, cancelled).await?; +// On any failure before retention: provider.release_startup(admission, cancelled).await?; +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)) | record reads, selection reads and writes, source activation and adoption, edit commits, candidate and page queries, legacy import | Provider records; the storage owner's contract defines the shapes | +| ProviderSettings ([#2017](https://github.com/arcships/dim/issues/2017)) | `user_agent` | The operator's User-Agent replacement | +| ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)) | `recording` | The recorder's directory | +| FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)) | `root_path` | The directory the wire recorder writes under | +| Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)) | `store.creationRecord` | The ChatGPT client-session rule (the Session's origin) | +| Session directory ([#2020](https://github.com/arcships/dim/issues/2020)) | session close observation | Releasing a retained startup admission | +| Account owners ([ManagedAccount](ManagedAccount.md)) | `availability`, `catalog`, `with_lease` | Account-backed models; the record's authority names the owner | + +Provider reads an account owner by the name its record's credential authority carries; the face names are in [ManagedAccount](ManagedAccount.md). + +### Operations + +All operations are marked on `Provider` and provided under `providerService`; requests, replies and errors are data. `cancelled` is the caller's cancellation argument, not a request field. + +| Operation | Intent | Request | Reply | Cancellation, timeout | Errors | +| --- | --- | --- | --- | --- | --- | +| `resolve` | The model one request resolves to | `{target?, cwd?}` | `Selection` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | +| `preferences` | Apply a patch to an adopted selection | `{selection, update}` | `Selection` | None; completes immediately | `invalid` | +| `selectable` | The models that can run a use, and the default | `{use: "chat" \| {modality}}` | `{models, default?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | +| `prepare_startup` | Admit a temporary connection and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `{selection, admission}` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | +| `retain_startup` | Bind the temporary connection the model carries to a Session | `{session, model}` | `{}` | None; completes immediately | `not_found` (the model carries no source, or the source is not bound), `closed` | +| `release_startup` | Release an admission before or after retention | `{admission}` | `{}` | None; completes immediately | `not_found`, `closed` | +| `invoke` | Run one model request | `{request, mode, consume, admit?}` | `{outcome}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `unavailable`, `cancelled`, `closed`, `provider_failed {retryable}` | +| `media_route` | A media model's route and the owner of its credential | `{target, operation}` | `{protocol, base_url, headers, realtime?, credential: Owner}` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | +| `with_lease` | Run the caller's attempt with a static model's credential | `{provider, model}` plus `attempt(lease) -> {rejected}` | `{}` | The caller cancels; the attempt stops | `not_found`, `unavailable`, `cancelled`, `closed` | + +`admission` is the caller's release handle before retention; `retain_startup` names the Session and the model it adopts, so a member Session that inherits the leader's model retains the same source by value and no caller holds the source. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Lease` is [ManagedAccount](ManagedAccount.md)'s one-attempt value; `with_lease` hands it to the caller's attempt and releases it when the attempt ends, so no lease id crosses. + +`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits through the optional `admit`/progress callbacks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(next)` receives chunks, ends and typed failures and returns how the call ended and whether output was accepted; output accepted before a failure prevents replay. `admit` runs before each attempt and returns `admitted` or `rejected {message}`; only a caller with its own budget passes it. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | Fix the input: an unknown use, an explicit target missing its model, a malformed preference patch | +| `invalid_connection` | Fix the startup connection: a rejected URL, user info, query, fragment, both an API key and a bearer, or an unsupported auth | +| `not_found` | The provider, model or admission does not exist; re-read or choose another | +| `unavailable` | The model cannot run now; the message names the reason; choose another model or fix the record | +| `auth_required` | Sign in through the account owner named by the record, then retry | +| `cancelled` | Nothing changed; the call stopped where it was cancelled | +| `closed` | This generation is unloading; call the next generation | +| `failed` | Provider's storage or a catalog read failed; retry the read | +| `provider_failed {retryable}` | The request failed after the owner's retries; `retryable` says whether a new `invoke` can succeed | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `resolve`, `selectable` | Read records and account state, apply the precedence and availability rule, return the value | The read stops; nothing changes | The call ends `cancelled` | Pending calls end `closed`; the next generation answers from current records | Provider's read tasks | +| `invoke` | Resolve or adopt the request's selection, adapt images, resolve the credential (account lease or static), send, adapt chunks, hand them to `consume`, retry or recover per the failure chain, settle the consumer | The transport is cancelled, the stream is dropped, the consumer is released; accepted output stays committed | The consumer callback is revoked; the call ends `cancelled`; admitted work is joined | Admission stops; in-flight requests are cancelled and joined; account leases are settled | Provider: request tasks, stream and lease. ModelProvider: the Timeline writes already committed | +| `prepare_startup` | Validate and admit the connection under an admission id bound to the calling row, select its model | Before admission; nothing is retained | The row's admissions are released | Admissions are dropped; a retained Session's connection is restored by its next generation | Provider: the admission; the calling row: its lifetime | +| `retain_startup` / `release_startup` | Read the model's source, add the Session to its owners, watch the Session; release an admission not yet retained | — | An unretained admission is released with the row | Retained sources survive the owner's reload as Session state is re-read | Provider: the source and its owners; the Session directory reports close | +| `media_route`, `with_lease` | Read the catalog and the credential owner, or hand a static credential to the attempt | The read stops; the attempt ends and the credential is dropped | The call ends `cancelled` | Pending calls end `closed` | Provider | + +## Exceptions with reasons + +- `with_lease` and the lease inside `invoke` hand the bearer to the caller's attempt for one request: the executor is the model owner or the media adapter and the account owner holds the grant, so the value crosses once and is never persisted, logged, quoted in an error or returned to a client. +- The `provider` client namespace is a client protocol, not a second service face: it is the mechanism's registration point for protected-local v3 clients, and every handler calls the operations above or the management operations this owner also owns. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part. Provider writes no Timeline event; it is not a Capability. ModelProvider, the branch Capability, consumes `invoke`. | +| §2 scopes | Process: records, catalogs and credentials outlive Sessions. Session and branch parts call the operations; no branch state is held. | +| §3 orthogonality | No other owner's state is read or changed. Account state comes from the account owner's operations; records from the storage owner's. | +| §4 rule 1 | No command event: model calls reach Provider as operations, not Timeline facts. | +| §4 rule 2 | No handoff: the request and its output stay with the caller and the Timeline. | +| §4 rule 3 | No before callback: `consume` writes through ModelProvider's own Timeline service, outside the commit lock. | +| §4 rule 4 | Core and assembly carry no business meaning; no prompt, tool or output policy appears here. | +| §4 rule 5 | No batches: Provider writes no Timeline fact. | +| §4 rule 6 | Context enters only through the request the caller built from adopted inputs and tool results. | +| §4 rule 7 | Callers use these operations; no caller reads a record, a connection or a catalog internal. | +| §4 rule 8 | Requirements are listed below; no runtime mechanism is added. | +| §4 rule 9 | No Timeline fact: selections and records are process state with owner writes. | +| §7 objects, ids, values, callbacks | Values: selections, lists, leases, routes. Callbacks: `consume`, `admit`. Ids: `admission`. No object crosses. | +| §7 no proxy | Account data comes from the account owner; the storage operations from the storage owner. Provider returns only its own records and decisions. | +| §7 one change | The delivery part migrates every caller and deletes every pre-migration name in one change. | +| ADR 002 D1 | Process: records, catalogs and credentials are shared across Sessions. | +| ADR 002 D2 | No wiring plugin: the operations are on the owner type. | +| ADR 002 D3 | Dependencies point from extensions to the core; Provider is a process service callers may depend on. | +| ADR 002 D4 | Structural configuration (the bundled catalog, the assembly) and business configuration (the `provider` source's user agent) are separate. | +| ADR 002 D5 | The face is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)).** Provider owns no SQL and no connection. It needs operations for: a record read by projection (header, all, one model, selected models, version); selection read and versioned write; per-model preferences; candidate lookup by criteria; provider list, model pages and management pages with their ordering and limits; source activation and per-provider adoption from bundle facts; one commit operation per edit family (create, delete, header patch, connection replacement, refresh, model create/edit/delete, enablement, preferences) with the existing preconditions and returned projections; legacy import as one batch; and `store.creationRecord` for a Session's origin. The storage owner's document defines the names and shapes. +- **ProviderSettings and ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)).** Their owner contracts define `user_agent` and `recording`; Provider reads both at request time. No requirement remains. +- **Session directory ([#2020](https://github.com/arcships/dim/issues/2020)).** Provider needs a close observation for a retained startup admission: when the Session closes without unload, the admission is released; an unload keeps it for restore. +- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `root_path` only; the recorder owns its JSONL file. +- **Account owners ([ManagedAccount](ManagedAccount.md)).** `availability`, `catalog`, `with_lease`; the face name comes from the record's credential authority. +- **Media executor (Modality's adapter contract).** The adapter resolves `media_route` and calls `with_lease` on the credential owner for the model target; Modality passes the target and settles the task, so no business caller holds a lease id. The adapter's service shape is Modality's contract. + +## Binding appendix + +`Provider` is the owner type; `providerService` is the wire name. `CancelledFn` is the binding's cancellation argument. The request and reply types are serde data; only `consume` and `admit` cross by reference. + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_types::{ModelId, ModelRequest, ModelSelection, ModelCapabilitySnapshot, ModalityModelSnapshot}; + +pub type Admission = String; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ResolveRequest { pub target: Option, pub cwd: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PreferencesRequest { pub selection: ModelSelection, pub update: ModelPreferences } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Use { Chat, Modality { operation: String } } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SelectableRequest { pub use_: Use } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SelectableReply { + pub models: SelectableModels, + pub default: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum SelectableModels { Chat(Vec), Modality(Vec) } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupRequest { + pub target: Option, + pub cwd: Option, + pub preferences: ModelPreferences, + pub connection: Option, + pub limits: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RetainRequest { pub session: String, pub model: ModelSelection } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum Mode { Dialogue { chain: Option }, Once } + +pub type ConsumeFn = Arc BoxFuture<'static, Consumed> + Send + Sync>; +pub type AdmitFn = Arc BoxFuture<'static, Admitted> + Send + Sync>; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InvokeRequest { + pub request: ModelRequest, + pub mode: Mode, + pub consume: ConsumeFn, + pub admit: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InvokeReply { pub outcome: Outcome } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MediaRouteRequest { pub target: ModelId, pub operation: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MediaRouteReply { + pub protocol: ModelProtocol, + pub base_url: String, + pub headers: BTreeMap, + pub realtime: Option, + /// The credential owner the media executor calls `with_lease` on: this owner, or an account owner. + pub credential: CredentialOwner, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LeaseRequest { pub provider: String, pub model: String } + +#[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum ProviderError { + #[error("{0}")] Invalid(String), + #[error("{0}")] InvalidConnection(String), + #[error("{0}")] NotFound(String), + #[error("{reason}")] Unavailable { reason: String }, + #[error("authentication is required")] AuthRequired, + #[error("cancelled")] Cancelled, + #[error("provider is unloading")] Closed, + #[error("{0}")] Failed(String), + #[error("{message}")] ProviderFailed { retryable: bool, message: String }, + #[error("{0}")] InvalidPath(String), +} + +impl PublicService for Provider {} + +#[rutis::service(name = "providerService")] +impl Provider { + pub async fn resolve(&self, request: ResolveRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn preferences(&self, request: PreferencesRequest) -> Result { /* ... */ } + pub async fn selectable(&self, request: SelectableRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn prepare_startup(&self, request: StartupRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn retain_startup(&self, request: RetainRequest) -> Result<(), ProviderError> { /* ... */ } + pub async fn release_startup(&self, admission: Admission) -> Result<(), ProviderError> { /* ... */ } + pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result<(), ProviderError> { /* ... */ } +} +``` + +The `provider` client namespace keeps its published method names and request shapes; handlers call the operations above and the management operations. No management operation is also published on `providerService`. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..c347503527 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -9,6 +9,12 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | +| [Provider](Provider.md) (owner contract) | model owner of the product profile: provider and model records, selection, credentials, execution, temporary connections, the wire recorder | — | — | [#2019](https://github.com/arcships/dim/issues/2019) | +| [ConfiguredModels](ConfiguredModels.md) (owner contract) | model owner of the API-key profile: the model file, its credentials and execution | — | — | [#2019](https://github.com/arcships/dim/issues/2019) | +| [Managed account owners](ManagedAccount.md) (owner contract) | the account role: record, login, tokens, availability, catalog, request leases, client namespace | — | — | [#2019](https://github.com/arcships/dim/issues/2019) | +| [DimOAuth](DimOAuth.md) (owner contract) | Dim account owner: record, login, leases, relay search and title | — | — | [#2019](https://github.com/arcships/dim/issues/2019) | +| [Managed OAuth accounts](ManagedOAuth.md) (owner contract) | OpenAI Codex and Grok account owners: record, login, leases | — | — | [#2019](https://github.com/arcships/dim/issues/2019) | +| [ManagedProviders](ManagedProviders.md) (owner contract) | ChatGPT account owner; the host binding and `managedSearch` face are retired | — | — | [#2019](https://github.com/arcships/dim/issues/2019) | | [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 | | [ShellInput](ShellInput.md) | — | `shell.*` methods, command runs | — | P1 | From 6efb14de1e5313a5d36ac0c38524a22da0e15111 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 19:33:18 +0800 Subject: [PATCH 2/9] design(provider): own records, settle startup by lifetime, confirm the lease boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provider owns its records, selection, preferences, candidates, pages, source activation, adoption, edit commits, legacy import and `store.creationRecord`; the storage engine keeps the file and transaction primitive as a private implementation and its public face keeps `storageReport` and the offline operations. A temporary startup connection is admitted under the calling row and moved to a Session by `retain_startup({session, model})`; a missed retain or release settles with the row, and a retained source with the Session. `release_startup({model})` is the optional early release. The Rpc examples adopt a model on a line through PromptAdoption's `configure` by line id instead of a Branch handle. The account owner cannot perform the model exchange itself, so `with_lease` hands the lease to the caller's attempt; the boundary and its alternatives are recorded and raised for maintainer confirmation. Refs #2019 · Refs #2015 --- docs/design/plugins/ManagedAccount.md | 2 +- docs/design/plugins/Provider.md | 62 +++++++++++++++------------ 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/docs/design/plugins/ManagedAccount.md b/docs/design/plugins/ManagedAccount.md index 61b7889f6a..8df1c2e82f 100644 --- a/docs/design/plugins/ManagedAccount.md +++ b/docs/design/plugins/ManagedAccount.md @@ -119,7 +119,7 @@ All operations are marked on the owner type and provided under the owner's face ## Exceptions with reasons -- `Lease` carries the bearer into the callback: the model owner or the media executor performs the exchange, the account owner holds the grant, and the value lives only for one attempt; the contract forbids storing, logging or returning the bearer to a client. +- `Lease` carries the bearer into the callback: the model owner or the media executor performs the exchange, the account owner holds the grant, and the value lives only for one attempt; the contract forbids storing, logging or returning the bearer to a client. The account owner cannot perform the exchange itself: the model protocol, transport, streaming, adaptation and the per-profile driver belong to the executor, and duplicating them in every account owner would make each account own a transport. A secret value in a reply is forbidden by AGENTS.md and an object or handle by §7. The boundary is raised for maintainer confirmation in [#2096](https://github.com/arcships/dim/pull/2096). - The external account plugin's face name is configured by its row because the plugin is built outside this repository; the host records the name in the Provider record's authority. ## Rule check diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md index 25d8e2a89c..c7b5573330 100644 --- a/docs/design/plugins/Provider.md +++ b/docs/design/plugins/Provider.md @@ -8,11 +8,11 @@ Provider is the model owner of the product profile: it decides which model a req Provider owns: -- **Records.** Provider, model and selection records: static and imported records, descriptor overrides, user models, enables, per-model preferences, workspace and global selections, source generations and per-provider adoption. Records are read and written through the storage owner's operations; Provider keeps no SQL. +- **Records.** Provider, model and selection records: static and imported records, descriptor overrides, user models, enables, per-model preferences, workspace and global selections, source generations and per-provider adoption. The records are Provider's own; the storage engine holds the file, lease and transaction primitive as a private implementation, and the rows never cross a public face. - **Selection.** The precedence among an explicit target, the workspace and global selections, the configured default and account-backed candidates; the availability rule execution applies; the adopted capability snapshot and configuration a selection carries. - **Credentials.** Static credentials read from the record or an external secret store, managed-account leases, and temporary startup connections. A credential is used for one request and never leaves Provider except as the one-attempt lease a media call needs. - **Execution.** One model request from the adopted selection through adaptation, transport, retries, credential recovery, streaming and settlement. Provider owns the driver that performs the request and its connection pool, request identity, stream set and tasks. -- **Temporary connections.** A startup connection admitted for one Session creation, the admission id that names it, and its settlement. +- **Temporary connections.** A startup connection admitted for one Session creation; it is bound to the calling row until a Session adopts it, then to that Session. - **Client management.** The reads and writes the `provider` client namespace serves, with their transactions and versions. - **The wire recorder.** The recorder its driver starts from ModelLog's `recording` value; the file, its redaction and its lifetime are Provider's. @@ -21,7 +21,7 @@ Callers keep: - Which model a Session adopts and when it changes; Provider answers the selection and the caller writes the Session's configuration. - The request's messages, system prompt, tools and metadata; Provider adapts and sends what the caller built. - What the output means: ModelProvider commits the stream to the Timeline and decides the turn's end; a one-shot caller collects the text. -- The summary budget and the retry display: the caller passes an admission callback and observes progress. +- The summary budget and the retry display: the caller passes an `admit` callback and observes progress. - Account login, logout and usage: the account owners' client namespaces, not Provider. - Which search service a tool uses: Web's own settings, with the account owner's availability read. @@ -30,7 +30,7 @@ Callers keep: | Choose the model for a Session creation or a model change | No: the precedence and the availability rule are Provider's state and decisions | `resolve` | | Apply a preference patch to an adopted selection | No: the patch is validated against the model's declarations | `preferences` | | List the models that can run a use, and the current default | No: the list is the execution rule, one snapshot | `selectable` | -| Admit a temporary connection for a Session creation | No: the credential is a resource bound to the calling row; expiring or releasing it is Provider's | `prepare_startup`, `retain_startup`, `release_startup` | +| Admit a temporary connection for a Session creation | No: the credential is a resource bound to the calling row and then to the Session; expiring or releasing it is Provider's | `prepare_startup`, `retain_startup`, `release_startup` | | Run one model request with retries, recovery and streaming | No: credentials, retry budgets, failure chains and output adaptation stay with the owner | `invoke` | | Learn a media model's route and where its credential comes from (the media executor) | No: the route is catalog state; the credential owner is the record's authority | `media_route` | | Run one media exchange with a static model's credential (the media executor) | No: the credential is Provider's resource, and a caller holding it would release it on every error path | `with_lease` | @@ -50,7 +50,10 @@ The Rpc entry chooses a model while creating a Session: let selection = provider .resolve(ResolveRequest { target: requested, cwd: Some(cwd) }, cancelled.clone()) .await?; -session.configure(ConfigureUpdate { model: Some(selection), ..Default::default() }, &branch).await?; +line_owner::(line)?.configure( + ConfigureRequest { sources: None, model: Some(selection), tools: None }, + cancelled.clone(), +).await?; ``` The Rpc entry changes only the preferences of the model already adopted: @@ -59,7 +62,10 @@ The Rpc entry changes only the preferences of the model already adopted: let next = provider .preferences(PreferencesRequest { selection: current, update: patch }, cancelled.clone()) .await?; -session.configure(ConfigureUpdate { model: Some(next), ..Default::default() }, &branch).await?; +line_owner::(line)?.configure( + ConfigureRequest { sources: None, model: Some(next), tools: None }, + cancelled.clone(), +).await?; ``` Modality lists the options for an operation: @@ -129,10 +135,11 @@ let destination = model_log.recording().await.ok().flatten(); A Session creation with a temporary connection: ```rust -let Started { selection, admission } = provider.prepare_startup(request, cancelled.clone()).await?; +let selection = provider.prepare_startup(request, cancelled.clone()).await?; let session = sessions.create(/* with selection */).await?; provider.retain_startup(RetainRequest { session: session.id().into(), model: selection }, cancelled).await?; -// On any failure before retention: provider.release_startup(admission, cancelled).await?; +// On a creation that fails before retention, the caller may release early: +provider.release_startup(ReleaseRequest { model: selection }, cancelled).await?; ``` ## Own contract @@ -141,12 +148,11 @@ provider.retain_startup(RetainRequest { session: session.id().into(), model: sel | Owner | Operation | Use | | --- | --- | --- | -| Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)) | record reads, selection reads and writes, source activation and adoption, edit commits, candidate and page queries, legacy import | Provider records; the storage owner's contract defines the shapes | | ProviderSettings ([#2017](https://github.com/arcships/dim/issues/2017)) | `user_agent` | The operator's User-Agent replacement | | ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)) | `recording` | The recorder's directory | | FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)) | `root_path` | The directory the wire recorder writes under | -| Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)) | `store.creationRecord` | The ChatGPT client-session rule (the Session's origin) | -| Session directory ([#2020](https://github.com/arcships/dim/issues/2020)) | session close observation | Releasing a retained startup admission | +| Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) | private transaction primitive; the public face keeps `storageReport` and the offline operations | Provider's records, selections, candidates, pages, source activation, adoption, edit commits, legacy import and `store.creationRecord` | +| Session directory ([#2020](https://github.com/arcships/dim/issues/2020)) | session close observation | Releasing a retained startup source | | Account owners ([ManagedAccount](ManagedAccount.md)) | `availability`, `catalog`, `with_lease` | Account-backed models; the record's authority names the owner | Provider reads an account owner by the name its record's credential authority carries; the face names are in [ManagedAccount](ManagedAccount.md). @@ -160,14 +166,14 @@ All operations are marked on `Provider` and provided under `providerService`; re | `resolve` | The model one request resolves to | `{target?, cwd?}` | `Selection` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `preferences` | Apply a patch to an adopted selection | `{selection, update}` | `Selection` | None; completes immediately | `invalid` | | `selectable` | The models that can run a use, and the default | `{use: "chat" \| {modality}}` | `{models, default?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | -| `prepare_startup` | Admit a temporary connection and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `{selection, admission}` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | +| `prepare_startup` | Admit a temporary connection under the calling row and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `{selection}` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `retain_startup` | Bind the temporary connection the model carries to a Session | `{session, model}` | `{}` | None; completes immediately | `not_found` (the model carries no source, or the source is not bound), `closed` | -| `release_startup` | Release an admission before or after retention | `{admission}` | `{}` | None; completes immediately | `not_found`, `closed` | +| `release_startup` | Release a source still bound to the calling row | `{model}` | `{}` | None; completes immediately | `not_found` (already retained by a Session), `closed` | | `invoke` | Run one model request | `{request, mode, consume, admit?}` | `{outcome}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `unavailable`, `cancelled`, `closed`, `provider_failed {retryable}` | | `media_route` | A media model's route and the owner of its credential | `{target, operation}` | `{protocol, base_url, headers, realtime?, credential: Owner}` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | | `with_lease` | Run the caller's attempt with a static model's credential | `{provider, model}` plus `attempt(lease) -> {rejected}` | `{}` | The caller cancels; the attempt stops | `not_found`, `unavailable`, `cancelled`, `closed` | -`admission` is the caller's release handle before retention; `retain_startup` names the Session and the model it adopts, so a member Session that inherits the leader's model retains the same source by value and no caller holds the source. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Lease` is [ManagedAccount](ManagedAccount.md)'s one-attempt value; `with_lease` hands it to the caller's attempt and releases it when the attempt ends, so no lease id crosses. +`prepare_startup` admits the source under the calling row; the row's unload releases it, so a missed `retain_startup` or `release_startup` settles with the row. `retain_startup({session, model})` moves the source to the Session named by the caller and the model's metadata; the Session's close releases it, so a missed failure-path release settles with the Session. `release_startup({model})` is the optional early release for a creation that failed; it answers `not_found` once a Session retains the source. A member Session that inherits the leader's model retains the same source by value. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Lease` is [ManagedAccount](ManagedAccount.md)'s one-attempt value; `with_lease` hands it to the caller's attempt and releases it when the attempt ends, so no lease id crosses. `invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits through the optional `admit`/progress callbacks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(next)` receives chunks, ends and typed failures and returns how the call ended and whether output was accepted; output accepted before a failure prevents replay. `admit` runs before each attempt and returns `admitted` or `rejected {message}`; only a caller with its own budget passes it. @@ -177,7 +183,7 @@ All operations are marked on `Provider` and provided under `providerService`; re | --- | --- | | `invalid` | Fix the input: an unknown use, an explicit target missing its model, a malformed preference patch | | `invalid_connection` | Fix the startup connection: a rejected URL, user info, query, fragment, both an API key and a bearer, or an unsupported auth | -| `not_found` | The provider, model or admission does not exist; re-read or choose another | +| `not_found` | The provider, model or source does not exist; re-read or choose another | | `unavailable` | The model cannot run now; the message names the reason; choose another model or fix the record | | `auth_required` | Sign in through the account owner named by the record, then retry | | `cancelled` | Nothing changed; the call stopped where it was cancelled | @@ -191,13 +197,13 @@ All operations are marked on `Provider` and provided under `providerService`; re | --- | --- | --- | --- | --- | --- | | `resolve`, `selectable` | Read records and account state, apply the precedence and availability rule, return the value | The read stops; nothing changes | The call ends `cancelled` | Pending calls end `closed`; the next generation answers from current records | Provider's read tasks | | `invoke` | Resolve or adopt the request's selection, adapt images, resolve the credential (account lease or static), send, adapt chunks, hand them to `consume`, retry or recover per the failure chain, settle the consumer | The transport is cancelled, the stream is dropped, the consumer is released; accepted output stays committed | The consumer callback is revoked; the call ends `cancelled`; admitted work is joined | Admission stops; in-flight requests are cancelled and joined; account leases are settled | Provider: request tasks, stream and lease. ModelProvider: the Timeline writes already committed | -| `prepare_startup` | Validate and admit the connection under an admission id bound to the calling row, select its model | Before admission; nothing is retained | The row's admissions are released | Admissions are dropped; a retained Session's connection is restored by its next generation | Provider: the admission; the calling row: its lifetime | -| `retain_startup` / `release_startup` | Read the model's source, add the Session to its owners, watch the Session; release an admission not yet retained | — | An unretained admission is released with the row | Retained sources survive the owner's reload as Session state is re-read | Provider: the source and its owners; the Session directory reports close | +| `prepare_startup` | Validate and admit the connection under the calling row, select its model | Before admission; nothing is retained | The row's unretained sources are released | Unretained sources are dropped; a retained Session's source is restored by its next generation | Provider: the source; the calling row: its lifetime | +| `retain_startup` / `release_startup` | Read the model's source, add the Session to its owners, watch the Session; release a source not yet retained | — | An unretained source is released with the row | Retained sources survive the owner's reload as Session state is re-read | Provider: the source and its owners; the Session directory reports close | | `media_route`, `with_lease` | Read the catalog and the credential owner, or hand a static credential to the attempt | The read stops; the attempt ends and the credential is dropped | The call ends `cancelled` | Pending calls end `closed` | Provider | ## Exceptions with reasons -- `with_lease` and the lease inside `invoke` hand the bearer to the caller's attempt for one request: the executor is the model owner or the media adapter and the account owner holds the grant, so the value crosses once and is never persisted, logged, quoted in an error or returned to a client. +- `with_lease` and the lease inside `invoke` hand the bearer to the caller's attempt for one request: the executor is the model owner or the media adapter and the account owner holds the grant, so the value crosses once and is never persisted, logged, quoted in an error or returned to a client. The account owner cannot perform the exchange itself: the model protocol, transport, streaming, adaptation and the per-profile driver are the executor's, and executing them in every account owner would duplicate the transport. A secret value in a reply is forbidden by AGENTS.md and an object or handle by §7. The boundary is raised for maintainer confirmation in [#2096](https://github.com/arcships/dim/pull/2096). - The `provider` client namespace is a client protocol, not a second service face: it is the mechanism's registration point for protected-local v3 clients, and every handler calls the operations above or the management operations this owner also owns. ## Rule check @@ -206,7 +212,7 @@ All operations are marked on `Provider` and provided under `providerService`; re | --- | --- | | §1 parts and Capabilities | One process part. Provider writes no Timeline event; it is not a Capability. ModelProvider, the branch Capability, consumes `invoke`. | | §2 scopes | Process: records, catalogs and credentials outlive Sessions. Session and branch parts call the operations; no branch state is held. | -| §3 orthogonality | No other owner's state is read or changed. Account state comes from the account owner's operations; records from the storage owner's. | +| §3 orthogonality | No other owner's state is read or changed. Account state comes from the account owner's operations; records are Provider's own. | | §4 rule 1 | No command event: model calls reach Provider as operations, not Timeline facts. | | §4 rule 2 | No handoff: the request and its output stay with the caller and the Timeline. | | §4 rule 3 | No before callback: `consume` writes through ModelProvider's own Timeline service, outside the commit lock. | @@ -216,8 +222,8 @@ All operations are marked on `Provider` and provided under `providerService`; re | §4 rule 7 | Callers use these operations; no caller reads a record, a connection or a catalog internal. | | §4 rule 8 | Requirements are listed below; no runtime mechanism is added. | | §4 rule 9 | No Timeline fact: selections and records are process state with owner writes. | -| §7 objects, ids, values, callbacks | Values: selections, lists, leases, routes. Callbacks: `consume`, `admit`. Ids: `admission`. No object crosses. | -| §7 no proxy | Account data comes from the account owner; the storage operations from the storage owner. Provider returns only its own records and decisions. | +| §7 objects, ids, values, callbacks | Values: selections, lists, leases, routes. Callbacks: `consume`, `admit`. Ids: the calling row and the Session. No object crosses. | +| §7 no proxy | Account data comes from the account owner; records are Provider's own. The storage engine is not a face. | | §7 one change | The delivery part migrates every caller and deletes every pre-migration name in one change. | | ADR 002 D1 | Process: records, catalogs and credentials are shared across Sessions. | | ADR 002 D2 | No wiring plugin: the operations are on the owner type. | @@ -227,9 +233,9 @@ All operations are marked on `Provider` and provided under `providerService`; re ## Requirements raised to mechanism owners -- **Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)).** Provider owns no SQL and no connection. It needs operations for: a record read by projection (header, all, one model, selected models, version); selection read and versioned write; per-model preferences; candidate lookup by criteria; provider list, model pages and management pages with their ordering and limits; source activation and per-provider adoption from bundle facts; one commit operation per edit family (create, delete, header patch, connection replacement, refresh, model create/edit/delete, enablement, preferences) with the existing preconditions and returned projections; legacy import as one batch; and `store.creationRecord` for a Session's origin. The storage owner's document defines the names and shapes. +- **Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)).** The engine's public face keeps only `storageReport` and the offline operations. Provider owns its records, selection, preferences, candidate and page queries, source activation, adoption, edit commits, legacy import and `store.creationRecord`; the engine supplies the private transaction primitive inside this crate, which is not a public operation. - **ProviderSettings and ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)).** Their owner contracts define `user_agent` and `recording`; Provider reads both at request time. No requirement remains. -- **Session directory ([#2020](https://github.com/arcships/dim/issues/2020)).** Provider needs a close observation for a retained startup admission: when the Session closes without unload, the admission is released; an unload keeps it for restore. +- **Session directory ([#2020](https://github.com/arcships/dim/issues/2020)).** Provider needs a close observation for a retained startup source: when the Session closes without unload, the source is released; an unload keeps it for restore. - **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `root_path` only; the recorder owns its JSONL file. - **Account owners ([ManagedAccount](ManagedAccount.md)).** `availability`, `catalog`, `with_lease`; the face name comes from the record's credential authority. - **Media executor (Modality's adapter contract).** The adapter resolves `media_route` and calls `with_lease` on the credential owner for the model target; Modality passes the target and settles the task, so no business caller holds a lease id. The adapter's service shape is Modality's contract. @@ -242,8 +248,6 @@ All operations are marked on `Provider` and provided under `providerService`; re use dim_agent_capabilities::host::CancelledFn; use dim_agent_types::{ModelId, ModelRequest, ModelSelection, ModelCapabilitySnapshot, ModalityModelSnapshot}; -pub type Admission = String; - #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ResolveRequest { pub target: Option, pub cwd: Option } @@ -285,6 +289,10 @@ pub struct StartupRequest { #[serde(rename_all = "camelCase")] pub struct RetainRequest { pub session: String, pub model: ModelSelection } +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReleaseRequest { pub model: ModelSelection } + #[derive(serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum Mode { Dialogue { chain: Option }, Once } @@ -346,9 +354,9 @@ impl Provider { pub async fn resolve(&self, request: ResolveRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn preferences(&self, request: PreferencesRequest) -> Result { /* ... */ } pub async fn selectable(&self, request: SelectableRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn prepare_startup(&self, request: StartupRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn prepare_startup(&self, caller: &Ctx, request: StartupRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn retain_startup(&self, request: RetainRequest) -> Result<(), ProviderError> { /* ... */ } - pub async fn release_startup(&self, admission: Admission) -> Result<(), ProviderError> { /* ... */ } + pub async fn release_startup(&self, request: ReleaseRequest) -> Result<(), ProviderError> { /* ... */ } pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result<(), ProviderError> { /* ... */ } From ce133c0a04144d3ec70a63800071e372d0da1c15 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 20:11:52 +0800 Subject: [PATCH 3/9] design(provider): replace the lease with a credential generation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The account owners hand out a credential value carrying the grant generation instead of a lease handle. `credential({provider, model})` answers the connection facts and refreshes inside its window; `rejected({provider, generation})` refreshes the current generation once, answers the current credential for a superseded one, and follows the sign-out rule when the refresh is rejected or the recovered generation is rejected again. The lease id, capacity, expiry, release, recovery callback and `finish_rejected` are removed; retries stay with Provider's `invoke`. The bearer is a trusted in-process value. ManagedAccount states where it never goes; Provider, ConfiguredModels, DimOAuth, ManagedOAuth and ManagedProviders link that paragraph. The maintainer-confirmation exception is removed. Refs #2019 · Refs #2015 --- docs/design/plugins/ConfiguredModels.md | 14 ++--- docs/design/plugins/DimOAuth.md | 23 ++++---- docs/design/plugins/ManagedAccount.md | 77 ++++++++++--------------- docs/design/plugins/ManagedOAuth.md | 22 ++++--- docs/design/plugins/ManagedProviders.md | 17 +++--- docs/design/plugins/Provider.md | 36 ++++++------ 6 files changed, 89 insertions(+), 100 deletions(-) diff --git a/docs/design/plugins/ConfiguredModels.md b/docs/design/plugins/ConfiguredModels.md index d6d47eedbc..46a81798c2 100644 --- a/docs/design/plugins/ConfiguredModels.md +++ b/docs/design/plugins/ConfiguredModels.md @@ -21,7 +21,7 @@ Callers keep everything they keep with Provider: the Session's adopted model and | List the models a use can run | No: the file and its limits are this owner's | `selectable` | | Run one model request | No: credentials, retries and streaming are the owner's | `invoke` | | A media model's route and credential | No: the file declares no modality operation | `media_route` answers `unavailable` for every operation | -| Run one exchange with a model's environment credential (the media executor) | No: the credential is this owner's resource | `with_lease` | +| Read a model's environment credential for one exchange (the media executor) | No: the file and the environment variable are this owner's | `credential` | | Apply a preference patch | No: the file declares no effort or tier | `preferences` is absent in this profile; the client protocol rejects preferences | | Admit a temporary connection | No: the file is the only connection source | `prepare_startup` is absent; the client protocol rejects startup | | Learn where the recorder writes | Yes: read ModelLog's `recording` value | Business | @@ -48,21 +48,21 @@ let outcome = provider ### Face and operations -Face `providerService`, marked on `ConfiguredModels`; operations `resolve`, `selectable`, `invoke`, `media_route` and `with_lease`, with [Provider](Provider.md)'s request and reply types. `media_route` answers `unavailable`: a model file declares no `.`, so no media call resolves. `with_lease` hands the environment credential to the caller's attempt for one exchange and drops it when the attempt ends. `preferences`, `prepare_startup`, `retain_startup` and `release_startup` do not exist in this profile; the recorder reads ModelLog's `recording` value. +Face `providerService`, marked on `ConfiguredModels`; operations `resolve`, `selectable`, `invoke`, `media_route` and `credential`, with [Provider](Provider.md)'s request and reply types. `media_route` answers `unavailable`: a model file declares no `.`, so no media call resolves. `credential` returns the environment credential for one exchange; the file carries no generation and this profile has no `rejected`, so a refusal is terminal for the caller. `preferences`, `prepare_startup`, `retain_startup` and `release_startup` do not exist in this profile; the recorder reads ModelLog's `recording` value. The file's entries declare both limits; a selection always carries them, so `resolve` and `selectable` cannot fail for an undeclared limit. `selectable(chat)` returns every entry in file order; `selectable(modality)` returns none. ### Errors -[Provider](Provider.md)'s kinds, minus `invalid_connection`, `invalid_path` and `output_limit`'s startup variants: `invalid` for a malformed request, `not_found` for a target missing from the file, `unavailable` for a media operation or a missing environment variable, `cancelled`, `closed`, `failed` and `provider_failed {retryable}`; `with_lease` has `not_found`, `unavailable`, `cancelled` and `closed`. +[Provider](Provider.md)'s kinds, minus `invalid_connection`, `invalid_path` and `output_limit`'s startup variants: `invalid` for a malformed request, `not_found` for a target missing from the file, `unavailable` for a media operation or a missing environment variable, `cancelled`, `closed`, `failed` and `provider_failed {retryable}`; `credential` has `not_found`, `unavailable`, `cancelled` and `closed`. ### Flows -[Provider](Provider.md)'s `resolve`, `selectable`, `invoke` and `with_lease` flows. The file is loaded at `apply`; a reload re-reads it. No record, selection or lease is persisted. +[Provider](Provider.md)'s `resolve`, `selectable`, `invoke` and `credential` flows. The file is loaded at `apply`; a reload re-reads it. No record, selection or credential is persisted. ## Exceptions with reasons -- `with_lease` hands the environment credential to the caller's attempt for one exchange; the same prohibition as [ManagedAccount](ManagedAccount.md) applies. +- The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); `credential` is the only operation that returns it. ## Rule check @@ -87,7 +87,7 @@ None. The model file and its validation are this owner's; no other owner's opera ## Binding appendix -`providerService` is [Provider](Provider.md)'s name; this profile registers the same name from `ConfiguredModels`. The types are shared; only the operations listed above exist. +`providerService` is [Provider](Provider.md)'s name; this profile registers the same name from `ConfiguredModels`. The types are shared, including `Credential` and `CredentialRequest` from [ManagedAccount](ManagedAccount.md); only the operations listed above exist. ```rust impl PublicService for ConfiguredModels {} @@ -98,6 +98,6 @@ impl ConfiguredModels { pub async fn selectable(&self, request: SelectableRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result<(), ProviderError> { /* ... */ } + pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } } ``` diff --git a/docs/design/plugins/DimOAuth.md b/docs/design/plugins/DimOAuth.md index ae243d2b7d..65f4ebad25 100644 --- a/docs/design/plugins/DimOAuth.md +++ b/docs/design/plugins/DimOAuth.md @@ -12,7 +12,7 @@ DimOAuth owns: - **Login.** Browser PKCE and device flows, the directory discovery from the email or the host default, the localhost callback listener's browser opening, and the token exchange. - **Tokens.** The 30-second freshness window, one serialized refresh under the account lock, rotation persisted before release, and the background renewal. - **The relay catalog.** The provider ids and models the plan serves, projected as the account catalog the model owner reads. -- **Request leases.** One request's relay base URL, headers and bearer, with the lease id, capacity and expiry [ManagedAccount](ManagedAccount.md) defines. +- **Credentials.** The relay base URL, headers and bearer for one request, with the grant generation [ManagedAccount](ManagedAccount.md) defines. - **Search and title.** The relay's `POST {relay}/web-search` and `POST {issuer}/v1/session/rename`. - **The client namespace `account.*`.** Status, recover, login begin/browser/device, login status/cancel, logout, usage, referral, reset batches and reset apply. @@ -26,7 +26,7 @@ Callers keep: | Requirement (callers) | Compose from [ManagedAccount](ManagedAccount.md)'s operations without breaking the owner's invariants? | Handling | | --- | --- | --- | | Sign in, sign out, read usage and resets | No: the flow, the record and the plan are DimOAuth's | Client namespace `account.*` | -| Run one relay request with the account's credential, recovering once on a rejection | No: the grant and the lease table are DimOAuth's | `with_lease` | +| Get the relay credential for a request, and the decision after a rejection | No: the grant, its refresh window and its generation are DimOAuth's | `credential`, `rejected` | | Search through the relay | No: the server-side model and the grant are DimOAuth's | `search` | | Generate a session title through the relay | No: the server model, quota and prompt are the relay's | `title` | | Learn whether the relay is signed in | No: state and its changes are DimOAuth's | `availability`, `subscribe` | @@ -71,7 +71,8 @@ Face `dimAccount`, marked on `DimOAuth`. The operations are [ManagedAccount](Man | --- | --- | --- | | `availability`, `subscribe` | `{}` → `{signed_in, identity?}`; the identity is the grant's issuer and subject, never a token | `cancelled`, `closed`, `failed` | | `catalog` | `{}` → `{account, models}`; the models are the relay's, each with its declared capabilities | `unavailable`, `cancelled`, `closed`, `failed` | -| `with_lease` | `{provider, model}` plus the attempt callback → `{recovered}`; `provider` must be one of the relay's; one serialized refresh on a rejection | `not_found`, `unavailable`, `cancelled`, `closed`, `rejected`, `failed` | +| `credential` | `{provider, model}` → `{protocol, base_url, headers, bearer, generation}`; `provider` must be one of the relay's; a read inside the 30-second window refreshes first | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | +| `rejected` | `{provider, generation}` → a credential; the current generation refreshes once under the account lock, a superseded generation answers the current credential; a rejected refresh or a rejected recovered generation follows the sign-out rule | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | | `search` | `{query, count}` → `{results: [{title, url, snippet, publishedAt?}]}` | `unavailable`, `failed`, `cancelled`, `closed` | | `title` | `{provider, text}` → `{title}`; `provider` must be the relay's | `unsupported_provider`, `unavailable`, `cancelled`, `closed`, `failed` | @@ -81,13 +82,14 @@ The `account.*` namespace keeps its published methods; handlers call the same ow | Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | -| `with_lease` | Read the grant atomically when fresh; inside the 30-second window take the lock and refresh; record the lease id; call the attempt; on `rejected` one recovery under the account lock; release the lease | The token ends the attempt; the lease is released and the call ends `cancelled` | The callback is revoked; the lease is released | The attempt ends; leases and callbacks are released; a persisted grant stays | DimOAuth: grant, lease id, expiry and recovery; the calling row: its attempt | -| `search` / `title` | Send the relay request with the current bearer; a 401 follows the same one-recovery rule as `lease` | The request is cancelled | Pending requests end `closed` | DimOAuth | +| `credential` | Read the grant atomically when fresh; inside the 30-second window take the lock and refresh; answer the facts and the generation | The wait ends; a started refresh continues under the owner | The call ends `cancelled` | Pending calls end `closed`; a persisted grant stays | DimOAuth's refresh task | +| `rejected` | Compare the generation; current → one serialized refresh, superseded → the current credential; a rejected refresh signs out the grant that holds the lock | The wait ends; the refresh continues | The call ends `cancelled` | Pending calls end `closed` | DimOAuth | +| `search` / `title` | Send the relay request with the current bearer; a 401 follows the same rule as `rejected` | The request is cancelled | Pending requests end `closed` | DimOAuth | | `account.*` | Run the login flow or the account read; write the record through FileStorage; publish the result | The attempt is cancelled | Attempts end with the generation; a completed token rotation settles before unload | DimOAuth | ## Exceptions with reasons -- `Lease` carries the bearer to the caller's attempt for one request; [ManagedAccount](ManagedAccount.md) states the rule and the prohibition on storing, logging or returning it. +- The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); DimOAuth's replies and errors omit it. - The account file is shared with the TypeScript subscriber under the published `auth.json.lock` marker protocol; FileStorage's contract records the marker exception, and DimOAuth keeps the file format. ## Rule check @@ -95,19 +97,19 @@ The `account.*` namespace keeps its published methods; handlers call the same ow | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part; no Timeline facts, no Capability. | -| §2 scopes | Process: the grant and leases outlive Sessions. | +| §2 scopes | Process: the grant and its generation outlive Sessions. | | §3 orthogonality | No other owner's state is read; FileStorage provides the file operations. | | §4 rules 1–6, 9 | No command events, handoffs, before callbacks, batches, context or Timeline state. | | §4 rule 7 | Web, SessionTitle and the model owner call the face; none reads `auth.json`, the lock or the token. | | §4 rule 8 | No infrastructure change; FileStorage's operations are the contract. | -| §7 ids, values, callbacks | The lease is a value with an id; availability and its changes are a read-only view. | +| §7 ids, values, callbacks | The credential is a value with a generation; availability and its changes are a read-only view. | | §7 no proxy | DimOAuth returns its own account data; no host binding stands between the caller and this owner. | | §7 one change | The delivery part deletes the account forwarding methods and migrates Web, SessionTitle and the model owner together. | | ADR 002 D1 | Process: the account is shared across Sessions. | | ADR 002 D2 | No wiring plugin. | | ADR 002 D3 | Depends on FileStorage only; the model owner depends on this face. | | ADR 002 D4 | The directory and account record are business state in the owner's store. | -| ADR 002 D5 | The face is language-neutral; the lease value is data. | +| ADR 002 D5 | The face is language-neutral; the credential value is data. | ## Requirements raised to mechanism owners @@ -126,7 +128,8 @@ impl DimOAuth { pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn rejected(&self, request: RejectedRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn search(&self, request: SearchRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn title(&self, request: TitleRequest, cancelled: CancelledFn) -> Result { /* ... */ } } diff --git a/docs/design/plugins/ManagedAccount.md b/docs/design/plugins/ManagedAccount.md index 8df1c2e82f..439ae202a0 100644 --- a/docs/design/plugins/ManagedAccount.md +++ b/docs/design/plugins/ManagedAccount.md @@ -11,13 +11,13 @@ An account owner owns: - **The account record.** The persisted grant and account state under the product home, written through FileStorage's operations with the account's own revision and lease. - **Login and tokens.** Login attempts, the pending exchange, token refresh, rotation and revocation. - **Model availability.** Whether the account is signed in and which models its plan serves; the catalog the plan projects. -- **Request leases.** One request's connection facts, their expiry and capacity, recovery after a rejection, and the final settlement. +- **The grant's generation.** The credential it hands out carries the generation it belongs to, so a rejection names the generation the provider refused; the owner decides whether to refresh or to answer with the current one. - **Its client namespace.** `account.*`, `account.codex.*`, `account.grok.*` or `account.chatgpt.*`, served to protected-local clients; handlers call the owner's operations. Callers keep: - Which account a provider uses: the Provider record's credential authority names the owner. -- The request itself: the model owner or the media executor performs the attempt with the lease the owner hands to its callback, and the owner settles the lease after the callback. +- The request itself and its retries: the model owner sends it, calls `rejected` on a refusal and retries within its own failure chain; the account owner performs one refresh at most, not the request. - What a login flow shows and when it starts: the client protocol. - The search query and its presentation: Web, through DimOAuth's search operation when its settings name the relay. - The title prompt and its fallback: SessionTitle, through DimOAuth's title operation. @@ -26,7 +26,8 @@ Callers keep: | --- | --- | --- | | Learn whether the account can serve, and follow changes | No: sign-in state and its changes are the owner's state | `availability`, `subscribe` | | Project the models the plan serves | No: the plan, the grant and the catalog are the owner's | `catalog` | -| Run one request with the account's credential, recovering once when the provider rejects it | No: the grant, the refresh and the lease's capacity are the owner's; a caller holding a lease id would have to release it on every error, cancel and unload path | `with_lease` | +| Get the connection facts for one request | No: the grant, its refresh window and its generation are the owner's | `credential` | +| Find out what to do after the provider rejected a generation | No: whether the rejected generation is current, and one refresh at most, are the owner's decision | `rejected` | | Search through the relay (Dim) | No: the grant and the server-side model are the owner's | `search` | | Generate a title through the relay (Dim) | No: the server model and quota are the owner's | `title` | | Show login, logout, usage and resets | No: the flows, records and plan are the owner's | The client namespace | @@ -36,24 +37,14 @@ An operation exists only where the row says No. ## Caller example -The model owner runs one attempt inside the owner's operation; the account owner hands over the lease, recovers once when the attempt reports a rejection, and settles the lease afterwards. No lease id appears here: +The model owner sends one request, recovers once from a rejection and keeps the retry count: ```rust -let WithLeaseReply { recovered } = account - .with_lease( - LeaseRequest { provider: record.provider_id.clone(), model: model.clone() }, - Arc::new(move |lease: Lease, cancelled: CancellationToken| { - Box::pin(async move { - // One exchange with `lease`. `Rejected` only when the provider rejected the credential. - match send_once(&lease, cancelled).await { - Err(CredentialRejected) => AttemptReply { rejected: true }, - _ => AttemptReply { rejected: false }, - } - }) - }), - cancelled.clone(), - ) - .await?; +let Credential { protocol, base_url, headers, bearer, generation } = + account.credential(CredentialRequest { provider: record.provider_id.clone(), model: model.clone() }, cancelled.clone()).await?; +// Send with these facts. On a credential rejection: +let next = account.rejected(RejectedRequest { provider: record.provider_id, generation }, cancelled.clone()).await?; +// Send once more with `next`; further retries are this caller's failure chain. ``` Web follows the Dim account's availability: @@ -87,24 +78,27 @@ All operations are marked on the owner type and provided under the owner's face | `availability` | Whether the account is signed in | `{}` | `{signed_in, identity?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | | `subscribe` | Follow availability changes | `{}` | `{subscription}` | The subscription ends with the caller's row | `closed` | | `catalog` | The models the plan serves | `{}` | `{account, models}` | The caller cancels; a catalog read may wait on the account's own refresh | `unavailable`, `cancelled`, `closed`, `failed` | -| `with_lease` | Run the caller's attempt with one request's connection facts, recovering once when the attempt reports a rejection | `{provider, model}` plus `attempt(lease) -> {rejected}` | `{recovered}` | The caller cancels; the attempt stops and the owner settles the lease | `not_found`, `unavailable`, `cancelled`, `closed`, `rejected`, `failed` | +| `credential` | The connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation}`; a read inside the refresh window refreshes first | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | +| `rejected` | The generation the provider refused; answer the credential to retry with | `{provider, generation}` | A credential; the current generation refreshes once, a superseded generation answers the current credential | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | | `search` (Dim) | Search through the relay | `{query, count}` | `{results}` | The caller cancels; the provider request is cancelled | `unavailable`, `failed`, `cancelled`, `closed` | | `title` (Dim) | Generate a title through the relay | `{provider, text}` | `{title}` | The caller cancels; an HTTP exchange is bounded at 10 s | `unsupported_provider`, `unavailable`, `cancelled`, `closed`, `failed` | -`Lease` is a value handed to the attempt callback: `{lease_id, expires_at, protocol, base_url, headers, bearer}`. The owner records the id for capacity (1024) and expiry (30 minutes) and settles it when the callback returns, the caller drops the call, the lease expires, or the owner closes or reloads; `lease_id` lets a caller release early, and settling is otherwise the owner's. One `with_lease` call performs at most one controlled recovery: it adopts a newer persisted grant or performs one serialized refresh, then calls the callback once more with the new lease. A second rejection settles the lease and applies the sign-out rule only when the rejected grant still owns the account. +`rejected` compares the generation with the current one: the current generation is refreshed once and the new credential returned; a generation already replaced answers the current credential without refreshing; a refresh the account rejects, or a recovered generation the provider rejects again, follows the sign-out rule and answers `account_required`. The caller never holds a lease, an id to release or an expiry. -`attempt` runs inside the account owner's call, not inside a lock: the owner holds no grant or file lock while the callback runs, and the callback must not call back into the same account owner. The callback may perform the network exchange for the request; `cancelled` is the call's token, which ends the attempt when the caller drops the call or the owner closes. +### The bearer's boundary + +`bearer` is a trusted in-process value, passed between parts of the same process; process-local plugins are not isolated from each other (AGENTS.md rule 11). What keeps it safe is where it never goes: a client reply, the UI, a log, an error text, a persisted record, the model context, or the Timeline. The account's own grant file is the token's store, not a copy of this reply. Every reply and error of this contract omits the bearer except `credential` and `rejected`, and errors quote at most the provider's status and code. [Provider](Provider.md), [ConfiguredModels](ConfiguredModels.md), [DimOAuth](DimOAuth.md), [ManagedOAuth](ManagedOAuth.md) and [ManagedProviders](ManagedProviders.md) link this paragraph instead of restating it. ### Errors | Kind | What the caller does next | | --- | --- | | `not_found` | The provider is not this owner's; re-read the record | -| `unavailable` | Sign in, renew the plan or wait for the account; the message names the reason | +| `account_required` | Sign in: the account is signed out, or the refresh it attempted was rejected | +| `unavailable` | The plan or the relay cannot serve the model now; the message names the reason | | `unsupported_provider` | This owner does not serve that provider; use the owner the record names | -| `cancelled` | Nothing changed; the attempt stopped and the lease is settled | +| `cancelled` | Nothing changed; the call stopped where it was cancelled | | `closed` | This generation is unloading; call the next generation | -| `rejected` | Both attempts were rejected; the owner settled the lease and applied the sign-out rule; the caller reports the failure | | `failed` | The account store or the provider request failed; retry the business step | ### Flows @@ -113,13 +107,13 @@ All operations are marked on the owner type and provided under the owner's face | --- | --- | --- | --- | --- | --- | | `availability`, `subscribe` | Read the account state; publish the value and its changes | The read stops; a subscription ends | The subscription ends | The watch is rebuilt from the store; subscribers end | The owner | | `catalog` | Read the grant, refresh if inside the window, project the plan's models | The wait ends; the owner's refresh continues | The call ends `cancelled` | Pending calls end `closed`; the next generation re-reads | The owner's refresh task | -| `with_lease` | Read the grant, refresh if needed, record the lease id, call `attempt`; on `rejected`, one controlled recovery, then `attempt` again; release the lease | The token ends the attempt; the lease is released and the call ends `cancelled` | The callback is revoked; the call ends `cancelled`; the lease is released | The attempt ends; every lease id and the callback are released; a persisted grant stays | The owner: lease id, expiry, capacity and recovery; the calling row: its attempt state | +| `credential` | Read the grant, refresh if inside the window, answer the facts and the generation | The wait ends; a started refresh continues | The call ends `cancelled` | Pending calls end `closed`; a persisted grant stays | The owner's refresh task | +| `rejected` | Compare the generation, refresh once or answer the current credential, or apply the sign-out rule | The wait ends; a started refresh continues | The call ends `cancelled` | Pending calls end `closed` | The owner | | `search` / `title` | Send the relay request with the grant's bearer | The request is cancelled | The call ends `cancelled` | Pending requests end `closed` | The owner | | Client namespace | Run the login flow, write the record through FileStorage and publish the result | The attempt is cancelled | The attempt stays queryable until its deadline | Attempts end with the generation | The owner | ## Exceptions with reasons -- `Lease` carries the bearer into the callback: the model owner or the media executor performs the exchange, the account owner holds the grant, and the value lives only for one attempt; the contract forbids storing, logging or returning the bearer to a client. The account owner cannot perform the exchange itself: the model protocol, transport, streaming, adaptation and the per-profile driver belong to the executor, and duplicating them in every account owner would make each account own a transport. A secret value in a reply is forbidden by AGENTS.md and an object or handle by §7. The boundary is raised for maintainer confirmation in [#2096](https://github.com/arcships/dim/pull/2096). - The external account plugin's face name is configured by its row because the plugin is built outside this repository; the host records the name in the Provider record's authority. ## Rule check @@ -127,12 +121,12 @@ All operations are marked on the owner type and provided under the owner's face | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part per account owner; no Timeline facts, no Capability. | -| §2 scopes | Process: grants, tokens and leases outlive Sessions. | +| §2 scopes | Process: grants and generations outlive Sessions. | | §3 orthogonality | The account owner reads no other owner's state; FileStorage provides file operations, Settings the directory list. | | §4 rules 1–6, 9 | No command events, handoffs, before callbacks, batches, context or Timeline state. | | §4 rule 7 | Callers use these operations; no caller reads the grant, the token or the attempt table. | | §4 rule 8 | FileStorage's operations are the only infrastructure dependency; no requirement beyond [#2080](https://github.com/arcships/dim/pull/2080). | -| §7 ids, values, callbacks | The lease is a value inside the owner's callback; the availability subscription is a read-only view; no object or lease id crosses. | +| §7 ids, values, callbacks | The credential is a value with a generation; availability is a read-only view; no object or id to release crosses. | | §7 no proxy | The account owner returns its own account data; the model owner calls the owner the record names. | | §7 one change | The delivery part migrates Provider, Web and the client namespace together. | | ADR 002 D1 | Process: the account and its tokens are shared across Sessions. | @@ -160,40 +154,31 @@ pub struct AccountAvailability { pub signed_in: bool, pub identity: Option, pub bearer: String, + pub generation: u64, } -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct AttemptReply { pub rejected: bool } - -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct WithLeaseReply { pub recovered: bool } - -/// The caller's attempt; `cancelled` ends it when the call or the owner ends. -pub type AttemptFn = - Arc BoxFuture<'static, AttemptReply> + Send + Sync>; - #[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum AccountError { #[error("{0}")] NotFound(String), + #[error("sign in to the account")] AccountRequired, #[error("{reason}")] Unavailable { reason: String }, #[error("{0}")] UnsupportedProvider(String), #[error("cancelled")] Cancelled, #[error("the account owner is unloading")] Closed, - #[error("the provider rejected the recovered credential")] Rejected, #[error("{0}")] Failed(String), } ``` diff --git a/docs/design/plugins/ManagedOAuth.md b/docs/design/plugins/ManagedOAuth.md index 2e644ec276..fbcca4198a 100644 --- a/docs/design/plugins/ManagedOAuth.md +++ b/docs/design/plugins/ManagedOAuth.md @@ -12,7 +12,7 @@ Each owner holds: - **Login.** Browser PKCE for Codex, device flow for Grok, the pending attempt and its deadline. - **Tokens.** Refresh, rotation and the one-controlled-recovery rule. - **The account's model availability.** The models the subscription serves, as the account catalog. -- **Request leases.** The lease ids, capacity and expiry [ManagedAccount](ManagedAccount.md) defines. +- **Credentials.** The connection facts for one request and the grant generation [ManagedAccount](ManagedAccount.md) defines. - **The client namespace** `account.codex.*` or `account.grok.*`. Callers keep the same responsibilities as [ManagedAccount](ManagedAccount.md): the model owner chooses the provider by its record, the client owns login UX, no caller reads the record. @@ -21,7 +21,7 @@ Callers keep the same responsibilities as [ManagedAccount](ManagedAccount.md): t | --- | --- | --- | | Sign in, cancel, sign out | No: the OAuth attempt and record are the owner's | Client namespace `account.codex.*` / `account.grok.*` | | Read account status for the provider list | No: the sign-in state is the owner's | `availability` | -| Run one request with the account's credential, recovering once on a rejection | No: the grant and the lease table are the owner's | `with_lease` | +| Get the credential for a request, and the decision after a rejection | No: the grant, its refresh window and its generation are the owner's | `credential`, `rejected` | | Project the plan's models | No: the plan and the grant are the owner's | `catalog` | ## Caller example @@ -30,12 +30,9 @@ The model owner runs one Codex request inside the owner's operation: ```rust codex_account - .with_lease( - LeaseRequest { provider: "openai-codex".into(), model: model.clone() }, - attempt, // one exchange with the lease; rejected on the provider's 401 - cancelled, - ) + .credential(CredentialRequest { provider: "openai-codex".into(), model: model.clone() }, cancelled.clone()) .await?; +// Send; on a credential rejection call `rejected` with the generation and send once more. ``` The client reads the provider list's account state through the client namespace, not the face: @@ -53,7 +50,7 @@ account.codex.status {} -> { authenticated, identity? } | OpenAI Codex | `codexAccount` | `openai-codex` | browser PKCE, callback at `http://localhost:1455/auth/callback` | `account.codex.*` | | Grok | `grokAccount` | `grok-build` | device | `account.grok.*` | -Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subscribe`, `catalog` and `with_lease`. The account record keeps its existing file, revision and `credentialEpoch`/`generation` fields; the catalog keeps the plan's models and their declared capabilities. +Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subscribe`, `catalog`, `credential` and `rejected`. The account record keeps its existing file, revision and `credentialEpoch`/`generation` fields; the catalog keeps the plan's models and their declared capabilities. ### Errors @@ -65,7 +62,7 @@ Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subs ## Exceptions with reasons -- `Lease` carries the bearer to the caller's attempt for one request; [ManagedAccount](ManagedAccount.md) states the rule. +- The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); these replies and errors omit it. - The legacy `openai-codex` record keeps its legacy fields; the hidden state shared with the ChatGPT account and the migration between the two accounts stay the owners' business and are described in the [Codex sign-in design](../../../crates/dim-oauth/docs/design.md). ## Rule check @@ -73,12 +70,12 @@ Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subs | Rule | Application | | --- | --- | | §1 parts and Capabilities | Two process parts, one implementation; no Timeline facts, no Capability. | -| §2 scopes | Process: grants and leases are shared across Sessions. | +| §2 scopes | Process: grants and generations are shared across Sessions. | | §3 orthogonality | No other owner's state is read. | | §4 rules 1–6, 9 | No events, handoffs, callbacks, batches, context or Timeline state. | | §4 rule 7 | Callers use the faces; none reads the record or the attempt table. | | §4 rule 8 | No infrastructure change. | -| §7 ids, values, callbacks | The lease is a value with an id; availability is a read-only view. | +| §7 ids, values, callbacks | The credential is a value with a generation; availability is a read-only view. | | §7 no proxy | Each owner returns its own account data. | | §7 one change | The delivery part deletes the forwarding shell and the object port together. | | ADR 002 D1 | Process scope. | @@ -102,7 +99,8 @@ impl OpenAICodexOAuthService { pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn rejected(&self, request: RejectedRequest, cancelled: CancelledFn) -> Result { /* ... */ } } impl PublicService for GrokOAuthService {} diff --git a/docs/design/plugins/ManagedProviders.md b/docs/design/plugins/ManagedProviders.md index 64f413fc78..d8033927ea 100644 --- a/docs/design/plugins/ManagedProviders.md +++ b/docs/design/plugins/ManagedProviders.md @@ -12,7 +12,7 @@ The remaining owner, the ChatGPT account, holds: - **Login.** Browser PKCE, the discovery document, the profile read and the pending attempt. - **Tokens.** The access token's 30-second freshness window, one serialized refresh, rotation and the sign-out rule. - **The plan catalog.** The models the ChatGPT plan serves, as the account catalog. -- **Request leases.** Lease ids, capacity and expiry [ManagedAccount](ManagedAccount.md) defines. +- **Credentials.** The connection facts for one request and the grant generation [ManagedAccount](ManagedAccount.md) defines. - **The client namespace** `account.chatgpt.*`. Removed with the host binding: @@ -25,7 +25,7 @@ Callers keep the same responsibilities as [ManagedAccount](ManagedAccount.md): t | Requirement (callers) | Compose from the account owners' operations without breaking their invariants? | Handling | | --- | --- | --- | -| Read the ChatGPT account's status, catalog and one-attempt credential | No: the grant, plan and lease table are this owner's | `availability`, `catalog`, `with_lease` | +| Read the ChatGPT account's status, catalog and credential | No: the grant, plan and its generation are this owner's | `availability`, `catalog`, `credential`, `rejected` | | Search through the Dim relay | No: the Dim account's grant is DimOAuth's | DimOAuth's `availability`, `subscribe`, `search` | | List the accounts a user can sign into | Yes: `provider.management` reports each record's account namespace | Business | | Sign in, cancel, sign out | No: the attempt and record are this owner's | `account.chatgpt.*` | @@ -43,9 +43,9 @@ The model owner runs a ChatGPT request inside the owner's operation: ```rust chatgpt_account - .with_lease(LeaseRequest { provider: "openai-chatgpt".into(), model: model.clone() }, attempt, cancelled) + .credential(CredentialRequest { provider: "openai-chatgpt".into(), model: model.clone() }, cancelled) .await?; -// The request itself is Provider's; the lease is handed to `attempt` for one exchange. +// The request itself is Provider's; on a rejection it calls `rejected` with the generation. ``` A client signs in through the namespace; no part calls it: @@ -59,7 +59,7 @@ account.chatgpt.login.status { attemptId } -> { state } ### Face -`chatgptAccount`, marked on `ChatGptAccount`, implements [ManagedAccount](ManagedAccount.md)'s `availability`, `subscribe`, `catalog` and `with_lease`. The provider id is `openai-chatgpt`; login is browser PKCE; the record keeps its existing file and revision fields; the catalog keeps the plan's models and capabilities. +`chatgptAccount`, marked on `ChatGptAccount`, implements [ManagedAccount](ManagedAccount.md)'s `availability`, `subscribe`, `catalog`, `credential` and `rejected`. The provider id is `openai-chatgpt`; login is browser PKCE; the record keeps its existing file and revision fields; the catalog keeps the plan's models and capabilities. The client namespace `account.chatgpt.*` keeps its published methods. The existing rule that a ChatGPT plan request needs an interactive client Session stays in Provider: Provider reads the Session's creation record and refuses a non-client Session with `invalid`. @@ -70,14 +70,14 @@ The client namespace `account.chatgpt.*` keeps its published methods. The existi ## Exceptions with reasons - The external account plugin's face name comes from its row: the plugin is built outside this repository, so the assembly supplies the name the Provider record's authority uses. -- `Lease` carries the bearer to the caller's attempt for one request; [ManagedAccount](ManagedAccount.md) states the rule. +- The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); these replies and errors omit it. ## Rule check | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part; ChatGPT is an account owner, not a Capability. | -| §2 scopes | Process: the grant and leases are shared across Sessions. | +| §2 scopes | Process: the grant and its generation are shared across Sessions. | | §3 orthogonality | No other owner's state is read; the host binding and its account forwarding are gone. | | §4 rules 1–6, 9 | No events, handoffs, callbacks, batches, context or Timeline state. | | §4 rule 7 | Callers use the account faces; no caller reads the binding or the account record. | @@ -106,6 +106,7 @@ impl ChatGptAccount { pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn rejected(&self, request: RejectedRequest, cancelled: CancelledFn) -> Result { /* ... */ } } ``` diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md index c7b5573330..5d89b6d10f 100644 --- a/docs/design/plugins/Provider.md +++ b/docs/design/plugins/Provider.md @@ -10,7 +10,7 @@ Provider owns: - **Records.** Provider, model and selection records: static and imported records, descriptor overrides, user models, enables, per-model preferences, workspace and global selections, source generations and per-provider adoption. The records are Provider's own; the storage engine holds the file, lease and transaction primitive as a private implementation, and the rows never cross a public face. - **Selection.** The precedence among an explicit target, the workspace and global selections, the configured default and account-backed candidates; the availability rule execution applies; the adopted capability snapshot and configuration a selection carries. -- **Credentials.** Static credentials read from the record or an external secret store, managed-account leases, and temporary startup connections. A credential is used for one request and never leaves Provider except as the one-attempt lease a media call needs. +- **Credentials.** Static credentials read from the record or an external secret store, the managed-account credentials Provider uses for a request, and temporary startup connections. A credential is used for one request; the only value that crosses is the credential a media executor reads for one call. - **Execution.** One model request from the adopted selection through adaptation, transport, retries, credential recovery, streaming and settlement. Provider owns the driver that performs the request and its connection pool, request identity, stream set and tasks. - **Temporary connections.** A startup connection admitted for one Session creation; it is bound to the calling row until a Session adopts it, then to that Session. - **Client management.** The reads and writes the `provider` client namespace serves, with their transactions and versions. @@ -33,7 +33,7 @@ Callers keep: | Admit a temporary connection for a Session creation | No: the credential is a resource bound to the calling row and then to the Session; expiring or releasing it is Provider's | `prepare_startup`, `retain_startup`, `release_startup` | | Run one model request with retries, recovery and streaming | No: credentials, retry budgets, failure chains and output adaptation stay with the owner | `invoke` | | Learn a media model's route and where its credential comes from (the media executor) | No: the route is catalog state; the credential owner is the record's authority | `media_route` | -| Run one media exchange with a static model's credential (the media executor) | No: the credential is Provider's resource, and a caller holding it would release it on every error path | `with_lease` | +| Read a static model's credential for one media exchange (the media executor) | No: the record, the route and the credential are Provider's | `credential` | | Read or write a Provider's management record | No: records, versions and transactions are Provider's | The `provider` client namespace; handlers call the same operations | | Show a retry countdown | Yes: the `invoke` progress callback | Business | | Learn where the recorder writes | Yes: read ModelLog's `recording` value | Business | @@ -76,14 +76,15 @@ let SelectableReply { models, default } = provider .await?; ``` -The media executor (the adapter that owns the protocol) resolves the route and then the credential owner it names; Modality passes the model target and holds no lease: +The media executor (the adapter that owns the protocol) resolves the route and then reads the credential from the owner it names; Modality passes the model target and holds nothing to release: ```rust let route = provider .media_route(MediaRouteRequest { target, operation: "image.generate".into() }, cancelled.clone()) .await?; -// `with_lease` resolves the face named by `route.credential` and runs the exchange inside it. -with_lease(&self.ctx, &route.credential, target, |lease| send_media(&lease), cancelled.clone()).await?; +// `credential` resolves the face named by `route.credential` and reads the value for this call. +let credential = credential_from(&self.ctx, &route.credential, target, cancelled.clone()).await?; +send_media(&credential).await?; ``` ModelProvider runs a turn; `consume` is the branch part's own callback that writes `step/*` events and reports how the stream ended: @@ -153,7 +154,7 @@ provider.release_startup(ReleaseRequest { model: selection }, cancelled).await?; | FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)) | `root_path` | The directory the wire recorder writes under | | Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) | private transaction primitive; the public face keeps `storageReport` and the offline operations | Provider's records, selections, candidates, pages, source activation, adoption, edit commits, legacy import and `store.creationRecord` | | Session directory ([#2020](https://github.com/arcships/dim/issues/2020)) | session close observation | Releasing a retained startup source | -| Account owners ([ManagedAccount](ManagedAccount.md)) | `availability`, `catalog`, `with_lease` | Account-backed models; the record's authority names the owner | +| Account owners ([ManagedAccount](ManagedAccount.md)) | `availability`, `catalog`, `credential`, `rejected` | Account-backed models; the record's authority names the owner | Provider reads an account owner by the name its record's credential authority carries; the face names are in [ManagedAccount](ManagedAccount.md). @@ -171,9 +172,9 @@ All operations are marked on `Provider` and provided under `providerService`; re | `release_startup` | Release a source still bound to the calling row | `{model}` | `{}` | None; completes immediately | `not_found` (already retained by a Session), `closed` | | `invoke` | Run one model request | `{request, mode, consume, admit?}` | `{outcome}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `unavailable`, `cancelled`, `closed`, `provider_failed {retryable}` | | `media_route` | A media model's route and the owner of its credential | `{target, operation}` | `{protocol, base_url, headers, realtime?, credential: Owner}` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | -| `with_lease` | Run the caller's attempt with a static model's credential | `{provider, model}` plus `attempt(lease) -> {rejected}` | `{}` | The caller cancels; the attempt stops | `not_found`, `unavailable`, `cancelled`, `closed` | +| `credential` | A static model's connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation: none}` | The caller cancels; no timeout | `not_found`, `unavailable`, `cancelled`, `closed` | -`prepare_startup` admits the source under the calling row; the row's unload releases it, so a missed `retain_startup` or `release_startup` settles with the row. `retain_startup({session, model})` moves the source to the Session named by the caller and the model's metadata; the Session's close releases it, so a missed failure-path release settles with the Session. `release_startup({model})` is the optional early release for a creation that failed; it answers `not_found` once a Session retains the source. A member Session that inherits the leader's model retains the same source by value. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Lease` is [ManagedAccount](ManagedAccount.md)'s one-attempt value; `with_lease` hands it to the caller's attempt and releases it when the attempt ends, so no lease id crosses. +`prepare_startup` admits the source under the calling row; the row's unload releases it, so a missed `retain_startup` or `release_startup` settles with the row. `retain_startup({session, model})` moves the source to the Session named by the caller and the model's metadata; the Session's close releases it, so a missed failure-path release settles with the Session. `release_startup({model})` is the optional early release for a creation that failed; it answers `not_found` once a Session retains the source. A member Session that inherits the leader's model retains the same source by value. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Credential` is [ManagedAccount](ManagedAccount.md)'s value: static credentials carry no generation; an account owner's carry the grant's. `invoke` calls the account owner's `credential`, sends, and on a refusal calls `rejected` with the refused generation before retrying within its own failure chain. `invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits through the optional `admit`/progress callbacks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(next)` receives chunks, ends and typed failures and returns how the call ended and whether output was accepted; output accepted before a failure prevents replay. `admit` runs before each attempt and returns `admitted` or `rejected {message}`; only a caller with its own budget passes it. @@ -196,14 +197,14 @@ All operations are marked on `Provider` and provided under `providerService`; re | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `resolve`, `selectable` | Read records and account state, apply the precedence and availability rule, return the value | The read stops; nothing changes | The call ends `cancelled` | Pending calls end `closed`; the next generation answers from current records | Provider's read tasks | -| `invoke` | Resolve or adopt the request's selection, adapt images, resolve the credential (account lease or static), send, adapt chunks, hand them to `consume`, retry or recover per the failure chain, settle the consumer | The transport is cancelled, the stream is dropped, the consumer is released; accepted output stays committed | The consumer callback is revoked; the call ends `cancelled`; admitted work is joined | Admission stops; in-flight requests are cancelled and joined; account leases are settled | Provider: request tasks, stream and lease. ModelProvider: the Timeline writes already committed | +| `invoke` | Resolve or adopt the request's selection, adapt images, read the credential (account owner or static), send, on a refusal call `rejected` and retry within the failure chain, adapt chunks, hand them to `consume`, settle the consumer | The transport is cancelled, the stream is dropped, the consumer is released; accepted output stays committed | The consumer callback is revoked; the call ends `cancelled`; admitted work is joined | Admission stops; in-flight requests are cancelled and joined; a started refresh finishes under the account owner | Provider: request tasks and stream. ModelProvider: the Timeline writes already committed | | `prepare_startup` | Validate and admit the connection under the calling row, select its model | Before admission; nothing is retained | The row's unretained sources are released | Unretained sources are dropped; a retained Session's source is restored by its next generation | Provider: the source; the calling row: its lifetime | | `retain_startup` / `release_startup` | Read the model's source, add the Session to its owners, watch the Session; release a source not yet retained | — | An unretained source is released with the row | Retained sources survive the owner's reload as Session state is re-read | Provider: the source and its owners; the Session directory reports close | -| `media_route`, `with_lease` | Read the catalog and the credential owner, or hand a static credential to the attempt | The read stops; the attempt ends and the credential is dropped | The call ends `cancelled` | Pending calls end `closed` | Provider | +| `media_route`, `credential` | Read the catalog and the credential owner, or read a static credential | The read stops; the credential is dropped | The call ends `cancelled` | Pending calls end `closed` | Provider | ## Exceptions with reasons -- `with_lease` and the lease inside `invoke` hand the bearer to the caller's attempt for one request: the executor is the model owner or the media adapter and the account owner holds the grant, so the value crosses once and is never persisted, logged, quoted in an error or returned to a client. The account owner cannot perform the exchange itself: the model protocol, transport, streaming, adaptation and the per-profile driver are the executor's, and executing them in every account owner would duplicate the transport. A secret value in a reply is forbidden by AGENTS.md and an object or handle by §7. The boundary is raised for maintainer confirmation in [#2096](https://github.com/arcships/dim/pull/2096). +- The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary): Provider never writes the account bearer it receives from `credential` or `rejected` to a client reply, the UI, a log, an error text, a persisted record, the model context or the Timeline. Static credentials in Provider's own records are the record's data, not this value. - The `provider` client namespace is a client protocol, not a second service face: it is the mechanism's registration point for protected-local v3 clients, and every handler calls the operations above or the management operations this owner also owns. ## Rule check @@ -222,7 +223,7 @@ All operations are marked on `Provider` and provided under `providerService`; re | §4 rule 7 | Callers use these operations; no caller reads a record, a connection or a catalog internal. | | §4 rule 8 | Requirements are listed below; no runtime mechanism is added. | | §4 rule 9 | No Timeline fact: selections and records are process state with owner writes. | -| §7 objects, ids, values, callbacks | Values: selections, lists, leases, routes. Callbacks: `consume`, `admit`. Ids: the calling row and the Session. No object crosses. | +| §7 objects, ids, values, callbacks | Values: selections, lists, credentials with a generation, routes. Callbacks: `consume`, `admit`. Ids: the calling row and the Session. No object crosses. | | §7 no proxy | Account data comes from the account owner; records are Provider's own. The storage engine is not a face. | | §7 one change | The delivery part migrates every caller and deletes every pre-migration name in one change. | | ADR 002 D1 | Process: records, catalogs and credentials are shared across Sessions. | @@ -237,8 +238,8 @@ All operations are marked on `Provider` and provided under `providerService`; re - **ProviderSettings and ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)).** Their owner contracts define `user_agent` and `recording`; Provider reads both at request time. No requirement remains. - **Session directory ([#2020](https://github.com/arcships/dim/issues/2020)).** Provider needs a close observation for a retained startup source: when the Session closes without unload, the source is released; an unload keeps it for restore. - **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `root_path` only; the recorder owns its JSONL file. -- **Account owners ([ManagedAccount](ManagedAccount.md)).** `availability`, `catalog`, `with_lease`; the face name comes from the record's credential authority. -- **Media executor (Modality's adapter contract).** The adapter resolves `media_route` and calls `with_lease` on the credential owner for the model target; Modality passes the target and settles the task, so no business caller holds a lease id. The adapter's service shape is Modality's contract. +- **Account owners ([ManagedAccount](ManagedAccount.md)).** `availability`, `catalog`, `credential`, `rejected`; the face name comes from the record's credential authority. +- **Media executor (Modality's adapter contract).** The adapter resolves `media_route` and reads the credential from the owner it names; Modality passes the target and settles the task, so no business caller holds a credential. The adapter's service shape is Modality's contract. ## Binding appendix @@ -324,13 +325,14 @@ pub struct MediaRouteReply { pub base_url: String, pub headers: BTreeMap, pub realtime: Option, - /// The credential owner the media executor calls `with_lease` on: this owner, or an account owner. + /// The credential owner the media executor calls `credential` on: this owner, or an account owner. pub credential: CredentialOwner, } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct LeaseRequest { pub provider: String, pub model: String } +pub struct CredentialRequest { pub provider: String, pub model: String } +// `Credential` is the shared value defined in ManagedAccount.md; static credentials carry no generation. #[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] @@ -359,7 +361,7 @@ impl Provider { pub async fn release_startup(&self, request: ReleaseRequest) -> Result<(), ProviderError> { /* ... */ } pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn with_lease(&self, request: LeaseRequest, attempt: AttemptFn, cancelled: CancelledFn) -> Result<(), ProviderError> { /* ... */ } + pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } } ``` From 0104189aec7b06e68c9eeeb404a6d0e502ae8125 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 20:14:08 +0800 Subject: [PATCH 4/9] design(provider): drop the old credential-recovery names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ManagedProviders retirement list keeps the forwarding methods that existed; the credential-recovery methods are replaced by the account face's `credential` and `rejected`, so `recover_rejected` and `finish_rejected` no longer appear in the contract. Refs #2019 · Refs #2015 --- docs/design/plugins/ManagedProviders.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/plugins/ManagedProviders.md b/docs/design/plugins/ManagedProviders.md index d8033927ea..d71df0d24d 100644 --- a/docs/design/plugins/ManagedProviders.md +++ b/docs/design/plugins/ManagedProviders.md @@ -18,7 +18,7 @@ The remaining owner, the ChatGPT account, holds: Removed with the host binding: - The `dyn ManagedProvider` object port and the binding slot, generation and validation around it. An external account plugin is a normal process row: it provides its account face and owns its lifecycle, including quiesce before RPC settlement. -- The account data forwarding: `providers`, `status`, `recover`, `begin_browser`, `complete_browser`, `begin_device`, `attempt_status`, `cancel_attempt`, `logout`, `usage`, `referral`, `reset_batches`, `apply_reset`, `catalog`, `credential`, `recover_rejected`, `finish_rejected`. Callers request the account owner the Provider record names. +- The account data forwarding: `providers`, `status`, `recover`, `begin_browser`, `complete_browser`, `begin_device`, `attempt_status`, `cancel_attempt`, `logout`, `usage`, `referral`, `reset_batches`, `apply_reset`, `catalog` and `credential`; the old credential-recovery methods are replaced by the account face's `credential` and `rejected`. Callers request the account owner the Provider record names. - The `managedSearch` face and its `search`, `usable`, `subscribe_usable` and `refresh_usable` methods. Web reads the Dim account's `availability` and calls its `search`; no host layer returns account data. Callers keep the same responsibilities as [ManagedAccount](ManagedAccount.md): the model owner selects the account by the record's credential authority, Web owns the search tool and its declaration, and the client owns the login UI. From 375e5da352867d4e6329c2f77b7466e2a03a9fd6 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 21:33:09 +0800 Subject: [PATCH 5/9] design(provider): self-check the contracts against round 3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix the binding appendices so they compile and carry the documented wire shape: try the errors with a snake_case `code` tag, inline the lease types, take `consume`/`admit` as direct parameters instead of request fields, add `caller: &Ctx` where a call is bound to the caller's row, and define every type the appendices use. Complete the error lists for `invoke`, `credential` and `rejected`. State what the contracts supersede and update the owner paragraphs in service-faces, the process-owner contract, provider management and the auxiliary model. Add client-visible-change statements (none), the §7 link, and the README By scope entries. Refs #2019 · Refs #2015 --- docs/design/appserver/auxiliary-model.md | 75 +---- docs/design/appserver/provider-management.md | 286 +----------------- .../contracts/process-owner-operations.md | 14 +- docs/design/plugins/ConfiguredModels.md | 10 + docs/design/plugins/DimOAuth.md | 18 +- docs/design/plugins/ManagedAccount.md | 28 +- docs/design/plugins/ManagedOAuth.md | 10 + docs/design/plugins/ManagedProviders.md | 11 + docs/design/plugins/Provider.md | 120 +++++--- docs/design/plugins/README.md | 2 +- docs/design/service-faces.md | 37 +-- 11 files changed, 177 insertions(+), 434 deletions(-) diff --git a/docs/design/appserver/auxiliary-model.md b/docs/design/appserver/auxiliary-model.md index 3efd6a38b1..04cd83734e 100644 --- a/docs/design/appserver/auxiliary-model.md +++ b/docs/design/appserver/auxiliary-model.md @@ -1,6 +1,6 @@ # AuxiliaryModel -Status: implemented (S4 native operation and named binding). Roadmap item S4 ([#53](https://github.com/arcships/dim/issues/53)). +Status: implemented (S4 native operation and named binding); the `auxiliaryModel` face is superseded by `providerService.invoke` ([Provider](../plugins/Provider.md)). Roadmap item S4 ([#53](https://github.com/arcships/dim/issues/53)). Overview: [Appendix B.2 Provider row](../overview.md#b2-app-server-process-plugins). Scope: [ADR 002](../../adr/002-plugin-scope.md) (process, provided by Provider and, in the model-config profile, by ConfiguredModels). @@ -69,82 +69,19 @@ tracking own an in-flight call. ConfiguredModels has no admission and tracks no ## 4. Interfaces +The `auxiliaryModel` face is deleted. See [Provider](../plugins/Provider.md) for `providerService.invoke`; the headings below stay because source comments link them. + ### 4.1 Language-neutral (ADR 002 D5) -`auxiliaryModel`, process scope, no instance key, provided by the profile's owner of -model selection (Provider in the product profile, ConfiguredModels in the model-config -profile). - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `complete` | async | `{model: {providerId, modelId}, request: {system?: string, messages: Message[], maxOutputTokens?: u32}}` | `{text, stopReason: "end_turn" \| "max_tokens" \| "stop_sequence", usage?: {promptTokens, completionTokens, totalTokens, cacheReadTokens?, cacheWriteTokens?, reasoningTokens?, cost?, currency?}}` | - -- `model` is required. The caller resolves it from its own configuration; Provider does not - fall back to another model. -- `messages` use the existing serializable `Message` type (dim-agent-types), for example - `[{role: "user", content: "…"}]`. No tools are offered; thinking output is dropped; only - text blocks form `text`. -- `stopReason` has three values. The Rust `ModelStopReason` also has `ToolUse`; since no tool - is offered, a tool stop is a provider defect and the call fails with `failed`. -- `maxOutputTokens` caps the reply; the default and the cap are the model's adopted output - allowance (Provider's derivation from the declared window and maximum, so the input budget - is at least half the window), not the declared maximum itself. -- Non-streaming: the consumer needs the whole text. -- Cancellation: the consumer drops the call (or sends the bridge protocol's cancel request). - The service has no timeout of its own; the budget is the consumer's. -- Errors are data `{code, message}`: `invalid_request`, `model_unavailable`, `failed`, - `cancelled` (§6). +Superseded: there is no `auxiliaryModel` service. A caller runs `providerService.invoke(request, Mode::Once, consume, None, cancelled)` and collects the text in its consumer. ### 4.2 Rust binding -In `dim-agent-capabilities::host`, next to `ModelSelectionHost`: - -```rust -pub struct AuxiliaryRequest { pub system: Option, pub messages: Vec, - pub max_output_tokens: Option } -pub struct AuxiliaryReply { pub text: String, pub stop_reason: ModelStopReason, - pub usage: Option } -pub enum AuxiliaryErrorCode { InvalidRequest, ModelUnavailable, Failed, Cancelled } -pub struct AuxiliaryError { pub code: AuxiliaryErrorCode, pub message: String } -pub trait CompleteAuxiliary: Send + Sync + 'static { - fn complete(&self, model: ModelId, request: AuxiliaryRequest, cancel: CancellationToken) - -> Pin> + Send + '_>>; -} -pub struct AuxiliaryModel(pub Arc); -``` - -`auxiliary_model::provide` publishes one `AuxiliaryModel` at the Rust type key and -`host_key("auxiliaryModel")`. Each owner's `apply` calls it with its own `CompleteAuxiliary` -implementation; its `Deps` gain `Arc`. +Superseded: `AuxiliaryModel`, `AuxiliaryRequest`, `AuxiliaryReply` and `CompleteAuxiliary` are deleted. The request is a `ModelRequest`; the reply is the caller's collected text and stop reason. ### 4.3 Named binding -The [target process binding](../contracts/process-owner-operations.md) moves callers of `auxiliaryModel.complete` to `providerService.complete` with the same request and stream. Retire the former catalog entry with its consumers. The binding below is the pre-migration name. - -The same owner-provided operation implements `HostDispatch` at -`host_key("auxiliaryModel")` through that shared `provide`; the process catalog registers -that shared name. An ordinary C4 row injects `auxiliaryModel` and calls -`complete({model, request})`; Rust SessionTitle names the same `auxiliaryModel` service -through its `AuxiliaryModel` binding and calls the owner directly without serialization. -The SDK declares it as `AuxiliaryModel` in -[`dimcode/plugin`](../../../npm/plugin.d.ts). This is the existing operation's binding, -not another plugin or a second model runner. - -The call takes one data object with `model` and `request`. Decode the native request once -at this boundary; unknown fields, invalid message data and invalid argument shapes reject -with `invalid_request`. Optional `system` and `maxOutputTokens` may be absent or null. -The reply uses the native `AuxiliaryReply` serialization, with camelCase fields and snake_case -stop reasons; absent usage is omitted. Errors reject with an Error carrying the existing -`code` and `message`, without a new reply envelope. Provider's calls use its admission, -task tracking and cleanup; ConfiguredModels lives for the process and has no admission, so -a call ends with its own result or the caller's cancellation. Credentials and connection -handles stay with the owner. - -An optional second argument, `cancelled: () => Promise`, uses the existing C5 function -reference mechanism to bind the native cancellation token. Resolving or rejecting the returned -Promise (including loss of its language runtime) cancels the original operation and waits for it to settle -before returning. Consumers resolve it on their timeout or closing; stopping an await alone is -not cancellation. No new bridge protocol or detached cancellation task is needed. +Superseded: the `auxiliaryModel` name leaves the catalog. The replacement operations are in [Provider](../plugins/Provider.md); the account credential they use is in [ManagedAccount](../plugins/ManagedAccount.md). ## 5. Flow diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 86c50ac553..3863e30761 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -3,7 +3,7 @@ Status: **Implemented**. Process-owned Provider management for [#329](https://github.com/arcships/dim/issues/329). [中文](../../zh/design/appserver/provider-management.md). -The [S4 auxiliaryModel](auxiliary-model.md) contract remains unchanged. +The S4 `auxiliaryModel` face is replaced by `providerService.invoke` ([Provider](../plugins/Provider.md)); [auxiliary-model.md](auxiliary-model.md) records the old shape. ## 1. Scope @@ -45,11 +45,11 @@ with its existing owner; management never writes another owner's state. | --- | --- | | `managementMethods`, process, namespace `provider` | Local v3 Desktop/CLI and trusted process callers; §3 extends this existing namespace | | Provider module boundary `stored_selection` (Rust) | Native data-boundary consumers such as Migration; §3.7 adds one pure function over an admitted record, not an RPC, host port or management method | -| Provider host port `SelectableModelsHost` (core `dim-agent-capabilities`), provided by the profile's model owner (Provider, or the configured model file) | In-process owners that route by model capability (Modality) and the `agent` tool's `models` action; §3.6 adds two reads, not a management method or RPC method | -| Provider host port `ModalityConnectionHost` (core `dim-agent-capabilities`), provided by the profile's model owner | Modality's process adapters for image generation, editing and enhancement; §3.6 defines one per-call resolution, not a management method or RPC method | +| `providerService.selectable` (owner contract [Provider](../plugins/Provider.md)) | In-process owners that route by model capability (Modality) and the `agent` tool's `models` action; one read with a `use` parameter, not a management method or RPC method | +| `providerService.media_route` and the credential owner's `credential` (owner contracts [Provider](../plugins/Provider.md), [ManagedAccount](../plugins/ManagedAccount.md)) | Modality's process adapters for image generation, editing and enhancement; the adapter reads the route and the credential value for one call | | Account namespaces | Account owners provide login, usage and logout. The [ChatGPT plan provider](chatgpt-plan.md) owns `account.chatgpt`. | -| `ProviderConnectionResolver`, `ModelSelectionHost` | Provider implements catalog/route decisions through existing types; no new core port | -| `auxiliaryModel.complete` | Existing caller-selected S4 contract, unchanged | +| Model selection and credentials | `providerService.resolve` and the account owners' `credential`; the old host ports are deleted ([Provider](../plugins/Provider.md)) | +| `auxiliaryModel.complete` | Deleted: the caller uses `providerService.invoke` with `Mode::Once` ([Provider](../plugins/Provider.md)) | | `provider` Settings source, user scope (`provider.json`) | The Provider part registers it; it holds `userAgent`, the User-Agent override (§2, Model request identity), so a user's choice is a declared, validated document rather than a request-local input | | Native CLI Provider flows | Migrate discovery, create, update and disconnect together with the new owner methods | @@ -1003,232 +1003,7 @@ Aimux applies it at its [HTTP send boundary](../../../crates/dim-agent-aimux/REA ### 3.6 Selectable models for process owners -The [target process binding](../contracts/process-owner-operations.md) moves `modelSelectionHost.resolve`, both `selectableModelsHost` reads and `auxiliaryModel.complete` to the data face `providerService` on the configured profile. Consumers switch their injection and retain the operation arguments, results and credential ownership. The separate binding names below describe the pre-migration catalog. - -A process owner that routes work by model capability cannot keep its own copy of -the availability rules of the models it routes to. The port below has one provider -per profile — Provider in the product profile, the configured model profile -(`dim-agent-aimux`) from its model file — and each provider owns -side-effect-free reads of the models it would serve, with the identifiers and -declared capabilities a routing decision needs. This section defines the port and -Provider's rules; the configured profile's rule is that page's. The read is a -process host port, not a management method: it is not on the `provider` namespace, -is not served over RPC, and does not change `provider.catalog`. - -**Why a port rather than a method on `ProviderService`.** A consumer plugin lives -in its own crate, and `xtask check` rejects a dependency on `dim-app-server`, the -composition layer, so the consumer cannot name `ProviderService`. The port and its -data type live in `dim-agent-capabilities`, which Provider and the consumer both -depend on; registering it as a process name lets a consumer name the port and -the catalog resolve it, and the dependency points from the extension to the core, -as [ADR 002 D3](../../adr/002-plugin-scope.md) requires. Each provider keeps its -implementation, its catalog and its rules. - -**Contract (language-neutral).** A process host port, no instance key, provided -by Provider in the product profile and by the configured model profile from its -model file: operation `selectableModels`, asynchronous, request `{}`, reply -`{models: ModelCapabilitySnapshot[]}`. The element is the existing -`ModelCapabilitySnapshot` — `{target: {providerId, modelId}, capabilities: -ModelCapabilities, reasoning?, serviceTier?}` — not a new model type: it already -carries the model and provider identifiers and the declared capabilities, and it -is the descriptor execution adopts. A selectable model always declares both -limits (§3.5), so the existing `capability_snapshot` conversion always succeeds. -Abandoning the call cancels its owner read; dropping the reply is not a successful -read. Errors use the public codes stated below. - -**Second operation: `selectableForModality`.** The same port carries one more -process read, for non-conversational uses (Modality §9.2): operation -`selectableForModality`, asynchronous, request `{}`, reply -`{models: ModalityModelSnapshot[]}` with each element -`{target: {providerId, modelId}, operations: string[]}`. `operations` holds the -`.` ids the model's catalog entry declares, in that entry's -order; a model that declares none is omitted. An entry declares its operations -in `metadata.raw.modalityCapabilities`, and an explicit list, an empty one -included, is the whole answer. An entry with no list is recognized as an image -model, because relay and account catalogs list such models without media -metadata: its id is `arcship-image`, a known ID in the `gpt-image-2` or -`grok-imagine-image` family, or names `seedream`, or its `type` is -`image`/`image-generation` with image or no stated output, or `imageGeneration` -is true, or its only output is `image`. Such a model declares -`image.generate`, and `image.edit` too when it also reads images or is a known -model; a `type` of `image-edit` declares `image.edit` alone, and -`imageGeneration: false` recognizes nothing. The connection rule below reads -the same declaration. The read applies the same provider, account, model, -route, credential and status rules as `selectableModels`, without its -text-modality, chat-kind and declared-text-limit requirements: a model without -a `text` modality, a non-chat model and a model with `limits_undeclared` -remain candidates when they declare a modality operation, while an unavailable -status, a disabled Provider or model, a missing route, a signed-out account and -a missing static credential still exclude them. It carries no reason field: the -consumer derives availability from the options and explains a persisted -default that is no longer selectable from its own snapshot. - -**Rules Provider applies.** Candidates are persisted model targets queried by -provider enablement, credential configuration and model status. Each candidate -is read through the exact-target catalog read, with account availability checked -by its owner. Bundled substitution, descriptor overrides, user models, routes -and disables are projected for that target using the execution rules. A model is -included only when the existing -`ProviderCatalog::selectable` accepts it: `unavailableReason` is absent and its ID -is not in `disabledModelIds`. That reason already covers every exclusion: a model -with `ModelStatus::Unavailable`, a model that declares no `text` modality, a -non-chat model on a driver other than `new-api-router`, a disabled Provider -record, a model with no route, a signed-out account, a missing static credential, -and an undeclared limit (`limits_undeclared`). The read adds no second predicate: -it reads the one selection already applies. The modality read is that same rule -minus the three requirements above, and both catalog builders derive an entry's -conversational and modality reasons from one classification of the entry, so a -new exclusion reason states its class once and the two reads cannot drift apart. -A model appears only if `select`, `configuration`, `apply_preferences`, the -per-request check and `auxiliaryModel` accept it at the same read. Execution -remains authoritative: a later write can make a model unselectable, and the -consumer passes the ID back to Provider, which re-checks. - -**Rules the configured profile applies.** Its candidates are every provider and -model entry of the model file, ordered by provider and then model id. The file -requires both limits, so each entry is returned with them; it declares no other -capability, so entries carry the text defaults. That profile has no account, -route, disable or preference input, and the read adds no such test: the file's -validation and its rule are its own page's -([aimux](../../../crates/dim-agent-aimux/README.md)). - -This read is not [#560](https://github.com/arcships/dim/issues/560)'s validation -contract. That contract (§3.7) takes an admitted persisted static record and an explicit -model ID and answers whether that selection can execute; this read takes no input and -enumerates what is available now. Both are defined on the same catalog and selectability -predicate, so they cannot disagree about a model. - -**Snapshot and consistency.** One call enumerates persisted target IDs, then -reads each target separately. Each target record read has its own committed -snapshot. A concurrent `provider.*` write can be visible for some targets and not -others, including targets of the same provider; a deleted target is omitted. -The reply has no aggregate version or retained cache. The next call reads the -current state. It makes no live request: it never refreshes or lists a provider -endpoint, and it writes no record, selection or preference. It uses the same -account-status read as `provider.catalog`. The reply is derived; a consumer must -not persist it or treat it as an adopted snapshot. Adoption stays with model -selection, which resolves a configuration once. - -**Errors.** The public face and its Rust binding return `cancelled` when the caller -cancels, `owner_closed` while Provider unloads, and `failed` when Provider storage -cannot be read. A provider whose own record or account status cannot be -read is omitted, as default resolution omits it; it never hides the others and the -read returns no per-provider error list. A caller that needs a provider's -diagnostic uses `provider.list` or `provider.management`. - -**Consumers.** Modality computes each operation's options and its automatic -default from these reads. For a category an adapter serves, the candidates are -both reads deduplicated, the execution-selectable models first and the modality -read's after, each in its read's order, and an operation keeps those a collected -adapter serves for it; a media model execution rejects therefore stays an option -where an adapter serves it, and a selectable model that declares no operation -stays one too. An operation no adapter serves takes the modality read's models -whose entry declares that operation id, and `image.understand` takes the -selectable models with `vision`. It reports "no adapter for the configured -model" when the configured model is absent. It does not call `provider.catalog` -and keeps no availability predicate of its own. The reply carries IDs and -capabilities only, not a display name: a client that renders an option joins the -ID with the model list of `provider.catalog` or `provider.management`, and -Modality copies no name. -Provider gains no per-consumer key, setting or filter: the read has no input, so a -caller that wants one provider filters the reply. Collaboration's `agent` tool -reads the same reply for its `models` action and hands the IDs to the leader's -model, and keeps no rule of its own either -([Collaboration](../plugins/Collaboration.md#7-the-models-a-member-can-run)). - -**What does not change.** `provider.catalog`, `provider.management`, -`provider.select`, model selection, adoption, preferences and their errors; the -client protocol and `PROTOCOL_VERSION`; persistence and its format; Timeline, -Dispatcher, callbacks, Session and branch parts; and the driver, route and -non-chat rules. The read adds no state, cache, notification, crate or module. - -**Rust binding.** The binding calls the typed operation directly, without JSON -or a bridge task. It takes a `CancellationToken`; cancelling it returns -`ModelPortError::Cancelled`. Each call owns a child token that is cancelled when -the call completes or is abandoned, without cancelling the caller's token. The -operation maps the owner's `HostError` into the public `ModelPortError` codes; -the dispatcher invokes that same operation and encodes its reply or error. - -The port is `SelectableModelsHost` in -`crates/dim-agent-capabilities/src/host.rs` beside `ModelSelectionHost`. Its two -reads are the operations §3.6 states: the port type holds the owner's closures, -its dispatcher writes the wire shape, and a Rust reader calls the same -operations through the binding. Provider provides it with -`provide_selectable_models` in `ProviderPlugin::apply`, and the configured model -profile (`dim-agent-aimux`) provides it from the entries of its model file, so -both deployments answer the same reads; that profile declares no modality -operation, so its `selectableForModality` read answers none -([aimux](../../../crates/dim-agent-aimux/README.md)). The catalog registers the -name shared ([service faces §4.10](../service-faces.md#410-宿主读取端口与-provider-选择)). - -The owner implementations are `ProviderService::selectable_models` and -`ProviderService::selectable_modality_models`; `ProductResolver` delegates to -both. A consumer that needs the read declares -`Keyed` in its `Deps` and gates on it (Modality). A consumer -that must load without Provider reads the name when it is provided and gates -nothing (Collaboration's `models` action); it takes a snapshot at load, so a -Provider reload does not reload it. No consumer reads `ProviderService` directly. -A non-Rust consumer calls `selectableModelsHost` by name, with the operations §3.6 -states; the face delegates to the same owner read, so a consumer of either language -gets the models execution would. - -**Connection contract.** Provider resolves one non-conversational connection for a trusted -in-process adapter. This is a native port beside `ProviderConnectionResolver`, not a -management method or a named data face. It accepts a model identity and operation and -returns one connection with its protocol, model and realtime declaration. The resolved -connection includes credential material and remains in process for that adapter call. - -Both native connection ports use the same owner resolution: static or managed record -read, catalog selection and credential lease. One modality call resolves once; its route -facts and credential come from that resolution. The chat path's temporary startup -connection and adopted capability snapshot do not apply. The owner does not add an HTTP -executor to this port; media protocol and transport behavior remain with the existing -adapters. A cross-language operation contract is tracked in [#1613](https://github.com/arcships/dim/issues/1613). - -**Rules.** It applies exactly the rules of the `selectableForModality` read — -provider, account, model, route, credential and status — and additionally -requires the model's catalog entry to declare `operation`, as the read above -derives it. A model that fails any of these is refused -before any network call: the availability cases with the reason execution reports -for that model, and an undeclared operation as an invalid request that names it. -The read and the connection cannot disagree, because they share the catalog and -its selection predicate. The managed account's credential lease reads the same -rule: it refuses only a reason that excludes every use, so a media model the -catalog marks as non-chat still leases for this call. That boundary rule reads -the stored reason together with the entry's status: an `unavailable` status -excludes every use whatever reason was stored, so a record an older projection -wrote for such a model is listed by neither read and leases nothing. - -**Realtime declaration.** An entry that serves a realtime operation declares the -transport it speaks in `metadata.raw.realtime: {protocol, path}`. Provider parses -it into `RealtimeDeclaration` and carries it on the connection reply as -`realtime`; an entry that declares none replies `null`, and the configured model -profile replies `null` for every target, because a model file has no catalog -entry. The operation is still declared in `metadata.raw.modalityCapabilities` -with every other one, so a model that lists `realtime.voice` without a transport -resolves a connection whose `realtime` is `null`: Modality refuses that model's -`open` before any network call instead of guessing a URL. `protocol` is the -adapter's name for the wire protocol it accepts, and `path` is appended to the -route's base URL by that adapter. - -**Credential rule and lifetime.** The connection lives for that one call. Provider -never persists it, never returns it to a client and never writes it to a task -record, result, diagnostic or error. Its `Debug` prints the model, the route, the -base URL, header names and whether a credential is present, and never a header -value, bearer or key; `ModelConnection` implements no `Debug`, so no other -connection formats one. A managed connection retains its recovery handle for -trusted in-process use, -but the in-tree media adapters do not invoke managed credential recovery. A media rejection is returned to the caller; automatic -refresh and retry are not provided by this port. The chat recovery path is -separate and does not establish a retry guarantee for non-conversational calls. - -**Rust binding.** `ModalityConnectionHost` holds `Arc`. -`resolve_for_modality(target, cancel)` returns `ModalityConnection { resolved, protocol, -model, realtime }`; `resolved` is `ResolvedModelConnection`, including its recovery -handle where applicable. `ProviderPlugin::apply` provides the typed port. The configured -model profile provides the same trait and refuses every operation because its entries -have no modality declaration. The catalog name has no dispatcher. A caller passes its -`CancellationToken` through the existing native resolution. +The selectable-model reads and the non-conversational connection port are replaced by the owner contracts: `providerService.selectable({use})` for the models execution would serve and the current default, and `providerService.media_route` plus the credential owner's `credential` for one media call. See [Provider](../plugins/Provider.md) and [ManagedAccount](../plugins/ManagedAccount.md) for the operations, errors, cancellation and the bearer's boundary. The `SelectableModelsHost`, `ModalityConnectionHost`, `ModelSelectionHost` and `ProviderConnectionResolver` types are deleted. ### 3.7 Offline validation of a stored selection @@ -1336,54 +1111,7 @@ pub fn stored_selection( ### 3.8 Media execution for adapters -Provider resolves a model's connection for one non-conversational call, and Modality passes it to -its adapter for that call ([Modality A.2](../plugins/Modality.md#a2-adapters-and-ocr)). That -connection is not a public contract and is not exposed as a data face. - -**Why the connection cannot be a face.** Its reply carries credential material for one call, and -`ResolvedModelConnection` is resolved for one final request and never serialized -(`dim-agent-capabilities` `host.rs`). -[Service faces §2.2](../service-faces.md#22-migration-marker) keeps secret values with the owner -and exposes operations that use them, so the only shape that could cross is an operation — the -request executed on the adapter's behalf — not the connection. - -**Decision: no such operation now.** The connection is Provider's private typed binding, not a -public service: what it returns is credential material for one call, so it neither becomes a data -face nor stays a catalog name. [Service faces §2.6](../service-faces.md#26-migration-rule) already -says a name whose role is a typed binding leaves the catalog. Media adapters execute in-process -(`dim-modality-aimux`) through this native path. No media operation, signing, -retry, redirect, upload, download or streaming behavior changes. - -**Why a `modalityRequest` executor is a different contract.** It would be a new HTTP executor, not -an existing operation serialized, and it cannot preserve what the native path does today -([#1613](https://github.com/arcships/dim/issues/1613)): - -| Existing behavior | What an operation must match | -| --- | --- | -| One resolution per adapter call | Resolve once per call and reuse that one resolution for the call's retries; a cache that answers a later call would report a configuration the adapter never resolved, so later calls resolve again | -| Streaming downloads to files with a 2 GiB limit (`dim-modality-aimux`) | Stream to a file; never buffer a whole reply into base64 | -| WebSocket realtime open/send/receive/close | A connection-scoped protocol, not one request and reply | -| Vendor route and credential routing, including the fal image routes and query parameters | The same route selection and credential handling the catalog declares | -| Redirects and per-vendor error mapping | The same rules the connection query applies now | -| Cancellation and release at every step | Cancels owner work; dropping the call settles it and keeps the caller's token | - -The `modalityRequest` operation proposed in an earlier revision of [#1399](https://github.com/arcships/dim/pull/1399) also accepted -Bedrock routes without SigV4 signing, while every bundled media adapter refuses a Bedrock -connection. Media support on Bedrock would be a new feature, not a serialization of an existing -one. - -**Acceptance, if the operation is built later.** The maintainer confirms the operation's shape, -ownership and coverage before implementation; existing media operations and their limits are -preserved or a scope change is stated; one resolution per call lifetime with no mixed snapshots; -Rust and an actual foreign-runtime flow exercise the same request, reply, cancellation and error -contract; tests cover the affected flow boundaries, including credential confinement, vendor -routes, query parameters, redirects, download streaming and realtime cleanup; file transfer -agrees with [#1564](https://github.com/arcships/dim/issues/1564) and its active changes rather than -adding a second upload implementation. - -**Consumer consequence.** Provider exposes no media-execution operation, so a foreign-language -adapter serves no media operation. Modality states that in its own document; -this page defines nothing about how an adapter declares or runs its work. +The media connection is no longer a port handed to an adapter. The adapter resolves `providerService.media_route({target, operation})`, reads the credential from the owner the route names, and sends one call; the account owner's `credential` returns a value with the grant generation. See [Provider](../plugins/Provider.md) and [ManagedAccount](../plugins/ManagedAccount.md). ## 4. Client integration diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 3b9d8f234c..2e5a81c121 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -1,12 +1,12 @@ # Process owner operations -The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelectionHost` and `auxiliaryModel` from the catalog when their consumers move to the owners below. +The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelectionHost`, `auxiliaryModel`, `modelHost` and `managedSearch` from the catalog. The Provider, account-owner and ModelLog rows below are superseded by [Provider](../plugins/Provider.md), [ManagedAccount](../plugins/ManagedAccount.md) and their per-owner contracts; the other owners' rows stand. ## Retained operations | Caller → owner | API to use | | --- | --- | -| Model selection, pickers and auxiliary callers → `providerService` | `resolve`, `selectableModels`, `selectableForModality`, `complete` keep their existing arguments and replies. Provider supplies these operations in the managed profile and ConfiguredModels in the API-key profile. | +| Model selection, pickers and auxiliary callers → `providerService` | `resolve`, `selectable`, `preferences`, `invoke` as [Provider](../plugins/Provider.md) defines them. Provider supplies these operations in the managed profile and ConfiguredModels in the API-key profile. | | Media selection → Modality | `modalityTargets.resolve`. | | Management clients → Provider / Grok OAuth / OpenAI Codex OAuth | Existing [Provider management RPCs](../appserver/provider-management.md) and account status, begin, attempt status, cancel and logout RPCs. Codex also handles its browser callback. | | Session consumers → Agent directory | [`sessions` operations](../appserver/sessions-service.md). Agent administration and Session creation/fork retain the existing `agent.create/list/close` and `session.create/fork` client RPCs. RPC, Agent configuration, Collaboration and Provider lifecycle consumers use directory-owned admission, generation observation, close and rollback. The directory keeps the Session lease through each admitted operation. | @@ -14,7 +14,7 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Presence consumers → Connection | `sessionClientsHost.presences`. Connection serves this operation directly and handles broadcast, socket registration, writes, close and detach. | | Activity consumers / daemon clients → ServerControl | `processActivity.activated/hold/release`; existing `daemon.ping/shutdown` RPCs. Shutdown settles the initiating reply before transport teardown. | | UI clients → UiHost / UiExtensions | Existing `ui.open/attach/replace/status/shutdown/close` RPCs and [extension listing, resources and notices](../client-ui-extensions.md). Transport supplies the authenticated connection identity. UiHost owns attach tokens, generations and disconnect cleanup. | -| Prompt, scenario and summary evaluation tools → active profile | Use `providerService` for their catalog/selection calls and `modelHost.invoke` for execution. | +| Prompt, scenario and summary evaluation tools → active profile | Use `providerService` for their catalog/selection calls and `invoke` for execution. | | Media execution and realtime → native adapter | Existing native connection binding and credential owner ([#1613](https://github.com/arcships/dim/issues/1613), [#1634](https://github.com/arcships/dim/issues/1634)). | | Transport, Web entry and Session subscriptions → Connection | Connection-owned attach, broadcast, close and detach using the authenticated connection identity. | @@ -23,9 +23,9 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Caller → owner | Methods and replies | | --- | --- | | Permission consumers → Agent directory | `sessions.permission({sessionId,branchId})` and `sessions.permissionDefaults({})` retain the existing policy replies. The first holds the Session lease; the second reads the current default without creating a Session. | -| Dialogue, summary and suggestion → active invocation owner | `modelHost.invoke(request, mode, consume, cancelled, hooks?) → value`. Full `ModelRequest` with pinned tools, configuration, cached prefix and capability snapshot. Attempt contract below. | -| Session configuration → `providerService` (managed profile) | `configuration(explicit?, cwd?, preferences) → ModelSelection`; `applyPreferences(current, update) → ModelSelection`. Bind the existing Provider operations. | -| Session creation/adoption and Collaboration → `providerService` (managed profile) | `prepareStartup(request) → {model, admissionId?}`, `checkStartup(source) → void`, `retainStartup({sessionId, generation, model, admissionId?}) → void`, `releaseStartup({admissionId}) → void`. Reuse the pending startup binding ID. Retain on success for that Session generation; release on failure or caller unload. | +| Dialogue, summary and suggestion → `providerService` | `invoke(request, mode, consume, admit?, cancelled) → {accepted}`. Full `ModelRequest` with pinned tools, configuration, cached prefix and capability snapshot; retries and credential recovery stay with the owner, see [Provider](../plugins/Provider.md). | +| Session configuration → `providerService` (managed profile) | `resolve({target?, cwd?}) → ModelSelection`; `preferences({selection, update}) → ModelSelection`, see [Provider](../plugins/Provider.md). | +| Session creation/adoption and Collaboration → `providerService` (managed profile) | `prepare_startup(request) → ModelSelection`, `retain_startup({session, model})`, `release_startup({model})`. The source is bound to the calling row until a Session retains it; a missed release settles with the row, a retained source with the Session, see [Provider](../plugins/Provider.md). | | Session creation / worktree management → ManagedWorktrees | `create({source, base?, branch?}) → CreatedWorktreeReply`, `discard(created) → void`, `list({}) → WorktreeView[]`, `pruneSelection({olderThanMs?, keep?, force}) → PruneSelection`, `remove({taskId, force}) → boolean`. Bind the existing operations. Failed Session creation discards the created worktree on its node. | | PluginManager → UiExtensions | `plugins({}) → string[]`, `refusal({plugin}) → string or null`, `register({plugin, name, package?}) → void`, `withdraw({plugin}) → void`. Bind the existing catalog methods. | @@ -57,4 +57,4 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | `hooks?` | `prepare(protocol or null) → ModelConfig or null` runs once after resolution. `beforeAttempt() → admitted or {rejected: message}` checks the summary budget before each attempt. `waiting(progress or null)` reports the existing retry schedule. | | Completion | Cancellation or driver shutdown releases a suspended consumer and joins accepted work. Invalid wire input returns `invalid_request`. Consumer exceptions remain consumer errors. | -The full-request consumer injects only `modelHost`. The managed profile registers Provider at that name; the API-key profile registers ConfiguredModels; standalone local configuration registers the local host. Each profile registers exactly one dispatcher at `modelHost`. Aimux relinquishes the catalog name and supplies the existing native driver. The selected owner resolves the request, invokes its driver, and settles credential recovery with the account owner. The local host uses its local connection. The caller receives output or a host error. Aimux owns its native driver, pool and unload signal. +The full-request consumer injects only `providerService`. The managed profile registers Provider at that name; the API-key profile registers ConfiguredModels; standalone local configuration registers the local host. Each profile registers exactly one dispatcher at `providerService`. Aimux supplies the native driver and owns its pool and unload signal without a catalog name. The selected owner resolves the credential with the account owner, invokes its driver and settles the retries; the caller receives output or a typed error. diff --git a/docs/design/plugins/ConfiguredModels.md b/docs/design/plugins/ConfiguredModels.md index 46a81798c2..5c06fe67bc 100644 --- a/docs/design/plugins/ConfiguredModels.md +++ b/docs/design/plugins/ConfiguredModels.md @@ -64,8 +64,14 @@ The file's entries declare both limits; a selection always carries them, so `res - The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); `credential` is the only operation that returns it. +## Client-visible changes + +None. The profile has no client namespace; `providerService` serves parts and is not a client protocol. + ## Rule check +[Design rules §7](https://github.com/arcships/dim/pull/2029) is the rule source. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part; no Timeline facts. | @@ -85,6 +91,10 @@ The file's entries declare both limits; a selection always carries them, so `res None. The model file and its validation are this owner's; no other owner's operation is needed. +## Supersedes + +- `service-faces.md`: the `modelHost` row and the configured-profile paragraph in §4.10. + ## Binding appendix `providerService` is [Provider](Provider.md)'s name; this profile registers the same name from `ConfiguredModels`. The types are shared, including `Credential` and `CredentialRequest` from [ManagedAccount](ManagedAccount.md); only the operations listed above exist. diff --git a/docs/design/plugins/DimOAuth.md b/docs/design/plugins/DimOAuth.md index 65f4ebad25..bb07419599 100644 --- a/docs/design/plugins/DimOAuth.md +++ b/docs/design/plugins/DimOAuth.md @@ -38,7 +38,7 @@ Web declares its search tool only while the relay account is signed in: ```rust let AccountAvailability { signed_in, .. } = dim_account.availability(cancelled.clone()).await?; if signed_in { - let mut changes = dim_account.subscribe(SubscriptionRequest {}, cancelled.clone()).await?; + let mut changes = dim_account.subscribe(cancelled.clone()).await?; // declare web_search; withdraw it when changes report signed_out } ``` @@ -71,8 +71,8 @@ Face `dimAccount`, marked on `DimOAuth`. The operations are [ManagedAccount](Man | --- | --- | --- | | `availability`, `subscribe` | `{}` → `{signed_in, identity?}`; the identity is the grant's issuer and subject, never a token | `cancelled`, `closed`, `failed` | | `catalog` | `{}` → `{account, models}`; the models are the relay's, each with its declared capabilities | `unavailable`, `cancelled`, `closed`, `failed` | -| `credential` | `{provider, model}` → `{protocol, base_url, headers, bearer, generation}`; `provider` must be one of the relay's; a read inside the 30-second window refreshes first | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | -| `rejected` | `{provider, generation}` → a credential; the current generation refreshes once under the account lock, a superseded generation answers the current credential; a rejected refresh or a rejected recovered generation follows the sign-out rule | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | +| `credential` | `{provider, model}` → `{protocol, base_url, headers, bearer, generation}`; `provider` must be one of the relay's; a read inside the 30-second window refreshes first | `not_found`, `account_required`, `unavailable`, `cancelled`, `closed`, `failed` | +| `rejected` | `{provider, generation}` → a credential; the current generation refreshes once under the account lock, a superseded generation answers the current credential; a rejected refresh or a rejected recovered generation follows the sign-out rule | `not_found`, `account_required`, `unavailable`, `cancelled`, `closed`, `failed` | | `search` | `{query, count}` → `{results: [{title, url, snippet, publishedAt?}]}` | `unavailable`, `failed`, `cancelled`, `closed` | | `title` | `{provider, text}` → `{title}`; `provider` must be the relay's | `unsupported_provider`, `unavailable`, `cancelled`, `closed`, `failed` | @@ -92,8 +92,14 @@ The `account.*` namespace keeps its published methods; handlers call the same ow - The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); DimOAuth's replies and errors omit it. - The account file is shared with the TypeScript subscriber under the published `auth.json.lock` marker protocol; FileStorage's contract records the marker exception, and DimOAuth keeps the file format. +## Client-visible changes + +None. The `account.*` method names, fields, error codes and user-visible behavior are unchanged; handlers call these operations. + ## Rule check +[Design rules §7](https://github.com/arcships/dim/pull/2029) is the rule source. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part; no Timeline facts, no Capability. | @@ -116,6 +122,12 @@ The `account.*` namespace keeps its published methods; handlers call the same ow - **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for `auth.json` and its backup; the `auth.json.lock` marker exception is already recorded there. - **Settings, storage, session directory.** None. +## Supersedes + +- `service-faces.md`: the `managedSearch` row and §4.6, whose `search` this owner answers. +- `crates/dim-app-server/README.md`: the managed provider contract's search paragraph; the account owner answers it directly. +- `plugins/SessionTitle.md` §3.3's `sessionTitleGenerator` name: the title operation is `dimAccount.title`. + ## Binding appendix `DimOAuth` is the owner type; `dimAccount` is the wire name. The request and reply types are the [ManagedAccount](ManagedAccount.md) types plus the search and title types this crate already exports. diff --git a/docs/design/plugins/ManagedAccount.md b/docs/design/plugins/ManagedAccount.md index 439ae202a0..e76c71c495 100644 --- a/docs/design/plugins/ManagedAccount.md +++ b/docs/design/plugins/ManagedAccount.md @@ -51,7 +51,7 @@ Web follows the Dim account's availability: ```rust let AccountAvailability { signed_in, .. } = account.availability(cancelled.clone()).await?; -let mut changes = account.subscribe(SubscriptionRequest {}, cancelled.clone()).await?; +let mut changes = account.subscribe(cancelled.clone()).await?; while let Some(available) = changes.next().await { /* declare or withdraw web_search */ } ``` @@ -78,8 +78,8 @@ All operations are marked on the owner type and provided under the owner's face | `availability` | Whether the account is signed in | `{}` | `{signed_in, identity?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | | `subscribe` | Follow availability changes | `{}` | `{subscription}` | The subscription ends with the caller's row | `closed` | | `catalog` | The models the plan serves | `{}` | `{account, models}` | The caller cancels; a catalog read may wait on the account's own refresh | `unavailable`, `cancelled`, `closed`, `failed` | -| `credential` | The connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation}`; a read inside the refresh window refreshes first | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | -| `rejected` | The generation the provider refused; answer the credential to retry with | `{provider, generation}` | A credential; the current generation refreshes once, a superseded generation answers the current credential | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `cancelled`, `closed`, `failed` | +| `credential` | The connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation}`; a read inside the refresh window refreshes first | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `unavailable`, `cancelled`, `closed`, `failed` | +| `rejected` | The generation the provider refused; answer the credential to retry with | `{provider, generation}` | A credential; the current generation refreshes once, a superseded generation answers the current credential | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `unavailable`, `cancelled`, `closed`, `failed` | | `search` (Dim) | Search through the relay | `{query, count}` | `{results}` | The caller cancels; the provider request is cancelled | `unavailable`, `failed`, `cancelled`, `closed` | | `title` (Dim) | Generate a title through the relay | `{provider, text}` | `{title}` | The caller cancels; an HTTP exchange is bounded at 10 s | `unsupported_provider`, `unavailable`, `cancelled`, `closed`, `failed` | @@ -116,8 +116,14 @@ All operations are marked on the owner type and provided under the owner's face - The external account plugin's face name is configured by its row because the plugin is built outside this repository; the host records the name in the Provider record's authority. +## Client-visible changes + +None. The `account.*`, `account.codex.*`, `account.grok.*` and `account.chatgpt.*` method names, fields, error codes and user-visible behavior are unchanged; handlers call these operations. + ## Rule check +[Design rules §7](https://github.com/arcships/dim/pull/2029) is the rule source. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part per account owner; no Timeline facts, no Capability. | @@ -147,6 +153,13 @@ Shared request, reply and error types; each owner's `#[rutis::service]` block is ```rust use dim_agent_capabilities::host::CancelledFn; +use rutis::host::BoxFuture; +use std::collections::BTreeMap; +use std::sync::Arc; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountIdentity { pub issuer: String, pub subject: String } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -170,8 +183,9 @@ pub struct Credential { pub generation: u64, } +/// The wire code is the variant's snake_case name; `details` carries its data. #[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase")] +#[serde(tag = "code", content = "details", rename_all = "snake_case")] pub enum AccountError { #[error("{0}")] NotFound(String), #[error("sign in to the account")] AccountRequired, @@ -184,3 +198,9 @@ pub enum AccountError { ``` `Subscription` is the owner's replayable watch over availability; it ends when the calling row unloads or the owner closes. + +## Supersedes + +- `service-faces.md`: the `grokOAuthService` and `openAICodexOAuthService` rows; the `managedSearch` row and §4.6, which the account owners' `search` replaces. +- `appserver/provider-management.md`: the account rows in §2 and §3.1 that describe the account catalog and status as reported by a host binding. +- `crates/dim-app-server/README.md`: the managed provider contract's account and lease paragraphs; the account owners answer them directly. diff --git a/docs/design/plugins/ManagedOAuth.md b/docs/design/plugins/ManagedOAuth.md index fbcca4198a..fc494f2863 100644 --- a/docs/design/plugins/ManagedOAuth.md +++ b/docs/design/plugins/ManagedOAuth.md @@ -65,8 +65,14 @@ Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subs - The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); these replies and errors omit it. - The legacy `openai-codex` record keeps its legacy fields; the hidden state shared with the ChatGPT account and the migration between the two accounts stay the owners' business and are described in the [Codex sign-in design](../../../crates/dim-oauth/docs/design.md). +## Client-visible changes + +None. The `account.codex.*` and `account.grok.*` method names, fields, error codes and user-visible behavior are unchanged; handlers call these operations. + ## Rule check +[Design rules §7](https://github.com/arcships/dim/pull/2029) is the rule source. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | Two process parts, one implementation; no Timeline facts, no Capability. | @@ -89,6 +95,10 @@ Both faces implement [ManagedAccount](ManagedAccount.md)'s `availability`, `subs - **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read` and `update` for the account record. - **Others.** None. +## Supersedes + +- `service-faces.md`: the `grokOAuthService` and `openAICodexOAuthService` rows. + ## Binding appendix ```rust diff --git a/docs/design/plugins/ManagedProviders.md b/docs/design/plugins/ManagedProviders.md index d71df0d24d..ac587f9fd6 100644 --- a/docs/design/plugins/ManagedProviders.md +++ b/docs/design/plugins/ManagedProviders.md @@ -72,8 +72,14 @@ The client namespace `account.chatgpt.*` keeps its published methods. The existi - The external account plugin's face name comes from its row: the plugin is built outside this repository, so the assembly supplies the name the Provider record's authority uses. - The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); these replies and errors omit it. +## Client-visible changes + +None. The `account.chatgpt.*` method names, fields, error codes and user-visible behavior are unchanged; handlers call these operations. + ## Rule check +[Design rules §7](https://github.com/arcships/dim/pull/2029) is the rule source. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part; ChatGPT is an account owner, not a Capability. | @@ -96,6 +102,11 @@ The client namespace `account.chatgpt.*` keeps its published methods. The existi - **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for the ChatGPT account record. - **Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)).** Provider reads a Session's creation record through `store.creationRecord` to require an interactive client Session for this provider; the requirement is stated in [Provider](Provider.md)'s requirements. +## Supersedes + +- `service-faces.md`: the `managedSearch` row and §4.6. +- `crates/dim-app-server/README.md`: the managed provider contract, including the binding, its validation and `ManagedSearch`. + ## Binding appendix ```rust diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md index 5d89b6d10f..14d7f0b858 100644 --- a/docs/design/plugins/Provider.md +++ b/docs/design/plugins/Provider.md @@ -60,7 +60,7 @@ The Rpc entry changes only the preferences of the model already adopted: ```rust let next = provider - .preferences(PreferencesRequest { selection: current, update: patch }, cancelled.clone()) + .preferences(PreferencesRequest { selection: current, update: patch }) .await?; line_owner::(line)?.configure( ConfigureRequest { sources: None, model: Some(next), tools: None }, @@ -90,16 +90,8 @@ send_media(&credential).await?; ModelProvider runs a turn; `consume` is the branch part's own callback that writes `step/*` events and reports how the stream ended: ```rust -let outcome = provider - .invoke( - InvokeRequest { - request, - mode: Mode::Dialogue { chain: failure_chain }, - consume: consumer, - admit: None, - }, - cancelled.clone(), - ) +let reply = provider + .invoke(request, Mode::Dialogue { chain: failure_chain }, consumer, None, cancelled.clone()) .await?; ``` @@ -107,10 +99,7 @@ The summary strategy runs with its own budget: ```rust provider - .invoke( - InvokeRequest { request, mode: Mode::Dialogue { chain: None }, consume, admit: Some(budget) }, - cancelled, - ) + .invoke(request, Mode::Dialogue { chain: None }, consume, Some(budget), cancelled) .await?; ``` @@ -119,10 +108,7 @@ SessionTitle and ImageUnderstanding run one request and keep the text: ```rust let selection = provider.resolve(ResolveRequest { target: Some(model), cwd: None }, cancel.clone()).await?; let reply = provider - .invoke( - InvokeRequest { request: ModelRequest::from(selection, messages), mode: Mode::Once, consume: collect_text, admit: None }, - cancel, - ) + .invoke(ModelRequest::from(selection, messages), Mode::Once, collect_text, None, cancel) .await?; ``` @@ -136,11 +122,11 @@ let destination = model_log.recording().await.ok().flatten(); A Session creation with a temporary connection: ```rust -let selection = provider.prepare_startup(request, cancelled.clone()).await?; +let selection = provider.prepare_startup(&self.ctx, request, cancelled.clone()).await?; let session = sessions.create(/* with selection */).await?; -provider.retain_startup(RetainRequest { session: session.id().into(), model: selection }, cancelled).await?; +provider.retain_startup(RetainRequest { session: session.id().into(), model: selection }).await?; // On a creation that fails before retention, the caller may release early: -provider.release_startup(ReleaseRequest { model: selection }, cancelled).await?; +provider.release_startup(&self.ctx, ReleaseRequest { model: selection }).await?; ``` ## Own contract @@ -169,14 +155,14 @@ All operations are marked on `Provider` and provided under `providerService`; re | `selectable` | The models that can run a use, and the default | `{use: "chat" \| {modality}}` | `{models, default?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | | `prepare_startup` | Admit a temporary connection under the calling row and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `{selection}` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `retain_startup` | Bind the temporary connection the model carries to a Session | `{session, model}` | `{}` | None; completes immediately | `not_found` (the model carries no source, or the source is not bound), `closed` | -| `release_startup` | Release a source still bound to the calling row | `{model}` | `{}` | None; completes immediately | `not_found` (already retained by a Session), `closed` | -| `invoke` | Run one model request | `{request, mode, consume, admit?}` | `{outcome}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `unavailable`, `cancelled`, `closed`, `provider_failed {retryable}` | +| `release_startup` | Release a source the calling row owns | `caller`, `{model}` | `{}` | None; completes immediately | `not_found` (already retained by a Session, or another row's), `closed` | +| `invoke` | Run one model request | `request`, `mode`, and the `consume` / optional `admit` callbacks as direct parameters | `{accepted}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed`, `provider_failed {retryable}` | | `media_route` | A media model's route and the owner of its credential | `{target, operation}` | `{protocol, base_url, headers, realtime?, credential: Owner}` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | -| `credential` | A static model's connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation: none}` | The caller cancels; no timeout | `not_found`, `unavailable`, `cancelled`, `closed` | +| `credential` | A static model's connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation: none}` | The caller cancels; no timeout | `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | `prepare_startup` admits the source under the calling row; the row's unload releases it, so a missed `retain_startup` or `release_startup` settles with the row. `retain_startup({session, model})` moves the source to the Session named by the caller and the model's metadata; the Session's close releases it, so a missed failure-path release settles with the Session. `release_startup({model})` is the optional early release for a creation that failed; it answers `not_found` once a Session retains the source. A member Session that inherits the leader's model retains the same source by value. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Credential` is [ManagedAccount](ManagedAccount.md)'s value: static credentials carry no generation; an account owner's carry the grant's. `invoke` calls the account owner's `credential`, sends, and on a refusal calls `rejected` with the refused generation before retrying within its own failure chain. -`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits through the optional `admit`/progress callbacks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(next)` receives chunks, ends and typed failures and returns how the call ended and whether output was accepted; output accepted before a failure prevents replay. `admit` runs before each attempt and returns `admitted` or `rejected {message}`; only a caller with its own budget passes it. +`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits through the optional `admit`/progress callbacks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(chunk)` reports `Continue`, `End`, `CredentialRejected` (the provider refused the credential, so `invoke` calls the account owner's `rejected` once and retries) or `Failed { retryable }`; output accepted before a failure prevents replay, and the reply's `accepted` says whether any output was accepted. `admit` runs before each attempt and answers `Admitted` or `Rejected { message }`; only a caller with its own budget passes it. Both callbacks are direct parameters, so the request data stays serde-only. ### Errors @@ -207,8 +193,14 @@ All operations are marked on `Provider` and provided under `providerService`; re - The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary): Provider never writes the account bearer it receives from `credential` or `rejected` to a client reply, the UI, a log, an error text, a persisted record, the model context or the Timeline. Static credentials in Provider's own records are the record's data, not this value. - The `provider` client namespace is a client protocol, not a second service face: it is the mechanism's registration point for protected-local v3 clients, and every handler calls the operations above or the management operations this owner also owns. +## Client-visible changes + +None. The `provider.*` client method names, request and reply fields, error codes and user-visible behavior are unchanged; handlers call the operations above. + ## Rule check +[Design rules §7](https://github.com/arcships/dim/pull/2029) is the rule source. + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part. Provider writes no Timeline event; it is not a Capability. ModelProvider, the branch Capability, consumes `invoke`. | @@ -243,11 +235,19 @@ All operations are marked on `Provider` and provided under `providerService`; re ## Binding appendix -`Provider` is the owner type; `providerService` is the wire name. `CancelledFn` is the binding's cancellation argument. The request and reply types are serde data; only `consume` and `admit` cross by reference. +`Provider` is the owner type; `providerService` is the wire name. `CancelledFn` is the binding's cancellation argument. The request and reply types are serde data; `consume` and `admit` are direct call parameters, never request fields. ```rust -use dim_agent_capabilities::host::CancelledFn; -use dim_agent_types::{ModelId, ModelRequest, ModelSelection, ModelCapabilitySnapshot, ModalityModelSnapshot}; +use dim_agent_capabilities::host::{CancelledFn, ModelChunk, ModelProtocol, RealtimeDeclaration}; +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; +use std::collections::BTreeMap; +use std::sync::Arc; +use dim_agent_types::{ + ModalityModelSnapshot, ModelCapabilitySnapshot, ModelId, ModelPreferences, ModelRequest, + ModelSelection, +}; +use rutis::Ctx; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -276,6 +276,20 @@ pub struct SelectableReply { #[serde(tag = "kind", rename_all = "camelCase")] pub enum SelectableModels { Chat(Vec), Modality(Vec) } +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupConnection { + pub api_format: ModelProtocol, + pub base_url: String, + pub api_key: Option, + pub auth_token: Option, + pub headers: BTreeMap, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupLimits { pub context_window: Option, pub max_output_tokens: Option } + #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct StartupRequest { @@ -294,29 +308,38 @@ pub struct RetainRequest { pub session: String, pub model: ModelSelection } #[serde(rename_all = "camelCase")] pub struct ReleaseRequest { pub model: ModelSelection } +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FailureChain { pub from_request_id: String, pub attempts: u32, pub waited_ms: u64 } + #[derive(serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum Mode { Dialogue { chain: Option }, Once } +/// What the consumer reports for one chunk; `CredentialRejected` asks the owner to recover once. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum Consumed { Continue, End, CredentialRejected, Failed { retryable: bool } } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum Admitted { Admitted, Rejected { message: String } } + pub type ConsumeFn = Arc BoxFuture<'static, Consumed> + Send + Sync>; pub type AdmitFn = Arc BoxFuture<'static, Admitted> + Send + Sync>; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct InvokeRequest { - pub request: ModelRequest, - pub mode: Mode, - pub consume: ConsumeFn, - pub admit: Option, -} +pub struct InvokeReply { pub accepted: bool } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct InvokeReply { pub outcome: Outcome } +pub struct MediaRouteRequest { pub target: ModelId, pub operation: String } +/// Who the media executor asks for the credential: this owner or the account owner named by the record. #[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MediaRouteRequest { pub target: ModelId, pub operation: String } +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CredentialOwner { Provider, Named { face: String } } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -325,17 +348,17 @@ pub struct MediaRouteReply { pub base_url: String, pub headers: BTreeMap, pub realtime: Option, - /// The credential owner the media executor calls `credential` on: this owner, or an account owner. pub credential: CredentialOwner, } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CredentialRequest { pub provider: String, pub model: String } -// `Credential` is the shared value defined in ManagedAccount.md; static credentials carry no generation. +pub struct StaticCredentialRequest { pub provider: String, pub model: String } +// `Credential` is the shared value in ManagedAccount.md; a static credential carries no generation. +/// The wire code is the variant's snake_case name; `details` carries its data. #[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase")] +#[serde(tag = "code", content = "details", rename_all = "snake_case")] pub enum ProviderError { #[error("{0}")] Invalid(String), #[error("{0}")] InvalidConnection(String), @@ -358,11 +381,18 @@ impl Provider { pub async fn selectable(&self, request: SelectableRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn prepare_startup(&self, caller: &Ctx, request: StartupRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn retain_startup(&self, request: RetainRequest) -> Result<(), ProviderError> { /* ... */ } - pub async fn release_startup(&self, request: ReleaseRequest) -> Result<(), ProviderError> { /* ... */ } - pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn release_startup(&self, caller: &Ctx, request: ReleaseRequest) -> Result<(), ProviderError> { /* ... */ } + pub async fn invoke(&self, request: ModelRequest, mode: Mode, consume: ConsumeFn, admit: Option, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn credential(&self, request: StaticCredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } } ``` The `provider` client namespace keeps its published method names and request shapes; handlers call the operations above and the management operations. No management operation is also published on `providerService`. + +## Supersedes + +- `service-faces.md`: the `modelHost` row and §4.2; the `providerService` and `providerConnectionResolver` rows; the `managedSearch` row where it names Provider; the Provider selection block in §4.10. +- `contracts/process-owner-operations.md`: the model selection, session configuration, session creation/adoption, model invocation and auxiliary rows, and the `modelHost` paragraph. +- `appserver/provider-management.md`: the surface-table rows for `ModelSelectionHost`, `SelectableModelsHost`, `ProviderConnectionResolver`, `ModalityConnectionHost` and `auxiliaryModel.complete`, and the port sections §3.6 and §3.8. +- `appserver/auxiliary-model.md`: the `auxiliaryModel` interface in §4, replaced by `invoke`. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index c347503527..d9a3b7f7e3 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -57,6 +57,6 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | -| Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | +| Process parts | Provider (model owner), ConfiguredModels, ChatGPT account (the ManagedProviders plugin), DimOAuth, OpenAI Codex, Grok, Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | | Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | | Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..b10cca1ee5 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -93,7 +93,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `loops` | `loops.start/next/list/stop` | 形状按 [Scheduler](plugins/Scheduler.md#126-interfaces) §12.6;`start`、`next`、`stop` 是迁改,`list` 是读取。投递 pass、恢复与 `settle_delivering` 不在此面。 | | `sessionFiles` | `sessionFiles.put/import/read/register/owns/owned_paths` | 形状按 [Session files](appserver/session-files.md) §9.1,`SessionFiles` 是进程内绑定。 | | `commandRules` | `commandRules.read` | Session 命令规则读取,按 [命令规则](appserver/permission-command-rules.md#41-language-neutral-adr-002-d5) §4.1。 | -| `managedSearch` | `managedSearch.search` | 凭据由实现持有,见 §4.6。 | +| 账户面(`dimAccount`、`codexAccount`、`grokAccount`、`chatgptAccount`) | `credential`、`rejected`、`availability`、`subscribe`、`catalog`;Dim 另有 `search`、`title` | 按 [ManagedAccount](plugins/ManagedAccount.md) 与各所有者契约;凭据由账户所有者持有。 | | `agentConfig` | `agentConfig.get()` | 形状见 §4.8。 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | | `skillsConfig` | `skillsConfig.get()` | 形状见 §4.8。 | @@ -111,7 +111,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | --- | --- | --- | | `agentIndex` | `sessions` | 目录查询走 `sessions` | | `settingsService` | `settings` | GoalBranch 的取消契约见 §4.1。 | -| `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | +| `providerService` | `providerService` | 完整请求与辅助请求都调 `invoke`,见 [Provider](plugins/Provider.md)。 | | `loader` | `rutis/loader` | 插件管理走数据面 | | `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 标题与 worktree 关联直接调 store | | `treeCommands`、`timelineTreeControl` | `timelineTree` | 分支操作直接调用 Session 的树;不保留别名 | @@ -188,21 +188,17 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow ### 3.6 入口、凭据与宿主资源 -按 #1292 逐批确定各项的公共操作,并按 §2.6 迁移登记。状态、资源和凭据留在各自的 owner。`managedSearch` 的搜索操作见 §4.6。`skillsCatalog` 的插件内容操作见 [Skills owner 契约](../architecture/rust-agent/plugins/Skills.md#plugin-content-data-face)。 +按 #1292 逐批确定各项的公共操作,并按 §2.6 迁移登记。状态、资源和凭据留在各自的 owner。账户面与 `providerService` 已按 [ManagedAccount](plugins/ManagedAccount.md) 与 [Provider](plugins/Provider.md) 改为数据面,不再列在本表;`skillsCatalog` 的插件内容操作见 [Skills owner 契约](../architecture/rust-agent/plugins/Skills.md#plugin-content-data-face)。 | 名字 | scope | provider | reason | | --- | --- | --- | --- | | `serverControl` | process | ServerControl | control | | `connectionHub` | process | Connection | control | -| `grokOAuthService` | process | GrokOAuth | secret | -| `openAICodexOAuthService` | process | OpenAICodexOAuth | secret | | `uiHost` | process | UiHost | control | | `uiExtensions` | process | UiExtensions | control | | `mentionIndex` | process | WorkspaceToolsOwner | host-resource | | `mcpService` | process | Mcp | host-resource | | `hooksService` | process | HooksSettings | host-resource | -| `providerService` | process | Provider | 当前为 secret,迁移后通过数据操作使用凭据 | -| `providerConnectionResolver` | process | Provider | host-resource | | `timelineFactory` | session | SessionScope | control | ## 4. 批次契约(#1292) @@ -218,9 +214,9 @@ PromptSettings 的三个只读端口按 [prompt overrides §3.1](appserver/promp 迁移前 `GoalBranch` 继续用类型化调用,读取随 branch stop token 取消。设置 owner 在 #1292 的批次内确定如何将调用方取消传递给读取操作,并验证 `settings.read` 的 `SettingsResult` 信封和现有错误语义。Goal 切到同一数据契约的 Rust 绑定时,覆盖分支停止中断设置读取的流程。 -### 4.2 `modelHost`:保留完整模型请求 +### 4.2 `modelHost`:已由 `providerService.invoke` 取代 -迁移前 `PromptSuggestion` 继续用类型化调用。模型 owner 在 #1292 的批次内定义能承载完整 `ModelRequest` 的公开操作,保留当轮 provider、model、system、tools、config、cached prefix、流式回复与取消。精简请求迁往 `providerService.complete`,随后移除 `auxiliaryModel`。PromptSuggestion 切到同一数据契约的 Rust 绑定时,覆盖 tools、config 和缓存前缀。 +`providerService.invoke` 承载完整 `ModelRequest`、失败链、重试与凭据恢复;见 [Provider](plugins/Provider.md)。`modelHost`、`auxiliaryModel` 与 `providerConnectionResolver` 的旧面删除。 ### 4.3 `scheduleJobs` @@ -254,19 +250,9 @@ workflowRuns.call(RunRequest) 进程内绑定和 wire 的行为一致性由 `session_files_flow.rs` 与 `attachments_flow.rs` 验证。 -### 4.6 `managedSearch` +### 4.6 `managedSearch`:已由账户所有者的 `search` 取代 -`managedSearch` 只公开搜索操作: - -```text -managedSearch.search {query, count} - -> {results: [{title, url, snippet, publishedAt?}]} - -> error {code: unavailable | search_failed, message} -``` - -- 取消是协议动作(调用方丢弃调用或发 bridge cancel),不是请求字段。 -- `ManagedProviders` 在 owner 内处理登录、凭据和租约。搜索调用迁到 `managedSearch` 后,批次按 §2.6 收敛旧登记([#1398](https://github.com/arcships/dim/pull/1398))。 -- Web 的搜索使用 `managedSearch`;进程内绑定直接调用同一类型化操作,wire 在边界解码与编码。绑定与 wire 共用取消行为,丢弃调用取消本次搜索,不取消调用方的父 token。Web 的 settings 仍走 `settings`。 +搜索是 DimOAuth 的 `search({query, count}) -> {results}`,Web 直接调用账户面;见 [ManagedAccount](plugins/ManagedAccount.md) 与 [DimOAuth](plugins/DimOAuth.md)。`managedSearch` 与 `usable`、`subscribe_usable`、`refresh_usable` 删除。 ### 4.7 `wakeups` @@ -361,15 +347,14 @@ toolchainSourceHost.list({}) -> {toolchains: [{bin, root}]} # sync -> error {code: failed, message} promptSuggestionSettingsHost.read({}) -> {enabled, maxChars} -> error {code: failed, message} -providerService.selectableModels({}) -> {models: [ModelCapabilitySnapshot]} -providerService.selectableForModality({}) -> {models: [ModalityModelSnapshot]} -providerService.resolve({explicit?: ModelId, cwd?}) -> ModelSelection - -> error {code: cancelled | owner_closed | invalid_request | model_unavailable | failed, message} +providerService.resolve({target?, cwd?}) -> ModelSelection +providerService.selectable({use}) -> {models, default?} + -> error {code: invalid | not_found | unavailable | auth_required | cancelled | closed | failed, message} ``` - 每个 operation 只收一个请求对象;没有输入的写 `{}`(`provider-management.md` §3.6 的形状),多一个参数或未知字段都是 `invalid_request`。 - 取消是协议动作:调用方丢弃等待,或被取消的绑定调用不再进入 owner;owner 自己的生命周期仍然约束它启动的 worker。 -- 回复就是 owner 的类型:`ExecutionSettings`、`PromptSuggestionSettings`、`ModelCapabilitySnapshot`、`ModalityModelSnapshot`、`ModelSelection` 都是 serde camelCase 数据。`InstalledToolchain` 的 `PathBuf` 换成 UTF-8 字符串(`{bin, root}`):某个 runtime 的目录不是 UTF-8 时只跳过那一项,其余照常给子进程用;`cwd` 的请求方向同理,`ModelSelectionRequest::at` 是 Rust 调用方换字段的唯一一处。 +- 回复就是 owner 的类型:`ExecutionSettings`、`PromptSuggestionSettings`、`ModelCapabilitySnapshot`、`ModalityModelSnapshot`、`ModelSelection` 都是 serde camelCase 数据,形状与 [Provider](plugins/Provider.md) 的操作一致。`InstalledToolchain` 的 `PathBuf` 换成 UTF-8 字符串(`{bin, root}`):某个 runtime 的目录不是 UTF-8 时只跳过那一项,其余照常给子进程用。 - 提供方仍是原来的部件(App Server 的 `ExecutionSettings`、`ToolchainSource`、`PromptSuggestionSettings`、`Provider`,以及 aimux 的 `ConfiguredModels`):`provide` 一次给出类型键上的绑定和 `host_key(name)` 上的 face;没有适配层,也没有第二份业务逻辑。 - 测试:`host_port_faces.rs` 比对 Rust binding 与 wire 的结果、请求形状、错误与取消;`provider_flow.rs` 等既有流程验证真实 owner 的读取。 From 13f9b948ed327e5a7bb63e0246bfde241e7456d3 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:29:38 +0800 Subject: [PATCH 6/9] design(provider): make the bindings writable and resolve the round 4 review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Declare the `invoke` callbacks as direct `impl Fn` parameters returning `Result<_, CallError>`, hand the consumer a serializable chunk, require `admit`, and report retry waits as `Retrying` chunks. Derive `Debug` on the error enums, use snake_case `code` tags, and fix the selectable union, the shared `FailureChain`, and the shared credential with an optional generation. Define the account catalog, the availability callback registration and the search/title types; keep `creationRecord` with SessionStore and read it through the dependency; state the ChatGPT client-session rule in Provider. State what the contracts supersede and update those paragraphs: resource-owner-operations, resource-faces, provider-management, auxiliary-model, Modality, ImageUnderstanding and the App Server README. Add the client-visible sections (none), the §7 and #2127 links, and the retry column in the error tables. Refs #2019 · Refs #2015 --- crates/dim-app-server/README.md | 2 + docs/design/appserver/auxiliary-model.md | 2 + docs/design/appserver/provider-management.md | 2 +- .../contracts/process-owner-operations.md | 2 +- .../contracts/resource-owner-operations.md | 34 +----- docs/design/plugins/ConfiguredModels.md | 17 ++- docs/design/plugins/DimOAuth.md | 61 ++++++++-- docs/design/plugins/ImageUnderstanding.md | 16 +-- docs/design/plugins/ManagedAccount.md | 64 +++++++--- docs/design/plugins/ManagedOAuth.md | 2 +- docs/design/plugins/ManagedProviders.md | 4 +- docs/design/plugins/Modality.md | 8 +- docs/design/plugins/Provider.md | 112 ++++++++++-------- docs/design/resource-faces.md | 3 +- docs/design/service-faces.md | 2 +- 15 files changed, 201 insertions(+), 130 deletions(-) diff --git a/crates/dim-app-server/README.md b/crates/dim-app-server/README.md index 063e2ab994..e2523d080c 100644 --- a/crates/dim-app-server/README.md +++ b/crates/dim-app-server/README.md @@ -623,6 +623,8 @@ unchanged transaction/backup/lifecycle behavior. ## Managed provider contract +> Superseded: the account owners' target contract is [ManagedAccount](../../docs/design/plugins/ManagedAccount.md) and the ChatGPT account's is [ManagedProviders](../../docs/design/plugins/ManagedProviders.md). The `dyn ManagedProvider` port, the `ManagedSearch` face and the lease paragraphs below are the pre-migration shape. + The product profile includes the local [ChatGPT plan provider](../../docs/design/appserver/chatgpt-plan.md). Its account operations live in `account.chatgpt` and its models use the managed catalog and connection path below. Catalog reads accept caller cancellation. Concurrent reads may share the account diff --git a/docs/design/appserver/auxiliary-model.md b/docs/design/appserver/auxiliary-model.md index 04cd83734e..9fccd6ccfe 100644 --- a/docs/design/appserver/auxiliary-model.md +++ b/docs/design/appserver/auxiliary-model.md @@ -85,6 +85,8 @@ Superseded: the `auxiliaryModel` name leaves the catalog. The replacement operat ## 5. Flow +> Sections 5–11 describe the retired `auxiliaryModel` flow; they are historical and superseded by [Provider](../plugins/Provider.md) and [DimOAuth](../plugins/DimOAuth.md). + ``` Consumer AuxiliaryModel (owner) catalog/connection ModelHost (Aimux) | complete(model, req) | | | diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 3863e30761..51e7f47034 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -50,7 +50,7 @@ with its existing owner; management never writes another owner's state. | Account namespaces | Account owners provide login, usage and logout. The [ChatGPT plan provider](chatgpt-plan.md) owns `account.chatgpt`. | | Model selection and credentials | `providerService.resolve` and the account owners' `credential`; the old host ports are deleted ([Provider](../plugins/Provider.md)) | | `auxiliaryModel.complete` | Deleted: the caller uses `providerService.invoke` with `Mode::Once` ([Provider](../plugins/Provider.md)) | -| `provider` Settings source, user scope (`provider.json`) | The Provider part registers it; it holds `userAgent`, the User-Agent override (§2, Model request identity), so a user's choice is a declared, validated document rather than a request-local input | +| `provider` Settings source, user scope (`provider.json`) | ProviderSettings owns the source and its `userAgent` ([#2094](https://github.com/arcships/dim/pull/2094)); Provider reads `user_agent` at request time (§2, Model request identity) | | Native CLI Provider flows | Migrate discovery, create, update and disconnect together with the new owner methods | Business logic stays in Provider, not `connection.rs`, `protocol.rs` or a wiring diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 2e5a81c121..85d60b15e0 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -1,6 +1,6 @@ # Process owner operations -The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelectionHost`, `auxiliaryModel`, `modelHost` and `managedSearch` from the catalog. The Provider, account-owner and ModelLog rows below are superseded by [Provider](../plugins/Provider.md), [ManagedAccount](../plugins/ManagedAccount.md) and their per-owner contracts; the other owners' rows stand. +The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelectionHost`, `auxiliaryModel`, `modelHost` and `managedSearch` from the catalog. The Provider and account-owner rows below are superseded by [Provider](../plugins/Provider.md), [ManagedAccount](../plugins/ManagedAccount.md) and their per-owner contracts; the other owners' rows stand. ## Retained operations diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5b2be8c345..c5187f2899 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -81,39 +81,7 @@ First import emits no notice. File and project profiles retain their lease and n ### Provider → sqliteStorage -| Operation family | Current call sites and proposed inputs/results | -| --- | --- | -| readSelection(scope); writeSelection(scope,expectedVersion,selection) | selection/select. Return the stored selection and version; the write checks the scope version and commits the selected model atomically. | -| readPreferences(providerId,modelId) | saved_preferences. Read the one model preference field and keep the existing absent-value behavior in Provider. | -| readRecord({providerId,projection}) | catalog, catalog_for, catalog_target, resolve_connection, probe, discovery and edit preparation. Select header/version, one target model, managed catalog or full editable record as required. Return missing or the matching persisted projection. A projection containing an inline credential returns its stored value. | -| findCandidates(criteria); listProviders(filter); queryModels(page); managementPage(page) | Candidate IDs/ordered models, provider list, filtered model pages and management windows use their existing indexed selectors, limits, ordering and row-error behavior. Pass bundle identity, required catalog inputs and account facts as data. Keep transaction-local adoption and page selection together wherever the existing query does both. | -| activateSource(revision,baseFacts); adoptProvider(id,revision,baseFacts) | Existing source activation and per-provider adoption transactions. Supply only the bundle facts required by the existing operation. | -| commitEdit({providerId,edit}) | Closed edit variants: create, delete, connection/header patch, model create/edit/reset/delete, preferences, single/bulk enablement and discovery refresh. Preserve each existing transaction's touched columns, indexes, write precondition and projection. Create checks absence; versioned edits check the expected version. Refresh and connection changes that compare the prior record keep that exact comparison. Return the committed version and requested existing projection. | -| importLegacy(batch) | The existing legacy import commits its related records together and returns the existing item results. Cancellation and rollback keep the original transaction boundary. | - -Provider validates edits and runs probe/discovery HTTP requests outside SQLite. A conditional -commit returns the original conflict on a stale snapshot. - -**Record reads.** `readRecord({providerId,projection}) → PersistedProviderRecord | null`. -Use the existing persisted managed/static variants and the five SQLite model projections: -`header`, `all`, `mutable`, `one{modelId}`, `selected{modelIds}`. Header and target reads -retain their original query bounds. A version-only read uses the existing header version lookup. - -**Conditional edits.** `commitEdit({providerId,edit})` selects one transaction by the edit tag. -Each variant carries its own precondition; callers cannot choose a weaker one. - -| Edit | Input and precondition | Reply to Provider | -| --- | --- | --- | -| create / delete | Admitted create record and absence / expected version. Built-in deletion disables the record. | Created record / void | -| patchHeader | Expected version, existing ProviderPatch header fields, UpdateReplyKind (full or summary) | Committed projection for the requested reply | -| replaceConnection / refreshStatic | Prior complete static record and admitted replacement. Compare the exact prior record in the transaction. | Committed record | -| refreshManaged | Previous optional version, discovered account catalog and current account facts. Preserve account identity and optional-version checks. | Committed managed record | -| createModel / deleteModel / editModel | Expected version and ModelEntry / modelId / {modelId, edit: ModelEdit or null}. Null resets the edit. | Committed catalog projection | -| preferences / enableModel / enableModels | Expected version and {modelId, patch: PreferencesPatch} / {modelId, enabled} / {modelIds}. Retain bundled and account facts used by the existing mutation. | Management projection / version / catalog projection | - -Discovery and credential admission run in Provider before the conditional write. SQLite executes -the existing mutation, including its index updates, in one transaction. Provider constructs the -existing business reply. `importLegacy` remains its existing separate bulk transaction. +Superseded by [Provider](../plugins/Provider.md): Provider owns its records, selections, preferences, candidates, pages, source activation, adoption, edit commits and legacy import. `sqliteStorage` keeps only `storageReport` and the offline operations; Provider uses the engine's private transaction primitive inside the crate. The operation families below are historical. ### Credential values in replies diff --git a/docs/design/plugins/ConfiguredModels.md b/docs/design/plugins/ConfiguredModels.md index 5c06fe67bc..85e27d7bb3 100644 --- a/docs/design/plugins/ConfiguredModels.md +++ b/docs/design/plugins/ConfiguredModels.md @@ -40,7 +40,7 @@ ModelProvider runs a turn through the same operation: ```rust let outcome = provider - .invoke(InvokeRequest { request, mode: Mode::Dialogue { chain }, consume, admit: None }, cancelled) + .invoke(request, Mode::Dialogue { chain }, consume, admit_all, cancelled) .await?; ``` @@ -54,7 +54,7 @@ The file's entries declare both limits; a selection always carries them, so `res ### Errors -[Provider](Provider.md)'s kinds, minus `invalid_connection`, `invalid_path` and `output_limit`'s startup variants: `invalid` for a malformed request, `not_found` for a target missing from the file, `unavailable` for a media operation or a missing environment variable, `cancelled`, `closed`, `failed` and `provider_failed {retryable}`; `credential` has `not_found`, `unavailable`, `cancelled` and `closed`. +[Provider](Provider.md)'s kinds, minus `invalid_connection` and the startup-only ones: `invalid` for a malformed request, `not_found` for a target missing from the file, `unavailable` for a media operation or a missing environment variable, `cancelled`, `closed`, `failed` and `provider_failed {retryable}`; `credential` has `not_found`, `unavailable`, `cancelled`, `closed` and `failed`. ### Flows @@ -97,7 +97,7 @@ None. The model file and its validation are this owner's; no other owner's opera ## Binding appendix -`providerService` is [Provider](Provider.md)'s name; this profile registers the same name from `ConfiguredModels`. The types are shared, including `Credential` and `CredentialRequest` from [ManagedAccount](ManagedAccount.md); only the operations listed above exist. +`providerService` is [Provider](Provider.md)'s name; this profile registers the same name from `ConfiguredModels` (today `ConfiguredModelsPlugin`, with `AimuxModels` as its catalog, in `crates/dim-agent-aimux`; the delivery renames it to `ConfiguredModels`). The types are shared, including `Credential` and `StaticCredentialRequest` from [Provider](Provider.md) and [ManagedAccount](ManagedAccount.md); only the operations listed above exist. ```rust impl PublicService for ConfiguredModels {} @@ -106,8 +106,15 @@ impl PublicService for ConfiguredModels {} impl ConfiguredModels { pub async fn resolve(&self, request: ResolveRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn selectable(&self, request: SelectableRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn invoke( + &self, + request: ModelRequest, + mode: Mode, + consume: impl Fn(ProviderChunk) -> BoxFuture<'static, Result> + Send + Sync + 'static, + admit: impl Fn() -> BoxFuture<'static, Result> + Send + Sync + 'static, + cancelled: CancelledFn, + ) -> Result { /* ... */ } pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn credential(&self, request: StaticCredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } } ``` diff --git a/docs/design/plugins/DimOAuth.md b/docs/design/plugins/DimOAuth.md index bb07419599..29ee48d28d 100644 --- a/docs/design/plugins/DimOAuth.md +++ b/docs/design/plugins/DimOAuth.md @@ -80,12 +80,12 @@ The `account.*` namespace keeps its published methods; handlers call the same ow ### Flows -| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | -| --- | --- | --- | --- | --- | +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | | `credential` | Read the grant atomically when fresh; inside the 30-second window take the lock and refresh; answer the facts and the generation | The wait ends; a started refresh continues under the owner | The call ends `cancelled` | Pending calls end `closed`; a persisted grant stays | DimOAuth's refresh task | | `rejected` | Compare the generation; current → one serialized refresh, superseded → the current credential; a rejected refresh signs out the grant that holds the lock | The wait ends; the refresh continues | The call ends `cancelled` | Pending calls end `closed` | DimOAuth | -| `search` / `title` | Send the relay request with the current bearer; a 401 follows the same rule as `rejected` | The request is cancelled | Pending requests end `closed` | DimOAuth | -| `account.*` | Run the login flow or the account read; write the record through FileStorage; publish the result | The attempt is cancelled | Attempts end with the generation; a completed token rotation settles before unload | DimOAuth | +| `search` / `title` | Send the relay request with the current bearer; a 401 follows the same rule as `rejected` | The request is cancelled | The call ends `cancelled` | Pending requests end `closed` | DimOAuth | +| `account.*` | Run the login flow or the account read; write the record through FileStorage; publish the result | The attempt is cancelled | The attempt stays queryable until its deadline | Attempts end with the generation; a completed token rotation settles before unload | DimOAuth | ## Exceptions with reasons @@ -126,19 +126,66 @@ None. The `account.*` method names, fields, error codes and user-visible behavio - `service-faces.md`: the `managedSearch` row and §4.6, whose `search` this owner answers. - `crates/dim-app-server/README.md`: the managed provider contract's search paragraph; the account owner answers it directly. -- `plugins/SessionTitle.md` §3.3's `sessionTitleGenerator` name: the title operation is `dimAccount.title`. + ## Binding appendix -`DimOAuth` is the owner type; `dimAccount` is the wire name. The request and reply types are the [ManagedAccount](ManagedAccount.md) types plus the search and title types this crate already exports. +`DimOAuth` is the owner type; `dimAccount` is the wire name. The request and reply types are the [ManagedAccount](ManagedAccount.md) types plus these: ```rust +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchRequest { pub query: String, pub count: u32 } + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchHit { + pub title: String, + pub url: String, + pub snippet: String, + pub published_at: Option, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchReply { pub results: Vec } + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", content = "details", rename_all = "snake_case")] +pub enum SearchError { + #[error("{reason}")] Unavailable { reason: String }, + #[error("{0}")] Failed(String), + #[error("cancelled")] Cancelled, + #[error("the account owner is unloading")] Closed, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TitleRequest { pub provider: String, pub text: String } + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TitleReply { pub title: String } + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", content = "details", rename_all = "snake_case")] +pub enum TitleError { + #[error("{0}")] UnsupportedProvider(String), + #[error("{reason}")] Unavailable { reason: String }, + #[error("cancelled")] Cancelled, + #[error("the account owner is unloading")] Closed, + #[error("{0}")] Failed(String), +} + +// The delivery maps the search types to the facade's `WebSearchRequest`/`WebSearchResponse` and the +// title types to `GenerateTitleRequest`/`GenerateTitleReply`; the operation shapes above are the face. + impl PublicService for DimOAuth {} #[rutis::service(name = "dimAccount")] impl DimOAuth { pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn subscribe(&self, caller: &Ctx, notify: NotifyFn, cancelled: CancelledFn) -> Result<(), AccountError> { /* ... */ } pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn rejected(&self, request: RejectedRequest, cancelled: CancelledFn) -> Result { /* ... */ } diff --git a/docs/design/plugins/ImageUnderstanding.md b/docs/design/plugins/ImageUnderstanding.md index 295cf84d4f..bc738bb770 100644 --- a/docs/design/plugins/ImageUnderstanding.md +++ b/docs/design/plugins/ImageUnderstanding.md @@ -11,8 +11,8 @@ Images a Session receives — attachments ([Attachments](Attachments.md) A.1) an ([WorkspaceTools § read results and images](../../architecture/rust-agent/plugins/WorkspaceTools.md#read-results-and-images)) — reach the conversational model only as references, and the model asks about them through the `image_understand` tool. Which model answers is Modality's `modality.image.understand` target -([Modality](Modality.md) A.1), resolved by its owner and executed through the existing -`auxiliaryModel` host. The conversational model never receives image pixels, and the image's +([Modality](Modality.md) A.1), resolved by its owner and executed through +`providerService.invoke`. The conversational model never receives image pixels, and the image's stored content never changes. ## 1. Scope and non-goals @@ -21,7 +21,7 @@ Owns: - the `image_understand` tool: its declaration, its reference and question parameters, its reference resolution against the calling branch, its limits, errors and reuse; -- the request it hands to the `auxiliaryModel` host: the image, the question and the +- the request it hands to `providerService.invoke`: the image, the question and the instruction, and nothing else. Does not own: @@ -29,7 +29,7 @@ Does not own: - how an image block becomes a reference in a request — ModelProvider, stated in [Attachments](Attachments.md) A.1; - which model answers — Modality's `modality.image.understand` resolution; -- executing a provider call — Provider's connection and the `auxiliaryModel` host; +- executing a provider call — Provider's `invoke` and the connection it resolves; - the stored image and its authorization — the Timeline and the branch facade. ## 2. Own contract @@ -55,7 +55,7 @@ image_understand {image, question} v Modality: the modality.image.understand target |-- configured default unavailable -------------------------> image_model_unavailable (owner's reason) - |-- execution through auxiliaryModel -> answer -------------> result text + |-- execution through providerService.invoke -> answer ------> result text '-- provider, account or connection failure ----------------> image_understand_failed ``` @@ -125,7 +125,7 @@ the resulting target for that call and its retries. Explicit, configured default precedence, and the reason an unavailable target reports, are Modality's rule; this design consumes the answer. -Execution uses the `auxiliaryModel` host's named-binding form: the resolved model, an +Execution uses `providerService.invoke` with `Mode::Once`: the resolved model, an instruction fixed by this design (the request's `system`, not the Agent System), one user message carrying the image block and the question, and the output limit. The request carries no conversation, no tool definitions and no Session identity. The answer is text. @@ -165,7 +165,7 @@ owner changes its own document. - **Ordering impact.** None: composed per request with the other entries. - **Owner and issue.** Prompt, [#798](https://github.com/arcships/dim/issues/798). -**No requirement raised to Provider or the assembly.** The `auxiliaryModel` host already takes the model for one call ([AuxiliaryModel](../appserver/auxiliary-model.md)); the product assembly only installs this part next to the other Session parts. +**No requirement raised to Provider or the assembly.** `providerService.invoke` already runs one request with `Mode::Once` ([Provider](Provider.md)); the product assembly only installs this part next to the other Session parts. **M4 TimelineTree: published branch-chain queries for Session parts.** @@ -209,7 +209,7 @@ Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [A | §4.4 No business meaning in core | No core change: the tool is registered through `toolRegistry`, and the reference rule stays in ModelProvider as Attachments already owns it. | | §4.5 Atomic batches | The design writes no event itself; Loop's ordinary tool-call batch covers the call and its result. | | §4.6 Context only from handed-off events | The answer reaches the model only as a tool result; no injection during request preparation. | -| §4.7 Public events and services only | The part uses `toolRegistry`, `treeCommands.query` with published chain scope (§5 M4) to resolve a reference, the declared `auxiliaryModel` host, `sessionFiles` to read stored image bytes, `guideEntries` for its input-guide entry, and Modality's M1 read. | +| §4.7 Public events and services only | The part uses `toolRegistry`, `treeCommands.query` with published chain scope (§5 M4) to resolve a reference, Provider's `invoke`, `sessionFiles` to read stored image bytes, `guideEntries` for its input-guide entry, and Modality's M1 read. | | §4.8 Requirements to mechanism owners | §5, M1–M4. The existing TimelineTree query gains published chain scope; no new runtime or rutis mechanism. | | §4.9 Only facts later decisions use enter the Timeline | Only the ordinary tool facts enter; the digest index is derived and discarded. | | §1 Capability and App Server boundary | A Session Capability in its own crate; the App Server only installs it. | diff --git a/docs/design/plugins/ManagedAccount.md b/docs/design/plugins/ManagedAccount.md index e76c71c495..79e4cedac8 100644 --- a/docs/design/plugins/ManagedAccount.md +++ b/docs/design/plugins/ManagedAccount.md @@ -51,8 +51,18 @@ Web follows the Dim account's availability: ```rust let AccountAvailability { signed_in, .. } = account.availability(cancelled.clone()).await?; -let mut changes = account.subscribe(cancelled.clone()).await?; -while let Some(available) = changes.next().await { /* declare or withdraw web_search */ } +account + .subscribe( + &self.ctx, + Arc::new(|availability: AccountAvailability| { + Box::pin(async move { + // Declare or withdraw web_search from `availability.signed_in`. + Ok(()) + }) + }), + cancelled.clone(), + ) + .await?; ``` The client namespace is the same owner's operations behind the client protocol; no part calls it. @@ -76,7 +86,7 @@ All operations are marked on the owner type and provided under the owner's face | Operation | Intent | Request | Reply | Cancellation, timeout | Errors | | --- | --- | --- | --- | --- | --- | | `availability` | Whether the account is signed in | `{}` | `{signed_in, identity?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | -| `subscribe` | Follow availability changes | `{}` | `{subscription}` | The subscription ends with the caller's row | `closed` | +| `subscribe` | Follow availability changes | `caller`, a `notify` callback | `{}` | The registration ends with the calling row or the owner's close; a call cancelled before registration changes nothing | `cancelled`, `closed` | | `catalog` | The models the plan serves | `{}` | `{account, models}` | The caller cancels; a catalog read may wait on the account's own refresh | `unavailable`, `cancelled`, `closed`, `failed` | | `credential` | The connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation}`; a read inside the refresh window refreshes first | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `unavailable`, `cancelled`, `closed`, `failed` | | `rejected` | The generation the provider refused; answer the credential to retry with | `{provider, generation}` | A credential; the current generation refreshes once, a superseded generation answers the current credential | The caller cancels; a refresh already started finishes under the owner | `not_found`, `account_required`, `unavailable`, `cancelled`, `closed`, `failed` | @@ -91,15 +101,15 @@ All operations are marked on the owner type and provided under the owner's face ### Errors -| Kind | What the caller does next | -| --- | --- | -| `not_found` | The provider is not this owner's; re-read the record | -| `account_required` | Sign in: the account is signed out, or the refresh it attempted was rejected | -| `unavailable` | The plan or the relay cannot serve the model now; the message names the reason | -| `unsupported_provider` | This owner does not serve that provider; use the owner the record names | -| `cancelled` | Nothing changed; the call stopped where it was cancelled | -| `closed` | This generation is unloading; call the next generation | -| `failed` | The account store or the provider request failed; retry the business step | +| Kind | Retry | What the caller does next | +| --- | --- | --- | +| `not_found` | No | The provider is not this owner's; re-read the record and use the owner it names | +| `account_required` | After sign-in | The account is signed out, or the refresh was rejected; the client signs in, then the caller calls again | +| `unavailable` | After the account changes | The plan or the relay cannot serve the model now; the message names the reason | +| `unsupported_provider` | No | This owner does not serve that provider; use the owner the record names | +| `cancelled` | Yes, by calling again | Nothing changed; the call stopped where it was cancelled | +| `closed` | Against the next generation | This generation is unloading; call the replacement generation | +| `failed` | Yes, after the store or provider recovers | The account store or the provider request failed; retry the business step | ### Flows @@ -108,6 +118,7 @@ All operations are marked on the owner type and provided under the owner's face | `availability`, `subscribe` | Read the account state; publish the value and its changes | The read stops; a subscription ends | The subscription ends | The watch is rebuilt from the store; subscribers end | The owner | | `catalog` | Read the grant, refresh if inside the window, project the plan's models | The wait ends; the owner's refresh continues | The call ends `cancelled` | Pending calls end `closed`; the next generation re-reads | The owner's refresh task | | `credential` | Read the grant, refresh if inside the window, answer the facts and the generation | The wait ends; a started refresh continues | The call ends `cancelled` | Pending calls end `closed`; a persisted grant stays | The owner's refresh task | +| `subscribe` | Register the callback under the calling row and publish the current value once | Before registration; nothing registered | The registration ends with the row | The registration ends; no further values | The owner: the registration; the row: its lifetime | | `rejected` | Compare the generation, refresh once or answer the current credential, or apply the sign-out rule | The wait ends; a started refresh continues | The call ends `cancelled` | Pending calls end `closed` | The owner | | `search` / `title` | Send the relay request with the grant's bearer | The request is cancelled | The call ends `cancelled` | Pending requests end `closed` | The owner | | Client namespace | Run the login flow, write the record through FileStorage and publish the result | The attempt is cancelled | The attempt stays queryable until its deadline | Attempts end with the generation | The owner | @@ -152,8 +163,10 @@ None. The `account.*`, `account.codex.*`, `account.grok.*` and `account.chatgpt. Shared request, reply and error types; each owner's `#[rutis::service]` block is in its own document. `CancelledFn` is the binding's cancellation argument. ```rust -use dim_agent_capabilities::host::CancelledFn; -use rutis::host::BoxFuture; +use dim_agent_capabilities::host::{CancelledFn, ModelProtocol}; +use dim_agent_types::ModelCapabilitySnapshot; +use rutis::host::{BoxFuture, CallError}; +use rutis::Ctx; use std::collections::BTreeMap; use std::sync::Arc; @@ -165,6 +178,21 @@ pub struct AccountIdentity { pub issuer: String, pub subject: String } #[serde(rename_all = "camelCase")] pub struct AccountAvailability { pub signed_in: bool, pub identity: Option } +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountSnapshot { pub generation: u64, pub identity: AccountIdentity } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountCatalog { + pub account: AccountSnapshot, + pub models: Vec, +} + +/// The owner calls this with each availability change while the calling row lives. +pub type NotifyFn = + Arc BoxFuture<'static, Result<(), CallError>> + Send + Sync>; + #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct CredentialRequest { pub provider: String, pub model: String } @@ -180,11 +208,12 @@ pub struct Credential { pub base_url: String, pub headers: BTreeMap, pub bearer: String, - pub generation: u64, + /// The grant generation; `None` for a static credential a profile owner answers. + pub generation: Option, } /// The wire code is the variant's snake_case name; `details` carries its data. -#[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] +#[derive(Debug, serde::Serialize, thiserror::Error)] #[serde(tag = "code", content = "details", rename_all = "snake_case")] pub enum AccountError { #[error("{0}")] NotFound(String), @@ -197,10 +226,11 @@ pub enum AccountError { } ``` -`Subscription` is the owner's replayable watch over availability; it ends when the calling row unloads or the owner closes. +The `notify` callback is invoked once with the current value when the registration starts, then on every change until the calling row unloads or the owner closes; it is not called inside a commit lock. ## Supersedes - `service-faces.md`: the `grokOAuthService` and `openAICodexOAuthService` rows; the `managedSearch` row and §4.6, which the account owners' `search` replaces. - `appserver/provider-management.md`: the account rows in §2 and §3.1 that describe the account catalog and status as reported by a host binding. - `crates/dim-app-server/README.md`: the managed provider contract's account and lease paragraphs; the account owners answer them directly. +- `resource-faces.md` §6: the managed OAuth and OAuth token store row, whose `lock`/`unlock` shape the account owner's FileStorage `read`/`update`/`write` replaces. diff --git a/docs/design/plugins/ManagedOAuth.md b/docs/design/plugins/ManagedOAuth.md index fc494f2863..e6fcb3efd4 100644 --- a/docs/design/plugins/ManagedOAuth.md +++ b/docs/design/plugins/ManagedOAuth.md @@ -107,7 +107,7 @@ impl PublicService for OpenAICodexOAuthService {} #[rutis::service(name = "codexAccount")] impl OpenAICodexOAuthService { pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn subscribe(&self, caller: &Ctx, notify: NotifyFn, cancelled: CancelledFn) -> Result<(), AccountError> { /* ... */ } pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn rejected(&self, request: RejectedRequest, cancelled: CancelledFn) -> Result { /* ... */ } diff --git a/docs/design/plugins/ManagedProviders.md b/docs/design/plugins/ManagedProviders.md index ac587f9fd6..b7b80e4bd6 100644 --- a/docs/design/plugins/ManagedProviders.md +++ b/docs/design/plugins/ManagedProviders.md @@ -100,7 +100,7 @@ None. The `account.chatgpt.*` method names, fields, error codes and user-visible ## Requirements raised to mechanism owners - **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for the ChatGPT account record. -- **Storage owner ([#2018](https://github.com/arcships/dim/issues/2018)).** Provider reads a Session's creation record through `store.creationRecord` to require an interactive client Session for this provider; the requirement is stated in [Provider](Provider.md)'s requirements. +- **SessionStore ([#2091](https://github.com/arcships/dim/pull/2091)).** Provider reads a Session's creation record through `creationRecord` to require an interactive client Session for this provider; the requirement is stated in [Provider](Provider.md)'s requirements. ## Supersedes @@ -115,7 +115,7 @@ impl PublicService for ChatGptAccount {} #[rutis::service(name = "chatgptAccount")] impl ChatGptAccount { pub async fn availability(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn subscribe(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn subscribe(&self, caller: &Ctx, notify: NotifyFn, cancelled: CancelledFn) -> Result<(), AccountError> { /* ... */ } pub async fn catalog(&self, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn credential(&self, request: CredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn rejected(&self, request: RejectedRequest, cancelled: CancelledFn) -> Result { /* ... */ } diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 9d5d97d89c..6d4390e1c9 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -40,10 +40,10 @@ All dependencies are process services at the same scope ([ADR 002 D3](../../adr/ | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | -| `Modality` | Process (control node) | Provider model selection (`ModelSelectionHost`) and non-conversational connection resolution; `pluginFiles` (UTF-8 and binary), `fsHost.readAt/closeRead` for opened readers; Settings business source `modality`; the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, A.2); HostPlatform of the control node (OCR); diagnostics | `modalityTasks` and `modalityTargets` process services; registers `modality` (`modality.*`) with `managementMethods` | +| `Modality` | Process (control node) | Provider's `providerService.resolve`/`selectable` and, for adapters, `media_route` plus the credential owner's `credential`; `pluginFiles` (UTF-8 and binary), `fsHost.readAt/closeRead` for opened readers; Settings business source `modality`; the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, A.2); HostPlatform of the control node (OCR); diagnostics | `modalityTasks` and `modalityTargets` process services; registers `modality` (`modality.*`) with `managementMethods` | | Adapter plugins | Process | their own provider dependencies | `modalityAdapter` provider copies at their provider ids; the built-in supplies only the family fallback (A.2) | -**Contracts depended on:** the [methods](../contracts/session-boundary.md) contract (namespaces registered with `managementMethods`, per-call progress sink, connection-bound notifications); the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, §1 and A.2); Provider's model selection (`ResolveModelSelection::resolve`, which rejects an unselectable explicit model; [AuxiliaryModel](../appserver/auxiliary-model.md)), its selectable-model read for the option list (§9.2), and, for every adapter operation and realtime session, its non-conversational connection resolution ([overview Appendix B.2](../overview.md#b2-app-server-process-plugins), §9.3); `pluginFiles` (extended) with binary atomic replace and a format version ([App Server README](../../../crates/dim-app-server/README.md#trusted-plugin-storage)); HostPlatform spawn with isolation ([HostPlatform](../../architecture/rust-agent/plugins/HostPlatform.md), isolation supplement in [overview Appendix B.1](../overview.md#b1-session-and-branch-capabilities)). +**Contracts depended on:** the [methods](../contracts/session-boundary.md) contract (namespaces registered with `managementMethods`, per-call progress sink, connection-bound notifications); the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, §1 and A.2); Provider's `resolve` (which rejects an unselectable explicit model; [Provider](Provider.md)), its `selectable` read for the option list (§9.2), and, for every adapter operation and realtime session, `media_route` plus the credential owner's `credential` (§9.3); `pluginFiles` (extended) with binary atomic replace and a format version ([App Server README](../../../crates/dim-app-server/README.md#trusted-plugin-storage)); HostPlatform spawn with isolation ([HostPlatform](../../architecture/rust-agent/plugins/HostPlatform.md), isolation supplement in [overview Appendix B.1](../overview.md#b1-session-and-branch-capabilities)). **Contracts defined here:** category and operation identifiers; default keys `modality.` and `modality..` in the `modality` settings document (Modality's own; Provider holds none); the `modalityAdapter` and `modalityTasks` services (A.2 and A.3; `modalityAdapter` is an in-process Rust binding today because its calls carry the non-serializable `ModalityConnection`, while `modalityTasks` is language-neutral; Rust binding in Appendix G); the `modality` settings document and its schema; task record and result formats (format version 1); the `modality.*` methods and the `modality.realtime.event` and `modality.realtime.ended` notifications. Provider knows nothing about modalities; Modality knows no provider-specific semantics outside its adapters. ## 2. Data and state @@ -293,7 +293,7 @@ Adapter capability derivation uses the selected copy's `available` and `operatio ### 9.2 Provider read-only contract - **Problem.** `modality.capabilities` must compute `options` and automatic resolution from the models Provider can select. Provider's model-selection port resolves one model, and the catalog reads are client management methods, so a process owner cannot enumerate the selectable set with its declared capabilities. -- **Existing mechanisms.** The single-model selection port cannot filter by an operation's capability. A new client method would expose management to the owner and duplicate the catalog. The Provider-side read-only contract is tracked separately by [#790](https://github.com/arcships/dim/issues/790). Delivered: the process host port `SelectableModelsHost` in `dim-agent-capabilities`, provided by Provider and by the configured model profile, whose `selectableModels` read enumerates the models execution would accept with their declared capabilities. +- **Existing mechanisms.** The single-model selection port cannot filter by an operation's capability. A new client method would expose management to the owner and duplicate the catalog. The Provider-side read-only contract is tracked separately by [#790](https://github.com/arcships/dim/issues/790). Delivered by the owner contract: `providerService.selectable` ([Provider](Provider.md)) enumerates the models execution would accept with their declared capabilities, in both profiles. - **Needed capability.** That read is shaped for execution: a model without a `text` modality, a non-chat model and a model whose text limits are undeclared never appear, so the image, video, speech, music, audio, asset, motion and realtime models Modality routes to are all missing. Provider adds one read to the same port, `selectableForModality`, returning each model it would select for a non-conversational use with the `.` ids its catalog entry declares. It applies the same provider, account, model, route, credential and status rules as `selectableModels`, without those three chat requirements. - **Ordering impact.** Read at each `capabilities` call and task submission; no reload and no Timeline. - **Owner/issue.** Provider, [#790](https://github.com/arcships/dim/issues/790) and this change. @@ -302,7 +302,7 @@ Adapter capability derivation uses the selected copy's `available` and `operatio - **Problem.** Image generation and editing adapters need a model's endpoint, protocol and credential material per call. Provider resolves connections only for a `ModelRequest`. - **Existing mechanisms.** `ProviderConnectionResolver` is tied to `ModelRequest`; adapters cannot own Provider credentials, and Modality must not store them. -- **Needed capability.** A per-call resolution of a model's non-conversational connection, owned by Provider, used only for that call and never persisted or returned to a client. Provider defines the contract on its own page ([provider management §3.6](../appserver/provider-management.md#36-selectable-models-for-process-owners)): the input, the reply, the selectability and credential rules, and the lifetime. The port is `ResolveModalityConnection` and `ModalityConnectionHost` in `dim-agent-capabilities` with `ModalityTarget` carrying the model identity and the operation; Modality resolves it per adapter call (`submit`, `wait`, `cancel_remote`) and passes the connection to the adapter. Adapters call it and hold no credentials. +- **Needed capability.** A per-call resolution of a model's non-conversational connection, owned by Provider, used only for that call and never persisted or returned to a client. Provider defines the contract on its own page ([Provider](Provider.md)): `media_route({target, operation})` gives the protocol, base URL and headers plus the credential owner, and that owner's `credential` gives the value for one call. The adapter resolves it per call (`submit`, `wait`, `cancel_remote`) and holds no credential beyond the call. - **Ordering impact.** Resolved at submit; no reload; credentials never enter task records, results, diagnostics or errors. - **Owner/issue.** Provider, [#799](https://github.com/arcships/dim/issues/799). diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md index 14d7f0b858..2143918904 100644 --- a/docs/design/plugins/Provider.md +++ b/docs/design/plugins/Provider.md @@ -21,7 +21,7 @@ Callers keep: - Which model a Session adopts and when it changes; Provider answers the selection and the caller writes the Session's configuration. - The request's messages, system prompt, tools and metadata; Provider adapts and sends what the caller built. - What the output means: ModelProvider commits the stream to the Timeline and decides the turn's end; a one-shot caller collects the text. -- The summary budget and the retry display: the caller passes an `admit` callback and observes progress. +- The summary budget and the retry display: the caller passes an `admit` callback and receives `Retrying` chunks. - Account login, logout and usage: the account owners' client namespaces, not Provider. - Which search service a tool uses: Web's own settings, with the account owner's availability read. @@ -35,7 +35,7 @@ Callers keep: | Learn a media model's route and where its credential comes from (the media executor) | No: the route is catalog state; the credential owner is the record's authority | `media_route` | | Read a static model's credential for one media exchange (the media executor) | No: the record, the route and the credential are Provider's | `credential` | | Read or write a Provider's management record | No: records, versions and transactions are Provider's | The `provider` client namespace; handlers call the same operations | -| Show a retry countdown | Yes: the `invoke` progress callback | Business | +| Show a retry countdown | Yes: the `Retrying` chunk | Business | | Learn where the recorder writes | Yes: read ModelLog's `recording` value | Business | | Decide the prompt, tools or output handling | Yes | Business | | Decide whether a search is offered | Yes: read the account owner's availability | Business | @@ -91,7 +91,7 @@ ModelProvider runs a turn; `consume` is the branch part's own callback that writ ```rust let reply = provider - .invoke(request, Mode::Dialogue { chain: failure_chain }, consumer, None, cancelled.clone()) + .invoke(request, Mode::Dialogue { chain: failure_chain }, consumer, admit_all, cancelled.clone()) .await?; ``` @@ -99,7 +99,7 @@ The summary strategy runs with its own budget: ```rust provider - .invoke(request, Mode::Dialogue { chain: None }, consume, Some(budget), cancelled) + .invoke(request, Mode::Dialogue { chain: None }, consume, budget, cancelled) .await?; ``` @@ -108,7 +108,7 @@ SessionTitle and ImageUnderstanding run one request and keep the text: ```rust let selection = provider.resolve(ResolveRequest { target: Some(model), cwd: None }, cancel.clone()).await?; let reply = provider - .invoke(ModelRequest::from(selection, messages), Mode::Once, collect_text, None, cancel) + .invoke(ModelRequest::from(selection, messages), Mode::Once, collect_text, admit_all, cancel) .await?; ``` @@ -137,8 +137,8 @@ provider.release_startup(&self.ctx, ReleaseRequest { model: selection }).await?; | --- | --- | --- | | ProviderSettings ([#2017](https://github.com/arcships/dim/issues/2017)) | `user_agent` | The operator's User-Agent replacement | | ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)) | `recording` | The recorder's directory | -| FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)) | `root_path` | The directory the wire recorder writes under | -| Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) | private transaction primitive; the public face keeps `storageReport` and the offline operations | Provider's records, selections, candidates, pages, source activation, adoption, edit commits, legacy import and `store.creationRecord` | +| Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) | private transaction primitive; the public face keeps `storageReport` and the offline operations | Provider's records, selections, candidates, pages, source activation, adoption, edit commits and legacy import | +| SessionStore ([#2091](https://github.com/arcships/dim/pull/2091)) | `creationRecord({id})` | The ChatGPT client-session rule | | Session directory ([#2020](https://github.com/arcships/dim/issues/2020)) | session close observation | Releasing a retained startup source | | Account owners ([ManagedAccount](ManagedAccount.md)) | `availability`, `catalog`, `credential`, `rejected` | Account-backed models; the record's authority names the owner | @@ -152,31 +152,31 @@ All operations are marked on `Provider` and provided under `providerService`; re | --- | --- | --- | --- | --- | --- | | `resolve` | The model one request resolves to | `{target?, cwd?}` | `Selection` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `preferences` | Apply a patch to an adopted selection | `{selection, update}` | `Selection` | None; completes immediately | `invalid` | -| `selectable` | The models that can run a use, and the default | `{use: "chat" \| {modality}}` | `{models, default?}` | The caller cancels; no timeout | `cancelled`, `closed`, `failed` | +| `selectable` | The models that can run a use, and the default | `{use: "chat" \| {modality}}` | `{models, default?}` | The caller cancels; no timeout | `invalid`, `cancelled`, `closed`, `failed` | | `prepare_startup` | Admit a temporary connection under the calling row and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `{selection}` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `retain_startup` | Bind the temporary connection the model carries to a Session | `{session, model}` | `{}` | None; completes immediately | `not_found` (the model carries no source, or the source is not bound), `closed` | | `release_startup` | Release a source the calling row owns | `caller`, `{model}` | `{}` | None; completes immediately | `not_found` (already retained by a Session, or another row's), `closed` | -| `invoke` | Run one model request | `request`, `mode`, and the `consume` / optional `admit` callbacks as direct parameters | `{accepted}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed`, `provider_failed {retryable}` | +| `invoke` | Run one model request | `request`, `mode`, and the `consume` / `admit` callbacks as direct parameters | `{accepted}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed`, `provider_failed {retryable}` | | `media_route` | A media model's route and the owner of its credential | `{target, operation}` | `{protocol, base_url, headers, realtime?, credential: Owner}` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | | `credential` | A static model's connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation: none}` | The caller cancels; no timeout | `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | `prepare_startup` admits the source under the calling row; the row's unload releases it, so a missed `retain_startup` or `release_startup` settles with the row. `retain_startup({session, model})` moves the source to the Session named by the caller and the model's metadata; the Session's close releases it, so a missed failure-path release settles with the Session. `release_startup({model})` is the optional early release for a creation that failed; it answers `not_found` once a Session retains the source. A member Session that inherits the leader's model retains the same source by value. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Credential` is [ManagedAccount](ManagedAccount.md)'s value: static credentials carry no generation; an account owner's carry the grant's. `invoke` calls the account owner's `credential`, sends, and on a refusal calls `rejected` with the refused generation before retrying within its own failure chain. -`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits through the optional `admit`/progress callbacks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(chunk)` reports `Continue`, `End`, `CredentialRejected` (the provider refused the credential, so `invoke` calls the account owner's `rejected` once and retries) or `Failed { retryable }`; output accepted before a failure prevents replay, and the reply's `accepted` says whether any output was accepted. `admit` runs before each attempt and answers `Admitted` or `Rejected { message }`; only a caller with its own budget passes it. Both callbacks are direct parameters, so the request data stays serde-only. +`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits as `Retrying` chunks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(chunk)` reports `Continue`, `End`, `CredentialRejected` (the provider refused the credential, so `invoke` calls the account owner's `rejected` once and retries) or `Failed { retryable }`; output accepted before a failure prevents replay, and the reply's `accepted` says whether any output was accepted. `admit` runs before each attempt and answers `Admitted` or `Rejected { message }`; a caller without its own budget passes `admit_all`, the binding's default that admits every attempt. Both callbacks are direct parameters, so the request data stays serde-only. A request for `openai-chatgpt` requires a client-origin Session: Provider reads the Session's creation record (`creationRecord`) and answers `invalid` for a non-client Session. ### Errors -| Kind | What the caller does next | -| --- | --- | -| `invalid` | Fix the input: an unknown use, an explicit target missing its model, a malformed preference patch | -| `invalid_connection` | Fix the startup connection: a rejected URL, user info, query, fragment, both an API key and a bearer, or an unsupported auth | -| `not_found` | The provider, model or source does not exist; re-read or choose another | -| `unavailable` | The model cannot run now; the message names the reason; choose another model or fix the record | -| `auth_required` | Sign in through the account owner named by the record, then retry | -| `cancelled` | Nothing changed; the call stopped where it was cancelled | -| `closed` | This generation is unloading; call the next generation | -| `failed` | Provider's storage or a catalog read failed; retry the read | -| `provider_failed {retryable}` | The request failed after the owner's retries; `retryable` says whether a new `invoke` can succeed | +| Kind | Retry | What the caller does next | +| --- | --- | --- | +| `invalid` | No | Fix the input: an unknown use, an explicit target missing its model, a malformed preference patch, or a non-client Session for the ChatGPT provider | +| `invalid_connection` | No | Fix the startup connection: a rejected URL, user info, query, fragment, both an API key and a bearer, or an unsupported auth | +| `not_found` | No | The provider, model or source does not exist; re-read the record or choose another | +| `unavailable` | After the model or account changes | The model cannot run now; the message names the reason; choose another model or fix the record | +| `auth_required` | After sign-in | Sign in through the account owner named by the record, then call again | +| `cancelled` | Yes, by calling again | Nothing changed; the call stopped where it was cancelled | +| `closed` | Against the next generation | This generation is unloading; call the replacement generation | +| `failed` | Yes, after the store recovers | Provider's storage or a catalog read failed; retry the read | +| `provider_failed {retryable}` | When `retryable` | The request failed after the owner's retries; `retryable` says whether a new `invoke` can succeed | ### Flows @@ -226,28 +226,35 @@ None. The `provider.*` client method names, request and reply fields, error code ## Requirements raised to mechanism owners -- **Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)).** The engine's public face keeps only `storageReport` and the offline operations. Provider owns its records, selection, preferences, candidate and page queries, source activation, adoption, edit commits, legacy import and `store.creationRecord`; the engine supplies the private transaction primitive inside this crate, which is not a public operation. +- **Storage engine ([#2018](https://github.com/arcships/dim/issues/2018)).** The engine's public face keeps only `storageReport` and the offline operations. Provider owns its records, selection, preferences, candidate and page queries, source activation, adoption, edit commits and legacy import; the engine supplies the private transaction primitive inside this crate, which is not a public operation. +- **SessionStore ([#2091](https://github.com/arcships/dim/pull/2091)).** `creationRecord({id})` for the ChatGPT client-session rule; SessionStore owns the record. - **ProviderSettings and ModelLog ([#2017](https://github.com/arcships/dim/issues/2017)).** Their owner contracts define `user_agent` and `recording`; Provider reads both at request time. No requirement remains. - **Session directory ([#2020](https://github.com/arcships/dim/issues/2020)).** Provider needs a close observation for a retained startup source: when the Session closes without unload, the source is released; an unload keeps it for restore. -- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `root_path` only; the recorder owns its JSONL file. - **Account owners ([ManagedAccount](ManagedAccount.md)).** `availability`, `catalog`, `credential`, `rejected`; the face name comes from the record's credential authority. - **Media executor (Modality's adapter contract).** The adapter resolves `media_route` and reads the credential from the owner it names; Modality passes the target and settles the task, so no business caller holds a credential. The adapter's service shape is Modality's contract. +- **Id routing ([#2127](https://github.com/arcships/dim/issues/2127)).** The line-owner calls in the caller examples use the runtime's id routing; this contract raises no new mechanism requirement. ## Binding appendix -`Provider` is the owner type; `providerService` is the wire name. `CancelledFn` is the binding's cancellation argument. The request and reply types are serde data; `consume` and `admit` are direct call parameters, never request fields. +The owner type is `ProviderService` today (`crates/dim-app-server/src/provider.rs`; the delivery renames it to `Provider`). `providerService` is the wire name. `CancelledFn` is the binding's cancellation argument. The request and reply types are serde data; `consume` and `admit` are direct call parameters, never request fields. ```rust -use dim_agent_capabilities::host::{CancelledFn, ModelChunk, ModelProtocol, RealtimeDeclaration}; +use dim_agent_capabilities::host::{ + CancelledFn, ModelProtocol, ModelStopReason, RealtimeDeclaration, +}; use dim_agent_runtime::PublicService; -use rutis::host::BoxFuture; -use std::collections::BTreeMap; -use std::sync::Arc; +use dim_agent_types::FailureChain; use dim_agent_types::{ - ModalityModelSnapshot, ModelCapabilitySnapshot, ModelId, ModelPreferences, ModelRequest, - ModelSelection, + MessagePart, ModalityModelSnapshot, ModelCapabilitySnapshot, ModelId, ModelPreferences, + ModelRequest, ModelSelection, ToolCall, Usage, }; +use rutis::host::{BoxFuture, CallError}; use rutis::Ctx; +use std::collections::BTreeMap; +use std::sync::Arc; +// `Credential` is the shared account value defined in ManagedAccount.md; the delivery places it in +// the account module both owners use. +use crate::account::Credential; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -273,7 +280,7 @@ pub struct SelectableReply { } #[derive(serde::Serialize, serde::Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase")] +#[serde(tag = "kind", content = "models", rename_all = "camelCase")] pub enum SelectableModels { Chat(Vec), Modality(Vec) } #[derive(serde::Serialize, serde::Deserialize)] @@ -308,14 +315,26 @@ pub struct RetainRequest { pub session: String, pub model: ModelSelection } #[serde(rename_all = "camelCase")] pub struct ReleaseRequest { pub model: ModelSelection } -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FailureChain { pub from_request_id: String, pub attempts: u32, pub waited_ms: u64 } - #[derive(serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum Mode { Dialogue { chain: Option }, Once } +/// One streamed fact for the consumer, serialized to the wire; the delivery maps each variant to +/// its `step/*` event. +#[derive(serde::Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum ProviderChunk { + Text { delta: String }, + Thinking { delta: String }, + ToolStart { id: String, name: String }, + ToolArguments { id: String, delta: String }, + ToolUse { call: ToolCall }, + Content { parts: Vec }, + Stop { reason: ModelStopReason }, + Usage { usage: Usage }, + Retrying { attempt: u32, delay_ms: u64 }, +} + /// What the consumer reports for one chunk; `CredentialRejected` asks the owner to recover once. #[derive(serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] @@ -325,9 +344,6 @@ pub enum Consumed { Continue, End, CredentialRejected, Failed { retryable: bool #[serde(tag = "kind", rename_all = "camelCase")] pub enum Admitted { Admitted, Rejected { message: String } } -pub type ConsumeFn = Arc BoxFuture<'static, Consumed> + Send + Sync>; -pub type AdmitFn = Arc BoxFuture<'static, Admitted> + Send + Sync>; - #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct InvokeReply { pub accepted: bool } @@ -354,10 +370,9 @@ pub struct MediaRouteReply { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct StaticCredentialRequest { pub provider: String, pub model: String } -// `Credential` is the shared value in ManagedAccount.md; a static credential carries no generation. /// The wire code is the variant's snake_case name; `details` carries its data. -#[derive(thiserror::Error, serde::Serialize, serde::Deserialize)] +#[derive(Debug, serde::Serialize, thiserror::Error)] #[serde(tag = "code", content = "details", rename_all = "snake_case")] pub enum ProviderError { #[error("{0}")] Invalid(String), @@ -369,7 +384,6 @@ pub enum ProviderError { #[error("provider is unloading")] Closed, #[error("{0}")] Failed(String), #[error("{message}")] ProviderFailed { retryable: bool, message: String }, - #[error("{0}")] InvalidPath(String), } impl PublicService for Provider {} @@ -382,17 +396,17 @@ impl Provider { pub async fn prepare_startup(&self, caller: &Ctx, request: StartupRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn retain_startup(&self, request: RetainRequest) -> Result<(), ProviderError> { /* ... */ } pub async fn release_startup(&self, caller: &Ctx, request: ReleaseRequest) -> Result<(), ProviderError> { /* ... */ } - pub async fn invoke(&self, request: ModelRequest, mode: Mode, consume: ConsumeFn, admit: Option, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn invoke( + &self, + request: ModelRequest, + mode: Mode, + consume: impl Fn(ProviderChunk) -> BoxFuture<'static, Result> + Send + Sync + 'static, + admit: impl Fn() -> BoxFuture<'static, Result> + Send + Sync + 'static, + cancelled: CancelledFn, + ) -> Result { /* ... */ } pub async fn media_route(&self, request: MediaRouteRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn credential(&self, request: StaticCredentialRequest, cancelled: CancelledFn) -> Result { /* ... */ } } ``` The `provider` client namespace keeps its published method names and request shapes; handlers call the operations above and the management operations. No management operation is also published on `providerService`. - -## Supersedes - -- `service-faces.md`: the `modelHost` row and §4.2; the `providerService` and `providerConnectionResolver` rows; the `managedSearch` row where it names Provider; the Provider selection block in §4.10. -- `contracts/process-owner-operations.md`: the model selection, session configuration, session creation/adoption, model invocation and auxiliary rows, and the `modelHost` paragraph. -- `appserver/provider-management.md`: the surface-table rows for `ModelSelectionHost`, `SelectableModelsHost`, `ProviderConnectionResolver`, `ModalityConnectionHost` and `auxiliaryModel.complete`, and the port sections §3.6 and §3.8. -- `appserver/auxiliary-model.md`: the `auxiliaryModel` interface in §4, replaced by `invoke`. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 8f891133b6..6d95b2dc3d 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -845,7 +845,8 @@ The owners that read node files or start node processes, and the operations they | WorkspaceTools file tools | `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions` | | SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`, `execHost.removeOutputDirectory` | | Settings sources and their CAS writes | `readBytes`, `stat`, `lock`, `readBytes {leaseId}`, `replace {leaseId}`, `unlock` | -| MCP auth store, managed OAuth and OAuth token stores | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | +| MCP auth store | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | +| Managed OAuth and OAuth token stores | `read`, `update`, `write`; the account owner answers [ManagedAccount](../plugins/ManagedAccount.md) | | Hooks project file (`.dimcode/hooks.json`) | `stat`, `readBytes` | | PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | | UI extension resources | `stat`, `openRead`, `readAt`, `closeRead` | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index b10cca1ee5..ceac8e932b 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -352,7 +352,7 @@ providerService.selectable({use}) -> {models, default?} -> error {code: invalid | not_found | unavailable | auth_required | cancelled | closed | failed, message} ``` -- 每个 operation 只收一个请求对象;没有输入的写 `{}`(`provider-management.md` §3.6 的形状),多一个参数或未知字段都是 `invalid_request`。 +- 每个 operation 只收一个请求对象;没有输入的写 `{}`,多一个参数或未知字段都是 `invalid`。 - 取消是协议动作:调用方丢弃等待,或被取消的绑定调用不再进入 owner;owner 自己的生命周期仍然约束它启动的 worker。 - 回复就是 owner 的类型:`ExecutionSettings`、`PromptSuggestionSettings`、`ModelCapabilitySnapshot`、`ModalityModelSnapshot`、`ModelSelection` 都是 serde camelCase 数据,形状与 [Provider](plugins/Provider.md) 的操作一致。`InstalledToolchain` 的 `PathBuf` 换成 UTF-8 字符串(`{bin, root}`):某个 runtime 的目录不是 UTF-8 时只跳过那一项,其余照常给子进程用。 - 提供方仍是原来的部件(App Server 的 `ExecutionSettings`、`ToolchainSource`、`PromptSuggestionSettings`、`Provider`,以及 aimux 的 `ConfiguredModels`):`provide` 一次给出类型键上的绑定和 `host_key(name)` 上的 face;没有适配层,也没有第二份业务逻辑。 From 7cc7e874e2e1a5b106486f68785fd16aad476309 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 13:31:00 +0800 Subject: [PATCH 7/9] design(provider): return the failure facts and align the retained pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `invoke` returns the updated `FailureChain` on success and `provider_failed { failure, chain }` on failure, so ModelProvider writes the runtime `ModelFailure` facts and the retry totals into `step/model-output-end`. Define the exported `admit_all`, and use the bare `ModelSelection` for `prepare_startup` everywhere. Restore the Supersedes section and update the retained pages the review named: the model invocation table in the process-owner contract, the DimOAuth subscribe example, the auxiliary-model migration note, the provider-management relation paragraph, and Modality's and ImageUnderstanding's selectable reads. Refs #2019 · Refs #2015 --- docs/design/appserver/auxiliary-model.md | 2 +- docs/design/appserver/provider-management.md | 18 +++++------ .../contracts/process-owner-operations.md | 11 ++++--- docs/design/plugins/DimOAuth.md | 16 ++++++++-- docs/design/plugins/ImageUnderstanding.md | 2 +- docs/design/plugins/Modality.md | 4 +-- docs/design/plugins/Provider.md | 31 ++++++++++++++----- 7 files changed, 57 insertions(+), 27 deletions(-) diff --git a/docs/design/appserver/auxiliary-model.md b/docs/design/appserver/auxiliary-model.md index 9fccd6ccfe..a28d04699d 100644 --- a/docs/design/appserver/auxiliary-model.md +++ b/docs/design/appserver/auxiliary-model.md @@ -73,7 +73,7 @@ The `auxiliaryModel` face is deleted. See [Provider](../plugins/Provider.md) for ### 4.1 Language-neutral (ADR 002 D5) -Superseded: there is no `auxiliaryModel` service. A caller runs `providerService.invoke(request, Mode::Once, consume, None, cancelled)` and collects the text in its consumer. +Superseded: there is no `auxiliaryModel` service. A caller runs `providerService.invoke(request, Mode::Once, consume, admit_all, cancelled)` and collects the text in its consumer. ### 4.2 Rust binding diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 51e7f47034..2d0d4e3fbc 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -1054,15 +1054,15 @@ contained in the persisted static record, so executing it requires that owner's this offline judgment. Static records are the contract's input; the account owner's catalog remains authoritative for managed models. -**Relation to §3.6.** The selectable-model read is a process host port with no input. It -enumerates what Provider would serve now, including managed account catalogs, and returns -capability snapshots for routing. This contract takes one persisted static record and one -explicit model, reads no account or store, and returns the route with the snapshot. They -share `static_catalog`, `ProviderCatalog::selectable` and `capability_snapshot`; for a -stored static-authority record both can see, a target appears in the §3.6 reply exactly -when this contract accepts it. The two differ in scope, not in rules: §3.6 answers "what -is available now", this contract answers "can this stored selection execute". Neither is -a management method or an RPC. +**Relation to §3.6.** `providerService.selectable({use})` takes the use and enumerates what +Provider would serve now, including managed account catalogs, with capability snapshots for +routing. This contract takes one persisted static record and one explicit model, reads no +account or store, and returns the route with the snapshot. They share `static_catalog`, +`ProviderCatalog::selectable` and `capability_snapshot`; for a stored static-authority record +both can see, a target appears in the `selectable` reply exactly when this contract accepts +it. The two differ in scope, not in rules: `selectable` answers "what is available now", +this contract answers "can this stored selection execute". Neither is a management method or +an RPC. **Consumer and migration.** Migration reads the target record with Provider's parser and converts legacy selections through Provider's frozen selection conversion. That conversion diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 85d60b15e0..0f6069f071 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -23,7 +23,7 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Caller → owner | Methods and replies | | --- | --- | | Permission consumers → Agent directory | `sessions.permission({sessionId,branchId})` and `sessions.permissionDefaults({})` retain the existing policy replies. The first holds the Session lease; the second reads the current default without creating a Session. | -| Dialogue, summary and suggestion → `providerService` | `invoke(request, mode, consume, admit?, cancelled) → {accepted}`. Full `ModelRequest` with pinned tools, configuration, cached prefix and capability snapshot; retries and credential recovery stay with the owner, see [Provider](../plugins/Provider.md). | +| Dialogue, summary and suggestion → `providerService` | `invoke(request, mode, consume, admit, cancelled) → {accepted, chain?}`. Full `ModelRequest` with pinned tools, configuration, cached prefix and capability snapshot; retries and credential recovery stay with the owner, see [Provider](../plugins/Provider.md). | | Session configuration → `providerService` (managed profile) | `resolve({target?, cwd?}) → ModelSelection`; `preferences({selection, update}) → ModelSelection`, see [Provider](../plugins/Provider.md). | | Session creation/adoption and Collaboration → `providerService` (managed profile) | `prepare_startup(request) → ModelSelection`, `retain_startup({session, model})`, `release_startup({model})`. The source is bound to the calling row until a Session retains it; a missed release settles with the row, a retained source with the Session, see [Provider](../plugins/Provider.md). | | Session creation / worktree management → ManagedWorktrees | `create({source, base?, branch?}) → CreatedWorktreeReply`, `discard(created) → void`, `list({}) → WorktreeView[]`, `pruneSelection({olderThanMs?, keep?, force}) → PruneSelection`, `remove({taskId, force}) → boolean`. Bind the existing operations. Failed Session creation discards the created worktree on its node. | @@ -52,9 +52,10 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Input | Contract | | --- | --- | -| `mode` | `once` for suggestions; `recovering` accepts an optional existing FailureChain. Dialogue supplies the replay decision. | -| `consume(next, cancelled)` | `next` yields one chunk, end or typed host error. Return `{kind: returned, value, replaySafe}` or `{kind: failed, error, replaySafe}`. The reader expires when the consumer settles. Accepted output prevents unsafe replay. | -| `hooks?` | `prepare(protocol or null) → ModelConfig or null` runs once after resolution. `beforeAttempt() → admitted or {rejected: message}` checks the summary budget before each attempt. `waiting(progress or null)` reports the existing retry schedule. | -| Completion | Cancellation or driver shutdown releases a suspended consumer and joins accepted work. Invalid wire input returns `invalid_request`. Consumer exceptions remain consumer errors. | +| `mode` | `Dialogue { chain? }` continues the failure chain a caller holds; `Once` makes one request with no retry and no model substitution. Both are [Provider](../plugins/Provider.md)'s `Mode`. | +| `consume` | A direct callback `impl Fn(ProviderChunk) -> BoxFuture<'static, Result>`; it answers `Continue`, `End`, `CredentialRejected` or `Failed { retryable }`. Output accepted before a failure prevents replay, and `InvokeReply.accepted` says whether any was accepted. | +| `admit` | A required direct callback `impl Fn() -> BoxFuture<'static, Result>`; it answers `Admitted` or `Rejected { message }` before each attempt, and `admit_all` is the exported callback that admits every attempt. | +| Retry display | Provider reports waits as `Retrying { attempt, delay_ms }` chunks to `consume`. | +| Completion | Cancellation or owner shutdown releases the suspended consumer and joins accepted work. A failed request returns `provider_failed { failure, chain }` with the runtime `ModelFailure` and the updated `FailureChain`; ModelProvider writes both to `step/model-output-end`. | The full-request consumer injects only `providerService`. The managed profile registers Provider at that name; the API-key profile registers ConfiguredModels; standalone local configuration registers the local host. Each profile registers exactly one dispatcher at `providerService`. Aimux supplies the native driver and owns its pool and unload signal without a catalog name. The selected owner resolves the credential with the account owner, invokes its driver and settles the retries; the caller receives output or a typed error. diff --git a/docs/design/plugins/DimOAuth.md b/docs/design/plugins/DimOAuth.md index 29ee48d28d..58f9014f55 100644 --- a/docs/design/plugins/DimOAuth.md +++ b/docs/design/plugins/DimOAuth.md @@ -38,8 +38,20 @@ Web declares its search tool only while the relay account is signed in: ```rust let AccountAvailability { signed_in, .. } = dim_account.availability(cancelled.clone()).await?; if signed_in { - let mut changes = dim_account.subscribe(cancelled.clone()).await?; - // declare web_search; withdraw it when changes report signed_out + // The owner calls `notify` once with the current value, then on every change; + // the registration ends with this Session part's row or the owner's close. + dim_account + .subscribe( + &self.ctx, + Arc::new(|availability: AccountAvailability| { + Box::pin(async move { + // Declare web_search from `availability.signed_in`. + Ok(()) + }) + }), + cancelled.clone(), + ) + .await?; } ``` diff --git a/docs/design/plugins/ImageUnderstanding.md b/docs/design/plugins/ImageUnderstanding.md index bc738bb770..0546562643 100644 --- a/docs/design/plugins/ImageUnderstanding.md +++ b/docs/design/plugins/ImageUnderstanding.md @@ -144,7 +144,7 @@ owner changes its own document. **M1 Modality: the operation target read.** - **Problem.** A Session part must learn which model `modality.image.understand` resolves to now. Modality's process surfaces are the task methods (`modalityTasks`) and the adapter copies (`modalityAdapter`); none of them answers "which model would this operation use now", and `modality.capabilities` is a management method served to clients, which a part is not. -- **Existing mechanisms, and why they fail.** `modality.capabilities` is a management method, and a part is not a client. `modalityTasks` is the task surface and refuses `understand` by design (Modality decision 6). Provider's `selectableModels` enumerates what execution accepts for chat, and `selectableForModality` widens that to models execution rejects for chat; neither applies Modality's persisted default or its explicit → default → automatic precedence, so a consumer using them would decide with a second rule. +- **Existing mechanisms, and why they fail.** `modality.capabilities` is a management method, and a part is not a client. `modalityTasks` is the task surface and refuses `understand` by design (Modality decision 6). Provider's `selectable` with `Use::Chat` enumerates what execution accepts for chat, and with `Use::Modality` widens that to models execution rejects for chat ([Provider](Provider.md)); neither applies Modality's persisted default or its explicit → default → automatic precedence, so a consumer using them would decide with a second rule. - **Needed capability.** One process service, `modalityTargets`: for `.`, the target it resolves to now, or the reason it is unavailable, with the same precedence and reason vocabulary as the snapshot. Read per call; no task, no credential, no gate, no reload. - **Ordering impact.** Per tool call. Modality stays Active when an adapter or model is absent. - **Owner and issue.** Modality, [#798](https://github.com/arcships/dim/issues/798) §9.4. diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 6d4390e1c9..07b39eab3a 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -294,7 +294,7 @@ Adapter capability derivation uses the selected copy's `available` and `operatio - **Problem.** `modality.capabilities` must compute `options` and automatic resolution from the models Provider can select. Provider's model-selection port resolves one model, and the catalog reads are client management methods, so a process owner cannot enumerate the selectable set with its declared capabilities. - **Existing mechanisms.** The single-model selection port cannot filter by an operation's capability. A new client method would expose management to the owner and duplicate the catalog. The Provider-side read-only contract is tracked separately by [#790](https://github.com/arcships/dim/issues/790). Delivered by the owner contract: `providerService.selectable` ([Provider](Provider.md)) enumerates the models execution would accept with their declared capabilities, in both profiles. -- **Needed capability.** That read is shaped for execution: a model without a `text` modality, a non-chat model and a model whose text limits are undeclared never appear, so the image, video, speech, music, audio, asset, motion and realtime models Modality routes to are all missing. Provider adds one read to the same port, `selectableForModality`, returning each model it would select for a non-conversational use with the `.` ids its catalog entry declares. It applies the same provider, account, model, route, credential and status rules as `selectableModels`, without those three chat requirements. +- **Needed capability.** That read is shaped for execution: a model without a `text` modality, a non-chat model and a model whose text limits are undeclared never appear, so the image, video, speech, music, audio, asset, motion and realtime models Modality routes to are all missing. Provider's `selectable({use})` returns each model it would select for a non-conversational use with the `.` ids its catalog entry declares ([Provider](Provider.md)). It applies the same provider, account, model, route, credential and status rules as the chat read, without those three chat requirements. - **Ordering impact.** Read at each `capabilities` call and task submission; no reload and no Timeline. - **Owner/issue.** Provider, [#790](https://github.com/arcships/dim/issues/790) and this change. @@ -462,7 +462,7 @@ The default snapshot is the one shape both methods return. A model reference is - `revision` is the `modality` settings document revision; one CAS covers every operation key in that document, so a `configure` for one operation also invalidates a client holding a draft for another. Only `configure` consumes it. - `default` is the persisted choice or `null`. An unavailable default has `available: false` and a `reason` such as `provider` for a model no longer selectable, `configuration` for a known model outside the operation's options, `runtime` when an adapter serving the model for this operation is unavailable, `build` for a category this build has no adapter for, or `adapter` when no adapter serves the model for the operation. For example, a category-wide default that only declares `video.generate` has a `configuration` reason on the `video.edit` row. - `effective` is the model a task or consumer would use now: it is resolved from the available options only, so it is `null` while no option can run, and a client never names a model the operation would refuse. It is the default when available. When `default` is `null`, it follows automatic resolution in §3.4 and `source` is `"automatic"` if a model is selected. An unavailable default yields `effective: null`, never a substituted model. -- `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. For adapter-backed tasks, the operation is available when one of its options is available. If none is available and a declared option reports `runtime`, the operation reports that reason. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. +- `options` lists the models that serve the operation. The candidates come from Provider's `selectable({use})` (§9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. For adapter-backed tasks, the operation is available when one of its options is available. If none is available and a declared option reports `runtime`, the operation reports that reason. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. - `configure` validates against the options the operation offers before the snapshot appends a persisted default. When `operation` is omitted for a category key, any operation in the category may offer the model. A declared Provider option is configurable even when it is unavailable. `image.understand` offers selectable vision models, and `ocr.recognize` requires a host target that can run here (A.2.1). It then writes or clears the default key through Settings' owner write with CAS. It accepts every A.1 operation that has a default key and never answers `modality_unavailable`: configuring is a settings write, not a runtime claim. An unknown category or operation answers `modality_unknown_operation`; `operation` is required where the operation has its own key (image, speech, OCR) and may be absent only for a category-keyed category. `model: null` clears that key (for OCR, `modality.ocr`); clearing restores automatic resolution, and a missing `model` is `invalid_params`. The write happens before the reply is sent, so a success means the default is persisted, and the reply is the same snapshot a following `modality.capabilities` call returns unless Provider changed in between. - Configurable and available are different properties: the first belongs to settings, the second to the runtime. A persisted default can name a model of an operation this build cannot run; the snapshot stays honest by keeping that operation's `available: false` and its `build` or `adapter` reason. Clients read the resolved model from `effective`. diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md index 2143918904..1d4944a0de 100644 --- a/docs/design/plugins/Provider.md +++ b/docs/design/plugins/Provider.md @@ -153,16 +153,16 @@ All operations are marked on `Provider` and provided under `providerService`; re | `resolve` | The model one request resolves to | `{target?, cwd?}` | `Selection` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `preferences` | Apply a patch to an adopted selection | `{selection, update}` | `Selection` | None; completes immediately | `invalid` | | `selectable` | The models that can run a use, and the default | `{use: "chat" \| {modality}}` | `{models, default?}` | The caller cancels; no timeout | `invalid`, `cancelled`, `closed`, `failed` | -| `prepare_startup` | Admit a temporary connection under the calling row and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `{selection}` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | +| `prepare_startup` | Admit a temporary connection under the calling row and select its model | `{target?, cwd?, preferences, connection?, limits?}` | `ModelSelection` | The caller cancels before admission | `invalid`, `invalid_connection`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed` | | `retain_startup` | Bind the temporary connection the model carries to a Session | `{session, model}` | `{}` | None; completes immediately | `not_found` (the model carries no source, or the source is not bound), `closed` | | `release_startup` | Release a source the calling row owns | `caller`, `{model}` | `{}` | None; completes immediately | `not_found` (already retained by a Session, or another row's), `closed` | -| `invoke` | Run one model request | `request`, `mode`, and the `consume` / `admit` callbacks as direct parameters | `{accepted}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed`, `provider_failed {retryable}` | +| `invoke` | Run one model request | `request`, `mode`, and the `consume` / `admit` callbacks as direct parameters | `{accepted, chain?}` | The caller cancels; the request stops and the consumer is released. No owner timeout; a request may wait on the transport through its configured HTTP timeout | `invalid`, `not_found`, `unavailable`, `auth_required`, `cancelled`, `closed`, `failed`, `provider_failed {failure, chain}` | | `media_route` | A media model's route and the owner of its credential | `{target, operation}` | `{protocol, base_url, headers, realtime?, credential: Owner}` | The caller cancels; no timeout | `invalid`, `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | | `credential` | A static model's connection facts for one request | `{provider, model}` | `{protocol, base_url, headers, bearer, generation: none}` | The caller cancels; no timeout | `not_found`, `unavailable`, `cancelled`, `closed`, `failed` | `prepare_startup` admits the source under the calling row; the row's unload releases it, so a missed `retain_startup` or `release_startup` settles with the row. `retain_startup({session, model})` moves the source to the Session named by the caller and the model's metadata; the Session's close releases it, so a missed failure-path release settles with the Session. `release_startup({model})` is the optional early release for a creation that failed; it answers `not_found` once a Session retains the source. A member Session that inherits the leader's model retains the same source by value. A connection never crosses. `Selection` is the adopted provider, model, configuration, capability snapshot and metadata. `Credential` is [ManagedAccount](ManagedAccount.md)'s value: static credentials carry no generation; an account owner's carry the grant's. `invoke` calls the account owner's `credential`, sends, and on a refusal calls `rejected` with the refused generation before retrying within its own failure chain. -`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits as `Retrying` chunks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(chunk)` reports `Continue`, `End`, `CredentialRejected` (the provider refused the credential, so `invoke` calls the account owner's `rejected` once and retries) or `Failed { retryable }`; output accepted before a failure prevents replay, and the reply's `accepted` says whether any output was accepted. `admit` runs before each attempt and answers `Admitted` or `Rejected { message }`; a caller without its own budget passes `admit_all`, the binding's default that admits every attempt. Both callbacks are direct parameters, so the request data stays serde-only. A request for `openai-chatgpt` requires a client-origin Session: Provider reads the Session's creation record (`creationRecord`) and answers `invalid` for a non-client Session. +`invoke`'s `mode` is `Dialogue { chain? }` or `Once`. `Dialogue` continues the failure chain when given one and reports retry waits as `Retrying` chunks; `Once` makes exactly one request with no retry and no model substitution, which is what a caller sending one paid request needs (Report's model generation). `consume(chunk)` reports `Continue`, `End`, `CredentialRejected` (the provider refused the credential, so `invoke` calls the account owner's `rejected` once and retries) or `Failed { retryable }`; output accepted before a failure prevents replay, and the reply's `accepted` says whether any output was accepted. `admit` runs before each attempt and answers `Admitted` or `Rejected { message }`; a caller without its own budget passes the exported `admit_all`. Both callbacks are direct parameters, so the request data stays serde-only. A request for `openai-chatgpt` requires a client-origin Session: Provider reads the Session's creation record (`creationRecord`) and answers `invalid` for a non-client Session. A failed request returns `provider_failed` with the `ModelFailure` facts and the updated `FailureChain`; a completed request returns the updated chain in the reply, so ModelProvider writes both into `step/model-output-end`. ### Errors @@ -176,7 +176,7 @@ All operations are marked on `Provider` and provided under `providerService`; re | `cancelled` | Yes, by calling again | Nothing changed; the call stopped where it was cancelled | | `closed` | Against the next generation | This generation is unloading; call the replacement generation | | `failed` | Yes, after the store recovers | Provider's storage or a catalog read failed; retry the read | -| `provider_failed {retryable}` | When `retryable` | The request failed after the owner's retries; `retryable` says whether a new `invoke` can succeed | +| `provider_failed {failure, chain}` | When `failure.retry_forbidden` is false | The request failed after the owner's retries; `failure` carries the runtime kind, status, provider code, cause and attempt totals, `chain` the updated retry budget; ModelProvider writes both to `step/model-output-end` | ### Flows @@ -243,7 +243,7 @@ use dim_agent_capabilities::host::{ CancelledFn, ModelProtocol, ModelStopReason, RealtimeDeclaration, }; use dim_agent_runtime::PublicService; -use dim_agent_types::FailureChain; +use dim_agent_types::{FailureChain, ModelFailure}; use dim_agent_types::{ MessagePart, ModalityModelSnapshot, ModelCapabilitySnapshot, ModelId, ModelPreferences, ModelRequest, ModelSelection, ToolCall, Usage, @@ -344,9 +344,14 @@ pub enum Consumed { Continue, End, CredentialRejected, Failed { retryable: bool #[serde(tag = "kind", rename_all = "camelCase")] pub enum Admitted { Admitted, Rejected { message: String } } +/// The default admit callback: admits every attempt. +pub fn admit_all() -> BoxFuture<'static, Result> { + Box::pin(async { Ok(Admitted::Admitted) }) +} + #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct InvokeReply { pub accepted: bool } +pub struct InvokeReply { pub accepted: bool, pub chain: Option } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -383,7 +388,8 @@ pub enum ProviderError { #[error("cancelled")] Cancelled, #[error("provider is unloading")] Closed, #[error("{0}")] Failed(String), - #[error("{message}")] ProviderFailed { retryable: bool, message: String }, + #[error("the model request failed")] + ProviderFailed { failure: ModelFailure, chain: FailureChain }, } impl PublicService for Provider {} @@ -410,3 +416,14 @@ impl Provider { ``` The `provider` client namespace keeps its published method names and request shapes; handlers call the operations above and the management operations. No management operation is also published on `providerService`. + +## Supersedes + +- `service-faces.md`: the `modelHost` row and §4.2; the `providerService` and `providerConnectionResolver` rows; the `managedSearch` row where it names Provider; the Provider selection block in §4.10. +- `contracts/process-owner-operations.md`: the model selection, session configuration, session creation/adoption, model invocation and auxiliary rows, and the `modelHost` paragraph. +- `contracts/resource-owner-operations.md`: § Provider → sqliteStorage, whose record operations move to Provider. +- `appserver/provider-management.md`: the surface-table rows for `ModelSelectionHost`, `SelectableModelsHost`, `ProviderConnectionResolver`, `ModalityConnectionHost` and `auxiliaryModel.complete`, the port sections §3.6 and §3.8, and the `provider` settings-source row in §2. +- `appserver/auxiliary-model.md`: the `auxiliaryModel` interface in §4; sections 5–11 are historical. +- `plugins/Modality.md`: the dependency rows, §9.2's selectable read and §9.3/§9.4's connection resolution, which name `SelectableModelsHost`, `SelectableModelsHost.selectableModels`, `selectableForModality`, `ModalityConnectionHost` and provider-management §3.6. +- `plugins/ImageUnderstanding.md`: the paragraphs that name `auxiliaryModel`, `selectableModels` and `selectableForModality`. +- Deleted names: `modelHost`, `modelSelectionHost`, `selectableModelsHost`, `providerConnectionResolver`, `modalityConnectionHost`, `auxiliaryModel`, the `modelHost.invoke` operation and `ProviderConnectionResolver`. From 05c7515410e0acf7d02de47690a3e404ac2d4d97 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:10:23 +0800 Subject: [PATCH 8/9] docs(provider): align the Prompt call, the settings row and the account link --- docs/design/appserver/provider-management.md | 2 +- docs/design/plugins/Provider.md | 10 ++++++---- docs/design/resource-faces.md | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 2d0d4e3fbc..3a94d4b612 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -50,7 +50,7 @@ with its existing owner; management never writes another owner's state. | Account namespaces | Account owners provide login, usage and logout. The [ChatGPT plan provider](chatgpt-plan.md) owns `account.chatgpt`. | | Model selection and credentials | `providerService.resolve` and the account owners' `credential`; the old host ports are deleted ([Provider](../plugins/Provider.md)) | | `auxiliaryModel.complete` | Deleted: the caller uses `providerService.invoke` with `Mode::Once` ([Provider](../plugins/Provider.md)) | -| `provider` Settings source, user scope (`provider.json`) | ProviderSettings owns the source and its `userAgent` ([#2094](https://github.com/arcships/dim/pull/2094)); Provider reads `user_agent` at request time (§2, Model request identity) | +| `provider` Settings source, user scope (`provider.json`) | [ProviderSettings](https://github.com/arcships/dim/pull/2094) owns it; it holds `userAgent`, the User-Agent override (§2, Model request identity), and publishes it as a value a model request reads | | Native CLI Provider flows | Migrate discovery, create, update and disconnect together with the new owner methods | Business logic stays in Provider, not `connection.rs`, `protocol.rs` or a wiring diff --git a/docs/design/plugins/Provider.md b/docs/design/plugins/Provider.md index 1d4944a0de..cda28a1452 100644 --- a/docs/design/plugins/Provider.md +++ b/docs/design/plugins/Provider.md @@ -50,8 +50,8 @@ The Rpc entry chooses a model while creating a Session: let selection = provider .resolve(ResolveRequest { target: requested, cwd: Some(cwd) }, cancelled.clone()) .await?; -line_owner::(line)?.configure( - ConfigureRequest { sources: None, model: Some(selection), tools: None }, +line_owner::(line)?.configure( + ConfigureRequest::Initial(ConfigureUpdate { sources: targets, model: Some(selection) }), cancelled.clone(), ).await?; ``` @@ -62,12 +62,14 @@ The Rpc entry changes only the preferences of the model already adopted: let next = provider .preferences(PreferencesRequest { selection: current, update: patch }) .await?; -line_owner::(line)?.configure( - ConfigureRequest { sources: None, model: Some(next), tools: None }, +line_owner::(line)?.configure( + ConfigureRequest::Initial(ConfigureUpdate { sources: targets, model: Some(next) }), cancelled.clone(), ).await?; ``` +`targets` is the line's current source targets. `configure` adopts sources and a model as one configuration, so a model change re-adopts the same targets with the new model ([Prompt adoption](https://github.com/arcships/dim/pull/2102), target, pending). + Modality lists the options for an operation: ```rust diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 6d95b2dc3d..be75f921e2 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -846,7 +846,7 @@ The owners that read node files or start node processes, and the operations they | SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`, `execHost.removeOutputDirectory` | | Settings sources and their CAS writes | `readBytes`, `stat`, `lock`, `readBytes {leaseId}`, `replace {leaseId}`, `unlock` | | MCP auth store | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | -| Managed OAuth and OAuth token stores | `read`, `update`, `write`; the account owner answers [ManagedAccount](../plugins/ManagedAccount.md) | +| Managed OAuth and OAuth token stores | `read`, `update`, `write`; the account owner answers [ManagedAccount](plugins/ManagedAccount.md) | | Hooks project file (`.dimcode/hooks.json`) | `stat`, `readBytes` | | PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | | UI extension resources | `stat`, `openRead`, `readAt`, `closeRead` | From 9ca30e0f8e4af324b2e0d4f106ed4e5de66ed5bc Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:15:20 +0800 Subject: [PATCH 9/9] docs(provider): record that no TypeScript source writes auth.json --- docs/design/plugins/DimOAuth.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/plugins/DimOAuth.md b/docs/design/plugins/DimOAuth.md index 58f9014f55..b7bda9c0da 100644 --- a/docs/design/plugins/DimOAuth.md +++ b/docs/design/plugins/DimOAuth.md @@ -102,7 +102,7 @@ The `account.*` namespace keeps its published methods; handlers call the same ow ## Exceptions with reasons - The bearer's boundary is [ManagedAccount](ManagedAccount.md#the-bearers-boundary); DimOAuth's replies and errors omit it. -- The account file is shared with the TypeScript subscriber under the published `auth.json.lock` marker protocol; FileStorage's contract records the marker exception, and DimOAuth keeps the file format. +- The account file is guarded by the published `auth.json.lock` marker protocol. The writers are this owner and the App Server's managed OAuth flow, both Rust (`crates/dim-oauth/src/store.rs`, `crates/dim-app-server/src/managed_oauth.rs`); no TypeScript source writes `auth.json`. The marker is FileStorage's claim protocol for this file ([#2080](https://github.com/arcships/dim/pull/2080)), not a cross-language exception. ## Client-visible changes @@ -131,7 +131,7 @@ None. The `account.*` method names, fields, error codes and user-visible behavio ## Requirements raised to mechanism owners -- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for `auth.json` and its backup; the `auth.json.lock` marker exception is already recorded there. +- **FileStorage ([#2080](https://github.com/arcships/dim/pull/2080)).** `read`, `update` and `write` for `auth.json` and its backup, with `claim`/`release` for the `auth.json.lock` marker. - **Settings, storage, session directory.** None. ## Supersedes