diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index 1fd80891c6..8c5c43d94e 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -20,6 +20,12 @@ runtime assembly and scripted model hosts: a newly assembled capability needs it entry here. Excluded rows can still appear as providers or consumers in the generated blocks. A service dependency is not necessarily a plugin with the same name. +The Session and branch owner contracts have no page here: they are owner parts of the Session, +branch and process scopes rather than plugins of the local-execution profile. See the design index +for [SessionScope](../../../design/plugins/SessionScope.md), [Request settings](../../../design/plugins/RequestSettings.md), +[Context facts](../../../design/plugins/ContextFacts.md), [Context projection](../../../design/plugins/ContextProjection.md), +[Summary strategy](../../../design/plugins/SummaryStrategy.md) and [File access facts](../../../design/plugins/FileAccessFacts.md) (#2025). + ## Index | Plugin | Process | Session parts | Branch parts | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 3d36fd9d6d..c654cc541a 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -4,11 +4,11 @@ | Caller → owner | Final API | | --- | --- | -| Branch management, input and history callers → `timelineTree` | `create/end/info/input/list/page/query` retain their existing signatures on the single Session tree face. Creation returns the branch ID. | +| Branch management, input and history callers → `timelineTree` | `create`, `end`, `set_default`, `directory`, `line` and `read` on the single Session tree face; creation returns the line id ([TimelineTree](https://github.com/arcships/dim/pull/2092), #2024). `query` is not the tree's: a stored Session's history is `store.query` on the process face ([SessionStore](https://github.com/arcships/dim/pull/2091), #2018). | | Language readers → PromptSources | `sessionLanguage.get`. | | Language updates → App Server | [`session.language.update`](session-access.md) accepts the existing language code or clear action. The owner serializes persistence, live-state replacement and Prompt adoption on main and loaded branches before replying. | | Prompt → PromptRegistry; guide and tool contributors → their registries | `initialPromptConfiguration.get`, `promptHost.load`, `guideEntries.register`, `toolRegistry.register`, `toolSourcesView.get/observe`. | -| Session and branch parts → their lifecycle; branch fact consumers → Dispatcher | `sessionLifecycle.activated/closing/hold/release`, `branchLifecycle.activated/closing`, `dispatcher.listen/consume/committed`. | +| Session and branch parts → their lifecycle; branch fact consumers → Dispatcher | `sessionScope.activated/closing/hold/release` and its fault operations ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093); `branchLifecycle.activated/closing`, `dispatcher.listen/consume/committed`. The old `sessionLifecycle` name is superseded. | ## New rutis APIs on existing owners @@ -16,43 +16,34 @@ | Caller → owner | New API | | --- | --- | -| Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | -| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Registered Session extension definitions must activate their instance rows. Host-added optional groups retain their optional rows. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | -| Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | -| Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | -| History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | -| Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | -| Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `query`; writes retain the ended/unknown errors. | -| InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | -| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | +| Branch directory readers → `timelineTree` | `timelineTree.directory({}) → {default, lines}` ([TimelineTree](https://github.com/arcships/dim/pull/2092), #2024). | +| Skills content and MCP publication → Session mounts | `sessionScope.mount({group, definitionId, instanceData}) → {instanceId}`; `unmount({instanceId})`. The owner admits groups whose configured parent is the Session group, waits for the definition's rows and settles a rejected instance. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | +| Goal → the target line's input owner | `line_owner::(line).submit(...)`; one validated atomic batch for the Goal record and trigger ([ADR 027](https://github.com/arcships/dim/pull/2029)). | +| Branch-detail RPC → timelineTree | `line({line})` for the record and `read({line, …})` for the facts; there is no `display` operation. | +| History RPC and line-read tools → timelineTree | `read({line, through, …})` at one cutoff, with the complete batches and the fixed head of an ended line; the reply carries the events or the selected fields. | +| Context RPC → target branch | `line_owner::(line).compact(...)` and `line_owner::(line).read(...)` ([ADR 027](https://github.com/arcships/dim/pull/2029)). | +| Goal and Shell admission → timelineTree | `line({line})` returns the matching record or `unknown` ([TimelineTree](https://github.com/arcships/dim/pull/2092)). Goal reads ended history through `read` at the line's fixed head; writes retain the ended/unknown errors. | +| InputQueue and Collaboration approvals → target branch | `line_owner::(line)`: `submit(...)` and `withdraw(...)` after submission checks; `line_owner::(line)`: `pending` and `decide`. | +| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `line_owner::(line).read(...)`, `line_owner::(line).adoptedConfiguration(...)`. Report's own tree reads are [TimelineTree's](https://github.com/arcships/dim/pull/2092), not this row's. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | -| Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → SessionFault or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | +| Fault producers and Session observers → `sessionScope` | `reportFault(fault) → void`, `failure() → SessionFault or none`, `observeFault(listener) → id`, `release({leaseId}) → boolean`. The listener receives the current failure (none included) and later reports; the calling row's unload releases the observation. The first fault wins until a storage failure supersedes it ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | | Compaction, stop and activity callers → `agentLoop` | `agentLoop.compact({}) → sequence`, `stopTurn({turnId, reason}) → sequence or null`; `agentLoop.state({}) → {phase, turnId?}`, `observe(listener)` delivers that snapshot. | ### Calls from a Session to a selected branch -Within a branch, inject its owner face directly. For Session callers the existing -`timelineTree` face gains `call({branchId,operation}, cancelled) → operation reply`. -TimelineTree resolves the admitted live branch once using its existing branch lookup and -dispatches on that branch instance. The operation is a tagged union of the calls below; -Direct variants use the owner method's arguments, reply and error. The compact RPC variant below returns the existing settled client result. The Session caller gets data. -Ended and unknown branches retain their original errors. Calls admitted before close stay -with that generation. Tree history, directory and batch input continue to use the tree's -own methods. +Within a branch, inject its owner face directly. A Session part reaches one line's owners by +line id: `line_owner::(line)?.op(..)` resolves the branch-group service at the instance the +runtime built for that line, and the caller calls that owner's typed operation. Any branch-group +data face is reachable this way except registration points and lifecycle services; there is no +generic operation-name dispatch and no `timelineTree.call`. A line that is not live answers +`NoLine`; a Session that is closing answers `SessionClosing`. `NoLine` is final for that line: +the caller takes no hold and does not retry it. `SessionClosing` ends the Session part's work. A +Session part never receives `NoSession`: only a process caller does, and it takes a hold from Agents +before calling again ([#2127](https://github.com/arcships/dim/issues/2127)). -| Session caller | Target operation | -| --- | --- | -| Context RPC / PromptSuggestion | `contextUsage.read`. The `compactAndWait` variant runs the existing compact RPC handler: it calls `agentLoop.compact` and waits for the compaction fact matching that command sequence and returns the existing completed/skipped/failed reply. The committed sequence watch and bounded query run inside the selected branch for that wait. | -| Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | -| InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | - -For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) -and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in -conversation extraction call `timelineTree.query` with the same explicit `through`, -existing bounded window and `include_publishing: false`. Zero yields an empty window. -A draft without a captured cutoff does not fetch a conversation. Plan generation never -substitutes a newer head. +Report's draft head, its bounded conversation window and the cutoff it keeps are stated by the +[TimelineTree contract](https://github.com/arcships/dim/pull/2092) and Report's own contract; this document keeps neither. ### Prompt, configuration and files @@ -66,11 +57,11 @@ substitutes a newer head. | Caller → owner | New API | | --- | --- | -| Loop → PrepareModelHost | `prepare({turnId, requestId, history, availableTools}) → ModelSettings`, with pinned tool definitions in order. | -| ContextPreparation → PrepareContextHost | `prepare({request, source:{turnId, requestId, through}}, cancelled) → ModelRequest`. | -| Context accounting and compaction → ContextModelHost | `describe(model facts) → {contextWindow, outputTokens, thresholdTokens, algorithm?}`, `count(request) → tokens`, `contributions({model, fixed?, messages}) → {algorithm, fixed?, messages}`, `estimate({model, algorithm, contribution}) → tokens`. | -| Loop and ContextPreparation → CompactionStrategyHost | `describe(model facts) → {name, replacementSize}`; `compact(input, cancelled) → completed, skipped or failed` with StrategyDiagnostics. Input carries history, checkpoint, request, legal cuts, trigger, budgets, prior diagnostics and model facts. | -| Loop and ContextPreparation → HistoryRenderer | `context({branchId, through}) → ContextHistory`, `renderedContext({branchId, through}) → {context, history: HistoryEntry[]}`, `snapshot({context, retainFrom, anchor}) → RecoverySnapshot`, `streamCheckpoint({branchId, through, retainFrom, batch}) → ProjectionCheckpoint`. | +| Loop → `requestSettings` | `settings() → {providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}`; Loop adds the pinned tools, the guide's system and the turn's ids ([Request settings](../../../docs/design/plugins/RequestSettings.md), #2093). | +| ContextPreparation → no host port | The request transformation has no owner and leaves the catalog; a content change enters only through adopted inputs or tool results (#2093). | +| Context accounting and compaction → `contextFacts` | `describe({model})`, `count({request})`, `contributions({model, fixed?, messages}) → {algorithm, fixed?, messages}`, `estimate({model, algorithm, contribution})` ([Context facts](../../../docs/design/plugins/ContextFacts.md), #2093). | +| Loop and ContextPreparation → `summaryStrategy` | `describe({model}) → {name, replacementSize}`; `compact(input, cancelled) → completed, skipped or failed` with diagnostics. The input carries history, checkpoint, request, legal cuts, trigger, budgets and prior diagnostics, and no model object ([Summary strategy](../../../docs/design/plugins/SummaryStrategy.md), #2093). | +| Loop and ContextPreparation → `contextProjection` | `renderedStream({through, batch})`, `renderedContext({through})`, `snapshot({context, retainFrom, anchor})`, `streamCheckpoint({through, retainFrom, batch})`, `snapshotFromCheckpoint({checkpoint, anchor})`; the fold is the branch's own ([Context projection](../../../docs/design/plugins/ContextProjection.md), #2093). | | Loop and ModelProvider → ContextPreparation | `prepare({source: ContextPrepareData, projection?}, cancelled) → ModelRequest`, `validate({requestId, request}, cancelled) → void`. Reuse the prepared projection at the original cutoff. | | ContextPreparation and usage readers → ContextUsage | `read({through?}, cancelled) → {through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource}`. | | Loop, ToolExecutor and Code Mode definition readers → `toolBinding` | `bind({requestId, through, tools, toolSources}) → void`, `bindCurrent({requestId, declared?}) → ToolDefinition[]`, `definitions({requestId}) → ToolDefinition[]`, `transfer({from, to}) → void`, `release({requestId}) → void`. ToolBinding retains the pinned handler generation. | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 1d34d18338..8302ab7e75 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -59,7 +59,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | Process (root) | Host start | Host shutdown | — (process parts provide their own) | | Agent (`agent`) | Agents creates an Agent | Agent close, host shutdown | Host-internal | -| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionIdentity`, `sessionLifecycle`, `treeCommands` | +| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope` ([SessionScope](plugins/SessionScope.md)); a Session's line directory is the TimelineTree part, and the branch group is reached by line id | | Branch (`branch`) | TimelineTree creates a branch | The branch ends, or its Session closes | `timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity` | Visibility follows the tree, as in [principles §2](../architecture/rust-agent/principles.md): @@ -67,7 +67,7 @@ Visibility follows the tree, as in [principles §2](../architecture/rust-agent/p | Direction | How | | --- | --- | | Up (an enclosing instance, the process) | Inject the service by name | -| Down (Session to branch) | `treeCommands`: input by branch id, branch creation. Never by injecting a branch service | +| Down (Session to branch) | `line_owner::(line)`: any branch-group data face by line id ([ADR 027](https://github.com/arcships/dim/pull/2029)), except registration points and lifecycle services; branch creation is `timelineTree.create`. Never by injecting a branch service | | Sideways (sibling branches, other Sessions) | Not visible. Go through a common ancestor's business service, such as `sessions` | The scope roots, the facades and their publication rules are mechanisms. Each Session and branch is @@ -114,11 +114,7 @@ R4). This table says what each name Dim defines is for. | `workflowFiles` | process | App Server | yes | Marked `#[rutis::service]` | | `eventHub` | process | EventHub | designed, not implemented | A producer declares a source and publishes an event; EventHub delivers it to the Sessions subscribed, through Agents' `sessions` ([EventHub](plugins/EventHub.md)) | | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | -| `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | -| `sessionIdentity` | `session` | SessionScope | yes | `get()`: `{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload. `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | -| `sessionConfig` | `session` | SessionScope | yes | `get()`: the creation-time configuration, the snapshot a tool call carries | -| `agentConfig` | `session` | SessionScope | yes | `get()`: the Agent's identity and default model | +| `sessionScope` | `session` | SessionScope | yes, except `openBranch` | `config`, `identity`, `phase`, `activated`, `closing`, `hold`, `release`, `reportFault`, `failure`, `observeFault`, `mount`, `unmount`; `openBranch` is Rust-only (`#[rutis::service(skip)]`) because the branch's runtime context has a shared lifecycle but no serde form ([SessionScope](plugins/SessionScope.md), #2093) | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | | `dispatcher` | `branch` | BranchScope | yes, `consume`, `listen` and reads; their Rust forms are the same `consume` and `subscribe`, which is Rust-only | Ordered consumption (§5.2) | | `branchLifecycle` | `branch` | BranchScope | yes | `activated`, `closing`. `registerOpening` registers work that branch opening waits for. | @@ -362,12 +358,11 @@ design is merged. R4–R7 concern how Dim uses rutis and are in The row learns its Session id from the C4 setup rather than from a service. - **Existing mechanisms considered:** C4's per-row setup carries the id but not the phases. `branchLifecycle` already exists for branch rows. -- **Needed:** `sessionLifecycle` (`activated`, `closing`, `hold`) and `sessionIdentity` - (`{sessionId, restored}`) as catalog services in `session`, with serde shapes, next to the existing - `branchLifecycle` and `timelineIdentity` in `branch`. `hold` returns a handle released by a call or - by the row's unload; in the serde form the handle is a hold id, which `release(id)` ends, and the - hold is a cleanup of the calling row. `sessionConfig` exposes the creation-time configuration the C4 - setup carried, so the setup goes. The process scope gets none: process parts follow the host's +- **Needed:** `sessionScope` (`activated`, `closing`, `hold`, `release`, the fault operations, and + the `config` and `identity` reads) as one catalog service in `session`, with serde shapes, next to + `branchLifecycle` and `timelineIdentity` in `branch`. `hold` answers a lease id bound to the + calling row, which `release` ends early and the row's unload settles. `config` exposes the + creation-time configuration the C4 setup carried, so the setup goes ([SessionScope](plugins/SessionScope.md)). The process scope gets none: process parts follow the host's start and shutdown through the rutis lifecycle. - **Effect:** none on the Timeline. It exposes the existing phases. - **Owner:** Dim runtime (SessionScope) and App Server (catalog). Delivered in phase 4 diff --git a/docs/design/plugins/ContextCompaction.md b/docs/design/plugins/ContextCompaction.md index fe2dd23d6a..1fea8226aa 100644 --- a/docs/design/plugins/ContextCompaction.md +++ b/docs/design/plugins/ContextCompaction.md @@ -110,14 +110,17 @@ provider must not depend on `TreeCommands`, which the branch tree provides. ### 2.1 Where the manual step lives +The manual compaction step is ContextPreparation's; the paragraphs that assign the command, the +single-flight slot and the steps to Loop are superseded by ContextPreparation's contract (#2027). +The text below records the earlier arrangement. + The Loop runs the manual compaction step itself, in a tracked task, by calling `ContextPolicy::compact_step`. It does not drive ContextPreparation through an event. The reasons: -- **The Loop already holds what the step needs.** Its `Deps` already inject `Timeline`, - `HistoryRenderer` and `ContextModelHost` - ([agent_loop.rs](../../../crates/dim-agent-capabilities/src/agent_loop.rs) `LoopPlugin::Deps`); - F1 adds `CompactionStrategyHost` beside them. The Loop already builds the request from the - latest `context/configured` in `start_preparation`. +- **The Loop already holds what the step needs.** Its `Deps` inject `Timeline`, the context + projection and the model facts ([agent_loop.rs](../../../crates/dim-agent-capabilities/src/agent_loop.rs) + `LoopPlugin::Deps`); the summary policy is `summaryStrategy` ([Summary strategy](SummaryStrategy.md)). + The Loop already builds the request from the latest `context/configured` in `start_preparation`. - **Nothing is handed over.** `context/prepare` hands a request to ContextPreparation and then to ModelProvider. A manual step makes no model request, so a handoff would only add a second command and a second single-flight slot (ContextPreparation's `current`). @@ -195,12 +198,9 @@ disconnect cancels nothing. ### 4.2 Ports (Rust, runtime-internal) -The existing `ContextModel` port is split in two. Each comes from its own Session value. - -| Port | Session value | Methods | F1 implementation | -| --- | --- | --- | --- | -| `ContextModel` (narrowed) | `ContextModelHost(Option>)` (existing) | `context_window`, `output_tokens`, `threshold_tokens`, `count_tokens`; `compact` moves out | `ProductContextModel` (§5.1) | -| `CompactionStrategy` (new) | `CompactionStrategyHost(Option>)` | `name`, `replacement_size(model)`, `compact(input, cancel) -> Completed {retain_from, replacement, strategy, diagnostics} \| Skipped {reason, diagnostics} \| Failed {error, diagnostics} \| Err(HostError)` | `ProductSummaryStrategy` (§5.2) | +The model facts and the summary policy are the `contextFacts` and `summaryStrategy` operations; +the profile that compacts installs both owners' parts. §4.2's object ports are replaced by the +[Context facts](ContextFacts.md) and [Summary strategy](SummaryStrategy.md) contracts (#2025). Both values are bound explicitly in every profile, as `ContextModelHost` is today. The policy exists when both are `Some`. One `Some` without the other is an assembly defect that @@ -508,14 +508,8 @@ pub struct ProductSummaryStrategyPlugin { host: DepKey } pub struct ContextMethodsPlugin; // Deps = (Keyed, Keyed); methods.register(ctx, "session.context", ..) -// dim-app-server/src/cli.rs, defaults::install_compaction, the one install of every profile -// that compacts; the product profile passes ProductContextModel and its product home, -// the --models profile passes AimuxModels and its --home: -builder.session_value(Arc::new(ContextModelHost(Some(model)))) - .require_feature(Feature::new("ContextCompaction") - .session("ProductSummaryStrategy", |names| names.part(ProductSummaryStrategyPlugin::new(names)?)) - .session("ContextMethods", |names| names.part(ContextMethodsPlugin))); -// The mock profile binds ContextModelHost(None) and CompactionStrategyHost(None). +// The binding shapes of these two parts are stated by the Context facts and Summary strategy +// contracts (#2025); this document keeps only the plugin row that installs them. ``` ## 5. Flows diff --git a/docs/design/plugins/ContextFacts.md b/docs/design/plugins/ContextFacts.md new file mode 100644 index 0000000000..c76aeac33d --- /dev/null +++ b/docs/design/plugins/ContextFacts.md @@ -0,0 +1,257 @@ +# Context facts + +Scope: session. Issue: #2025. + +The owner answers a model's context limits and how many tokens a request, a message or a request's fixed prefix take. Today the same need is the `contextModelHost` object: a `resolve(request)` call that returns an object whose methods the callers use one at a time. This document replaces the object with four reads. The owner has no state beyond its resolved counting rules and writes nothing. + +## Use and scope: responsibility split + +The owner answers: + +- **The model's limits.** The context window, the output allowance every request reserves, the input threshold that triggers compaction, and the counting algorithm's identity when one exists. +- **A request's count.** The tokens of one complete request as the model's counter sees them. +- **A request's components.** The fixed contribution (system and tools), one contribution per message, and the estimate of a contribution. + +Callers keep: + +- What the budget decision is: ContextPreparation's threshold rule, the retention reserve and the fallback cuts. +- Which requests are counted and when a saved count may be reused: ContextUsage's statistics and its baseline association. +- How a summary's planned size is computed: the summary owner asks for the planned message's count. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| ContextPreparation decides whether a request is over the input budget | No: the limits, the reserve rule and the counter are the owner's knowledge; composing them in the caller duplicates the model's capacity facts | `describe`, `count` | +| Loop runs a compaction step and needs the window and the request's count | Yes: `describe` and `count` | Business composition | +| ContextUsage records a request's statistics additively | No: the counter's algorithm, its fixed contribution and its per-message contribution are one counting rule; splitting them across callers breaks the equality between `count` and the sum of the components | `contributions`, `estimate` | +| The summary owner plans the replacement size | Yes: `describe` for the algorithm and `count` for the planned message | Business composition | + +## Caller example + +```rust +// ContextPreparation: one request's budget. +let limits = owner.describe(DescribeRequest { model: selection.clone() }).await?; +let counted = owner.count(CountRequest { request: request.clone() }).await?; +let over = counted.tokens > limits.threshold_tokens; +``` + +```rust +// ContextUsage: the contributions of one request, when the model has an additive counter. +// A model without an additive counter has no algorithm; the caller keeps complete-request counts only. +if owner.describe(DescribeRequest { model: selection.clone() }).await?.algorithm.is_none() { + return Err(UsageError::NotCountable); +} +let parts = owner.contributions(ContributionsRequest { + model: selection.clone(), + fixed: Some(Fixed { system, tools }), + messages, +}).await?; +// Contributions are the counter's facts; the caller estimates them, now and after a restart. +let total = match parts.fixed { + Some(fixed) => owner.estimate(EstimateRequest { + model: selection.clone(), + algorithm: parts.algorithm.clone(), + contribution: fixed, + }).await?.tokens, + None => 0.0, +} + { + let mut sum = 0.0; + for message in parts.messages { + sum += owner.estimate(EstimateRequest { + model: selection.clone(), + algorithm: parts.algorithm.clone(), + contribution: message, + }).await?.tokens; + } + sum +}; +``` + +## Own contract + +### Dependencies + +None. The capability snapshot, the config and the messages arrive in the request data; the model catalog is read by the profile that installs the owner, not while answering. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `describe` | The model's limits and counter identity | `{model}` | `{contextWindow, outputTokens, thresholdTokens, algorithm?}` | None; the owner completes the read | `not_adopted`, `closed` | +| `count` | One complete request's tokens | `{request}` | `{tokens}` | None | `not_adopted`, `closed` | +| `contributions` | The fixed and per-message contributions of a request, as the counter's facts | `{model, fixed?, messages}` | `{algorithm, fixed?: Contribution, messages: [Contribution]}` | None | `not_adopted`, `unsupported`, `closed` | +| `estimate` | The tokens of one contribution | `{model, algorithm, contribution}` | `{tokens}` | None | `not_adopted`, `unsupported`, `algorithm_mismatch`, `closed` | + +`model` is the Session's model selection: provider, model, adopted capability snapshot, config and metadata; `count` takes the request, which already carries the selection. `contributions` answers the counter's facts in request order and, when `fixed` is present, the fixed contribution of the given system and tools. A `Contribution` is the serialized-byte and image facts the counter works from, so a caller can save it and estimate it again after a restart. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `not_adopted` | all | Adopt the model again and retry: the snapshot is missing, belongs to another provider or model, or the output allowance is absent | +| `unsupported` | `contributions`, `estimate` | This model has no additive counter; keep only complete-request counts | +| `algorithm_mismatch` | `estimate` | Recompute with the algorithm `describe` and `contributions` reported; a saved contribution of another algorithm cannot be estimated | +| `closed` | all | This generation is unloading; call the replacement generation | + +`describe` and `count` do not fail for a model without an additive counter: `algorithm` is absent and `count` still answers. + +### Flows + +The four operations hold no resource and wait for nothing; their rows cover only owner close. + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `describe`, `count`, `contributions`, `estimate` | The owner resolves the model from the request data, counts and answers | A dropped call answers nothing and leaves nothing | An in-flight call ends `closed`; the generation answers no further call | The calling row drops the call; the owner closes | + +## Exceptions with reasons + +- A profile that does not install this owner has no `contextFacts` name; a part that requires it fails at assembly. Profiles that do not compact therefore omit both `contextFacts` and `summaryStrategy` rather than binding an absent value. + +- `algorithm` is absent for a model whose count cannot be composed from contributions: reporting an algorithm it does not have would make `contributions` and `estimate` look available. +- `estimate` takes the algorithm as data: a caller that saved contributions in a Timeline fact reads them back after a restart, and the saved algorithm is the only proof that the numbers share one rule. +- `not_adopted` covers both a missing snapshot and a snapshot of another model: the caller's next step is the same, adopting the model again. + +## Verification + +- `describe` answers the window, allowance and threshold of an adopted model; a missing or foreign snapshot is `not_adopted`. +- `count` equals the fixed contribution plus the message contributions, each summed through `estimate`, for a model with an additive counter; a saved contribution estimates again after a restart with the same number. +- `contributions` answers the counter's facts for a model with an additive counter and is `unsupported` otherwise; `estimate` with another algorithm is `algorithm_mismatch`. +- A call in flight when the generation closes ends `closed`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part publishing four reads; it writes no Timeline event and folds no state. | +| §2 scopes | Session: the limits are properties of the model the Session runs, shared by its branches. | +| §3 orthogonality | No other owner's state is read; the model selection is data. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of an object: the reply is data. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning: the budget rule stays with ContextPreparation. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path. | +| §4 rule 7 | Callers use the reads; no caller holds a counter object. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact: counts are statistics, persisted by ContextUsage in its own record. | +| §7 values, ids and objects | Every reply is a value; the old `Arc` no longer crosses. | +| §7 one interface | One name, `contextFacts`, on the owner type. | +| §7 cross-language | Requests and replies are data. | +| ADR 002 D1 | Session: the model facts are shared by the Session's branches. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The profile that installs the owner reads its catalog; the owner injects nothing. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Supersedes + +This contract replaces the `contextModelHost` object; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Context accounting and compaction → ContextModelHost` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `contextModelHost` row. + +Rule D: no client wire protocol or user-visible behavior changes; the statistics ContextUsage persists keep the same facts. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::{Message, ModelRequest, ModelSelection, SystemPrompt, ToolDefinition}; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DescribeRequest { + pub model: ModelSelection, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Limits { + pub context_window: f64, + pub output_tokens: f64, + pub threshold_tokens: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub algorithm: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CountRequest { + pub request: ModelRequest, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CountReply { + pub tokens: f64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Fixed { + pub system: Option, + pub tools: Option>, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ContributionsRequest { + pub model: ModelSelection, + pub fixed: Option, + pub messages: Vec, +} + +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Contribution { + pub serialized_bytes: u64, + pub images: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ContributionsReply { + pub algorithm: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fixed: Option, + pub messages: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EstimateRequest { + pub model: ModelSelection, + pub algorithm: String, + pub contribution: Contribution, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ContextFactsError { + #[error("{message}")] + NotAdopted { message: String }, + #[error("{message}")] + Unsupported { message: String }, + #[error("{message}")] + AlgorithmMismatch { message: String }, + #[error("{message}")] + Closed { message: String }, +} + +impl PublicService for ContextFacts {} + +#[rutis::service(name = "contextFacts")] +impl ContextFacts { + pub async fn describe(&self, request: DescribeRequest) -> Result { /* ... */ } + pub async fn count(&self, request: CountRequest) -> Result { /* ... */ } + pub async fn contributions( + &self, + request: ContributionsRequest, + ) -> Result { /* ... */ } + pub async fn estimate(&self, request: EstimateRequest) -> Result { /* ... */ } +} +``` + +`ContributionsReply.fixed` and `.messages` are the counter's facts, aligned with the request's messages; `estimate` turns one into tokens. `Contribution` stays the serialized-bytes and image facts the counter works from. Errors derive `serde` with `#[serde(tag = "code", rename_all = "snake_case")]`, so the wire code is the variant name. diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md new file mode 100644 index 0000000000..3b51aa16bc --- /dev/null +++ b/docs/design/plugins/ContextProjection.md @@ -0,0 +1,301 @@ +# Context projection + +Scope: branch. Issue: #2025. + +The owner folds its own branch's facts into the context a model request carries, renders that context to messages, and encodes or decodes the recovery snapshot that lets a later fold start after a compaction. Today the same need is the `historyRenderer` value: a table of Rust functions at Session scope, whose methods take a caller-supplied `&Timeline` or `&Session`, plus a Session-level `context_in` that folds another branch's history by id. This document replaces the value with branch-scoped operations. + +## Use and scope: responsibility split + +The owner answers: + +- **The context at a cutoff.** Which events place context, how a compaction's replacement and baseline apply, and the positions the fold covered. +- **Rendered entries.** The context and its `HistoryEntry` list at one cutoff, for callers that need both. +- **A request-local projection.** The rendered entries and the compaction in force at a cutoff, folded page by page; the fold releases each page and the reply carries no event list, so a long history is not held whole. +- **Recovery snapshots.** Encode the projection at a completed compaction's cut, validate a saved snapshot against its anchor, and decode the checkpoint it carries. + +Callers keep: + +- Which cutoff a request uses: Loop's committed position and its fixed `through`. +- Whether a saved count or projection may be reused: ContextPreparation's validation rules. +- When a snapshot is saved and which interpreter is current: ContextPreparation's compaction flow. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Loop builds a request's context at a fixed cutoff | No: which events carry context, how compaction replaces a range and how the baseline folds are the owner's knowledge; composing them from `timeline.query` puts a second projection in the caller | `renderedStream`, `renderedContext` | +| ContextPreparation checks the budget at its own cutoff and compacts | Yes: the same reads, and the projection Loop hands over | Business composition | +| A compaction saves its snapshot after the fact commits | No: encoding and the anchor check are one rule with decoding | `snapshot`, `streamCheckpoint` | +| A later preparation resumes from a saved snapshot | No: the owner validates the snapshot against its anchor before decoding | `snapshotFromCheckpoint`, `snapshot` | +| A test or an example inspects a folded context | Yes: `renderedContext` answers the context and the entries | Business | + +## Caller example + +```rust +// Loop: the request's context at the committed cutoff. +let streamed = projection + .rendered_stream(RenderedStreamRequest { through, batch: 256 }) + .await?; +let request = settings.request( + streamed.history.iter().map(|entry| std::sync::Arc::new(entry.message.clone())).collect(), +); +``` + +```rust +// ContextPreparation: the snapshot of a completed compaction. +let snapshot = projection + .snapshot(SnapshotRequest { context, retain_from: cut, anchor: fact.clone() }) + .await?; +``` + +```rust +// A later preparation: the checkpoint a saved snapshot carries, if the anchor matches. +let Some(checkpoint) = projection + .snapshot_from_checkpoint(SnapshotFromCheckpointRequest { checkpoint, anchor }) + .await? +else { + return Ok(None); // the snapshot does not resume here; the fold starts earlier +}; +``` + +## Own contract + +### Dependencies + +`B:Timeline` — the owner folds the branch's own facts through the branch's Timeline operations; it never asks another branch or the Session for events. The projection policy is factory configuration: the assembly installs the owner with the policy in force, and a host that needs another policy installs another part. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `renderedStream` | The rendered entries and the compaction in force at a cutoff, folded page by page, without retaining events | `{through, batch}` | `{history, configuration?, prompt?, ancestry, compaction?, branches, compactionCut?}` | The caller drops the call; the fold stops at its last page | `future_sequence`, `invalid`, `storage`, `closed` | +| `renderedContext` | The context and rendered entries at a cutoff, with the events the projection kept | `{through}` | `{context, history}` | The caller drops the call | `future_sequence`, `invalid`, `storage`, `closed` | +| `snapshot` | Encode the projection at a completed compaction's cut | `{context, retainFrom, anchor}` | `{snapshot}` | None; the owner completes the read | `invalid`, `storage`, `closed` | +| `streamCheckpoint` | The checkpoint of the fold that starts after a compaction's cut | `{through, retainFrom, batch}` | `{checkpoint}` | The caller drops the call | `future_sequence`, `invalid`, `storage`, `closed` | +| `snapshotFromCheckpoint` | A snapshot that carries an already-computed checkpoint | `{checkpoint, anchor}` | `{snapshot}` or none when the anchor does not match | None | `invalid`, `storage`, `closed` | + +`through` is a committed sequence of this branch; `batch` is the page size of the fold; `retainFrom` is the id of the compaction's cut event; `anchor` is the completed compaction fact a snapshot anchors to. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `future_sequence` | `renderedStream`, `renderedContext`, `streamCheckpoint` | Fix the cutoff: it is above the branch's committed head | +| `invalid` | all | Fix the request: a batch size of zero, a cut outside the branch chain, an anchor that is not a completed compaction, a snapshot whose interpreter is not current | +| `storage` | all | The branch's facts could not be read; the request fails for this attempt; a retry re-reads | +| `closed` | all | The branch is closing; stop preparing requests | + +`snapshotFromCheckpoint` answers none, not an error, when the snapshot cannot be used at that anchor: the caller folds from an earlier point. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `renderedStream` | The owner selects the snapshot a checkpoint validates, folds page by page from its resume position, releases each page, and answers the streamed projection | A dropped call stops the fold at its last page; no state is written | An in-flight fold ends `closed`; the generation answers no further call | The calling row drops the call; the owner holds no resource between pages | +| `renderedContext` | The owner folds the same content without the request-local form | A dropped call ends the read | `closed` | The owner | +| `snapshot` | The owner folds to the cut, builds the checkpoint and encodes it with the snapshot's digest | A dropped call answers nothing; nothing is written | `closed` | The owner | +| `streamCheckpoint` | The owner finds the cut's position, resumes from a valid snapshot and folds to the cutoff | A dropped call ends the fold | `closed` | The owner | +| `snapshotFromCheckpoint` | The owner encodes the given checkpoint at the anchor | A dropped call ends the read | `closed` | The owner | + +## Exceptions with reasons + +- `renderedStream` and `renderedContext` take a cutoff, not a branch id: the owner is a branch part and folds its own branch's facts; a Session-scoped fold by branch id returned another owner's history and is removed. +- The projection policy is factory configuration rather than a Session value: a table of Rust functions cannot cross languages, and a host that substitutes the projection installs another part, so no Rust-only value sits on the public face. +- `snapshotFromCheckpoint` answers none instead of failing when the anchor does not match: a snapshot is optional acceleration, and the caller's next step is the same fold the snapshot would have skipped. `snapshot` is the caller's own cutoff and answers `invalid` when the interpreter is not current or the cut is outside the chain; it never answers none. +- `streamCheckpoint` takes `batch`: a streamed fold's page size is the caller's memory decision, and the checkpoint must be built from the same fold the caller will use. + +## Verification + +- A fold at a cutoff returns the events that place context and the compaction in force, with positions that compare across the branch chain. +- `renderedStream` releases each page and its reply carries no event list: a fold larger than one page keeps only the current projection. `renderedContext` materializes the events and is the inspection read. +- `snapshot` encodes the checkpoint of a completed compaction and answers `invalid` for another interpreter or a cut outside the chain; it never answers none. `snapshotFromCheckpoint` answers none when the anchor does not match. +- `context_in` no longer exists; every read is the caller's own branch. +- A call in flight when the branch closes ends `closed`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part. It folds the branch's facts but writes none, so it is not a Capability; the projection policy is its factory configuration. | +| §2 scopes | Branch. The fold reads its own branch's Timeline and nothing across scopes. | +| §3 orthogonality | No other owner's state is read; the projection is a pure function of the branch's public facts. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of a business object; the streamed projection is a value. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | The projection policy is configuration, not a core special case. | +| §4 rule 5 | The fold reads committed facts; publishing facts is not affected. | +| §4 rule 6 | The projection renders what the branch's adopted inputs and tool results placed; it adds no context path of its own. | +| §4 rule 7 | Callers use these operations; no caller folds from `timeline.query` itself. | +| §4 rule 8 | No infrastructure change: the branch's Timeline already serves the reads. | +| §4 rule 9 | No Timeline fact; a snapshot is optional derived state. | +| §7 values, ids and objects | Every reply is a value; the caller's `&Timeline` and `&Session` no longer cross. | +| §7 no proxy lookup | The owner folds its own branch; the Session-level `context_in` is removed. | +| §7 one interface | One name, `contextProjection`, on the owner type; `historyRenderer` leaves the catalog. | +| §7 cross-language | Requests and replies are data. | +| ADR 002 D1 | Branch: the projection is derived from the branch's facts and shares their lifetime. | +| ADR 002 D2 | No wiring plugin: the part is the owner; the policy is its configuration. | +| ADR 002 D3 | Depends on the branch's Timeline, at its own scope. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None: the owner needs only the branch's `timeline` operations. + +## Supersedes + +This contract replaces the `historyRenderer` value; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Loop and ContextPreparation → HistoryRenderer` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `historyRenderer` row. +- `docs/design/plugins/ContextCompaction.md` §4.2 and the sections that name `HistoryRenderer`: the projection is this owner's, and the history renderer's name leaves the catalog. + +Rule D: no client wire protocol or user-visible behavior changes; the streamed reply keeps the fields the callers use, and the model-visible text is unchanged. + +Left to the upper layer: #2102's `PrepareRequest.projection` still names the internal `history::StreamedContext`. The wire types are `crate::context_projection::{StreamedContext, Entry, History}` as defined here; #2102 aligns its import to these names when it rebases on this contract. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::{ + AgentEvent, ContextBaselineEntry, Message, ProjectionCheckpoint, RecoverySnapshot, + TimelinePosition, +}; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RenderedStreamRequest { + pub through: u64, + pub batch: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StreamedContext { + pub history: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub configuration: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt: Option, + /// Root first: how positions compare across the branch chain. + pub ancestry: Vec, + /// The completed compaction in force, with its cut and baseline. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + /// Root first: the segments the fold read. + pub branches: Vec, + /// The position of the cut in effect. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction_cut: Option, +} + +/// The wire form of one rendered entry. The owner maps `HistoryEntry` to it +/// (an `Arc` and an `Arc<[ContextBaselineEntry]>` become owned values); +/// the internal type is unchanged. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Entry { + pub id: String, + pub message: Message, + pub tool_context: bool, + pub baseline: Vec, + pub event_id: String, + pub position: TimelinePosition, +} + +/// The wire form of a folded context. The owner maps `ContextHistory` to it +/// (`Arc` becomes an owned event); the internal type is unchanged. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct History { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub checkpoint: Option, + pub ancestry: Vec, + pub events: Vec, + pub positions: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RenderedContextRequest { + pub through: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RenderedContextReply { + pub context: History, + pub history: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SnapshotRequest { + pub context: History, + pub retain_from: String, + pub anchor: AgentEvent, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SnapshotReply { + pub snapshot: RecoverySnapshot, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StreamCheckpointRequest { + pub through: u64, + pub retain_from: String, + pub batch: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckpointReply { + pub checkpoint: ProjectionCheckpoint, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SnapshotFromCheckpointRequest { + pub checkpoint: ProjectionCheckpoint, + pub anchor: AgentEvent, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ProjectionError { + #[error("{message}")] + FutureSequence { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + Storage { message: String }, + #[error("{message}")] + Closed { message: String }, +} + +impl PublicService for ContextProjection {} + +#[rutis::service(name = "contextProjection")] +impl ContextProjection { + pub async fn rendered_stream( + &self, + request: RenderedStreamRequest, + ) -> Result { /* ... */ } + pub async fn rendered_context( + &self, + request: RenderedContextRequest, + ) -> Result { /* ... */ } + pub async fn snapshot(&self, request: SnapshotRequest) -> Result { /* ... */ } + pub async fn stream_checkpoint( + &self, + request: StreamCheckpointRequest, + ) -> Result { /* ... */ } + pub async fn snapshot_from_checkpoint( + &self, + request: SnapshotFromCheckpointRequest, + ) -> Result, ProjectionError> { /* ... */ } +} +``` + +`Entry` and `History` are this face's wire forms of `dim_agent_capabilities::history::HistoryEntry` and `dim_agent_runtime::ContextHistory`; the owner maps them in one place, and the internal types stay unchanged. `ProjectionCheckpoint`, `RecoverySnapshot`, `AgentEvent`, `TimelinePosition`, `Message` and `ContextBaselineEntry` already derive serde, so `Entry` and `History` need no code change elsewhere. `renderedStream` carries no folded event list; `renderedContext` and the snapshot reads carry the events because their callers need them. Errors cross as `{code, message}`, `code` from the variant name. diff --git a/docs/design/plugins/FileAccessFacts.md b/docs/design/plugins/FileAccessFacts.md new file mode 100644 index 0000000000..799f74f55f --- /dev/null +++ b/docs/design/plugins/FileAccessFacts.md @@ -0,0 +1,195 @@ +# File access facts + +Scope: session. Issue: #2025. + +The owner answers what one call's target path is and which file-access facts hold for it: inside the workspace, inside a system path, an owned Session file, or covered by a grant. Permission asks before approving a file call; the process preparation asks for the confirmed workspace roots before running a command. Today the same need is the `FileAccessFacts` object and its `ReadFileAccessFacts` trait; this document replaces both with two reads. + +## Use and scope: responsibility split + +The owner answers: + +- **The facts.** Workspace, system, owned and grant membership under the branch's effective access preset and the grant mode the call asks for, plus the reason a workspace discovery failed when it did. +- **The confirmed roots.** The workspace and the managed worktree roots a command's process boundary may use. + +Callers keep: + +- What the facts mean: Permission's risk and approval decision, and which facts it shows. +- Which paths a tool is asked to read or write. +- The process boundary decision: the command preparation applies the roots it is given. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Permission decides a file call with the facts under the branch's access preset | No: the grant rule reads the preset, and the owned and grant facts come from two owners the caller would otherwise each hold | `check`; Permission keeps resolving the target, as ADR 014 D3 assigns it | +| A command's preparation needs the confirmed workspace boundary | No: the workspace and the managed worktree roots are validated against the Session's workspace; a caller that composed them could start a process outside the boundary | `workspaceRoots` | + +## Caller example + +```rust +// Permission: one file call's target and facts under the requested access. +let facts = access + .check(Check { access: FileAccess::WorkspaceReadWrite, mode: GrantMode::Write, path: resolved }, cancelled) + .await?; +let inside = facts.workspace || facts.system || facts.owned || facts.grant; +``` + +```rust +// HostPlatform: the boundary a command may use. +let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; +``` + +## Own contract + +### Dependencies + +- The Session's working directory and identity: the owner's own Session part. +- `P:fileStorage` — `stat` and the path validation the workspace root uses. +- `P:sessionFiles` — whether the Session owns the target file. +- `S:sessionGrants` — the Session's file grants, read by `check` only. +- `P:worktrees` — managed worktree roots that extend the workspace. +- `P:hostPlatform` — the platform roots the `system` fact compares against. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `check` | Answer the facts of one resolved path under the branch's access preset | `{access, mode, path}` | `{workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | +| `workspaceRoots` | The workspace and managed worktree roots a command may use | `{cwd}` | `{roots}` | The caller drops the call | `invalid`, `unavailable`, `cancelled`, `closed` | + +`access` is the branch's access preset (`dim_agent_types::FileAccess`: `read-only`, `workspace-read-write`, `unrestricted`); `mode` is the grant mode the call asks for (`dim_agent_types::grant::GrantMode`: `read`, `write`); `path` is the path the caller already resolved, as ADR 014 D3 assigns resolution to Permission. A write grant is inert under `read-only` and active under `workspace-read-write`; `unrestricted` does not widen grants because it already allows every write. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `invalid` | both | Fix the input: an empty path, or a path the workspace cannot resolve | +| `unavailable` | both | The owned-file or grant facts could not be read; Permission denies the call, and a command is not started with an unconfirmed boundary | +| `cancelled` | both | Nothing was decided; the caller's own cancellation ended the read | +| `closed` | both | The Session is closing; the call is refused | + +`discoveryError` is a field, not an error: a failed workspace discovery answers `workspace: false` with the reason, and the caller keeps the original file approvals visible with that reason. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `check` | The owner answers the facts for the caller's resolved path, reading the owned file and the grants | A dropped call ends the reads; nothing is decided | An in-flight call ends `closed` | The calling row; the owner holds no resource | +| `workspaceRoots` | The owner resolves the cwd, returns the workspace and the managed worktree roots | A dropped call ends the read | `closed` | The calling row | + +## Exceptions with reasons + +- No `sessionId` in the request: the owner is the Session's instance, so the Session id is the owner's own identity; a request field would let one Session ask for another's facts. +- `discoveryError` is a field: a workspace that cannot be discovered is a fact the caller shows, not a refusal; approvals the user already gave stay available. +- `access` is the three-valued access preset, not a read/write flag: under `read-only` a write grant is inert, and the owner decides that from the preset the caller passes. +- `workspaceRoots` fails rather than answering an empty list: a command started with an unconfirmed boundary would run outside the workspace the user approved. + +## Verification + +- `check` answers the four facts for the resolved path; a write grant under `read-only` answers `grant: false`; a relative path is `invalid`. +- An owned Session file and a granted path each answer their fact under the requested mode; a path outside every fact answers all false. +- A failed discovery answers `workspace: false` with `discoveryError` and no error. +- `workspaceRoots` answers the workspace plus the managed worktree roots; `unavailable` when the workspace cannot be read. +- A call in flight when the Session closes ends `closed`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part publishing two reads; it writes no Timeline event and folds no state. | +| §2 scopes | Session: the facts derive from the Session's workspace, files and grants. | +| §3 orthogonality | Reads the Session's own owners and process services; changes nothing. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of a business object; the facts are data. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning: Permission's risk rules stay with Permission. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path. | +| §4 rule 7 | Callers use the reads; no caller holds the owner's path state. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact. | +| §7 values, ids and objects | Every reply is a value; the old `Arc` no longer crosses. | +| §7 one interface | One name, `fileAccessFacts`, on the owner type. | +| §7 cross-language | Requests and replies are data; the path is a UTF-8 string. | +| ADR 002 D1 | Session: the facts are the Session's workspace and grants. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Reads process services at an enclosing scope and Session owners at its own. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Supersedes + +This contract replaces the object shape of the file-access facts; the delivery in #2025 carries the migration. + +- [ADR 014](../../adr/014-file-access-facts.md): the query is stated here as a Session-scoped operation `check`, with the Session instance supplying the session id and `FileAccess` and `GrantMode` as the same query arguments the ADR names. Resolution stays with Permission, as ADR 014 D3 assigns it; the reply carries the four facts and no `target`. +- `crate::file_access::ReadFileAccessFacts` and the `FileAccessFacts` wrapper: the two reads replace the trait and the object. + +Rule D: no client wire protocol or user-visible behavior changes; the change is plugin-facing. + +## Binding appendix + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_runtime::PublicService; +use dim_agent_types::grant::GrantMode; +use dim_agent_types::FileAccess; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Check { + pub access: FileAccess, + pub mode: GrantMode, + pub path: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileFactsReply { + pub workspace: bool, + pub system: bool, + pub owned: bool, + pub grant: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub discovery_error: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WorkspaceRoots { + pub cwd: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Roots { + pub roots: Vec, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum FactsError { + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + Unavailable { message: String }, + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, +} + +impl PublicService for FileAccessFacts {} + +#[rutis::service(name = "fileAccessFacts")] +impl FileAccessFacts { + pub async fn check(&self, request: Check, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn workspace_roots( + &self, + request: WorkspaceRoots, + cancelled: CancelledFn, + ) -> Result { /* ... */ } +} +``` + +`cancelled` is the binding's cancellation argument, not a request field. Paths cross as UTF-8 strings; a path that is not UTF-8 is `invalid`. Errors cross as `{code, message}`, `code` from the variant name. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..62f95cb967 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,12 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [SessionScope](SessionScope.md) (owner contract) | — | the Session's creation record, identity, phase, leases, fault record, content mounts and branch construction behind `sessionScope` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Request settings](RequestSettings.md) (owner contract) | — | the default request settings value behind `requestSettings` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Context facts](ContextFacts.md) (owner contract) | — | the model's limits and token counting behind `contextFacts` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Context projection](ContextProjection.md) (owner contract) | — | — | the branch's context fold and recovery snapshots behind `contextProjection` | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Summary strategy](SummaryStrategy.md) (owner contract) | — | the summary policy for compaction behind `summaryStrategy` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [File access facts](FileAccessFacts.md) (owner contract) | — | the Session's resolved file facts and confirmed roots behind `fileAccessFacts` | — | [#2025](https://github.com/arcships/dim/issues/2025) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | @@ -20,7 +26,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [Pursuit](Pursuit.md) (evaluator judge mode of Goal) | — | `judge` on `session.goal.set` | completion requests decided by evaluator branches; conclusion inputs and Goal's outcomes | M2; #422 | | [ModelRecovery (proposal)](ModelRecovery.md) | — | — | proposed disposer registration (Loop port not implemented); the handover input it writes | [#1210](https://github.com/arcships/dim/issues/1210) | | [Web](Web.md) | — | `web_search`, `web_fetch` tools | — | P2; optional package | -| [ContextCompaction](ContextCompaction.md) (supplements to Loop and ContextPreparation; [ContextUsage proposal](ContextUsage.md)) | — | `ContextModelHost`, summary `CompactionStrategyHost`, `session.context.*` | `context/compact` command and compaction step in Loop; K-turn cut and usage query in ContextPreparation | P2 | +| [ContextCompaction](ContextCompaction.md) (supplements to Loop and ContextPreparation; [ContextUsage proposal](ContextUsage.md)) | — | `session.context.*`; the model facts and the summary policy are [Context facts](ContextFacts.md) and [Summary strategy](SummaryStrategy.md) (#2025) | `context/compact` command and compaction step in Loop; K-turn cut and usage query in ContextPreparation | P2 | | [Prompt](Prompt.md) | — | `guideEntries`: the input guide's frame, the entries in force and their composition | `Prompt`: the System its publisher adopts carries the composition over the entries in force, and a host-prepared request carries the same composition, placed by Loop | #548 | | [PromptSources](PromptSources.md) | — | the named sources, their policy texts at the factory configuration, and the state and rule entries | — | #548 | | [EnvironmentClients](EnvironmentClients.md) | App Server read-only `sessionClientsHost` presence (Connection and UiHost) | — | presence snapshots as `` inputs at branch open and on `ClientsChanged` | #1019 | diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md new file mode 100644 index 0000000000..4e9ed4e3af --- /dev/null +++ b/docs/design/plugins/RequestSettings.md @@ -0,0 +1,165 @@ +# Request settings + +Scope: session. Issue: #2025. + +The owner publishes the model settings a turn starts from: the Session's model selection, its adopted capability snapshot, the config to send and the request metadata, as one value. Today the same need is the `prepareModelHost` object port; this document replaces it. The owner has no state of its own and writes nothing. + +## Use and scope: responsibility split + +The owner publishes: + +- **The default settings value.** `{providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}` derived once, when the Session is assembled, from the creation record and — when the profile has one — the model catalog. +- **The allowance repair, at the read boundary.** The adopted output allowance is bounded by the model's declared output and half the window at the point where Loop reads the value, including a restored Session that replays an older `context/configured` fact: the same rule runs on the replay path, so an allowance equal to or above the window never reaches the request. Prompt's repair at adoption may run too, but it is not the only place. + +Callers keep: + +- Which messages the request carries: Loop's history and guide. +- Which tools it declares: ToolBinding's pinned definitions for the request. +- The turn and request ids and the session id in the metadata: Loop writes them. +- The adopted configuration published during the run: Prompt adopts sources and model changes into the Timeline as `context/configured`, and Loop reads that record instead of this value. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Loop prepares the model settings of a turn that has no adopted configuration yet | No: the catalog defaults and the allowance rule are the owner's knowledge; composing them in Loop duplicates the provider profile's decision | `settings` | +| Loop requests with a configuration Prompt adopted during the run | Yes: Loop reads the adopted record from the Timeline | Business | +| A caller changes the model for the next turn | Yes: Prompt adopts the change as the `context/configured` Timeline record; the creation record does not change | Business | + +## Caller example + +```rust +// Loop: the first request of a Session before any configuration is adopted. +let defaults = request_settings.settings(); +let settings = ModelSettings { + provider_id: defaults.provider_id, + model_id: defaults.model_id, + capability_snapshot: defaults.capability_snapshot, + config: defaults.config, + system: Some(guide.compose_system(&branch, defaults.system)), + tools: Some(binding.definitions(&request_id)?), + metadata: { + let mut metadata = defaults.metadata.unwrap_or_default(); + metadata.session_id = Some(session_id); + metadata.turn_id = Some(turn_id); + metadata.extensions.insert("requestId".into(), request_id.into()); // per request, written by Loop + Some(metadata) + }, +}; +``` + +## Own contract + +### Dependencies + +None. The assembly provides the value; the aimux profile also reads its model catalog while building it. The owner reads no other owner's state. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `settings` | The Session's default request settings | `{}` | `{providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}` | None | None | + +### Errors + +None: the value is fixed before the Session is published. A profile that cannot derive settings fails its own assembly instead of answering an error here. + +### Flows + +None: the operation holds no resource and waits for nothing. + +## Exceptions with reasons + +- `config` may already be the adopted allowance repair: the owner repairs the stored allowance against the declared limits, so a request started from this value cannot exceed the model's capacity. +- The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`), and Loop reads that record through the same repair; the value is never stale for its one use. +- `metadata` carries the profile's static extensions. The per-request members — session, turn and request id — are Loop's: the aimux request log reads `requestId` from the request in flight, so the value cannot carry it. + +## Verification + +- `settings` answers the record's model, snapshot and config; with a catalog entry, the config is the catalog default repaired to the declared allowance. +- A Session whose configuration was adopted mid-run is requested from the adopted record, not from this value. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part that publishes a value; it writes no Timeline event and folds no state. | +| §2 scopes | Session: the value derives from the Session's record. | +| §3 orthogonality | No other owner's state is read after assembly. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of a business object. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in the core: the provider profile decides the catalog defaults. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: the value carries no messages. | +| §4 rule 7 | Loop calls the operation; no caller reads the owner's inputs. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact: settings that a later turn reads are Prompt's adopted record, not this value. | +| §7 values, ids and objects | The reply is a value; no object, id or handle crosses. | +| §7 one interface | One name, `requestSettings`, on the owner type; the old `prepareModelHost` operation and object are removed. | +| §7 cross-language | The reply is data. | +| ADR 002 D1 | Session: the settings derive from the Session's creation record. | +| ADR 002 D2 | No wiring plugin: the value is on the owner's own service and the part reads the catalog directly. | +| ADR 002 D3 | The aimux profile reads its own process service while assembling; the default profile reads nothing. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Supersedes + +This contract replaces the `prepareModelHost` object; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Loop → PrepareModelHost` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `prepareModelHost` row. + +Rule D: no client wire protocol or user-visible behavior changes; the aimux request log keeps its `requestId`, now written by Loop. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::{ + ModelCapabilitySnapshot, ModelConfig, RequestMetadata, SystemPrompt, +}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestSettings { + pub provider_id: String, + pub model_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub capability_snapshot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub system: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RepairRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RepairReply { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, +} + +impl PublicService for RequestSettings {} + +#[rutis::service(name = "requestSettings")] +impl RequestSettings { + pub fn settings(&self) -> RequestSettings { /* ... */ } + /// The one allowance rule: Loop calls it on the configuration it reads, and a + /// restored Session calls it on the replayed record before the first request. + pub fn repair(&self, request: RepairRequest) -> RepairReply { /* ... */ } +} +``` + +`ModelSelection` and the reply's members are `dim_agent_types` data; `settings` answers the value itself and `repair` answers the bounded configuration. Errors: this owner has none. diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md new file mode 100644 index 0000000000..321ff2a8cc --- /dev/null +++ b/docs/design/plugins/SessionScope.md @@ -0,0 +1,390 @@ +# SessionScope + +Scope: session. Issue: #2025. + +SessionScope is the runtime's Session owner: the creation record and identity, the phase, the activity leases and the failure record that accepted work and callers share, and the Session subtree's content instances. This document is the owner's target contract. The branch tree (#2024) and the Session store (#2018) are separate owners; their calls appear here only as dependencies or requirements. + +## Use and scope: responsibility split + +SessionScope owns: + +- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed, initial title and excluded tools, fixed when the Session is built. Every member is fixed for the Session's whole life; a caller reads the live reply language from `sessionLanguage`, never from this value. +- **Identity.** The Session id and whether the Session was restored from the store. +- **The phase.** Loading, Active, Closing, Closed, monotonic and never replaced by an earlier phase. `activated` and `closing` are the waits on the two transitions. +- **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `hold` answers an id for accepted work; the id is bound to the calling row and the owner settles it at the row's unload. A lease reports nothing and cancels nothing. +- **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. +- **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. +- **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). + +Callers keep as business: + +- When their background work may start and must stop: BranchLine, Skills, ShellInput and FileAccess wait on the phase. +- Which work counts as accepted: the extent of ShellInput's command, the lifetime of BackgroundExec's task, Report's draft and Collaboration's member. +- What a fault means for their work; the failure record says only that the Session stopped. +- Which definitions to mount and when to retire them. +- Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). +- Acting on a line's owners: the mechanism resolves a branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services. The route answers `SessionClosing` when this Session is closing, which ends the part's work, and `NoLine` when the line is not live, which is final for that line. `NoSession` never reaches a Session part ([#2127](https://github.com/arcships/dim/issues/2127)). SessionScope publishes no operation, request or reply for that path. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Read the creation record: WorkspaceTools' root and role, ToolRegistry's declaration, Permission's preset, ShellInput's cwd, PromptSources' system prompt and language seed | No: the record is the owner's state and has no other source | `config` | +| Read identity: Attachments' ownership check, Permission and tool-source attribution, the store key | No | `identity` | +| Wait for publication or for close to start: BranchLine's writer, Skills' replacement, ShellInput's refusal, FileAccess' gate | No: polling a value makes every caller write the wait | `activated`, `closing` | +| Read the phase now: Goal's state read, MCP's admission, ShellInput's refusal | No | `phase` | +| Keep accepted work from being ended by an idle release: ShellInput's command, BackgroundExec's task, Report's draft, Collaboration's member; each run outlives the call that started it | No: the idle-release decision is the owner's, and a callback cannot cover work that continues after the call returns | `hold`, settled at the row's unload | +| End a hold early, after the work's last fact, so an idle release may happen sooner | No: the id is bound to the calling row and only the owner releases it | `release` | +| Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | +| Read the current fault | No | `failure` | +| Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | +| Act on one line's owners by line id: any branch-group data face — `inputQueue.submit` or `withdraw`, `contextUsage.read`, `prompt.adoptedConfiguration`, `approval.pending` — except registration points and lifecycle services ([ADR 027 D1 and D3](https://github.com/arcships/dim/pull/2029)) | No: a part cannot address a line's instance itself, and a forwarding operation here would be the facade §7 forbids | Not this owner: the runtime routes by line id ([#2127](https://github.com/arcships/dim/issues/2127)), and the caller calls that owner's typed operation | +| Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | +| Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | + +An operation exists only where the row says No. + +## Caller example + +Skills replaces content after publication, and stops when the Session closes: + +```rust +if !scope.activated().await.active { + return Ok(()); // the Session never published +} +let mounted = scope + .mount(MountDefinition { + group: CONTENT_GROUP.into(), + definition_id: skill.id.clone(), + instance_data: value, + }) + .await?; +// The instance is the Session's: its close shuts the content down. Retiring it earlier +// keeps an obsolete definition from staying published. +scope.unmount(UnmountRequest { instance_id: mounted.instance_id }).await?; +``` + +ShellInput refuses after closing starts and holds the Session while a command runs: + +ShellInput's run outlives the `shell.run` call: a cancelled call returns at once and the +run keeps its hold until it leaves ShellInput's registry. BackgroundExec and Report keep the +same shape. The id belongs to the part's row; the owner settles it at the row's unload, and +the part releases it when the work ends only so an idle release may happen sooner. + +```rust +// ShellInput: the run's hold lives in the part's registry, not in the call. +if !matches!(scope.phase().phase, Phase::Loading | Phase::Active) { + return Err(RpcError::closed()); +} +let lease = scope.hold(ctx).await?.lease_id; +self.runs.lock().unwrap().insert(run_id, lease); +``` + +A part in another language subscribes to the fault record: + +```ts +// The subscription belongs to this row: its unload releases it, and release ends it earlier. +const { leaseId } = await sessionScope.observeFault(async fault => { + if (fault?.storage) record(fault.storage) +}) +``` + +TimelineTree opens a branch after admitting it: + +```rust +// `openBranch` is the one Rust-only method; TimelineTree is the only caller. +let branch = scope + .open_branch(ctx, OpenBranchRequest { branch_id: id, ancestors }, cancelled) + .await?; +// The tree owns `branch` from here: it hands it to the branch's parts and closes it +// before the Session scope unloads. +self.nodes.insert(id, branch); +``` + +## Own contract + +### Dependencies + +SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope no longer publishes the Agent's configuration, the Skills or Collaboration factory texts, or the names of the five host ports (`historyRenderer`, `contextModelHost`, `prepareModelHost`, `prepareContextHost`, `compactionStrategyHost`); those names leave the catalog (delivery). + +The Session store constructs the Timeline engine and its Session-scope binding; SessionScope installs that binding in the Session instance and never hands it to a process caller. The operations are the engine's (#2018): the Session face publishes the per-line reads and the completion subscriptions, while `query` and `sessionConfig` stay on the process face `store` because an unloaded Session has no Session instance to host them. On the Session face the Session id is the instance's identity: its requests carry no `sessionId`, and a request that names another Session is `invalid`. One engine, one operation set, one spelling per operation. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `config` | The Session's creation record | `{}` | `SessionConfig` | None; the owner completes the read | None | +| `identity` | Who this Session is | `{}` | `{sessionId, restored}` | None | None | +| `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | +| `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | +| `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | +| `hold` | Keep an idle release from ending this Session while accepted work runs | `{}` | `{leaseId}` | None; the call does not wait | `closed` | +| `observeFault` | Receive the current fault and later reports until released or the row unloads | `{listener}` | `{leaseId}` | None; the call does not wait | `closed` | +| `release` | End a lease or a subscription before the row unloads | `{leaseId}` | `{released}`: false when the id was already released | None | `invalid` when the id belongs to another row; `closed` | +| `reportFault` | Record the fault that stopped the Session | `{fault}` | `{}` | None | None | +| `failure` | The fault in force, if any | `{}` | `{fault?}` | None | None | +| `mount` | Create a Session-owned content instance from a definition | `{group, definitionId, instanceData}` | `{instanceId}` | The caller drops the call; an instance it no longer waits for is shut down before the reply | `invalid`, `not_ready`, `cleanup`, `closed` | +| `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `unknown` when no live instance has the id; `cleanup`; `closed` | +| `openBranch` (Rust-only, `#[rutis::service(skip)]`) | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | + +A registered Session extension definition must activate its instance rows; a host-added optional group keeps its optional rows, so a Pending row there is not `not_ready`. + +`listener` is a callback by reference: it runs outside the owner's locks and outside the Timeline's commit lock. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `closed` | `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading, or an idle release is decided; stop starting work. An idle-release decision can be withdrawn while `phase` is still `active`, so a lease holder that must continue retries `hold` after the next publication | +| `invalid` | `release`, `mount` | Fix the id or the definition: an id of another row, a group outside this Session's subtree, an unknown definition | +| `unknown` | `unmount` | The id names no live instance of this Session; nothing to retire | +| `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | +| `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | +| `build` | `openBranch` | The branch did not open: `message` says why, `cleanup` is a shutdown that also failed; the tree records the branch as failed and settles it | + +`reportFault`, `failure`, `config`, `identity`, `phase`, `activated` and `closing` have no error kinds: nothing in the owner refuses them. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | +| `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is still written to the record but reaches no new subscriber | SessionScope; the listener's work by the calling row | +| `release` | The owner removes the lease or subscription and disposes it | A dropped call leaves the lease in place; the row's unload settles it | An id of an unloaded generation is `closed` | SessionScope | +| `mount` | The owner creates the instance in the Session subtree, waits for its required rows, then answers the id | A dropped call shuts the half-made instance down; a definition that never activates is shut down and answers `not_ready` | New mounts are refused; in-flight mounts settle, and every instance is shut down when the Session scope unloads | SessionScope | +| `unmount` | The owner shuts the instance down, propagates a shutdown failure as `cleanup`, and forgets the id | A dropped call does not cancel the shutdown | The Session's unload shuts down every remaining instance | SessionScope | +| `openBranch` | The owner admits the id, waits for the branch scope and its required parts, and hands the context to the tree | A dropped call settles the half-made branch before it is visible | `closed` once the Session is closing; a Construction in flight settles or ends `closed` | SessionScope creates; TimelineTree holds and closes (Exceptions) | + +#### Delivery mapping: the current instance errors + +`SessionInstanceError::Create` today covers both a caller's bad definition and a runtime creation failure; the delivery splits it into `invalid` (the group is outside the Session's subtree, the definition is unknown) and `not_ready` (the definition's row failed to activate, with the row and its state). `remove` silently succeeds for an unknown id today; the delivery makes a repeated `unmount` answer `{}` and an id this Session never issued `unknown`. + +### Flows not listed below + +`config`, `identity`, `phase`, `activated`, `closing`, `reportFault` and `failure` hold no resource. A call in flight when the Session closes answers its value or ends: `activated` answers `{active: false}`, `closing` returns, `failure` keeps the last recorded fault, and `reportFault` keeps writing to the record after close. + +## A branch's runtime context: the handover + +`openBranch` hands one object between two owners. Both cite [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md) for the scope tree, its close rights and the unload order, and [single-tree §Close](../../architecture/rust-agent/single-tree.md#关闭) for what a failed construction settles before its cause is reported. + +| Question | Answer | +| --- | --- | +| Who creates | SessionScope, inside the Session subtree, after the branch scope and its required parts are Active and the branch's loop state exists. | +| Who holds | TimelineTree: the context is inserted under the line id and handed to that line's parts; SessionScope keeps no reference after the reply. | +| Handover order | The line is admitted first, in the tree's directory; the construction answers only when the context is runnable; a failed construction settles its cleanup before the reply, and the line never becomes visible. | +| Who closes | TimelineTree, when the line ends and when the tree closes, before the Session scope unloads. | +| TimelineTree closes first | Normal Session close: every line's context closes, then the Session scope unloads. | +| SessionScope closes first | `openBranch` refuses new lines with `closed`; a construction in flight settles or ends `closed`; a context already handed over is closed by the tree in the Session's close. | +| Reload | The Session scope never reloads, so a context never outlives its generation. | + +## Exceptions with reasons + +- `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the directory and the close to TimelineTree, and the branch's whole capability machine runs behind that context. Ids, values and callbacks cannot carry it. §7 allows the object only with a lifecycle design both sides cite, and [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md) is that design: the handover table above states who creates, holds and closes it and what either side's close means. +- The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). +- `config` is the creation snapshot, serialized from the persisted record: `interactive` is omitted when true because only the native store writes that form, so a caller that decodes the value treats absence as true. Its `language` is the creation seed; `session.language.update` rewrites the stored record in place and never this value, and the live reply language is `sessionLanguage`. +- The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. +- A fault listener that returns an error stops receiving: the owner drops the registration and the lease, and the fault record is unchanged. +- `identity` carries no version: the id and the restored flag are fixed at creation. `failure` answers `{fault}` with the fault or none, matching the reply column. +- A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. `release` only lets an idle release happen sooner. +- Content instance ids are the Session's, not the caller's: the Session's close shuts down every instance it mounted, so a part that never unmounts leaves obsolete content published until the Session ends, without breaking the owner. + +## Verification + +- `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close; a lost id is settled at the row's unload; another row's id is `invalid` on release. +- `observeFault` delivers the fault in force and later reports; `release` answers `released: true` then `false`; another row's id is `invalid`; the row's unload stops delivery. +- `reportFault` keeps the first fault; a storage fault after a non-storage one wins; a non-storage fault after a storage one loses. +- `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `unknown` for an id this Session never issued. +- `activated` answers false when the Session closes before publishing; `closing` returns when the close starts. +- `openBranch` answers `closed` during the Session's close; a failed construction settles the branch scope before the reply; the tree closes every branch before the Session scope unloads. +- `identity` and every member of `config` are fixed; `phase` only moves forward through the four phases. A reply-language change never touches this value: the live language is `sessionLanguage`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part, the scope itself. It writes no Timeline event and folds no state, so it is not a Capability; it provides the Session's own state and the mounts. | +| §2 scopes | Session. Branch state and the branch directory stay with TimelineTree; the store's operations stay with the Session store. | +| §3 orthogonality | No other owner's state is read or changed. A caller that needs a new operation gets a general one here or composes it. | +| §4 rule 1 | No command event: the owner writes no Timeline fact. | +| §4 rule 2 | No handover of business objects; the phase and the fault record are the owner's own state. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | Core and assembly carry no business meaning: no content format, no prompt, no branch policy. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: content instances are mounted for their own owners; the owner adds no model-visible text. | +| §4 rule 7 | Callers use these operations; no caller reads the hold count, the fault slot or an instance's fiber. | +| §4 rule 8 | No infrastructure change. SessionScope is the runtime's Session part and its shape is the runtime's decision; the operations above are the data face those decisions already require. | +| §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | +| §7 values, ids and objects | The record, identity, phase and fault are values; a lease id is bound to the calling row and settled at its unload; a content instance id belongs to the Session and is settled by `unmount` or the Session's end; the one object is `openBranch`, with the handover design above. | +| §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | +| §7 one interface | One name, `sessionScope`, on the owner type; the wire calls every method except `openBranch`, which is marked `#[rutis::service(skip)]`; no facade or wrapper type. | +| §7 cross-language | Every operation is data, a callback by reference or an id, except `openBranch`: it hands TimelineTree the branch's runtime context, which has no serde form, and the tree is a Rust part. That is the only Rust-only method, and it is marked skip. | +| §7 one change | The implementation task deletes the old names and migrates every caller in one change. | +| ADR 002 D1 | Session scope: the record, phase, leases, faults and mounts live and die with the Session. | +| ADR 002 D2 | No wiring plugin: the operations are on the owner type; no adapter exists beside it. | +| ADR 002 D3 | No dependency: SessionScope injects nothing. | +| ADR 002 D4 | The mount list and the record are structural; no business setting is read here. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +- [#2127](https://github.com/arcships/dim/issues/2127), owned by the dim runtime, and [#2024](https://github.com/arcships/dim/issues/2024): route by line id so a Session part resolves a branch-group data face with `line_owner::(line)?` and calls that owner's typed operation, per [ADR 027 D1–D3](https://github.com/arcships/dim/pull/2029). The instance key never leaves the instance, the caller keeps no resolution between calls, and this owner adds no forwarding operation, operation-name routing or reply envelope. TimelineTree supplies the line id and the line's state, never the address. +- The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence` and `batch_end` are TimelineTree's own operations, and the Session access surface must not restate them. History reads of a line go through `timelineTree.read`, never a second `query`. +- [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` exist only on the process `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. + +## Supersedes + +This contract replaces the Session-scope paragraphs and rows that state these names; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `sessionLifecycle` rows of "Retained operations" and "New rutis APIs on existing owners", the `sessionLoader` row, the Report rows and the Report paragraph of "Calls from a Session to a selected branch" (now pointers to TimelineTree's `read` and `directory`), and the "Calls from a Session to a selected branch" section — a branch-group data face is resolved by line id, and `timelineTree.call` is removed rather than kept. `line_owner::(line)` reaches any branch-group data face except registration points and lifecycle services ([ADR 027 D1 and D3](https://github.com/arcships/dim/pull/2029); the routing mechanism is [#2127](https://github.com/arcships/dim/issues/2127)). +- `docs/design/service-faces.md`: §3.6's `timelineFactory` row, §3.2's `agentConfig`, `skillsConfig` and `collaborationConfig` rows, and §3.4's `timelineStore` row, which is now a pointer to this contract. +- `docs/design/resource-faces.md` §5: the `timelineStore` rows and the Session-scope sentence, now pointers to this contract; the engine and its process face remain #2018's. +- `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table, the `session` row of the scope table, and R2's needed names. + +These documents still name the deleted Session services in dependencies; #2025's delivery updates them in the same change: `docs/design/session-typescript.md` (307, 320-322, 329, 373, 405, 470), `docs/design/contracts/session-boundary.md:560`, `docs/design/contracts/session-access.md:566`, `docs/design/appserver/session-files.md:449`, the design-tree pages `ShellInput.md:35`, `Questions.md:50,575`, `SessionTitle.md:75-76,126,408`, `Collaboration.md:47,63`, `Report.md:133`, `Pursuit.md:46,184`, `EventHub.md:399,597`, `EnvironmentClients.md:155`, `CodeMode.md:455`, `thin-instances.md:281`, and the implementation pages `WorkspaceTools.md`, `Skills.md`, `ToolRegistry.md`, `PromptSources.md`, `PromptSuggestion.md`, `Questions.md`, `ShellInput.md`, `Prompt.md`, `Permission.md`, `Hooks.md`, `BranchTool.md`, `Attachments.md` and `TimelineTree.md`, which list `S:SessionConfig`, `S:SessionIdentity`, `S:SessionLifecycle` or `S:SessionLoader` as injected services. + +Rule D: no client wire protocol or user-visible behavior changes; every change here is plugin-facing. + +## Binding appendix + +The service is marked on the owner type under one name; the Session-scope entries for `sessionConfig`, `sessionIdentity`, `sessionLifecycle`, `sessionLoader` and `timelineFactory` stop existing (`store.sessionConfig` remains the store's process read). + +```rust +use dim_agent_runtime::{PublicService, SessionConfig, SessionFault, TimelineContext}; +use rutis::Ctx; +use std::sync::Arc; + +pub type LeaseId = String; +pub type InstanceId = u64; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Identity { + pub session_id: String, + pub restored: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PhaseReply { + pub phase: Phase, +} + +/// The wire form of the four phases; the owner maps its internal phase onto it. +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + Loading, + Active, + Closing, + Closed, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ActivatedReply { + pub active: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LeaseRequest { + pub lease_id: LeaseId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LeaseReply { + pub lease_id: LeaseId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReleaseReply { + pub released: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MountDefinition { + pub group: String, + pub definition_id: String, + pub instance_data: serde_json::Value, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MountedInstance { + pub instance_id: InstanceId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UnmountRequest { + pub instance_id: InstanceId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OpenBranchRequest { + pub branch_id: String, + pub ancestors: Vec<(String, u64)>, +} + +pub type FaultListener = + Arc) -> rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum SessionScopeError { + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + NotReady { message: String }, + #[error("{message}")] + Cleanup { message: String }, + #[error("{message}")] + Build { + message: String, + cleanup: Option, + }, + #[error("{message}")] + Unknown { message: String }, +} + +impl PublicService for SessionScope {} + +#[rutis::service(name = "sessionScope")] +impl SessionScope { + pub fn config(&self) -> SessionConfig { /* ... */ } + pub fn identity(&self) -> Identity { /* ... */ } + pub fn phase(&self) -> PhaseReply { /* ... */ } + pub async fn activated(&self) -> ActivatedReply { /* ... */ } + pub async fn closing(&self) { /* ... */ } + pub async fn hold(&self, caller: &Ctx) -> Result { /* ... */ } + pub async fn observe_fault( + &self, + caller: &Ctx, + listener: FaultListener, + ) -> Result { /* ... */ } + pub async fn report_fault(&self, fault: SessionFault) { /* ... */ } + pub fn failure(&self) -> Option { /* ... */ } + pub async fn release( + &self, + caller: &Ctx, + request: LeaseRequest, + ) -> Result { /* ... */ } + pub async fn mount(&self, definition: MountDefinition) -> Result { /* ... */ } + pub async fn unmount(&self, request: UnmountRequest) -> Result<(), SessionScopeError> { /* ... */ } + /// The one Rust-only method: the branch's runtime context has no serde form, + /// and TimelineTree, which holds and closes it, is a Rust part. + #[rutis::service(skip)] + pub async fn open_branch( + &self, + caller: &Ctx, + request: OpenBranchRequest, + cancelled: dim_agent_capabilities::host::CancelledFn, + ) -> Result, SessionScopeError> { /* ... */ } +} +``` + +`caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller-row and cancellation arguments, not request fields; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. Errors derive `serde` with `#[serde(tag = "code", rename_all = "snake_case")]`, so the wire `code` is the variant name; `build` also carries `cleanup`. `openBranch` has no serde reply and is marked skip. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md new file mode 100644 index 0000000000..aa158a73d9 --- /dev/null +++ b/docs/design/plugins/SummaryStrategy.md @@ -0,0 +1,273 @@ +# Summary strategy + +Scope: session. Issue: #2025. + +The owner replaces a range of a branch's history with a summary produced by model calls: it picks the cut the retention rule allows, summarizes the transcript in bounded chunks, and reports what it did. Today the same need is the `compactionStrategyHost` object, and `CompactionInput` carries the context model object so the owner can count. This document replaces the object with two operations and removes the object field. + +## Use and scope: responsibility split + +The owner answers: + +- **The plan.** The strategy's name and the planned token size of its replacement, so the caller can reserve the space before the strategy runs. +- **The replacement.** One compaction from a request at a cutoff: the chosen cut, the replacement messages, and the model calls and usage it took. The caller measures the duration. +- **The outcome as data.** `completed`, `skipped` or `failed`, each with diagnostics; a failure inside the strategy is an outcome, not an error. + +Callers keep: + +- When a compaction runs: the automatic threshold, the manual command and the recovery rule are ContextPreparation's and Loop's business. +- The legal cuts and the retention limit: the policy that computes them is the caller's. +- Publishing the compaction fact and saving a snapshot: the caller commits what the strategy reported. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Loop or ContextPreparation replaces a range of history when the budget is exceeded or the operator asks | No: the summary prompt, the chunking, the retry budget and the diagnostics are one policy; composing them in a caller duplicates the summarizer | `compact` | +| The retention rule reserves the replacement's planned size before running | No: the plan comes from the same target rule the prompt states, and only the owner knows it | `describe` | + +## Caller example + +```rust +// ContextPreparation: the planned size, then the compaction. +let plan = strategy.describe(DescribeRequest { model: selection.clone() }).await?; +let reserved = plan.replacement_size; +let outcome = strategy + .compact(CompactionRequest { + history, + checkpoint, + request: request.clone(), + retain_limit, + cuts, + trigger: CompactionTrigger::Threshold, + estimated_input_tokens, + baseline_source, + baseline_prompt_tokens, + delta_tokens, + provider_budget, + prior: None, + }, cancel.clone()) + .await?; +match outcome.outcome { + StrategyOutcome::Completed { retain_from, replacement, diagnostics } => { + write_compaction(retain_from, replacement, diagnostics).await? + } + StrategyOutcome::Skipped { reason, .. } => record_skip(reason), + StrategyOutcome::Failed { error, diagnostics } => record_failed(error, diagnostics), +} +``` + +## Own contract + +### Dependencies + +- `S:contextFacts` — the limits and the token count the plan and the chunk budget need. +- `P:modelHost` — the summarizer's model calls, under the existing failure and credential policy. +- `P:providerConnectionResolver` — the connection each summarizer request uses; the connection lives only inside the call. +- `P:summaryPromptSettingsHost` — optional: the operator's system prompt override, read once when the owner loads. +- `S:guideEntries` — the `` entry, registered until the owner unloads. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `describe` | The strategy's name and the planned size of its replacement | `{model}` | `{name, replacementSize}` | None; the owner completes the read | `not_adopted`, `closed` | +| `compact` | Replace the history before a cut with a summary | `{history, checkpoint?, request, retainLimit?, cuts, trigger, estimatedInputTokens, baselineSource, baselinePromptTokens?, deltaTokens?, providerBudget?, prior?}` | `{outcome}`: `completed`, `skipped` or `failed`, each with diagnostics | Stops the model call in flight; the compaction then answers nothing and writes nothing | `cancelled`, `closed`, `invalid` | + +`model` is a model selection; the owner asks `contextFacts` for its limits and counts. `retainLimit` is the cut the retention rule allows; `cuts` lists every legal cut in order; `request` is the request whose context is compacted. + +`completed` carries `{retainFrom, replacement, diagnostics}`; `skipped` carries `{reason, diagnostics}`; `failed` carries `{error, diagnostics}`. A compaction with no legal cut, or nothing before the cut, is `skipped { reason: "nothing_to_compact" }` with no model call. `diagnostics` holds the model call count, the summed usage and the strategy's own record; the caller measures the duration in its compaction record. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `cancelled` | `compact` | The call was stopped before any model work or by the caller's cancellation; the history is unchanged | +| `closed` | both | The owner is unloading; the compaction did not run | +| `invalid` | `compact` | Fix the input: a cut outside the history, or a request without an adopted model. A history with no legal cut is the `skipped` outcome, not an error | +| `not_adopted` | `describe` | Adopt the model again; without it the plan cannot be computed | + +A strategy failure after model work is the `failed` outcome with its diagnostics, not an error: the caller writes the compaction fact with those diagnostics. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `describe` | The owner reads the limits and the planned size from `contextFacts` | A dropped call ends the read | `closed` | The owner | +| `compact` | The owner picks the cut, summarizes in chunks under the input budget, and answers the outcome with diagnostics | The model call in flight is stopped; the call answers nothing and the history is unchanged | An in-flight compaction ends `cancelled`; the generation answers no further call | The model call by the owner; the compaction fact by the caller | + +## Exceptions with reasons + +- A profile that does not compact installs neither this owner nor `contextFacts`; a part that requires `summaryStrategy` fails at assembly instead of reading an absent policy. + +- `describe` and `compact` take the model selection as data and ask `contextFacts` for the limits: a model object in the input made the strategy hold another owner's counter, and a number in the input would freeze the capacity the request actually has. +- `failed` is an outcome rather than an error: the compaction fact reports the same diagnostics as a completion, and the caller writes that fact either way. +- `prior` carries the earlier pass of a re-planned compaction: the caller re-plans when the first pass does not fit, and the second pass must continue the same request budget. + +## Verification + +- A threshold compaction over the retention limit completes, skips or fails with diagnostics; a compaction with no legal cut is `skipped { reason: "nothing_to_compact" }` and sends no model call. +- `describe` equals the target rule plus the empty wrapper's count; a caller that reserved that size keeps it. +- A cancel during the model call answers nothing and leaves the history unchanged. +- A re-planned compaction sums both passes' model calls and usage. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part publishing two operations. It writes no Timeline event and folds no state; the compaction fact is the caller's. | +| §2 scopes | Session: the summarizer's policy and its model calls are shared by the Session's branches. | +| §3 orthogonality | Reads `contextFacts` and the model services; writes nothing outside its own calls. | +| §4 rule 1 | No command event: the caller writes the compaction start and result facts. | +| §4 rule 2 | No handover of an object; the outcome is data. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | The summary prompt and the target rule are this owner's configuration, not core behavior. | +| §4 rule 5 | No batches. | +| §4 rule 6 | The replacement returns to the caller, which places it in the compaction fact; the owner adds no second path. | +| §4 rule 7 | Callers use the two operations; no caller reads the owner's prompt or chunk state. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | The compaction fact is the durable record; the strategy writes none itself. | +| §7 values, ids and objects | Requests and replies are data; the model object no longer crosses. | +| §7 one interface | One name, `summaryStrategy`, on the owner type. | +| §7 cross-language | Every request and reply is data; the cancellation is the caller's dropped call. | +| §7 one change | The implementation task removes `compactionStrategyHost` and migrates both callers in one change. | +| ADR 002 D1 | Session: the policy has no branch state and serves every branch. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Depends on process services at an enclosing scope and on `contextFacts` at its own. | +| ADR 002 D4 | The target rule and the prompt are factory configuration; the operator's override is read at load. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Supersedes + +This contract replaces the `compactionStrategyHost` object; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Loop and ContextPreparation → CompactionStrategyHost` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `compactionStrategyHost` row. +- `docs/design/plugins/ContextCompaction.md` §4.2's ports table: `CompactionStrategyHost` becomes this owner's two operations, and `CompactionInput.model` leaves the input; the document's remaining mentions of the object ports are descriptive, and the delivery removes them. + +Rule D: no client wire protocol or user-visible behavior changes; `completed`, `skipped` and `failed` keep their fact shapes and the summary's model-visible text is unchanged. + +## Binding appendix + +```rust +use crate::context_projection::Entry; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ + BaselineSource, CompactionStrategyRecord, CompactionTrigger, ContextBaselineEntry, Message, + ModelRequest, ModelSelection, ProviderOutputBudgetFacts, Usage, +}; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DescribeRequest { + pub model: ModelSelection, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Plan { + pub name: String, + pub replacement_size: f64, +} + +/// The wire form of one legal cut. The owner maps `CompactionCut` to it. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Cut { + pub retain_from: String, + pub entry: usize, + pub within_limit: bool, +} + +/// The wire form of the strategy's diagnostics. The owner maps +/// `StrategyDiagnostics` to it; the caller measures the duration itself. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Diagnostics { + pub model_call_count: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_usage: Option, + pub record: CompactionStrategyRecord, +} + +/// The wire form of the previous compaction's checkpoint; owned vectors replace +/// the internal `Arc<[..]>` fields. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CompactionCheckpoint { + pub retain_from: String, + pub replacement: Vec, + pub context_baseline: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub replacement_parts: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CompactionRequest { + pub history: Vec, + pub checkpoint: Option, + pub request: ModelRequest, + pub retain_limit: Option, + pub cuts: Vec, + pub trigger: CompactionTrigger, + pub estimated_input_tokens: f64, + pub baseline_source: BaselineSource, + pub baseline_prompt_tokens: Option, + pub delta_tokens: Option, + pub provider_budget: Option, + pub prior: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", tag = "status", rename_all_fields = "camelCase")] +pub enum StrategyOutcome { + Completed { + retain_from: String, + replacement: Vec, + diagnostics: Diagnostics, + }, + Skipped { + reason: String, + diagnostics: Diagnostics, + }, + Failed { + error: String, + diagnostics: Diagnostics, + }, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompactionReply { + pub outcome: StrategyOutcome, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum StrategyError { + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + NotAdopted { message: String }, +} + +impl PublicService for SummaryStrategy {} + +#[rutis::service(name = "summaryStrategy")] +impl SummaryStrategy { + pub async fn describe(&self, request: DescribeRequest) -> Result { /* ... */ } + pub async fn compact( + &self, + request: CompactionRequest, + cancelled: dim_agent_capabilities::host::CancelledFn, + ) -> Result { /* ... */ } +} +``` + +`cancelled` is the binding's cancellation argument, not a request field. `Entry` is the wire entry defined by [Context projection](ContextProjection.md); `Cut`, `Diagnostics` and `CompactionCheckpoint` are this face's wire forms of `CompactionCut`, `StrategyDiagnostics` and `CompactionCheckpoint`, mapped by the owner in one place. The internal types stay unchanged, and `Usage`, `CompactionStrategyRecord`, `Message`, `ContextBaselineEntry` and `ReplacementParts` already derive serde. A strategy failure is the `failed` outcome, not an error. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index e5dd257f13..e9ec1ae69a 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -605,16 +605,19 @@ code the operation already uses, so one code vocabulary serves the local and the ## 5. `store` and `timelineStore` The repository and Timeline operations use two names on the daemon that owns the state: process -`store` provides the repository operations (§5.2), retaining its existing Timeline `query`, -and Session-scoped `timelineStore` provides the Timeline operations and completion notifications -below. Both use the existing state owner; the split follows §9(6), without changing Session +`store` provides the repository operations (§5.2), retaining its existing Timeline `query`. +The Session-scoped `timelineStore` and its completion notifications keep their operations and +notification shape in the [SessionStore contract](https://github.com/arcships/dim/pull/2091) +(#2018); SessionScope only installs the binding in the Session instance. On the Session face the +Session id is the instance's identity, not a request field: a request that names another Session +is `invalid`. Both use the existing state owner; the split follows §9(6), without changing Session placement or the storage engine. SessionTitle and FileAccess use the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md). | Family | Operations | | --- | --- | -| Timeline (`timelineStore`) | `createSession`, `sessionConfig`, `releaseSession`, `rollbackSession`, `append` (sync), `head`, `branches`, `readPage`, `readSegments`, `query`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot` | -| Timeline completion (`timelineStore`) | `commits`, `closeCommits`; notifications `{subscriptionId, batchId, branchId, through, result}` | +| Timeline (`timelineStore`) | The face stays and its owner is SessionStore; only the binding is installed in a Session instance ([SessionStore](https://github.com/arcships/dim/pull/2091), #2018). On the Session face the Session id is the instance's identity: the requests carry no `sessionId`, and a request that names another Session is `invalid`. | +| Timeline completion (`timelineStore`) | Replaced by the [SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018). | | Session rows (`store`) | The repository operations listed in §5.2 | | Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | @@ -654,7 +657,7 @@ notification {subscriptionId, batchId, branchId, through, result: "committed" | #### Binding shapes and lifecycle -The Timeline methods take one request object. Keys are `{sessionId, branchId}`; +The process store's Timeline engine methods take one request object. Keys are `{sessionId, branchId}`; `head` returns `{sequence}`, `branches {sessionId}` returns `{branches:[{info,sequence}]}`. `readPage {sessionId,branchId,after,limit,through}` returns `{events}`. `limit` is a target event count: the final complete atomic batch may exceed it. `readSegments {sessionId,segments: @@ -666,7 +669,7 @@ it does not introduce a separate wire operation or replace an override with fall `batchEnd {sessionId,branchId,sequence}` validates the boundary and returns `{}`; `batchEndAt` returns `{sequence}` for the containing batch's end through the backend's existing operation, without repeated remote probes. `trace` takes the same position and returns `{trace}`. -`query` takes the scope, query and optional page described in §5.2 and keeps that canonical reply. +`query` takes the scope, query and optional page described in §5.2 and keeps that canonical reply; on the Session-scoped binding, the request carries no `sessionId` because the instance identity supplies it. `createSession {sessionId,config}`, `releaseSession {sessionId}`, `rollbackSession {sessionId}` and `saveSnapshot {sessionId,branchId,snapshot}` return `{}`. `sessionConfig {sessionId}` returns diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..c506c11ebb 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -94,10 +94,10 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `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。 | -| `agentConfig` | `agentConfig.get()` | 形状见 §4.8。 | +| ~~`agentConfig`~~ | 无 | 面移出(#2093):Agent 的配置不归 Session,值仍由装配提供 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | -| `skillsConfig` | `skillsConfig.get()` | 形状见 §4.8。 | -| `collaborationConfig` | `collaborationConfig.get()` | 形状见 §4.8。 | +| ~~`skillsConfig`~~ | 无 | 面移出(#2093):工厂文本只在自己的 part 内读 | +| ~~`collaborationConfig`~~ | 无 | 面移出(#2093):工厂文本只在自己的 part 内读 | | `worktreeAssociations` | `store.associateWorktree` | 形状见 §4.8。 | | `toolSourcesView` | `toolSourcesView.get/observe` | 同一 ToolRegistry owner 的独立只读观察面;贡献注册仍由 `toolRegistry` 负责,见 [工具贡献 §7.5](../architecture/rust-agent/tool-contributions.md#75-服务接口)。 | @@ -126,7 +126,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 数据面 `execHost`:`start`/`wait`/`kill`/`settle`/`output`/`tail`/`removeOutputDirectory`/`shell`/`write`/`resize`/`info`/`confined`/`configured`([resource and store data faces](resource-faces.md) §3,#1295);`hostPlatform` 是提供方和它的 Rust binding | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | -| `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | +| `timelineStore` | 连接与批次 | Session 面由 [SessionScope](plugins/SessionScope.md) 取代(#2093);进程面 `store` 见 #2018 | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 @@ -180,11 +180,11 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | | `fileReads` | branch | FileReads | hot-path | 待迁移;按 #1292 定义操作面 | -| `historyRenderer` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | -| `contextModelHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | -| `prepareModelHost` | session | PrepareModelHost | hot-path | 待迁移;按 #1292 定义操作面 | -| `prepareContextHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | -| `compactionStrategyHost` | session | ProductSummaryStrategy | hot-path | 待迁移;按 #1292 定义操作面 | +| ~~`historyRenderer`~~ | session | SessionScope | hot-path | 由 `contextProjection` 取代([Context projection](plugins/ContextProjection.md),#2093) | +| ~~`contextModelHost`~~ | session | SessionScope | hot-path | 由 `contextFacts` 取代([Context facts](plugins/ContextFacts.md),#2093) | +| ~~`prepareModelHost`~~ | session | PrepareModelHost | hot-path | 由 `requestSettings` 值取代([Request settings](plugins/RequestSettings.md),#2093) | +| ~~`prepareContextHost`~~ | session | SessionScope | hot-path | 无目标,移出目录(#2093) | +| ~~`compactionStrategyHost`~~ | session | ProductSummaryStrategy | hot-path | 由 `summaryStrategy` 取代([Summary strategy](plugins/SummaryStrategy.md),#2093) | ### 3.6 入口、凭据与宿主资源 @@ -203,7 +203,7 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `hooksService` | process | HooksSettings | host-resource | | `providerService` | process | Provider | 当前为 secret,迁移后通过数据操作使用凭据 | | `providerConnectionResolver` | process | Provider | host-resource | -| `timelineFactory` | session | SessionScope | control | +| ~~`timelineFactory`~~ | session | SessionScope | control | 由 `sessionScope.openBranch` 取代([SessionScope](plugins/SessionScope.md),#2093) | ## 4. 批次契约(#1292) @@ -299,6 +299,8 @@ loops.stop {sessionId, loopId} -> 记录形状,未结算时另带 {settled: fa ### 4.8 旧主机端口:`agentConfig` 等五个 +`agentConfig`、`skillsConfig` 与 `collaborationConfig` 三个面由 [SessionScope 契约](plugins/SessionScope.md) 取代(#2093):值是各自的安装函数提供的 `session_value`,面从目录移出;下面的形状只记录旧面。 + 这五个端口的内容是配置或一次写入:所有者把操作绑定到端口类型上,`#[rutis::service]` 生成 dispatcher,名字 shared;Rust 调用方直接调同一个方法,不另写适配层。`collaborationSession` 的审批目标读取由 [Collaboration owner](subagent-tool-approval.md#31-data-face) 定义。 ```text