diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 3d36fd9d6d..eef8146492 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -21,14 +21,14 @@ | 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`. | +| Context RPC → target branch | `contextPreparation.compact` and `contextUsage.read`; the owner contracts are [ContextPreparation](../plugins/ContextPreparation.md) and [ContextUsage](../plugins/ContextUsage.md). | | 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. | +| InputQueue and Collaboration approvals → target branch | `inputQueue.submit`, `inputQueue.withdraw` (the queue runs the submit checks for a Steer), and `approval.pending/decide` on the selected branch; see [InputQueue](../plugins/InputQueue.md). | | 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. | | 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. | | 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. | +| Compaction → `contextPreparation`; stop and activity callers → `agentLoop` | `contextPreparation.compact(..)`; `agentLoop.stopTurn/state/observe`; see [Loop](../plugins/Loop.md) and [ContextPreparation](../plugins/ContextPreparation.md). | ### Calls from a Session to a selected branch @@ -43,9 +43,9 @@ own methods. | 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. | +| Context RPC / PromptSuggestion | `contextUsage.read`; Context RPC's `compactAndWait` is `contextPreparation.compact`, which answers the outcome itself. | | 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. | +| InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the queue runs the submit checks for a Steer. `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 @@ -58,20 +58,20 @@ substitutes a newer head. | Caller → owner | New API | | --- | --- | -| ToolBinding, Session language and Agent configuration → `prompt` | `prompt.initialCompletion({}) → void or opening error`; `prompt.configure({sources, model?}) → unchanged, adopted or superseded`. | -| Prompt and guide adoption → `contextPreparation` | `contextPreparation.publish({adopted, changes, model?, toolAdoption?, inputs}) → sequence or null`; `awaitPublished({sequence}) → sequence`. Publication commits adoption atomically. | +| ToolBinding, Session language and Agent configuration → `prompt` | `prompt.configure({sources, model?, tools?}) → unchanged, adopted or superseded`; the opening adoption is internal. See [Prompt adoption](../plugins/PromptAdoption.md). | +| Prompt and guide adoption → `prompt` | publication is `prompt.configure`; see [Prompt adoption](../plugins/PromptAdoption.md). | | File read/edit/write tools → branch FileReads | `binding({path}) → TextFileBinding or null`, `writeBinding({path}) → absent, compacted or bound`, `record({path, binding, established}) → void`. The original read supplies the established sequence; file I/O stays on the file node. | ### Model preparation, history and tools | 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 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. | +| Loop → RequestSettings | `settings() → settings`; the model profile's defaults before an adoption ([#2093](https://github.com/arcships/dim/pull/2093), target). | +| ContextPreparation → PrepareContextHost | The model profile's request builder stays the host port `prepare` calls; the owner contract is [ContextPreparation](../plugins/ContextPreparation.md). | +| Context accounting and compaction → ContextFacts | `describe`, `count`, `contributions`, `estimate`; ContextFacts is the owner ([#2093](https://github.com/arcships/dim/pull/2093), target). | +| ContextPreparation → SummaryStrategy | `describe(model facts) → {name, replacementSize}`; `compact(input, cancelled) → completed, skipped, failed or cancelled` with StrategyDiagnostics; SummaryStrategy is the owner ([#2093](https://github.com/arcships/dim/pull/2093), target). | +| Loop and ContextPreparation → ContextProjection | `renderedStream`, `renderedContext`, `snapshot`, `streamCheckpoint`, `snapshotFromCheckpoint`; ContextProjection is the owner ([#2093](https://github.com/arcships/dim/pull/2093), target). | +| Loop and ModelProvider → ContextPreparation | `prepare({source, projection}, cancelled) → void`, `validate({request}, cancelled) → void`, `compact({}, cancelled) → outcome`; the owner contract is [ContextPreparation](../plugins/ContextPreparation.md). | +| ContextPreparation and usage readers → ContextUsage | `read({through?}, cancelled) → UsageRead`, `estimate({requestId, through}, cancelled) → Estimate`, `confirm({requestId}) → void`; the owner contract is [ContextUsage](../plugins/ContextUsage.md). | +| Loop and ToolExecutor → `toolBinding` | `bind({requestId, turnId, through, declared, sources})`, `adopted({requestId}) → {adoption, tools}`, `claim({requestId, calls, context})`, `transfer({from, to})`, `release({requestId})`, `retain_only({requestId})`; settlement follows the line's facts and `retain_only` is the Loop's rebuild step ([#2100](https://github.com/arcships/dim/pull/2100), target). | | Nested tool execution → `toolExecutor` | `open({parentCallId, context}, cancelled) → gateId`, `invoke({gateId, call}) → ToolResult`, `close({gateId}) → ToolEffect[]`. Close joins children in order; interruption releases the gate. | diff --git a/docs/design/contracts/session-access.md b/docs/design/contracts/session-access.md index a95d829712..d5639bc562 100644 --- a/docs/design/contracts/session-access.md +++ b/docs/design/contracts/session-access.md @@ -344,7 +344,7 @@ Not in this contract: `createdBy` (the Session's origin) and the `client` parame | Result fact | `input/deleted { input_id }`, written only by InputQueue, only when it consumes an `input/withdraw` while it holds that input unapplied | | Held | InputQueue holds an input from its `input/message` until it writes `input/applied` or `input/deleted` for it. | | No effect | Unknown id, input already applied, or already deleted: InputQueue writes no result fact or replacement input and no failure event exists; the caller's reply is `notHeld` | -| Client path | `session.input.withdraw {sessionId, branchId, inputId, reason?, steer?}`, provided by InputQueue through `sessionMethods` (namespace `session.input`; Session-scoped part `InputMethods`, implemented in S1, that calls the branch's withdrawal service), so Rpc names no owning service → `{status: "deleted", sequence}` or `{status: "notHeld"}`. With `steer` (a `UserInput`), only a `deleted` reply also carries `steer: {inputId, sequence}` for the committed replacement, and with it `warnings?: [{check, message}]` for the submit checks' work that did not happen (Hooks A.6.2), absent when there is none. The warnings describe the replacement this call wrote, so they appear only with its receipt: a reply that wrote no replacement carries neither | +| Client path | `session.input.withdraw {sessionId, branchId, inputId, reason?, steer?}`, provided by InputQueue through `sessionMethods` (namespace `session.input`; Session-scoped part `InputMethods` that calls the branch's withdrawal operation; the queue runs the submit checks), so Rpc names no owning service → `{status: "deleted", sequence}` or `{status: "notHeld"}`. With `steer` (a `UserInput`), only a `deleted` reply also carries `steer: {inputId, sequence}` for the committed replacement, and with it `warnings?: [{check, message}]` for the submit checks' work that did not happen (Hooks A.6.2), absent when there is none. The warnings describe the replacement this call wrote, so they appear only with its receipt: a reply that wrote no replacement carries neither | | Process and branch-part path | `sessions.withdraw` for process callers, InputQueue's branch withdrawal service for branch parts: by the `input_id` returned when the caller wrote the input | | Write path | The service appends `input/withdraw`, then replies with InputQueue's decision for that command. InputQueue's recheck uses only its own decision state (held set), never a lock on another owner's facts | | Withdraw and re-submit as Steer | InputQueue accepts the replacement only when it accepts withdrawal of the old held input. The replacement Steer `input/message` and the old input's `input/deleted` commit in one atomic result batch, with `input/deleted` last. A `notHeld` decision creates no replacement | @@ -362,9 +362,10 @@ the message. If application wins, the original is consumed normally and no replacement is created. Other held inputs and explicit new submissions, including identical text, remain independent. -InputMethods runs the existing validation and submission checks before admitting -a Steer command. A blocked check writes neither a command nor a replacement and -leaves a still-held input retryable. Passing the checks is not a reservation: +InputQueue runs the existing submission checks before admitting a Steer command, +after InputMethods validates the operator's content. A blocked check writes +neither a command nor a replacement and leaves a still-held input retryable. See +[InputQueue](../plugins/InputQueue.md). Passing the checks is not a reservation: InputQueue must still decide when it consumes the command. Two callers may both pass their checks, but cannot both replace the same original input. @@ -528,8 +529,8 @@ while the first write is still unpublished. | `input` | `Session::input(InputMessageData, branch)` (existing; returns the committed input for an id the branch already holds); a key is `InputBlock::Raw { key: Some(name), retire }` | | `lookup` | `Session::lookup(branch, submission_id)`, shared with `session.input_lookup`: a query of the branch's committed input identities; waits for the found input's publication | | `history` | `Session::sequence(branch)`, failing `future_sequence` below `at_least`, then `AgentIndex::history_page(id, branch, after, limit, through)` | -| `withdraw` | `Session::service::(branch)` then `InputQueue::withdraw(InputWithdrawData { input_id, reason, steer: None }) -> Result`. The data face permits only plain withdrawal and returns `Deleted { sequence }` or `NotHeld`. `InputMethods` uses the Rust-only `withdraw_checked` for an already checked Steer candidate, retains its committed event, and confirms publication before returning the receipt (A.4). | -| `pending` | Capture `Session::publication(branch).sequence()`, wait through it with `Session::dispatch_watch(branch)` while observing publication closure, then `Session::service::(branch)` and `InputQueue::pending(input_id) -> bool`: the branch's queue answers §2's rule; an id it does not hold is `false` | +| `withdraw` | `line_owner::(line)?.withdraw(WithdrawInput { input_id, reason, steer }) -> Result`; the queue runs the submit checks for a Steer and returns `Deleted { sequence }` or `NotHeld`. See [InputQueue](../plugins/InputQueue.md) (A.4). | +| `pending` | `line_owner::(line)?.pending(PendingRequest { input_id, published_cutoff: None }) -> Pending`: the owner applies its published-cutoff default and answers §2's rule; an id it does not hold is `false` | | `stop`, `idle` | `Session::stop`, `Session::idle` (existing) | | `delete` | `AgentIndex::delete(id)` (S5c, crate-internal): admission gate, close, `SessionStore::delete_session`, forget | | `SessionConfig` | Rust struct below | diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 0bbd6f4f3c..107455fd98 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -14,7 +14,7 @@ This contract defines three registration services in the language-neutral form o Proposed (P3, with RemoteGateway; not implemented): Rpc decides what a connection is served from its `ConnectionEntry {name, deviceId}`: a local connection gets Session and management methods, a connection with a `deviceId` (a paired device through RemoteGateway) never gets management methods, and an exported rutis link gets management methods only when exported. Today Rpc serves every connection by the existing transport profile rules (A.3). There is no port and no Management plugin. Providers are optional plugins installed only when enabled. Rpc reads `managementMethods` on each call and depends on no provider, so a provider that is disabled, Pending, Failed or reloading affects only its own namespace (§3.2). The method tables and ToolRegistry do not depend on the parts that register with them; those parts depend on them. A tool registered later is offered from the next request, and a withdrawn one is no longer offered, without a Session reload (A.5). -Acting on a tool call or an input before it is committed is not a service of this contract. Approval and the Session input path are unchanged; InputQueue's withdrawal is its owner's change ([overview Appendix B](../overview.md#appendix-b-supplements-to-existing-plugins)). +Acting on a tool call or an input before it is committed is not a service of this contract. Approval and the Session input path are unchanged; the withdrawal operation is [InputQueue](../plugins/InputQueue.md)'s. ## 1. Structure diff --git a/docs/design/plugins/ContextCompaction.md b/docs/design/plugins/ContextCompaction.md index fe2dd23d6a..42fd49869e 100644 --- a/docs/design/plugins/ContextCompaction.md +++ b/docs/design/plugins/ContextCompaction.md @@ -2,8 +2,9 @@ Status: Implemented on the F1 branch (approved design; implementation notes in §12). Roadmap item F1 ([#72](https://github.com/arcships/dim/issues/72)). Overview: [Appendix B.1 ContextPreparation row](../overview.md#b1-session-and-branch-capabilities). -Scope: [ADR 002](../../adr/002-plugin-scope.md): Session parts plus supplements to the existing -branch capabilities Loop and ContextPreparation. §12 records where the implementation refines this text. +Scope: [ADR 002](../../adr/002-plugin-scope.md): the compaction policy and the supplements it needs. The owner contracts are +[ContextPreparation](ContextPreparation.md) and [ContextUsage](ContextUsage.md); this document keeps the trigger, +retention, record and recovery rules. §12 records where the implementation refines this text. The trigger, retention and recovery rules follow the [#128](https://github.com/arcships/dim/issues/128) research ([compaction-trigger](../research/compaction-trigger.md)); its reserve and retention share are @@ -18,14 +19,12 @@ are decided by running the evaluation (§13.4). §14 maps the compaction-quality turns verbatim. The replaced range is normally everything since the previous compaction point, together with the previous replacement. From then on, the branch advances on the new result. -Compaction is part of how the Loop controls the context window. It is a Loop step, like a -model call or a tool batch, and it is not tied to a turn. While a compaction step runs, the -Loop does not advance to its next step. Otherwise the context could overflow during +Compaction is how a line keeps its context window. The command and the step are ContextPreparation's ([ContextPreparation](ContextPreparation.md)); the Loop starts no request while a step runs, so its steps stay consistent with the replacement. Otherwise the context could overflow during compaction, and new events would be decided on the old context, inconsistent with the replacement. -Automatic compaction already runs inside a request's preparation (`context/prepare` → -compaction → `model/call`), and the Loop waits for that request's terminal +Automatic compaction runs inside a request's preparation (`context/prepare` → +compaction → `model/call`); the manual command is `contextPreparation.compact` ([context_policy.rs](../../../crates/dim-agent-capabilities/src/context_policy.rs)). It runs in every profile that installs it through `defaults::install_compaction` ([cli.rs](../../../crates/dim-app-server/src/cli.rs)): the product profile and the `--models` @@ -43,10 +42,8 @@ F1 separates three layers (§2.2) and adds: `{retain_from, replacement: Message[], strategy, …}`, where `retain_from` is the id of the first Timeline event kept verbatim. There is one replay rule for every strategy: everything before `retain_from` is replaced by `replacement`. -4. **One compaction path.** ContextPolicy's compaction step is one function. Automatic - compaction calls it during preparation, and the Loop's manual step calls it too. -5. **Manual compaction as a Loop step.** `session.context.compact` writes the command - `context/compact`, and the Loop schedules a compaction step: +4. **One compaction path.** ContextPolicy's compaction step is one function, run by ContextPreparation for both the automatic threshold and the manual command. +5. **Manual compaction as ContextPreparation's operation.** `session.context.compact` calls `contextPreparation.compact`, which writes the command `context/compact` and runs the step: - Inside a turn, the step runs at the next step boundary, before the next request is prepared. - With no turn running, the step runs at once and writes only its compaction facts. @@ -68,8 +65,7 @@ unreleased. - **Not inside Provider.** The capability snapshot travels on the `ModelRequest`. Credentials are resolved by `ProviderConnectionResolver`, as ModelProvider resolves them for every turn. Execution is `ModelHost`. -- **No second state machine.** The Loop sequences every step. ContextPreparation runs the - compaction function only inside a request preparation the Loop has already handed to it. +- **No second state machine.** ContextPreparation runs the compaction function for its own preparation and for the manual command; the Loop keeps turn and request order and starts no request while a step runs. ## 2. Structure @@ -86,16 +82,17 @@ unreleased. | provides S:CompactionStrategyHost(Some(summary strategy)) | | ContextMethods (new part) | | registers session.context with sessionMethods: compact, usage | - | compact -> TreeCommands.get(b).service::().compact() - | usage -> TreeCommands.get(b).service::().usage() + | compact -> line_owner::(line).compact(..) + | usage -> line_owner::(line).read(..) +---------------------------------^---------------------------------+ Rpc (C1) dispatches ---' Branch scope (one Timeline, one Dispatcher) +-------------------------------------------------------------------+ - | Loop (supplement): sequences steps | + | Loop: sequences turns and steps | | model request -> context/prepare (handoff, unchanged) | - | compaction step (manual) -> ContextPolicy::compact_step | + | starts no request while a compaction step runs | | ContextPreparation (supplement) | + | manual: compact command, single-flight slot, step task | | in preparation: ContextPolicy::prepare -> compact_step | | ContextPolicy::compact_step: retention rule, strategy.compact, | | validate, append context/compaction, snapshot | @@ -110,8 +107,7 @@ provider must not depend on `TreeCommands`, which the branch tree provides. ### 2.1 Where the manual step lives -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 manual command and the step are ContextPreparation's; see [ContextPreparation](ContextPreparation.md). This section's earlier account of the Loop holding the step is superseded. The reasons it gave: - **The Loop already holds what the step needs.** Its `Deps` already inject `Timeline`, `HistoryRenderer` and `ContextModelHost` @@ -130,7 +126,7 @@ The Loop runs the manual compaction step itself, in a tracked task, by calling | Layer | What it fixes | Where | Changes when a new strategy is added | | --- | --- | --- | --- | -| Mechanism | When compaction runs, and that the Loop holds while it runs: the automatic trigger in preparation, the manual Loop step, the retention rule, validation, commit | Loop, ContextPolicy | No | +| Mechanism | When compaction runs, and that ContextPreparation holds while it runs: the automatic trigger in preparation, the manual command, the retention rule, validation, commit | ContextPreparation, ContextPolicy | No | | Contract | The record and its replay: `context/compaction {retain_from, replacement, strategy, context_baseline}`, where `retain_from` is a Timeline event id; replay puts `replacement`, then the keyed baseline, then the entries placed by `retain_from` and later events. The record references Timeline events, not rendering details, so another `HistoryRenderer` or strategy still finds the cut. Replay is deterministic, so fork, reload and prompt-cache prefixes see the same messages | `dim-agent-types`, `history.rs` projection | No | | Strategy | Its own messages of the replacement (the summary), the replacement's planned size, and the cut within the retention rule. The pinned inputs and the digest are the mechanism's parts (§5.9, §5.10, §4.3) | `CompactionStrategyHost` Session value | It is replaced | @@ -138,7 +134,7 @@ The Loop runs the manual compaction step itself, in a tracked task, by calling `CompactionStrategyHost` Session value: the assembly registers another value, or another Session part that provides it, instead of `ProductSummaryStrategy`. -- ContextPreparation and the Loop depend on the key, not on the strategy's plugin, so no +- ContextPreparation depends on the key, not on the strategy's plugin, so no optional dependency is added. - Old records stay replayable because replay never calls the strategy. - Examples of later strategies: a sliding window with notes, or old tool calls rendered as short @@ -150,10 +146,10 @@ part that provides it, instead of `ProductSummaryStrategy`. | Item | Owner | Kind | | --- | --- | --- | -| `context/compact {}` | Loop | New command event (§4.3) | +| `context/compact {}` | ContextPreparation | New command event (§4.3) | | `context/compaction-start` | Written by ContextPolicy for its caller | New fact (§4.3) | | `context/compaction` | Written by ContextPolicy for its caller, or by the settling owner on reload | Existing fact, changed (§4.3) | -| Compaction slot: at most one outstanding command `{sequence, consumed, running: Option}` | Loop | Private. Set by `AgentLoop::compact` or by consuming a command; cleared by that command's result. Settled on load (§5.5) | +| Compaction slot: at most one outstanding command `{sequence, consumed, running: Option}` | ContextPreparation | Private. Set by `contextPreparation.compact` or by consuming a command; cleared by that command's result. Settled on load (§5.5) | The Session values hold no state. A resolved connection lives only inside one strategy call. @@ -173,11 +169,9 @@ methods are declared with `interruption: report`, `progress: false`, `notificati `session.context.compact`: -- It calls `AgentLoop::compact`, which returns a command sequence `c`: a newly written - `context/compact`, or the command already outstanding on the branch (§5.4). Concurrent or - repeated calls therefore join one in-flight compaction. -- It then waits on the branch Timeline for the result that carries its command: - the first `context/compaction` with `command = c`. +- It calls `contextPreparation.compact`, which returns the step's outcome; the owner writes or + joins the command `c` and runs the step (§5.4). Concurrent or repeated calls therefore join one + in-flight compaction. - It maps the outcome: `completed` → `{status: "completed", sequence}`; `skipped` → `{status: "skipped", reason}`; `failed` → `compaction_failed`; `cancelled` → `compaction_cancelled`. @@ -236,9 +230,9 @@ failures before any model work. | Event | Writer | Consumer | Data | | --- | --- | --- | --- | -| `context/compact` (new) | Loop, through its public write operation `AgentLoop::compact` | Loop, in sequence order | `{}` | -| `context/compaction-start` (new) | ContextPolicy in `compact_step`, for its caller (Loop step or ContextPreparation) | Loop (rebuild), ContextPreparation (steer deferral and rebuild), clients | `{turn_id?, request_id?, command?, through, trigger: "manual" \| "threshold" \| "provider_output_budget_exhausted", strategy}` | -| `context/compaction` (changed) | ContextPolicy, for its caller; on reload, the settling owner | Loop (manual step terminal), ContextPreparation (steer deferral), ContextPolicy (retry reuse), projection, ContextMethods, clients | `{turn_id?, request_id?, command?, start?, through, outcome}` | +| `context/compact` (new) | ContextPreparation, through its `compact` operation | ContextPreparation, in sequence order | `{}` | +| `context/compaction-start` (new) | ContextPolicy in `compact_step`, for its caller (ContextPreparation's manual step or preparation) | ContextPreparation (steer deferral and rebuild), clients | `{turn_id?, request_id?, command?, through, trigger: "manual" \| "threshold" \| "provider_output_budget_exhausted", strategy}` | +| `context/compaction` (changed) | ContextPolicy, for its caller; on reload, the settling owner | ContextPreparation (manual step terminal and steer deferral), ContextPolicy (retry reuse), ContextProjection, ContextMethods, clients | `{turn_id?, request_id?, command?, start?, through, outcome}` | `outcome` is one of: @@ -273,8 +267,8 @@ failures before any model work. - `failed` when no request could be built (no `context/configured`, no capability snapshot); - `cancelled` when a pending command was dropped by an interrupt or settled on reload. - Automatic compaction that never reaches the strategy writes neither fact, as today. -- At most one start per branch is unmatched at any time: the Loop never runs a manual step while - a request is in flight, and ContextPreparation runs one preparation at a time. +- At most one start per branch is unmatched at any time: ContextPreparation never runs a manual step while + a request is in flight, and it runs one preparation at a time. - On reload, an unmatched start means a compaction was in flight, and its owner writes the `cancelled` result (§5.8). Automatic compaction also writes a `cancelled` result when it is cancelled after its start by an interrupt. Steer waits for the result (§5.3). @@ -390,7 +384,7 @@ Readers update with the struct: **Dynamic events (decision A).** `context/compact` and `context/compaction-start` are `EventKind` variants. #2 does not move them: it carries event types the core does not define as opaque data with the same envelope, so core events keep their variants and wire form. `context/compact` -is owned by the Loop, and `context/compaction-start` by the owner of the compaction facts. +is owned by ContextPreparation, and `context/compaction-start` by the owner of the compaction facts. **Diagnostics (breaking).** `CompactionDiagnosticsRecord` becomes strategy-neutral. The summary-oriented required fields move into a strategy-owned object: @@ -493,20 +487,19 @@ pub struct DigestEntries { pub entries: Vec, pub dropped: bool } // impl ContextPolicy { async fn compact_step(&self, step: CompactionStep, cancel: CancellationToken) -> Result, HostError>; } // committed fact -// dim-agent-capabilities/src/agent_loop.rs -impl AgentLoop { pub fn compact(&self) -> Result; } // appends context/compact -impl PublicService for AgentLoop {} // dim-agent-capabilities/src/context_preparation.rs -impl ContextPreparation { pub async fn usage(&self, cancel: CancellationToken) - -> Result; } +impl ContextPreparation { pub async fn compact(&self, request: CompactionRequest, cancelled: CancelledFn) + -> Result; } impl PublicService for ContextPreparation {} +// The parts below belong to their owners' contracts (#2025, #2027); this sketch records the F1 +// installation and is not a contract. // dim-agent-capabilities: context_model.rs, summary_strategy.rs, context_methods.rs (new) pub struct ProductContextModel; // ResolveContextModel, no dependencies -pub struct ProductSummaryStrategyPlugin { host: DepKey } // new(names) -// Deps = (Keyed, Keyed); provides CompactionStrategyHost +pub struct ProductSummaryStrategyPlugin { host: DepKey } // new(names) +// Deps = (Keyed, Keyed); provides SummaryStrategy pub struct ContextMethodsPlugin; -// Deps = (Keyed, Keyed); methods.register(ctx, "session.context", ..) +// Deps = (Keyed, line owners by id); 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, @@ -810,13 +803,13 @@ Callers: - **ContextPreparation, inside `prepare`.** At the threshold (§5.6) or under `recovery`. The rest of `prepare` is unchanged. -- **The Loop's manual step.** Trigger `Manual`. The request is built as `start_preparation` +- **The manual command's step.** Trigger `Manual`. The request is built as `start_preparation` builds one: the latest `context/configured` settings and system with the projected messages, without binding tools. **Steer during compaction.** From `context/compaction-start` through its terminal `context/compaction`, a steer never cancels or restarts the compaction, regardless of its -producer. Inputs are accepted and applied in their normal order, but the Loop consumes them +producer. Inputs are accepted and applied in their normal order, and the Loop consumes them only after the result commits. The source `through` stays fixed. An automatic preparation whose request was replaced finishes the compaction before ending that request `Cancelled` with `replaced by steer`; the Loop then consumes the pending inputs and prepares a new @@ -854,13 +847,13 @@ Without a provider baseline the full local estimate and its error remain (#128). ``` step/model-start {T, R1} ... step/model-output-end {T, R1, completed} - k context/compact {} writer: Loop (AgentLoop::compact) - -- Loop consumes k: a request is in flight -> pending + k context/compact {} writer: ContextPreparation (compact) + -- ContextPreparation consumes k: a request is in flight -> pending step/tool-call {T, R1} ... step/tool-result {T, R1} - -- Loop consumes the tool result (boundary b): pending -> compaction step - s context/compaction-start {turn_id: T, writer: ContextPolicy (Loop's step) + -- Loop consumes the tool result (boundary b): the pending command starts in ContextPreparation + s context/compaction-start {turn_id: T, writer: ContextPolicy (ContextPreparation's step) command: k, through: b, trigger: manual, strategy: "summary"} - m context/compaction {turn_id: T, command: k, writer: ContextPolicy (Loop's step) + m context/compaction {turn_id: T, command: k, writer: ContextPolicy (ContextPreparation's step) start: s, through: b, outcome} -- Loop consumes m: the step is over -> next_model as usual input/consumed* ; step/model-start {T, R2} Loop (unchanged) @@ -870,8 +863,8 @@ Without a provider baseline the full local estimate and its error remain (#128). **With no turn running:** ``` - k context/compact {} writer: Loop (AgentLoop::compact) - -- Loop consumes k: no request in flight -> compaction step at once + k context/compact {} writer: ContextPreparation (compact) + -- ContextPreparation consumes k: no request in flight -> compaction step at once s context/compaction-start {command: k, through: k, writer: ContextPolicy trigger: manual, strategy: "summary"} m context/compaction {command: k, start: s, through: k, outcome} writer: ContextPolicy @@ -894,21 +887,21 @@ Without a provider baseline the full local estimate and its error remain (#128). **Scheduling rules:** - **Boundary.** A step boundary is where the Loop would prepare the next request (`next_model` - without a budget-retry source) or where the turn ends. A pending step starts at the first - boundary. + without a budget-retry source) or where the turn ends. ContextPreparation starts a pending step + at the first boundary; the Loop does not advance across it. - If the turn ends instead, the step runs right after `turn/end`, with no turn. - A budget retry belongs to its request and is not a boundary. - **Through.** `through` is the sequence of the event whose consumption started the step. - **One outstanding command.** By the maintainer's decision, repeated requests are an interaction - concern: deduplication belongs to the interaction boundary, not to the Loop's state machine or - the Timeline. - - `AgentLoop::compact` is the only writer of `context/compact`. Under the Loop's lock it checks + concern: deduplication belongs to the interaction boundary, not to ContextPreparation's state + machine or the Timeline. + - `contextPreparation.compact` is the only writer of `context/compact`. Under its lock it checks whether a command is outstanding on the branch (written and without a result). If one is, it - writes nothing and returns that command's sequence, and the caller waits for that command's + writes nothing and returns that command's outcome, and the caller waits for that command's result. Otherwise it writes the command. - - The Loop's slot holds at most one outstanding command. Its result clears the slot. - - **Defensive rule.** A `context/compact` the Loop consumes while another command is outstanding - (one not written through `AgentLoop::compact`, or old data) is settled at once with + - ContextPreparation's slot holds at most one outstanding command. Its result clears the slot. + - **Defensive rule.** A `context/compact` ContextPreparation consumes while another command is outstanding + (one not written through `contextPreparation.compact`, or old data) is settled at once with `context/compaction {command: , outcome: skipped {reason: "a compaction is already in progress"}}`, without a start. It is not queued. - **No advance.** While a step runs, `next_model` and `try_start` wait for its fact. Inputs queue @@ -917,36 +910,36 @@ Without a provider baseline the full local estimate and its error remain (#128). **Steer.** Inputs wait as in §5.3, joining the next request or starting a turn after the step. Interrupt, failure, reload and restart are in §5.8. -### 5.5 What the Loop gains +### 5.5 What ContextPreparation gains -All in `crates/dim-agent-capabilities/src/agent_loop.rs`: +All in `crates/dim-agent-capabilities/src/context_preparation.rs`: 1. **Subscription.** `context/compact`, `context/compaction-start` and `context/compaction` are - added. `CompactionStrategyHost` + consumed. `SummaryStrategy` is added to `Deps`. -2. **Public write.** `AgentLoop::compact()` returns the outstanding command's sequence, or appends - `context/compact` and returns its sequence (§5.4). `AgentLoop` gets the `PublicService` marker. -3. **Compaction slot**, at most one outstanding command. On consuming that command, the Loop marks +2. **Public operation.** `compact()` joins or writes the outstanding command, runs its step and + answers the outcome (§5.4). `ContextPreparation` gets the `PublicService` marker. +3. **Compaction slot**, at most one outstanding command. On consuming that command, the owner marks the step waiting, and starts it at once if no request is in flight. Another command consumed while one is outstanding is skipped (§5.4). 4. **Boundaries.** - - `next_model` (except with a budget-retry source) and `turn/end` start a pending step instead - of advancing. - - `next_model` and `try_start` do nothing while a step runs. + - The Loop's `next_model` (except with a budget-retry source) and `turn/end` are the boundaries at which + ContextPreparation starts a pending step; the Loop does not advance across them. + - The Loop's `next_model` and `try_start` do nothing while a step runs. 5. **The step task.** It is tracked like the preparation task, builds the request as `start_preparation` does, and calls `ContextPolicy::compact_step`. -6. **Step terminal.** On consuming the result of the outstanding command, the Loop clears the +6. **Step terminal.** On consuming the result of the outstanding command, the owner clears the slot. If its step ran, the Loop resumes: `next_model` inside a turn, `try_start` otherwise. Results of other commands (skips, settlements) change nothing. 7. **Interrupt.** A `stop/interrupt` cancels the running step, whose result is `cancelled` with its `start`, or writes `cancelled` without `start` for a waiting command. The command is settled once. 8. **Rebuild.** The slot is folded from command, start and result pairs: - - A manual start without a result: the step was running. The Loop writes the `cancelled` + - A manual start without a result: the step was running. ContextPreparation writes the `cancelled` result with that `start` and `command`. - - A command with neither a start nor a result: it was waiting. The Loop writes a `cancelled` - result with that `command` and no `start`. Each command is settled once. An unloading Loop - starts no further step. + - A command with neither a start nor a result: it was waiting. ContextPreparation writes a `cancelled` + result with that `command` and no `start`. Each command is settled once. An unloading + ContextPreparation starts no further step. Unchanged: turn and request lifecycles, input consumption, tool batches, steer of model requests, budget recovery, `LoopSnapshot` and `context/prepare`. @@ -1000,16 +993,16 @@ time: ### 5.8 Failure, interrupt, reload and restart -| Case | Timeline facts | What the Loop does next | What the client sees | +| Case | Timeline facts | What ContextPreparation does next | What the client sees | | --- | --- | --- | --- | | Strategy error or validation failure, manual inside a turn | start, then `context/compaction {start, failed}` | Continues the turn uncompacted (`next_model`). If the next request exceeds the input budget, the existing budget recovery forces a compaction (fallback cut); if that also fails, the request and the turn fail | Running, then `failed`; reply `compaction_failed` | | Same, manual outside a turn | start, then `failed` | Nothing more (`try_start` if an input is waiting) | Running, then `failed`; reply `compaction_failed` | | Same, automatic | start, then `failed` | Unchanged: the request continues uncompacted; under recovery the request fails | Running, then `failed` | -| Recovery compaction completed, the request still exceeds `B` | start, then `completed`; no further `model/call` | The preparation fails with the budget error that names what keeps the request above `B` (§5.3); the Loop does not compact again, so the turn fails with it | The compaction shows `completed`, with its mark when its own parts cannot shrink; the turn shows the budget error | +| Recovery compaction completed, the request still exceeds `B` | start, then `completed`; no further `model/call` | The request fails with the budget error that names what keeps it above `B` (§5.3); ContextPreparation does not compact again, so the turn fails with it | The compaction shows `completed`, with its mark when its own parts cannot shrink; the turn shows the budget error | | Manual, no request can be built (no configuration or snapshot) | `failed` without `start` | As above | Pending, then `failed` | | `stop/interrupt` during a running step (manual or automatic) | `cancelled {reason}` for the start, or `completed` if the strategy had already returned | Manual inside a turn: the turn ends `Cancelled` through `next_model`. Automatic: the request ends `Cancelled` as today | Running, then `cancelled` or `completed`; reply to match | | `stop/interrupt` while a manual command is pending | `cancelled` without `start` | Turn behaviour unchanged | Pending, then `cancelled` | -| Plugin reload | For each unmatched start, the owner writes `cancelled: "capability reloading"` with that `start`: the Loop for a manual start, ContextPreparation for an automatic one (before its existing reloading terminal). For a pending command, the Loop writes `cancelled` without `start` | No replay. A rebuilt turn ends `Failed` as today | Running or pending, then `cancelled`; a waiting reply is `operation_interrupted` or `compaction_cancelled` | +| Plugin reload | For each unmatched start, ContextPreparation writes `cancelled: "capability reloading"` with that `start` (manual or automatic; manual before its existing reloading terminal). For a pending command, it writes `cancelled` without `start` | No replay. A rebuilt turn ends `Failed` as today | Running or pending, then `cancelled`; a waiting reply is `operation_interrupted` or `compaction_cancelled` | | Process crash or restart mid-compaction | On the next load, the same settlement as a reload, from the same unmatched starts and commands | Same as reload | Running (from history) until the load, then `cancelled` | **About crashes and restarts:** @@ -1240,8 +1233,8 @@ A `failed` fact carries the same cost diagnostics as a completed one whenever th | Part | Relationship | | --- | --- | -| Loop | Supplement (§5.5). Budget recovery becomes active in the product profile | -| ContextPreparation, ContextPolicy | Supplement (§5.3, §5.6): `compact_step`, retention rule, validation of any strategy, `usage` | +| Loop | Starts no request while a compaction step runs; budget recovery is unchanged | +| ContextPreparation, ContextPolicy | Supplement (§5.3–§5.6): the manual command, the single-flight slot and the step, `compact_step`, the retention rule and validation of any strategy | | Projection (`history.rs`), snapshots | One replay rule using `replacement` and `retain_from`; `HistoryEntry.source`; cut validation and the snapshot state become event-based (interpreter version bump); the decode callback checks the anchor event (#130) | | Timeline core, memory and SQLite stores | Snapshot anchoring becomes structural only (#130, §4.3) | | `HistoryRenderer` | Render-time projections that run on every request without a record are not compaction. An example is truncating old tool output by a fixed rule. They belong to the existing injectable `HistoryRenderer`, not to a strategy | @@ -1262,19 +1255,19 @@ A `failed` fact carries the same cost diagnostics as a completed one whenever th | --- | --- | | Principles §1 (Capability, App Server boundary) | New parts and supplements live in `dim-agent-capabilities`; the App Server only installs them in its product profile. | | §1 one event bus | The command and the fact are on the branch Timeline and consumed through its Dispatcher. The method's wait reads that Timeline. Clients see the compaction state from the same facts, so there is no side channel. | -| §3 dependency direction | New parts depend on core services. ContextPreparation and the Loop depend on the `ContextModelHost` and `CompactionStrategyHost` keys, which every profile binds explicitly. No optional dependency. | -| §3 changing another module (Loop) | Approved change. The need is the Loop's own control of the context window: compaction is a Loop step like a model call or a tool batch, and the Loop must not advance on a context the replacement supersedes. It closes within the Loop: automatic compaction already runs in its request preparation, and the manual step uses the same function under the same sequencer. | -| §3 extension without change (three layers) | The mechanism (Loop step and trigger) and the contract (record and replay) are fixed. The strategy is a replaceable Session value. A new strategy changes neither the Loop, nor the record, nor replay, and replay of old records never calls a strategy (§2.2). | -| §4 rule 1 (command events) | The client asks the owner of progression with `context/compact`. The Loop decides when to serve it, and the result is one `context/compaction` that references the command. | +| §3 dependency direction | New parts depend on core services. ContextPreparation depends on `ContextFacts` and `SummaryStrategy`, which every profile binds explicitly. No optional dependency. | +| §3 changing another module (ContextPreparation) | Approved change. The need is ContextPreparation's own control of the context window: the manual command and the step are its operations, and the Loop must not advance on a context the replacement supersedes. It closes within ContextPreparation: automatic compaction already runs in its preparation, and the manual step uses the same function under the same sequencer. | +| §3 extension without change (three layers) | The mechanism (step and trigger) and the contract (record and replay) are fixed. The strategy is a replaceable Session value. A new strategy changes neither ContextPreparation, nor the record, nor replay, and replay of old records never calls a strategy (§2.2). | +| §4 rule 1 (command events) | The client asks the owner of progression with `context/compact`. ContextPreparation decides when to serve it, and the result is one `context/compaction` that references the command. | | §4 rule 2 (handoff) | Model requests are handed over with `context/prepare` as today. A manual step hands nothing over. | -| §4 rule 3 (before callback; handlers) | No before callback. Loop handlers register the step task and return. | +| §4 rule 3 (before callback; handlers) | No before callback. ContextPreparation handlers register the step task and return. | | §4 rule 4 (no business meaning in core) | Timeline, Dispatcher and facades unchanged. The digest is composed by ContextPolicy from the declarations on `step/tool-result` facts; no core part names an effect kind. | | §4 rule 5 (atomic batch) | Each new write is one event. | | §4 rule 6 (context only from handed-off events) | The replacement reaches the model only through the projection of a completed fact. Pending inputs are not consumed by a step (AGENTS rule 10). | -| §4 rule 7 (public events and services) | `TreeCommands`, `Branch::service` on `PublicService`s, `ProviderConnectionResolver`, `ModelHost`, `sessionMethods`. | +| §4 rule 7 (public events and services) | `line_owner::(line)` data faces, `ProviderConnectionResolver`, `ModelHost`, `sessionMethods`. | | §4 rule 8 (infrastructure unchanged) | Dispatcher, envelope, rutis, loader, Agent assembly and facades unchanged. There is one infrastructure change (#130): snapshot anchoring in Timeline and both stores drops its knowledge of `context/compaction` and keeps only structural checks, and the owner's decode callback receives the anchor event. The requirement comes from Timeline itself: it must not know event content (principles §4 rule 4; Timeline checks only the envelope and reserved core domains, ADR 001). It closes within Timeline's own contract: a snapshot is a cache with a structural anchor. Valid snapshots behave the same, and an invalid one is a cache miss. | -| §4 rule 9 (only needed facts) | `context/compact` is read by the Loop's later decisions and on reload. `context/compaction` is used by projection. `context/compaction-start` and the visible result are facts by the maintainer's decision, for two reasons. First, they do not only drive a state machine: they are content that users and other state machines need in order to read the history (a UI connecting at any time must see that a compaction is running or how it ended). Second, reload settlement uses them: an unmatched start means a compaction was in flight. The Loop and ContextPreparation rebuild from start/result pairs, which is more precise than commands alone because it tells a running compaction from a pending one and covers automatic compaction. Usage writes nothing. The completed result's `modelUsage` and `insufficientSpace` are descriptive fields of that required fact: the trigger reads the latest start's `through`, recovery reads the budget, and only a client reads the cost and the mark. The digest adds no fact: it is composed into the existing replacement from declarations the `step/tool-result` facts already carry. The next compaction's roll-forward is why the completed result stores the entries as data (`digest_entries`): that decision reads the field, never the rendered message, and the field is an optional part of a fact the projection already reads. | -| ADR 002 D1 (scope) | Window facts, strategy and methods: Session. Command, step and slot: branch, in the Loop. The pinning, the digest, the retention rule and the mark are branch-scope ContextPolicy work: they read the branch's events and compose its record. | +| §4 rule 9 (only needed facts) | `context/compact` is read by ContextPreparation's later decisions and on reload. `context/compaction` is used by projection. `context/compaction-start` and the visible result are facts by the maintainer's decision, for two reasons. First, they do not only drive a state machine: they are content that users and other state machines need in order to read the history (a UI connecting at any time must see that a compaction is running or how it ended). Second, reload settlement uses them: an unmatched start means a compaction was in flight. The Loop and ContextPreparation rebuild from start/result pairs, which is more precise than commands alone because it tells a running compaction from a pending one and covers automatic compaction. Usage writes nothing. The completed result's `modelUsage` and `insufficientSpace` are descriptive fields of that required fact: the trigger reads the latest start's `through`, recovery reads the budget, and only a client reads the cost and the mark. The digest adds no fact: it is composed into the existing replacement from declarations the `step/tool-result` facts already carry. The next compaction's roll-forward is why the completed result stores the entries as data (`digest_entries`): that decision reads the field, never the rendered message, and the field is an optional part of a fact the projection already reads. | +| ADR 002 D1 (scope) | Window facts, strategy and methods: Session. Command, step and slot: branch, in ContextPreparation. The pinning, the digest, the retention rule and the mark are branch-scope ContextPolicy work: they read the branch's events and compose its record. | | ADR 002 D2 (no wiring modules) | ContextMethods exposes owners' operations through `sessionMethods`. | | ADR 002 D3 (dependencies) | Hard dependencies on core only. A Provider or Aimux reload propagates to the strategy part (accepted cost). | | ADR 002 D4 (configuration) | No configuration; provisional constants are code (#128). | @@ -1311,7 +1304,7 @@ Internal Rust changes: and its `decode` callback becomes `fn(&RecoverySnapshot, &AgentEvent)`. `MemoryTimelineStore::save_snapshot` and the SQLite store's save and lookup drop the compaction kind and status checks. -- `PublicService` on `AgentLoop` and `ContextPreparation`. +- `PublicService` on `ContextPreparation`. **Requirements raised to mechanism owners:** none. @@ -1321,8 +1314,8 @@ Internal Rust changes: | --- | --- | | Which model compacts | The request's own model, in the summary strategy; a separate model is deferred | | Trigger and retention | #128: trigger at `B − min(max(0.10 × B, 16,000), 0.20 × B)`; keep the longest tail that fits `min(0.25 × B, 0.5 × B − resident)` (§5.3), and replace everything when no kept tail fits the bound; manual steps keep at most the latest turn; `validate` compares the trigger's estimate with `B`; `bytes / 4` and 1,600 tokens per image unchanged. The reserve and share are provisional heuristics | -| Manual compaction | A Loop step scheduled by `context/compact`, inside or outside a turn, never creating a turn | -| Where the step runs | In the Loop, calling the one ContextPolicy compaction function (§2.1) | +| Manual compaction | ContextPreparation's operation, scheduled by `context/compact`, inside or outside a turn, never creating a turn | +| Where the step runs | In ContextPreparation, calling the one ContextPolicy compaction function (§2.1) | | Record | `retain_from` (Timeline event id), `replacement` and `strategy` with one replay rule; optional ids, `command`, `cancelled`; changed directly (unreleased) | | Ports | `ContextModel` (window facts) and `CompactionStrategy` (replacement), each from its own Session value | | Other strategies, composition | Not done in F1 | @@ -1419,7 +1412,7 @@ window, and the same App Server on a `--models` file whose entry declares a smal Timeline holds exactly one `context/compact`, one start and one result, and every caller receives the same reply. - A `context/compact` consumed while another is outstanding (written without - `AgentLoop::compact`) gets `skipped: "a compaction is already in progress"` at once, with no + `contextPreparation.compact`) gets `skipped: "a compaction is already in progress"` at once, with no start, and the outstanding compaction completes normally. - `stop/interrupt` or a plugin reload with one outstanding command settles it `cancelled` once. 8. **Compaction state for clients.** @@ -1546,8 +1539,8 @@ fix, the smallest choice was made and is recorded here. | Adoption | `compact_step` validates the strategy's result before it appends the fact, then adopts the committed fact as Timeline middleware left it: the projection, the reduction check and the snapshot use the committed `retain_from`, `replacement` and baseline. A committed cut that cannot be projected fails the preparation, as a committed cursor did before. | | Diagnostics | `retainFrom` is absent when the strategy found no cut (`skipped`), and `estimatedOutputTokens` is absent when no candidate request could be projected. | | v1 | There is no v1-to-native conversion in production code: the frozen samples decode as v1 events only, and `v1::EventRef` has no form for `context/compact`, `context/compaction-start` or the changed `context/compaction`, so v1 connections no longer receive compaction facts. The old flat diagnostics type moved into the v1 module. | -| Loop subscription | The Loop subscribes to `context/compact` and `context/compaction`; starts are folded only at rebuild, where they tell a running step from a pending command. | -| One outstanding command | Maintainer's decision during review: repeated requests are deduplicated at the interaction boundary. `AgentLoop::compact` joins an outstanding command instead of writing another, the slot holds at most one command, a command consumed while another is outstanding is skipped, and the waiter matches its own command id (§4.1, §5.4, acceptance 7). This replaces an earlier active/pending split, so commands can no longer interleave with a running step. | +| Compaction subscription | ContextPreparation subscribes to `context/compact` and `context/compaction`; starts are folded only at rebuild, where they tell a running step from a pending command. | +| One outstanding command | Maintainer's decision during review: repeated requests are deduplicated at the interaction boundary. `contextPreparation.compact` joins an outstanding command instead of writing another, the slot holds at most one command, a command consumed while another is outstanding is skipped, and the waiter matches its own command id (§4.1, §5.4, acceptance 7). This replaces an earlier active/pending split, so commands can no longer interleave with a running step. | | Snapshot anchor | Timeline keeps the structural checks of §4.3. The old `resume ≤ through` check needed the anchor's content; it is replaced by the structural "resume precedes the anchor on the anchor's branch", and the owner's decode checks `through` before the anchor. | | A skipped re-plan | When the second pass of §5.3 step 4 returns `skipped`, the first result is committed: a strategy that skips a continuation has nothing to add, and the first result is already validated and composed. Its diagnostics stay the first pass's. | | Native storage example | The record example in [native-storage-format](../appserver/native-storage-format.md) uses the changed record and the v3 interpreter. | diff --git a/docs/design/plugins/ContextPreparation.md b/docs/design/plugins/ContextPreparation.md new file mode 100644 index 0000000000..ae9a891775 --- /dev/null +++ b/docs/design/plugins/ContextPreparation.md @@ -0,0 +1,229 @@ +# ContextPreparation + +Scope: branch. Issue: #2027. + +ContextPreparation turns a step's source data into the model request ModelProvider runs, and owns the context budget and the compaction step. The policy details are in [ContextCompaction](ContextCompaction.md); the current implementation is described in the [ContextPreparation plugin page](../../architecture/rust-agent/plugins/ContextPreparation.md). + +## Use and scope: responsibility split + +ContextPreparation owns: + +- **The prepared request.** The request's system, messages and tools at the step's fixed cutoff, from the source data Loop passes and the projection Loop renders at that cutoff. +- **The projection.** The history that becomes the request, rendered by Loop through ContextProjection at the same cutoff and consumed inside the preparation; it crosses once, as a value, and is never persisted. +- **The budget.** The input threshold, the output allowance, the retention reserve and the projection's growth check; an estimate above the threshold starts a compaction before any model call. +- **The compaction step.** The manual command, its single-flight slot and the threshold trigger; the step writes `context/compaction-start` and one `context/compaction`, and Loop starts no request while a step runs. +- **Preparation recovery.** After a reload, a `context/prepare` without a matching `model/call` or `model-output-end`, and a compaction start without a result, settle as terminal facts without redoing host work. +- **The digest entry.** The `dim-digest` guide entry, registered while a strategy is bound. + +Callers keep as business: + +- Which request runs and when: Loop's turn and step order. +- The adopted configuration and its publication: Prompt. +- The numbers and their calibration: ContextUsage. +- The model settings before adoption: RequestSettings. +- The model call and its settlement: ModelProvider and Provider. +- When the operator asks for a compaction: the client calls `compact`. + +| Requirement (caller) | Can callers compose it from the operations below without breaking ContextPreparation's invariants? | Handling | +| --- | --- | --- | +| Loop starts a step's request at a cutoff | No: the request's content, budget and handoff facts are the owner's; the projection crosses once as a value at the same cutoff | `prepare` with the source data and the projection | +| ModelProvider confirms the final request fits the budget before sending it | No: the estimate reuse and the counter are the owner's, and a caller cannot know which estimate still matches | `validate` | +| The operator asks for a manual compaction and needs its outcome | No: the single-flight command, the step and its outcome are one state machine | `compact` | +| A caller reads whether a compaction is running | Yes: `context/compaction-start` and `context/compaction` are public facts | Business composition with `timelineTree.read` | +| A caller reads the current usage numbers | Not this owner: ContextUsage owns the numbers | ContextUsage's `read` | + +An operation exists only where the row says No. + +## Caller example + +Loop prepares a step at its cutoff; the projection is rendered once and handed over as a value: + +```rust +let projection = context_projection + .rendered_stream(RenderedStreamRequest { through: cutoff, batch: 256 }) + .await?; +context_preparation + .prepare( + PrepareRequest { + source: ContextPrepareData { turn_id, request_id, through: cutoff, ..source }, + projection, + }, + cancel.clone(), + ) + .await?; +// No request object crosses: the owner writes model/call, and Loop consumes that fact in order. +``` + +ModelProvider validates the final request, after image adaptation: + +```rust +context_preparation + .validate(ValidateRequest { request }, cancel.clone()) + .await + .map_err(|error| match error { + PreparationError::OverBudget { .. } => HostError::budget(), + other => HostError::from(other), + })?; +``` + +The operator asks for a manual compaction; the reply is the step's outcome and the caller's cancel stops only the wait: + +```rust +let outcome = line_owner::(line)? + .compact(CompactionRequest {}, cancel.clone()) + .await?; +match outcome { + CompactionOutcome::Completed { sequence } => reply_done(sequence), + CompactionOutcome::Skipped { reason } => reply_skipped(reason), + CompactionOutcome::Failed { reason } => reply_failed(reason), +} +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| ContextProjection (#2025, branch) | `renderedStream`, `renderedContext`, `snapshot`, `streamCheckpoint`, `snapshotFromCheckpoint` | The request's history, the compaction's cut and the recovery snapshot. | +| ContextFacts (#2025, Session) | `describe`, `count`, `contributions`, `estimate` | The model's limits and the request's tokens. | +| SummaryStrategy (#2025, Session) | `describe`, `compact` | The replacement's planned size and the compaction itself. | +| ContextUsage | `estimate`, `confirm`, `read` | The budget baseline and the saved contributions. | +| GuideEntries (#2026) | `register` | The `dim-digest` entry while a strategy is bound. | +| BranchScope | `timeline`, `dispatcher`, `timelineIdentity`, `branchLifecycle` | The line's facts, order, identity and phase. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `prepare` | Admit a step's request, build it at its fixed cutoff and publish the handoff facts | `{source, projection}` | `{}` once `model/call` or the failure terminal is committed | The caller's cancel before admission writes nothing; after admission the owner settles the request | `invalid` (malformed source data or a projection from another cutoff), `cancelled`, `closed` | +| `validate` | Confirm the final request fits the budget, reusing the estimate when it still matches | `{request}` | `{}` | The caller's cancel stops the check; nothing changes | `over_budget` (the request is too large; the caller fails the turn or recovers), `invalid` (missing or foreign capability snapshot), `cancelled`, `closed` | +| `compact` | Run one manual compaction step and answer its outcome | `{}` | `{outcome}`: `completed{sequence}`, `skipped{reason}`, `failed{reason}` or `cancelled{reason}` | The command is written before the first await; the caller's cancel or a dropped wait stops only the wait, and a later call joins the committed step | `cancelled` (the wait stopped; the step continues), `closed` | + +Loop writes `context/prepare` before the call. `prepare` then writes `model/call`, or, when the host or the budget refuses before ModelProvider is reached, the `step/model-output-end` terminal as the stated exception in [ModelProvider](ModelProvider.md). The projection is consumed inside the call and never persisted; the request is the durable form, and no prepared object crosses. `validate`'s reuse is expressed by the request data and the preparation's own record, never by object identity. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `invalid` | `prepare`, `validate` | Fix the input: malformed source data, a projection from another cutoff, a capability snapshot that belongs to another model | +| `over_budget` | `validate` | The request is over the input threshold; end the turn or run the compaction path, then build a new request | +| `cancelled` | `prepare`, `validate`, `compact` | Nothing was committed by the cancelled call; a committed compaction continues and answers `cancelled{reason}` | +| `closed` | all | The line is closing; stop preparing requests; the next generation serves a reloaded line | + +`compact` reports a failed summary as the `failed` outcome, not an error: the compaction fact carries the same diagnostics either way. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `prepare` | Take the single-flight slot, apply the budget to the projection, build the request, write `model/call` (or its failure terminal) | Before admission: nothing written. After admission: the preparation task finishes or ends cancelled; a steer waits for a running compaction | New preparations are refused; in-flight ones settle with `model-output-end`; an unconsumed handoff is discarded; recovery settles the facts without host work | ContextPreparation; the request's external effect by ModelProvider and Provider | +| `validate` | Reuse the matching estimate or count the final request; answer, or fail the request | The check stops; nothing changes | In-flight checks end `closed` | ContextPreparation | +| `compact` | Join or write the command, run the step at the boundary or immediately, write `context/compaction-start` and the outcome | The wait stops; the committed step continues and its result is read by a later call | An in-flight step is cancelled and settled `cancelled`; recovery reports a start without a result | ContextPreparation; the summary model calls by SummaryStrategy and Provider | +| digest entry | Register on `apply`, withdraw on unload | — | The entry leaves with the part; a reloaded part registers the new text | ContextPreparation | + +## Exceptions with reasons + +- The threshold compaction runs inside `prepare`, not as a separate operation: an over-threshold request must either fit after the step or fail as that request, and a caller composing the two calls would have to hold the request and the slot across them. + +## Supersedes + +- `docs/design/contracts/runtime-owner-operations.md`: the `contextPreparation` `publish`/`awaitPublished` row and the `agentLoop.compact` row; the Loop and ContextPreparation host-port rows keep their owners (#2025) and this contract's callers. +- `docs/design/service-faces.md` section 3.5: the `contextPreparation` and `configurationPublisher` rows. +- [ContextCompaction](ContextCompaction.md) section 1 items 4-5, section 1.1, section 2, section 2.1, section 2.2, section 3, section 4.1, section 4.3, section 5.3-5.5, section 5.8, section 10 and section 12: the command, the single-flight slot and the step are this owner's, and the Loop starts no request while a step runs. +- [Prompt](Prompt.md) section 6.3: the published System is Prompt adoption's, and ContextPreparation reads the adopted fact. + +## Verification + +- A prepared request equals the request built from the same source data and cutoff; the projection is rendered once, crosses once, and is not persisted. +- An over-threshold estimate runs the compaction inside `prepare`; a compaction that cannot fit the request writes `model-output-end` and no recovery request follows. +- `validate` reuses the estimate for the unchanged final request and counts the request otherwise; a request over the threshold is `over_budget`. +- A cancel during `prepare` before admission writes nothing; a cancel during `compact` stops the wait and the step settles later. +- A reload settles an unmatched `context/prepare` and a compaction without a result as terminal facts and performs no host work. +- The `dim-digest` entry exists only while a strategy is bound. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds the line's facts and writes prepare and compaction facts. | +| §2 scopes | Branch: the request and its compaction belong to one line. | +| §3 orthogonality | No other owner's state is read; the model facts and the summary come from Session owners' operations. | +| §4 rule 1 | A manual compaction is the `context/compact` command; the outcome is the owner's fact. | +| §4 rule 2 | The request's handover is `model/call`; after it ModelProvider owns the call. | +| §4 rule 3 | Handlers register tasks; host preparation runs in those tasks. | +| §4 rule 4 | No business meaning: what a request is for stays with Loop. | +| §4 rule 5 | A compaction start and its outcome commit as the owner decides; the request's facts keep their order. | +| §4 rule 6 | The context is the projection; nothing enters outside the prepared request. | +| §4 rule 7 | Callers use the three operations; the owner uses the siblings' operations. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Compaction facts are durable history; a recovery snapshot is optional and never replaces them. | +| §7 values, ids and objects | The request and the projection cross as data; no object, handle or callback crosses. | +| §7 one interface | One name, `contextPreparation`, on the owner type; `configurationPublisher`, `usage` and the crate-private projection slot are removed. | +| §7 cross-language | Every operation is data; no method exists only for Rust. | +| ADR 002 D1 | Branch: preparation and compaction are per-line work. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- #2025 (ContextProjection): `renderedStream` is Loop's call; the projection crosses to `prepare` as a value at the same cutoff, as the ContextProjection contract states. +- #2025 (PrepareContextHost): the model profile's request builder remains the host port `prepare` calls; the owner contract does not replace it. +- #2025 (ContextFacts, SummaryStrategy): the counting and summary operations above replace `contextModelHost` and `compactionStrategyHost`; this contract uses only those operations. +- #2026 (GuideEntries): `register` must accept a line-scoped entry and withdraw it with the part. +- #2025 (Session access): the client's `session.context.compact` reaches `line_owner::(line)?.compact(..)` by line id; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `ContextPreparation` type; the wire name stays `contextPreparation`. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::{ContextPrepareData, ModelRequest}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PrepareRequest { + pub source: ContextPrepareData, + pub projection: crate::history::StreamedContext, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ValidateRequest { + pub request: ModelRequest, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CompactionRequest {} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "outcome", rename_all = "camelCase")] +pub enum CompactionOutcome { + Completed { sequence: u64 }, + Skipped { reason: String }, + Failed { reason: String }, + Cancelled { reason: String }, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case", rename_all_fields = "camelCase")] +pub enum PreparationError { + #[error("invalid: {message}")] + Invalid { message: String }, + #[error("over budget")] + OverBudget { estimated_input_tokens: f64, threshold_tokens: f64 }, + #[error("cancelled")] + Cancelled, + #[error("closed")] + Closed, +} + +#[rutis::service] +impl ContextPreparation { + pub async fn prepare(&self, request: PrepareRequest, cancelled: CancelledFn) -> Result<(), PreparationError> { /* .. */ } + pub async fn validate(&self, request: ValidateRequest, cancelled: CancelledFn) -> Result<(), PreparationError> { /* .. */ } + pub async fn compact(&self, request: CompactionRequest, cancelled: CancelledFn) -> Result { /* .. */ } +} +``` diff --git a/docs/design/plugins/ContextUsage.md b/docs/design/plugins/ContextUsage.md index c18c0bb55d..51423a518f 100644 --- a/docs/design/plugins/ContextUsage.md +++ b/docs/design/plugins/ContextUsage.md @@ -1,180 +1,216 @@ -# ContextUsage:保存计算结果,不保存每次回调 +# ContextUsage -Status: Draft. -Scope: branch ContextUsage 的贡献、累计值、压缩、provider 基准、持久化与恢复。 -Decision: [ADR 023](../../adr/023-context-usage.md)。Issue: [#1320](https://github.com/arcships/dim/issues/1320)。 -合同:[ContextCompaction](ContextCompaction.md#51-productcontextmodel)、[保存边界](../owner-state-indexed-reads.md)、[插件合同](../plugin-contract.md)、[设计规则](../../architecture/rust-agent/principles.md)、[ADR002](../../adr/002-plugin-scope.md)、[rutis](../rutis-usage.md)。 +Scope: branch. Issue: #2027. -## 1. 决定与边界 +ContextUsage owns the numbers of a line's effective context: what each source contributed, the cumulative totals, the compaction cuts and the provider's measured baseline. The counting rules are decided in [ADR 023](../../adr/023-context-usage.md); the saved formats are this contract's (below). The compaction interaction is [ContextCompaction §5.7](ContextCompaction.md#57-compaction-state-for-clients). This document is the owner's target contract. -`contextUsage` 为 internal(hot-path):接口使用本地请求引用和计数器,不跨语言传递;外部统计沿用 `session.context.usage`。 +## Use and scope: responsibility split -ContextUsage 是现有上下文功能内的独立 branch Capability,维护有效上下文的数字。生产者继续写原事实,不调用 Usage 更新、确认、删除或清理统计。Timeline/Store 不做 token 计算。 +ContextUsage owns: -保留现有 session.context.usage 成功回复。尚无当前统计时返回 `context_usage_unavailable`,表示下一次实际模型请求后可用;模型解析失败仍返回 `context_model_failed`,未配置仍返回 `context_not_configured`。ContextPreparation.usage 委托本 owner,不为查询统计构造模型请求。read 固定源截止和当前 tools 身份,等待该目标完成后返回;已就绪读不查历史消息、不重复消息计数、不保存;当前动态工具身份首次出现时按§3取得固定贡献。无配置直接 NotConfigured,不先渲染正文;可组合计数不支持返回 Model/Unsupported,不退回完整历史重建。 +- **Contributions.** One number per source that actually produced context: an adopted input, a settled assistant output, a tool result, a compaction's replacement and its baseline. The contribution is `{serialized_bytes, images}`; the count is bytes / 4 + images × 1600 under the counter identity `dim/window-facts/v1`. +- **The saved totals.** One `context-usage/recovered` v5 record per changed source and a `context-usage/covered` v1 extension for an already checked no-effect tail at a fixed read or turn-end handoff. A processed but no-effect source outside those handoffs only advances the in-memory position and writes no record. +- **The request baseline.** The estimate a preparation reserves for a request at a cutoff, the sources it counted, and the provider's measured prompt tokens when they verify that same request. +- **Recovery.** After a reload, the latest saved totals, the covered position and the counter controls. An uncovered source invalidates the derived numbers; a cold recovery never consumes a source body, and a missing predecessor answers unavailable rather than recounting history. -保存已经计算出的数字是必要优化:输入/输出已入上下文后,未来显示不应再次读取它们。处理过无关事件、delta、model-start 不构成保存理由。数字结果与单独 boundary 合为一份;不保存逐源数字树或请求正文。 +Callers keep as business: -## 2. 对象、改变条件与重载决定 +- What the budget decision is: ContextPreparation's threshold and retention rules. +- Which model a request runs and how it is counted: ContextFacts and RequestSettings. +- Whether a saved count may be reused: ContextPreparation asks for the estimate and validates the final request. +- What a usage number means to a client: the client renders it. -| 实际对象 | 业务事件与具体条件 | 重载时保留/取得 | 持久化决策 | -| --- | --- | --- | --- | -| 内容贡献 | input/consumed 经 render_input 实际产生消息;output-end 结算保留的助手消息;tool-result 产生结果/附带消息;完成 compaction 产生 replacement/基线 | 保留已经计算出的贡献;只计算未处理来源及真正新增内容 | 消息贡献合并进该次数字结果,不另存同源 boundary,不复制正文 | -| 普通历史累计值 | 新源实际产生消息时累加 serialized_bytes、images、message_count;更新最后 HistoryEntry ID/来源位置 | 直接恢复数字;压缩不重写既有累计值 | 随数字结果保存;即使估算 token 四舍五入后相同,贡献/条目身份改变仍保存 | -| 压缩边界 | 仅 context/compaction.status=completed 且有效 retain_from | 保留切点、扣除的累计贡献、新 replacement/基线贡献;先前摘要被替换 | 同一数字结果;failed/skipped 无压缩状态保存 | -| 输出结算标记 | model-start 打开 request;output-end 关闭;旧 tool-result 无 call_event_id 时仅结算仍打开输出 | 从该 request 的 model-start/output-end/旧 flush 边界点查;不续跑旧模型请求 | 内存,不保存 started/settled 集合;原终态足够表达 | -| provider 基准 | 有有效 prompt_tokens,且请求、覆盖前缀、算法、固定内容、压缩均匹配;同请求更新测量 | 已建立基准恢复;尚未建立的实时关联作废;不读旧 request.messages 补证 | 基准与当前数字同一结果;相同数值、相同身份不写新数字结果 | -| 处理位置 | 六类相关源处理完且对应数字已保存;空消息/重复无效 usage 只提高内存位置 | 从数字结果及其匹配的小位置缓存取得 | 不逐源保存;无效果尾部在业务结束/固定读取交接处合并位置缓存,见§5 | - -算法标识沿用 `dim/window-facts/v1`。贡献是两个整数 `{serialized_bytes,images}`,计数为字节/4+图片×1600;消息序列化边界严格复用现有 ContextCounter。Text 消息计完整 Message;parts 分项,Image 只计图片;ToolResult Blocks 只计实际 content blocks,不计 structuredContent 或额外包装。未 consumed 的输入不计入。 - -来源查询先限定六类源,再要求 `context.render=true`;`context/configured`、`model/usage` 是独立控制源,保留处理。带 `parent_call_id` 的子执行事实不进入上下文,不读取其正文、不计算贡献、不保存数字结果。 - -数字结果的完整字段: - -- 顶层:`schema=context-usage/v5`、`source_through`、`epoch`、`branches`、`initialized`、`current`。 -- `initialized={branch,sequence}`:本epoch首次建立当前累计值的来源截止,branch是branches中的序号。缺少旧统计时不因此补写更早位置。 -- 可选 `legacy_result`:被复用的v1–v3统计事件ID;只读引用,不复制或改写它的节点。仅在真实统计变更后的正常结果中保存,不为升级单独写一份。 -- `current={at:{branch,sequence},totals}`:at 是累计值对应的来源位置;不另存重复的 boundary_sequence。 -- `totals.configuration`:Ready 时保存 event_id、request_identity、control_identity、configured_tools、algorithm、fixed 和 limits(window/output/threshold);不支持/不可用有明确状态。 -- `totals.ordinary={serialized_bytes,images}`、`message_count`、`last_entry={id,at}`、`local`、`growth`:普通消息累计贡献、条数、最后条目、本地估算及压缩策略用的累计增长数字。message_count为整数或null;null仅表示旧统计未保存条数,不表示0。 -- `totals.compression`:event_id、cut、removed、replacement、removed_messages、replacement_messages,或缺省。 -- `totals.calibration`:request_id、request_at、anchor_at、configuration、compression、request_identity、local、prompt_tokens,或缺省。 - -不新写root或数字节点,不复制逐消息正文、所有请求、Weak引用、started/settled数组。兼容读取可以按legacy_result访问已存在的旧节点。当前用量是固定贡献+ordinary−removed+本次replacement/基线。每次压缩替换上一份 replacement,而不是累加历次摘要。 - -current.at 是这份累计值对应的来源位置;source_through 是本份结果已处理到的位置。无效果来源只提高处理位置,不产生新 current。两者不能互相替代,否则压缩可能漏掉已经计入的消息。 - -## 3. 每种来源读什么、算什么 - -| 来源 | 字段和查询 | 计算/写入条件 | +| Requirement (caller) | Can callers compose it from the operations below without breaking ContextUsage's invariants? | Handling | | --- | --- | --- | -| input/consumed | input_id;按 ID 点读 input/message 的 blocks、user | 复用 render_input;每个新 Message 计数一次。没有 Message 时不写数字结果 | -| step/model-output-end | request_id、status;该 request 的最后完整 content 及之后仍保留的 delta | 复用 settled_request_output;不读被完整内容覆盖的 delta;保留内容计数一次,空输出不写数字结果 | -| step/tool-result | request_id、call_event_id、calls、contents、isError、contextMessages | 复用现有 tool_result_message;附带消息同源合并。旧 flush 先按 request 索引取得打开/结算边界,避免重复输出 | -| context/configured | 实际采用的 settings、system、tools | 算法相同保留 ordinary,只计算改变的固定部分/限制并撤销不适用基准;相同固定身份与限制零计数/零数字结果 | -| context/compaction | status;completed 时读 retain_from、replacement、context_baseline | 切点点查已保存累计值;只算新的 replacement/基线;失败/跳过不算正文 | -| model/usage | request_id、usage;只取 prompt_tokens 及缓存输入量 | 有匹配基准且测量变化才替换;相同数值不重复累加,不重算消息 | - -六类是恢复源。model-start 不是持久进度源;打开输出的标记由请求控制事实按需取得。context/prepare、model/call、context/budget 用于有限实时关联,不读取它们的历史消息数组,不因为这些回调保存统计。 - -固定 tools 已在配置中时直接采用它。否则使用原 ToolRegistry 当前声明及 source key/version。集合身份不变直接复用 fixed 数字,不重新序列化工具。读取注册表当前声明的复制成本仍按工具数量计,不冒充零成本;不调用 bind/bind_current。动态集合不产生额外 Timeline 事件。只在内存缓存 configuration ID、source key/version 摘要、实际控制内容身份和固定贡献;source 版本变化但内容相同则复用数字。当前读采用这份固定贡献,并仅采用身份匹配的 provider 基准;重载重新取得当前集合。数字已就绪时,显式 context/configured 变化按原规则保存;尚未就绪时等待实际请求。 - -## 4. 复用已经计算出的数值 - -| 已有数值 | 用法 | -| --- | --- | -| Usage 当前 ordinary/fixed/compression 数字 | 直接用于显示、预算和压缩扣除,旧消息计数调用为0 | -| ContextPolicy 本次已算的完整请求估算 | ContextPreparation 将数值与本次不可变 Arc、算法/限制一起保留到最终校验;同一对象复用该数值,不能再 count_tokens 一次 | -| Usage 数字与本次准备请求严格同一有效前缀 | 原预算/最终校验入口可读同一 numeric estimate;只核对配置、切点、最后条目/消息数与本次准备的来源证明,不全文比较。请求经过实际增补/替换,失效后只计实际新请求一次 | -| model/usage.prompt_tokens | 直接作为匹配请求的输入实测,不从 completion_tokens/total_tokens 推导 | -| context/budget.full_estimate | 只有覆盖边界、固定内容和算法匹配才复用为该调用本地总量;它不是单条消息贡献 | -| context/budget.provider_baseline 或 compaction diagnostics | 不反推单条贡献;前者是混合估算,后者不等于 replacement 的贡献 | - -现有历史事实没有逐消息贡献,完整请求的一个总数也不能拆出任意压缩切点。新增输入/结算输出的单源贡献仍各计算一次。这项计算不因“共享了同一个函数”就算成复用了数值。请求构造、host 实际改变内容后的最终计数、压缩新摘要计数是各自真实工作,分别记账。 - -复用只改已有预算和校验的数值传递,不增加 ModelProvider/AgentLoop 的 Usage confirm/discard,不增加请求事件载荷、请求基准事实或 producer→Usage 更新调用。`UsageEvidence` 不携带持久 root;压缩策略需要的增长只通过私有累计数字前驱查询相减取得,不增加公开历史统计 API。临时数值证明不跨重载、不使请求正文常驻。 - -## 5. 保存与位置缓存 +| A client or a Session method reads the current usage at a cutoff | No: the totals, the cut and the baseline are one record; folding them from facts in the caller is a second cache | `read` | +| ContextPreparation reserves the input budget of a request at a cutoff | No: the estimate is tied to the sources it counted at that cutoff and reused only while they still match | `estimate` | +| ContextPreparation confirms the final request that was sent | No: only the owner may save contributions for a request, and only once the request retains what the estimate counted | `confirm` | +| A caller learns why usage is unavailable | Yes: `not_configured` and `not_ready` name the next step | Business | +| A caller recounts history after a compaction | Yes: the compaction's replacement and baseline arrive as facts and the owner folds them | Business | -同一原子源批次按原位置处理,用转移结果的标量标记记录变化:新增消息数/贡献、实际配置身份/限制改变、成功压缩、有效基准替换。不要 clone整份状态或重算集合比较。`context-usage/recovered` 的每份结果内部包含该源之后的累计值,不同时写 boundary;本批有几个需要保留切点的内容源,就保存几份,最后一份也是当前结果。提交后才发布。 +An operation exists only where the row says No. -不同源批次不为少写而等候未来事件。同批多个普通消息源仍须保留压缩切点可寻址的累计值:本批每个实际产生消息的源保存一份 numeric 结果,最后一份同时承担当前结果,不额外再写一份全批快照。固定配置/基准变化也保存其来源边界;不能把较晚基准套到较早切点。一个源中的多条 Message 合并为一个边界,因为 retain_from 按源事件切割。 +## Caller example -空消息、失败/跳过压缩、无效/重复 provider 数字没有新 numeric。它们如果发生在最后保存的数字之后,需要确认“已经处理且无效果”,否则每次重载都会重新检查同一段来源。确定保存一种小型派生缓存: +A Session method reads the current numbers: -`context-usage/covered`:`schema=context-usage-covered/v1`、`result_id`、`source_through`。result_id指向它延伸的最新数字结果。不含state、贡献数组、正文或请求身份。 +```rust +let usage: UsageRead = line_owner::(line)?.read(ReadUsage { through: None }, cancelled).await?; +// {through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource} +// baselineSource is dim_agent_types::BaselineSource: provider_baseline | full_estimate +``` -仅在以下条件全部满足时写一份:本 owner 已处理固定范围;存在晚于当前 numeric/covered 的相关源;本范围没有需要保存的数字变化;到达 turn/end 的已完成范围,或正在兑现固定 read 目标。无相关源、已被结果覆盖、只有 model-start/delta/interrupt 时不写。多个无效果源在同一交接处只写一份;普通实时回调不写。后续有 numeric 时覆盖这段处理位置,不再另外写 covered。 +ContextPreparation reserves a request's budget, then confirms the request that was sent: -该缓存是避免重复检查无效果尾部的性能数据,不是业务事实,也不是所有 owner 的通用快照。未变化的普通 getter为0写入;等待新来源的 getter可能等到 owner 完成必要保存,不能把这种情况伪称为已经就绪读取。读一次失败/空来源之后,再次重载不重做这项工作。 +```rust +let estimate = line_owner::(line)? + .estimate(EstimateRequest { request_id, through }, cancelled.clone()) + .await?; +let reserved = estimate.estimated_input_tokens; +// ... the final request is built and validated ... +context_usage.confirm(ConfirmRequest { request_id }).await?; +``` -## 6. 恢复、切点和查询范围 +## Own contract -正常恢复先读最新 numeric 和最新 covered,各1次。只有 covered.result_id 匹配当前 numeric 且范围合法才采用其位置;更早数字的缓存不延伸新结果。用 kind/位置索引探测覆盖位置之后到固定读头 S 的六类来源,沿用实时处理的 context.render 筛选(配置、provider usage 独立保留),不读取 status、渲染内容或来源正文。有任一来源则统计未就绪,等待真实请求已有投影;不补算旧来源。没有来源才点读保存配置的计数控制字段并复用数字,正常单分支共4次逻辑 query。祖先数字的探测范围覆盖原统计分支之后的完整可见分支链。未显式配置 tools 时,当前集合首次/版本变化另需一次该配置 system 字段点读。冷加载不写 numeric、covered 或失效事件;S 之后的新来源仍由实时任务处理。 +### Dependencies -S 在订阅实时来源之前固定。发布后才启动数字任务,但不能在任务被调度时重新取 S,将已经交付的新输入或请求归入旧历史。 - -压缩切点:按 retain_from 的逻辑ID取得来源位置;在同一 epoch 的 numeric 结果中按 `data.current.at.branch = 切点分支序号 AND data.current.at.sequence < 切点` 倒序取最近累计值,再按其数字扣除。采用已有 Field 排序语法;必须由[源位置索引](../appserver/timeline-state-read-indexes.md)执行,不用事件提交位置代替源位置,不用 LIMIT1 掩盖历史筛选。单分支2次逻辑query(ID位置+数字边界);祖先切点按固定chain各段定位,最多R次范围探测,R是分支链长度。边界之前无普通消息时累计值为0,不能因此遍历旧来源。 - -切点不能回到已被替换的范围。初始化之前的数字不能假设为0;缺少统计的首次初始化按§6.2处理。数字结果 source_through 可能小于自身提交位置,查询同时核对事件在固定可见范围;数值索引不是绕过祖先 cutoff 的权限。 - -输出结算状态按 request 的已有 request_id 索引取得最后 start/end/旧 flush边界。正常重载没有打开输出时不读取任何旧输出内容;资源 owner 补出的终态属于新的真实内容源。已有 numeric 之前的输出不重计。 - -### 6.1 统计版本与旧数据 - -新写私有统计使用context-usage/v5;读取v4原有数值及v1–v3累计数字。v5允许旧统计未保存的message_count、压缩消息条数和控制缓存字段缺失或为null,并增加可选legacy_result。缺失消息条数不使用数值证据的请求快捷校验;请求沿已有实际请求校验,不把未知条数填0,不为建立无法证明的provider关联读取旧请求。v4没有这些缺失语义,缺字段仍按损坏处理。 - -这是私有派生统计的显式版本决定,native v41、公开事件和Query API不变。Store将扩展data视为所属owner的数据;现有epoch/源位置索引字段不变。不把不兼容结构继续标成v4。旧统计原字节保留;未知schema、算法不兼容和实际读取的坏引用报错,不猜测、不重算掩盖。 - -v1–v3恢复从最新结果的state.root.summary取得ordinary、固定贡献、压缩、基准、last_entry和growth。source_through、branches与可见截止必须合法,算法须匹配。恢复时补取配置的实际控制字段和tools声明存在性,只探测未覆盖源后缀是否存在;有来源则等待实际请求,不读取来源正文,无新来源时0旧消息计数、0数字补写。未来需要升级前切点的累计值时,先按ID读取legacy_result及所需数字节点,整段已累计范围直接采用它的summary,只读取落在切点上的节点;不回放消息,不把旧节点改写为新事件。 - -### 6.2 确实没有统计 - -生产旧库可能从未保存 ContextUsage 数字。没有数字时直接等待真实请求;不探测旧内容,不读取旧 System/tools,不解析完整配置或计算固定贡献。未配置仍返回明确的未配置错误。resume 不为显示用量初始化完整历史,也不后台分页补算;统计未建立时,usage 返回明确的未就绪错误,界面不显示伪造的 0 或把旧请求用量冒充当前值。只有压缩 replacement、没有普通消息的迁移会话同样等待实际请求,不在加载时读取 replacement 或 context_baseline。新分支同样等到实际请求已有投影再建立当前累计值。 +| Owner | Operation | Use | +| --- | --- | --- | +| ContextFacts (#2025, Session) | `describe`, `contributions`, `estimate` | The additive counter, the fixed contribution and one contribution's size. | +| ToolRegistry (#2026, Session) | `declarations` | The current tool declarations and source versions when the adopted configuration names no tools ([ToolRegistry](https://github.com/arcships/dim/pull/2103), target, pending). | +| BranchScope | `timeline`, `dispatcher`, `branchLifecycle` | The line's facts, their order and its phase. | -首次实际请求由 Loop 取得一份有效上下文,交给 ContextPreparation;Policy 复用消息、来源位置与压缩边界,不再次读取。缺少数字时,Usage 对这份内容计算初始贡献和本次请求估算;Policy 使用该估算,不再调用完整消息计数。 +### Operations -只有最终请求仍使用固定截止 S 的投影,且本次没有采用 C>S 的压缩,Usage 才保存已经算出的贡献。采用新压缩时丢弃旧截止的临时贡献,使用已算的最终请求 tokens 完成本次请求;下一次真实请求包含该压缩时再建立数字。不得把 S 的内容标成覆盖至 C,也不得把 C 的替换结果保存为 S 的数字。 +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `read` | The effective context's numbers at a cutoff | `{through?}` | `{through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource}` | The caller cancels; the read stops and nothing changes | `not_configured`, `not_ready`, `unsupported`, `cancelled`, `closed` | +| `estimate` | The budget baseline of a request at a cutoff | `{requestId, through}` | `{estimatedInputTokens, baselineSource}` | The caller cancels before the count completes; nothing is saved | `not_configured`, `unsupported`, `cancelled`, `closed` | +| `confirm` | Save the contributions for a request that was sent with the estimate's projection | `{requestId}` | `{}` | None; the owner completes the save | `unknown` (no estimate for the id), `closed` | -只将数字和来源截止交给 Usage 的按序任务,正文在请求准备结束后释放。初始化保存一份当前数字,不补建更早位置;与新来源按固定截止串接,不能漏计或重复累加。之后沿既有请求关联接收首轮 provider 基准。正常首次请求读取1遍、消息计数1遍,恢复读取0条历史正文。请求专有附加消息或不支持可组合计数的模型仍走实际请求计数合同,不把该总量保存成 Timeline 内容统计。 +`read` answers at `through`, or at the branch's current sequence when absent. `estimate` counts the owner's sources at `through`; it is idempotent for one request id and cutoff, and a repeated call answers the same numbers. `confirm` makes those numbers the request's contribution; without it the estimate is discarded at the next request or at close. A saved result is written only for a source that actually changed the numbers; a checked no-effect tail at a fixed read or turn-end handoff extends the covered record, and any other no-effect source only advances the in-memory position. -初始累计之前没有数字的位置不能当成 0。实际压缩没有可证明的累计前驱时,使统计未就绪;不从链头读历史扣除,不建立任意旧切点恢复能力。实际请求按前述固定 S 规则建立新数字;手工压缩没有请求时等待下一次真实请求。请求侧只传递已经取得的数值,不增加 producer confirm/discard、模型请求基准事实或每条来源快照。 +### Errors -fork优先复用祖先可见数字和边界;不可见或没有兼容数字时按 6.2 等待实际请求建立数字。不能使用父分支切点之后的统计。 +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `not_configured` | `read`, `estimate` | Adopt a model first; without a configuration there are no numbers | +| `not_ready` | `read` | The next real model request establishes the totals; answer that usage is unavailable | +| `unsupported` | `read`, `estimate` | This model has no additive counter; keep only complete-request counts | +| `unknown` | `confirm` | No estimate was reserved for the id, or it was discarded; save nothing | +| `cancelled` | `read`, `estimate` | Nothing changed; retry at the same cutoff | +| `closed` | all | The line is closing; the next generation serves a reloaded line | -## 7. provider 基准与异常 +A missing predecessor makes the numbers unavailable rather than recounting history: `not_ready` is the caller's answer until an actual request establishes a new total. A real model preparation passes its request id and cutoff to `estimate`; the numbers are saved only after `confirm` names the request that retained what was counted. -建立准备关联前等待 Dispatcher 已交付到该请求覆盖位置,避免更早的配置通知清掉新关联。实时关联保留一个准备槽和一个最近调用槽。Dispatcher 收到匹配的 model/usage 时,为该事实位置暂存请求身份、来源位置及已验证的数字校准基准;不保留请求正文。数字任务处理该事实前等待 Dispatcher 已交付到该位置,消费后立即删除暂存项。后续调用或配置变化不能抹掉已经收到的测量依据;重载不恢复这些实时暂存项。预算/校验通过数字读取验证实际请求的配置、压缩、消息数和覆盖位置,保存该次验证的 Arc 的 Weak、原 prepare 身份和已经算出的 local。call 与这个已验证对象相同且请求/配置/提示身份未变才形成候选;不能只和最初 prepare 对象比较,因为正常准备流程也会生成新的不可变请求。弱引用不保留正文;不持久化地址,不用失效地址比较,不建请求表。覆盖期间配置/压缩/动态工具改变,候选作废。图片或请求专有增补不能证明可校准时使用本地估算,不读取历史 request.messages 补证。 +### Flows -统计覆盖该源位置后,候选只保留配置/压缩身份、覆盖位置本地总量及request_id。有效model/usage要求prompt_tokens有限且>0,且不少于cache_read+cache_write之和。当前估算为实测输入+覆盖后本地增量,缓存量不再重复相加。相同request后续usage替换旧测量;旧候选不覆盖更晚基准。相同身份与数值不写新numeric。已建立基准存numeric;未建立候选在重载作废,旧活任务不重启。 +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `read` | Read the in-memory totals at the cutoff; a cold read seeks the saved totals by epoch, branch ordinal and source sequence | The read stops | Pending reads end `closed`; the next generation reloads the saved totals | ContextUsage | +| `estimate` | Count the sources at the cutoff, or reuse the saved numbers that cover them, and record the association with the request id | Nothing is saved; the association is dropped | The association is dropped; contributions are saved only for confirmed requests | ContextUsage | +| `confirm` | Write the contributions the estimate counted, then keep the association for calibration | — | A request confirmed before close keeps its saved contributions; an unconfirmed one is discarded | ContextUsage | +| provider measurement | A settled `model/usage` for the associated request updates the baseline | — | A measurement for an unconfirmed request is ignored | ContextUsage | -异常取消释放当前读取和临时请求关联,已完成数字正常提交;重载探测到未覆盖来源时仅将统计置为未就绪,不补算该缺口,由下一次真实请求的最终投影建立新数字。可处理的模型/工具异常由其owner结算原终态,不为Usage写paused。提交失败不推进持久处理位置或发布成功数字;读取取消不撤销已接受的业务事件。 +## Exceptions with reasons -## 8. 实际流程的数量 +- `estimate` counts the owner's sources at a cutoff, not a projection value: the request is built after the reservation, and counting the final request again is `validate`'s separate budget check. +- The provider baseline keeps one `Weak` reference to the verified request inside the owner: it is optional evidence, and losing it loses the fast path, never a saved number. +- A saved result and its position are one record: a separate per-source tree or a copy of the request body would duplicate what the facts already hold. +- `context-usage/recovered` is v5 and `context-usage/covered` is v1. The covered record extends a saved result only for an already checked no-effect tail at a fixed read or turn-end handoff; a no-effect source at another position changes only memory. A format change is its own decision (AGENTS.md), not part of this contract. -以下“计数”指ContextCounter处理消息或固定内容,不包括请求必须的构造、网络和原流式持久化。B_in/B_out为本轮实际采用的输入/保留输出大小,F为变化的固定内容大小。 +## Supersedes -| 流程 | 数字/位置新增事件 | 正文读取与计算 | -| --- | --- | --- | -| 普通一轮,无工具/压缩,有新的有效provider基准 | 输入numeric1、基准numeric1、输出numeric1,共3;covered0 | 输入/输出各一次贡献,处理B_in+B_out;无旧历史计数;prepare/最终校验复用同一次已确定数值 | -| 没有有效或没有变化的provider基准 | 输入/输出numeric2 | 仍只有输入/输出两次消息贡献;usage只改标量,不再计一次输出 | -| Goal自动执行一轮并继续 | 同上;Goal运行快照0 | 只计算原续行输入与本轮输出 | -| 数字已就绪后固定配置改变 | numeric1;Prompt引用0 | 仅变化固定部分F;消息贡献0次重算 | -| 同值配置/提示、重复已覆盖统计读取 | 0 | 0贡献计算;提示刷新原逐目标比较另计 | -| 无内容失败,相关源尚未覆盖后turn结束 | numeric0、covered1 | 空结算判定及小控制查询;旧正文0;再重载不检查这段失败来源 | -| 中断并保留部分输出 | 该输出numeric1;不另为interrupt保存 | 只读取本请求保留的完整内容+后续片段,按保留字节计一次 | -| 压缩完成 | 新替换贡献numeric1;原compaction事实保留 | 2次切点定位+replacement/基线贡献;旧前缀0次求和/计数 | -| 正常已结算重载 | 0 | 4个逻辑query;1份numeric及配置控制;0消息正文和消息计数,存在未覆盖来源则直接未就绪,动态tools首次另读system并计算固定贡献 | +- `docs/design/service-faces.md` section 3.5: the `contextUsage` row. +- The former `ContextUsage.md` statement that `contextUsage` is an `internal(hot-path)` interface using local request references; the three operations above replace it. -一轮原事实明确为input/message、applied、consumed、turn/start/end、model-start/output-end、model/usage、context/budget、context/prepare、model/call各1,加D个原输出事实,共11+D。Usage增加2或3,不是再加2份boundary和逐model-start快照。带工具的一轮按真实tool-call/tool-result及附带消息另列,不用假设积压量作为优化依据。 +## Verification -## 9. 必要修改与机制要求 - -| 位置 | 必要修改 | -| --- | --- | -| context_usage.rs、context_usage/sources.rs | v4小数字状态、按实际转移保存、covered合并、输出控制按需取得、原read屏障 | -| context_usage/numeric.rs | 私有数字树不保留;累计边界使用已保存numeric事实 | -| context_model.rs、host.rs | 唯一可组合计数定义;可选默认接口保持旧计数实现兼容 | -| history.rs/settled_output.rs | 复用已有投影/结算;不复制转换规则或缓存历史 | -| context_preparation.rs、context_policy.rs | usage委托;本次请求已有数值在原prepare/validate间复用;不拥有第二套累计统计 | -| defaults.rs、lib.rs | 原上下文功能安装与内部服务名 | -| ModelProvider、AgentLoop等 | 不要求Usage确认/清理调用,不增加事件字段或统计状态 | - -| owner / 问题 | 现有能力与确定要求 | 序号/取消/重载 | -| --- | --- | --- | -| Store / #1320 | ID、kind/位置、request_id足够读取新源;按源数值位置取前驱尚无索引,补通用标量范围索引与匹配 | 原fixed scope与事务;v40索引方案归机制文档;不在Store计token | -| Timeline / #1320 | 现有append/query足够 | 不改before/提交/发布;数字保存失败不发布;无新状态CRUD | +- `read` answers the current totals, `not_configured` without a model and `not_ready` before the first real request; an unsupported counter answers `unsupported`. +- `estimate` for one request id and cutoff answers the same numbers twice; a changed cutoff counts again; a no-effect source outside the handoff writes no new record, and one at the handoff extends the covered record. +- `confirm` saves one record per changed source; a second `confirm` writes nothing new; `confirm` without an estimate is `unknown`. +- A settled `model/usage` calibrates the next request for the confirmed association; an incompatible control or content invalidates the association without a recount. +- `read` and `estimate` map to the Session codes as today: `not_configured` → `context_not_configured`, `not_ready` → `context_usage_unavailable`, `unsupported` and `unknown` → `context_model_failed`. +- A reload reads the latest saved totals and the covered position; an uncovered source makes `read` answer `not_ready` rather than recounting. +- A call in flight when the line closes ends `closed`. -## 10. Rule check与删减 +## Rule check -| 规则 | 本设计 | +| Rule | Application | | --- | --- | -| principles§1;ADR002 D1 | 统计、任务与恢复归独立branch Capability | -| ADR002 D2–D5 | 无接线层、新用户配置;贡献/服务合同语言中立 | -| §4 1–4 | 不启动其它owner任务,不代交接;handler只通知自己的任务;无before I/O | -| §4 5、6 | 原上下文事实不变,统计不进入模型上下文;保存成功后发布 | -| §4 7、8 | 声明原依赖;机制需求见§9 | -| §4 9 | 数字服务预算/显示/压缩;位置缓存只避免重复处理已确认无效果的尾部 | - -删去数字树、独立boundary、每个model-start保存、started/settled持久数组、每次只推进内存位置也保存完整状态、request-base事实、生产者confirm/discard。保留的贡献累计数字、切点、基准和小处理位置缓存各有明确读路径。复用现有上下文flow验证计数等价、同批/分批、重复/迟到usage、空输出、压缩、fork、提交崩溃和关闭;记录实际SQL候选、解码字节、计数调用和WAL,不以LIMIT1或输出行数代替证明。 +| §1 parts and Capabilities | One branch part and a Capability: it folds the line's facts and writes its own saved records. | +| §2 scopes | Branch: the numbers belong to one line's effective context. | +| §3 orthogonality | No other owner's state is read; the counter and the tool declarations arrive through their owners' operations. | +| §4 rule 1 | No command event: the owner writes its own saved results. | +| §4 rule 2 | No handover: the numbers stay in the owner; `estimate` answers a value. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning: the budget rule stays with ContextPreparation. | +| §4 rule 5 | A saved record commits as one batch with its position. | +| §4 rule 6 | No context path: the numbers add no message. | +| §4 rule 7 | Callers use the three operations; the owner folds the public facts. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Saved numbers are derivable state; the facts remain authoritative. | +| §7 values, ids and objects | The request is data and the reply is a value; no projection, handle or callback crosses. | +| §7 one interface | One name, `contextUsage`, on the `ContextUsage` type; `ContextPreparation::usage` is removed. | +| §7 cross-language | Every operation is data. | +| ADR 002 D1 | Branch: the numbers are per-line. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | + +## Requirements raised to mechanism owners + +- #2026 (ToolRegistry): `declarations` answers `{tools, sources}` as data ([ToolRegistry](https://github.com/arcships/dim/pull/2103), target, pending); ContextUsage reads it when the adopted configuration names no tools. +- #2025 (ContextFacts): `contributions` and `estimate` must accept the model selection as data, as the target contract states. +- #2025 (ContextProjection): `estimate` counts the line's sources at a cutoff; it does not take a `StreamedContext`. The projection stays in ContextPreparation. +- #2025 (Session access): the Session methods read `line_owner::(line)?.read(..)`; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `ContextUsage` type; the wire name stays `contextUsage`. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::BaselineSource; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UsageRead { + pub through: u64, + pub context_window: f64, + pub output_tokens: f64, + pub threshold_tokens: f64, + pub estimated_input_tokens: f64, + pub baseline_source: BaselineSource, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReadUsage { + #[serde(skip_serializing_if = "Option::is_none")] + pub through: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EstimateRequest { + pub request_id: String, + pub through: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Estimate { + pub estimated_input_tokens: f64, + pub baseline_source: BaselineSource, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfirmRequest { + pub request_id: String, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case", rename_all_fields = "camelCase")] +pub enum UsageError { + #[error("not configured")] + NotConfigured, + #[error("not ready")] + NotReady, + #[error("unsupported counter")] + Unsupported, + #[error("no estimate for this request")] + Unknown, + #[error("cancelled")] + Cancelled, + #[error("closed")] + Closed, +} + +#[rutis::service] +impl ContextUsage { + pub async fn read(&self, request: ReadUsage, cancelled: CancelledFn) -> Result { /* .. */ } + pub async fn estimate(&self, request: EstimateRequest, cancelled: CancelledFn) -> Result { /* .. */ } + pub async fn confirm(&self, request: ConfirmRequest) -> Result<(), UsageError> { /* .. */ } +} +``` diff --git a/docs/design/plugins/InputQueue.md b/docs/design/plugins/InputQueue.md new file mode 100644 index 0000000000..1f9871a75d --- /dev/null +++ b/docs/design/plugins/InputQueue.md @@ -0,0 +1,226 @@ +# InputQueue + +Scope: branch. Issue: #2027. + +InputQueue owns when a line's inputs become applicable: it consumes committed inputs in order, decides when each is applied, withdrawn or deleted, and answers whether one is still pending. The current implementation is described in the [InputQueue plugin page](../../architecture/rust-agent/plugins/InputQueue.md). + +## Use and scope: responsibility split + +InputQueue owns: + +- **The queue.** The inputs a line holds unapplied, their modes, the open turn and the starting flag, in commit order. +- **Application.** Steer and append inputs apply at once; a queue input applies when no turn runs or is about to start; a handover input waits for the turn it names and is deleted at that turn's end. The decisions produce `input/applied`, `input/deleted` and one replacement `input/message` for an accepted Steer, in one atomic batch. +- **The withdrawal decision.** Whether a held input is withdrawn, and the conditional replacement of an accepted Steer. +- **The pending read.** Whether an input is still held and unapplied at a published cutoff, including the block-presence answer the read contract defines. +- **The submission admission.** An input is accepted once per submission id; a repeated submission answers the committed input. + +Callers keep as business: + +- What an input says and which mode it uses: the operator entry, a client, a plugin. +- The operator's content validation: the Session entry. The submit checks are the queue's call to SubmitChecks before it admits a Steer. +- The turn's run: Loop. +- What a client shows for the queue: the client reads the pending and history reads. + +| Requirement (caller) | Can callers compose it from the operations below without breaking InputQueue's invariants? | Handling | +| --- | --- | --- | +| The operator entry writes a withdrawal, optionally replacing the input with a Steer | No: the checks, the conditional decision and the atomic replacement are the queue's; two calls would let a second withdrawal replace the deleted input | `withdraw` | +| A plugin or another owner writes an input to the line by line id | No: the submission admission, the order and the turn decision are the owner's | `submit` | +| A caller answers whether an input is still pending | No: membership at a published cutoff is the queue's folded state | `pending` | +| A client reads a line's pending inputs as a page | Not this owner: the page read is `session.input.pending` on TimelineTree (#2103); this owner answers one input's membership | TimelineTree's page read | +| A client withdraws an input it wrote | Yes: `withdraw` without a Steer candidate | Business | + +An operation exists only where the row says No. + +## Caller example + +The operator entry validates the content, then asks for the conditional withdrawal and replacement; the queue runs the submit checks before admitting it: + +```rust +let answer = line_owner::(line)? + .withdraw( + WithdrawInput { + input_id, + reason, + steer: Some(candidate), + }, + cancel.clone(), + ) + .await?; +// Deleted { sequence } | NotHeld +``` + +A plugin submits an input into a line it does not own: + +```rust +let InputRef { input_id, sequence } = input_queue + .submit(input, cancel.clone()) + .await?; +``` + +A Session method reads whether an input is still pending at a cutoff: + +```rust +let Pending { pending } = input_queue + .pending(PendingRequest { input_id, published_cutoff: Some(head) }, cancel) + .await?; +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| SubmitChecks (#2026, Session) | `check` | The registered checks the operator's Steer must pass before the queue admits it. | +| BranchScope | `timeline`, `dispatcher`, `timelineIdentity`, `branchLifecycle` | The line's facts, their order, its identity and its phase. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `submit` | Admit one input into the line, once per submission id | `{input}` | `{inputId, sequence}`; a repeated submission id answers the committed input | The caller cancels before the append; nothing is written | `invalid` (the input fails its own shape or scope), `line_ended` (the line has ended), `cancelled`, `closed` | +| `withdraw` | Withdraw one held input, optionally replacing it with a Steer | `{inputId, reason?, steer?}` | `{status}`: `deleted{sequence}` or `notHeld` | The caller cancels the wait; a committed withdrawal stands and a later call answers `notHeld` | `input_blocked` (a submit check refused the Steer), `invalid` (a malformed Steer candidate), `publication_unknown` (committed but publication unconfirmed), `cancelled`, `closed` | +| `pending` | Whether one input is held and unapplied at a published cutoff | `{inputId, publishedCutoff?}` | `{pending}` | The caller cancels the wait for the cutoff; nothing changes | `closed`, `cancelled` | + +`submit` accepts an input whose submission id is new; the same id answers the input already committed, so a retry is safe. A Steer candidate in `withdraw` runs the registered checks in name order; the first block answers `input_blocked` and writes nothing, and the accepted candidate's blocks are appended to the operator's content before the replacement is written. `pending` answers one input's membership; the Session's page read stays on TimelineTree and does not call this operation. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `invalid` | `submit`, `withdraw` | Fix the input: a malformed candidate, a scope the line does not accept | +| `line_ended` | `submit` | The line has ended; read its facts for history or choose an open line | +| `input_blocked` | `withdraw` | The check's message says why; the withdrawal and the replacement were not written; change the input | +| `publication_unknown` | `withdraw` | The batch committed but its publication was not confirmed; query the line's facts after recovery instead of retrying the withdrawal. The wire code is the existing `publication_unknown` | +| `cancelled` | `submit`, `withdraw`, `pending` | Nothing was written by the cancelled call; a committed withdrawal stands | +| `closed` | all | The line is closing; stop writing inputs to it | + +A withdrawal of an input the queue no longer holds is `notHeld`, not an error: the caller's next step is the same, and a `notHeld` decision writes no result and no replacement. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `submit` | Admit the submission id, append the input through the line's entry, answer the committed id and sequence | Before the append: nothing is written | New submissions are refused; a committed input stays for the next generation | InputQueue: the append and its admission | +| `withdraw` | Admit the command, run the Steer's checks if any, decide against the held input, write the withdrawal command and the atomic result, answer after publication | The wait stops; a committed withdrawal and its replacement stand | An owed result is settled by the generation's recovery; a later generation answers from the facts | InputQueue: the decision and the result batch; SubmitChecks: a check's own work | +| `pending` | Read the input's membership at the published cutoff, after the queue dispatched to it | The wait stops | Pending reads end `closed`; the next generation rebuilds membership from the facts | InputQueue | + +## Exceptions with reasons + +- `withdraw` runs the operator's submit checks itself: the checks are registered on the Session, but only the queue knows whether the input is still held and only the queue can make the replacement atomic, so a Session entry composing the two would race a second withdrawal. +- A Steer candidate carries the operator's content and the checks' blocks as data: the candidate is never an adopted input and never enters model context, so it crosses with the command that decides it. + +## Supersedes + +- `docs/design/contracts/runtime-owner-operations.md`: the `inputQueue` rows and the `timelineTree.input` row that names the queue's input entry. +- `docs/design/service-faces.md` sections 3.4 and 3.5: the `inputQueue` row and the statement that `inputQueue.withdraw` only withdraws while Steer goes through the Session entry's checks. +- `docs/design/contracts/session-access.md` section 2's pending derivation, section A.4's checks-before-the-call text and the Rust binding row that names `withdraw_checked`. +- `docs/design/timeline-branches.md` section 6: the message path written through `TreeCommands.input`. + +## Verification + +- `submit` accepts one input per submission id; a repeated id answers the committed input; a new id appends in order; an ended line answers `line_ended` and writes nothing. +- `withdraw` of a held input writes `input/deleted`; a `notHeld` decision writes no result and no replacement; a Steer candidate whose check blocks writes nothing and answers `input_blocked`. +- An accepted Steer's replacement `input/message` precedes the original's `input/deleted` in one batch, and a retry after a lost reply cannot replace the deleted input again. +- `pending` answers true only for an input held and unapplied at the published cutoff; an input the queue does not hold is false. The page read of `session.input.pending` stays on TimelineTree. +- A reload rebuilds membership from the facts without reading input bodies; an owed accepted withdrawal is settled from its command. +- A call in flight when the line closes ends `closed`; a committed withdrawal keeps its result. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds input facts and writes application, deletion and replacement facts. | +| §2 scopes | Branch: the queue belongs to one line. A Session part writes an input by line id through `submit`. | +| §3 orthogonality | No other owner's state is read; the checks arrive through SubmitChecks' operation. | +| §4 rule 1 | A withdrawal is the `input/withdraw` command; the queue decides and writes the result. | +| §4 rule 2 | An applied input is handed to Loop by `input/applied`; after it only Loop's commands apply. | +| §4 rule 3 | Handlers register tasks and return; the submission checks run in the caller's call, not in a handler. | +| §4 rule 4 | No business meaning: the checks' meaning is their registrars'. | +| §4 rule 5 | The replacement and the deletion commit in one batch, replacement first. | +| §4 rule 6 | A Steer candidate is not an adopted input and never enters model context. | +| §4 rule 7 | Callers use the three operations; the checks are SubmitChecks'. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Applied and deleted results are published after their batch commits. | +| §7 values, ids and objects | Inputs, ids and the candidate are data; the result is a value; no object crosses. | +| §7 one interface | One name, `inputQueue`, on the `InputQueue` type; `withdraw_checked` and the `pending` Rust method are removed. | +| §7 cross-language | Every operation is data. | +| ADR 002 D1 | Branch: the queue is per line. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | + +## Requirements raised to mechanism owners + +- #2026 (SubmitChecks): `check` must accept `{entry, branchId, user, mode}` and answer proceed with blocks and warnings or a block, with the caller's cancellation; InputQueue calls it for an operator Steer. +- #2026 (InputMethods): `session.input.withdraw` calls `withdraw` by line id; `session.input.pending` keeps its page read on TimelineTree and does not call `pending`. The Session entry keeps the operator's content validation and the client's reply shape. +- #2025 (Session access): a Session part calls `line_owner::(line)?.submit/withdraw/pending`; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `InputQueue` type; the wire name stays `inputQueue`. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::InputMessageData; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InputRef { + pub input_id: String, + pub sequence: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WithdrawInput { + pub input_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub steer: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "status", rename_all = "camelCase")] +pub enum Withdrawal { + Deleted { sequence: u64 }, + NotHeld, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PendingRequest { + pub input_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub published_cutoff: Option, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Pending { + pub pending: bool, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case", rename_all_fields = "camelCase")] +pub enum InputQueueError { + #[error("invalid: {message}")] + Invalid { message: String }, + #[error("input blocked: {message}")] + InputBlocked { message: String }, + #[error("line ended")] + LineEnded, + #[error("publication unconfirmed")] + Interrupted, + #[error("cancelled")] + Cancelled, + #[error("closed")] + Closed, +} + +#[rutis::service] +impl InputQueue { + pub async fn submit(&self, input: InputMessageData, cancelled: CancelledFn) -> Result { /* .. */ } + pub async fn withdraw(&self, input: WithdrawInput, cancelled: CancelledFn) -> Result { /* .. */ } + pub async fn pending(&self, request: PendingRequest, cancelled: CancelledFn) -> Result { /* .. */ } +} +``` diff --git a/docs/design/plugins/Loop.md b/docs/design/plugins/Loop.md new file mode 100644 index 0000000000..bc92b9921d --- /dev/null +++ b/docs/design/plugins/Loop.md @@ -0,0 +1,202 @@ +# Loop + +Scope: branch. Issue: #2027. + +Loop owns one line's turns: when a turn starts, which request runs, how a tool batch settles, and when the turn ends. ContextPreparation owns the request's content and its compaction, ModelProvider owns one model call, and ToolExecutor owns tool execution; the current implementation is described in the [Loop plugin page](../../architecture/rust-agent/plugins/Loop.md). + +## Use and scope: responsibility split + +Loop owns: + +- **Turn and step order.** Which input opens a turn, the one request a step runs, when the request's calls settle, and the turn's single end. +- **Input adoption.** Which applied inputs drive a turn, which join the next request, and which a turn consumed. +- **The compaction boundary.** No request starts while ContextPreparation's compaction step runs; the step, its command and its outcome belong to ContextPreparation. +- **Turn and step facts.** `turn/start`, `turn/end`, `input/consumed`, `step/model-start`, `context/prepare`, `step/tool-call`, the recovery terminals, and the failure chain a continuation carries. +- **Recovery.** After a reload, unsettled requests, open turns, interrupts and undispatched calls settle without repeating an external effect. +- **The run state.** The phase and the open turn, as a value other owners and clients read. + +Callers keep as business: + +- What a turn is for, and which input the operator or a plugin sends. +- The request's messages, system prompt and tools: ContextPreparation, Prompt and ToolBinding supply them. +- Which model runs and what a failure means: ModelProvider decides the request's settlement, and Provider runs it. +- When a manual compaction is asked for: the client calls ContextPreparation. +- What a tool call does: ToolExecutor and the tool's owner. + +| Requirement (caller) | Can callers compose it from the operations below without breaking Loop's invariants? | Handling | +| --- | --- | --- | +| A collaborator stops a member line's turn only while that turn is the open one | No: the open-turn check and the interrupt commit must happen under the lock that opens and closes turns, or a stale interrupt voids the next turn's queued inputs | `stopTurn` | +| A client or UI reads the running state and follows changes | No: the phase is Loop's folded state, and a poll loop in every caller duplicates the fold | `state`, `observe` | +| A Session method answers a turn read: identity, outcome, active output | Yes: `timelineTree.read` at the line's head answers identity and outcome, and ModelProvider's `progress` answers the active request | Business composition; `session.turn.get` is migrated in the delivery | +| A client asks for a manual compaction | Not this owner: the command, the policy and the outcome are ContextPreparation's | ContextPreparation's `compact` | +| A caller learns whether a turn is running before writing an input | Yes: `state` | Business | + +An operation exists only where the row says No. + +## Caller example + +Collaboration stops the member's turn that consumed the request's input; the answer says whether an interrupt was written: + +```rust +let Some(_) = agent_loop + .stop_turn(StopTurn { turn_id: turn, reason: INTERRUPTED.into() })? +else { + return Ok(()); // the turn already ended; nothing was written +}; +``` + +A client reads the phase, then follows changes for the rest of its connection: + +```rust +let RunState { phase, turn_id } = agent_loop.state()?; +agent_loop + .observe(&ctx, Arc::new(move |state| show(&state))) + .await?; +``` + +`observe` calls the listener once with the current value, then on every change, until the calling row unloads or the owner closes. + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| RequestSettings (#2025) | `settings` | The Session's default model settings before a configuration is adopted. | +| ContextPreparation | `prepare` | Build the request at the source's cutoff from the projection and publish the handoff facts. | +| ToolBinding (#2028) | `bind`, `adopted`, `claim`, `transfer`; `release` and `retain_only` | Pin the request's tool generation, read its declarations, register the calls' claims and move the record to a retry. Settlement otherwise follows the line's facts; the Loop calls `retain_only` after its own rebuild, because ToolBinding outlives a Loop reload and only the new Loop knows the request it is on, and may call `release` when it knows a request ended sooner. | +| GuideEntries (#2026) | `compose` | The System the request carries. | +| Provider (#2019) | — | Not called by Loop; ModelProvider calls `invoke`. | +| BranchScope | `timeline`, `dispatcher`, `timelineIdentity`, `branchLifecycle` | The line's facts, their order, its identity and its phase. | + +The exact names above are the siblings' contracts; Loop calls those operations, not their old objects. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `stopTurn` | Stop one turn if it is still the open one | `{turnId, reason}` | `{sequence?}`: absent when the turn already ended or the id is not the open turn | None; the check and the commit are one lock section | `closed` | +| `state` | The phase and the open turn now | `{}` | `{phase: idle\|running\|stopping, turnId?}` | None | `closed` | +| `observe` | The current state, then every change, until the row unloads | the listener argument | `{}` | The row's unload ends the subscription; nothing is released by the caller | `closed` | + +`listener` is a callback by reference: it runs outside Loop's turn lock and outside the Timeline's commit lock. A lease id is bound to the calling row; the owner drops it at the row's unload, so a caller that loses the id leaks nothing. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `closed` | `stopTurn`, `state`, `observe` | The line is closing; stop starting work on the line; the next generation serves a reloaded line | + +`stopTurn` has no other refusal: a turn that already ended is an absent reply, not an error, because the caller's next step is the same. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `stopTurn` | Take the turn lock, check the id is the open turn and not ending, append `stop/interrupt` under the same lock, answer its sequence | No wait to cancel; a dropped call leaves the committed interrupt | An interrupt before close settles the open turn as cancelled; a turn without one is settled by the close | Loop | +| `state` | Read the folded phase and open turn | Nothing to release | `closed` | Loop | +| `observe` | Register the listener under the calling row, call it once, then on each change | The row's unload drops the listener | The generation stops calling and releases every listener | Loop; the listener's own work by the calling row | +| internal turn pipeline | A driving input opens `turn/start`; the step reads the adopted configuration or `requestSettings`, `guideEntries.compose`, binds the tool generation and reads its declarations, writes `context/prepare`, calls `contextPreparation.prepare` with the source and projection, then follows `model/call`, the model facts and `step/tool-call` to the turn's single end | A stop cancels the step's task; the turn ends cancelled after the settlements Loop owes | A reload settles open turns, in-flight requests and undispatched calls as cancelled; no external effect is repeated | Loop; the request's external effect by Provider | + +The request pipeline's own tasks and cancellation are Loop's: handlers register tasks and return, and cleanup cancels and joins them before the generation unloads. + +## Exceptions with reasons + +None. Every cross-owner call lands on an operation above or on a sibling's operation named in Dependencies. + +## Supersedes + +- `docs/design/contracts/runtime-owner-operations.md`: the `agentLoop` rows (`compact`, `stopTurn`, `state`, `observe`); the compaction row now points at ContextPreparation. +- `docs/design/service-faces.md` section 3.5: the `agentLoop` and `loopState` rows. +- [ContextCompaction](ContextCompaction.md) section 1 items 4-5, section 1.1 and section 2.1: the manual compaction command and step are ContextPreparation's, and the Loop only starts no request while a step runs. + +## Verification + +- `stopTurn` on the open turn writes one turn-scoped interrupt; on an ended turn it writes nothing; a stale id after an interrupt writes nothing. +- `state` reports `running` for an open turn, `stopping` after an interrupt, `idle` otherwise, and the open turn's id only while it is open. +- `observe` delivers the current value, then one call per change; the row's unload and the owner's close stop delivery. +- A reload settles an open turn as cancelled, an in-flight request as cancelled, and an undispatched call with an error result, without calling a model or a tool again. +- The compaction step's facts are ContextPreparation's; Loop starts no request while `context/compaction-start` has no matching `context/compaction`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds its own facts and writes its own turn facts. | +| §2 scopes | Branch: turns and steps belong to one line and end with it. The Session entry `session.turn.get` reads values and facts, not Loop's state. | +| §3 orthogonality | No other owner's state is read or changed; the request's content is the siblings' operations. | +| §4 rule 1 | A stop is the `stop/interrupt` command; the turn's end is Loop's fact. | +| §4 rule 2 | A turn's input handover is `input/applied`; after it only Loop's commands apply. | +| §4 rule 3 | Handlers register tasks; the step's host work runs in those tasks. | +| §4 rule 4 | No business meaning: what a turn is for stays with the caller. | +| §4 rule 5 | A turn end is one batch; the settlements and the end commit together. | +| §4 rule 6 | Context enters only through adopted inputs and tool results. | +| §4 rule 7 | Callers use the three operations; Loop uses the siblings' operations. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Every turn and step terminal fact is published after its batch commits. | +| §7 values, ids and objects | The state is a value; `observe` takes a callback; no object or handle crosses. | +| §7 one interface | One name, `agentLoop`, on the `Loop` type; the old `compact`/`stop_turn` methods and `dyn LoopState` trait are removed. | +| §7 cross-language | Every operation is data or a callback; no method exists only for Rust. | +| ADR 002 D1 | Branch: a turn is work bound to one line. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | + +## Requirements raised to mechanism owners + +- #2028 (ToolBinding): Loop needs `bind`, `adopted`, `claim`, `transfer`, `release` and `retain_only` as data operations. Settlement otherwise follows `step/tool-result` and `turn/end`; `retain_only` is the Loop's own rebuild step, since ToolBinding keeps its records across a Loop reload, and `release` lets the Loop settle a request it knows has ended. +- #2026 (GuideEntries): Loop needs `compose` as a data operation returning the System text for one line and a base System; the current `compose_system` takes Rust values. +- #2025 (Session access): the Session entry `session.turn.get` reaches `line_owner::(line)?.state()` and `timelineTree.read` by line id; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `Loop` type; the wire name stays `agentLoop`. + +```rust +use rutis::Ctx; +use std::sync::Arc; + +pub type RunStateListener = Arc rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LoopPhase { + Idle, + Running, + Stopping, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RunState { + pub phase: LoopPhase, + #[serde(skip_serializing_if = "Option::is_none")] + pub turn_id: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StopTurn { + pub turn_id: String, + pub reason: String, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Stopped { + #[serde(skip_serializing_if = "Option::is_none")] + pub sequence: Option, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum LoopError { + #[error("closed")] + Closed, +} + +#[rutis::service] +impl Loop { + pub fn stop_turn(&self, request: StopTurn) -> Result { /* .. */ } + pub fn state(&self) -> Result { /* .. */ } + pub async fn observe(&self, caller: &Ctx, listener: RunStateListener) -> Result<(), LoopError> { /* .. */ } +} +``` diff --git a/docs/design/plugins/ModelProvider.md b/docs/design/plugins/ModelProvider.md new file mode 100644 index 0000000000..b49b640e93 --- /dev/null +++ b/docs/design/plugins/ModelProvider.md @@ -0,0 +1,161 @@ +# ModelProvider + +Scope: branch. Issue: #2027. + +ModelProvider owns one line's model call: it consumes `model/call`, runs the request through Provider, commits the streamed output to the line's Timeline, and settles one terminal fact. Provider owns the model, the credential, retries and the transport; the current implementation is described in the [ModelProvider plugin page](../../architecture/rust-agent/plugins/ModelProvider.md). + +## Use and scope: responsibility split + +ModelProvider owns: + +- **The call's lifetime.** The one call a `model/call` fact starts, its cancellation, its drain and its generation. +- **Streamed output.** The `step/text`, `step/thinking`, `step/tool-use-start`, `step/tool-use` and `step/model-content` blocks, their ids and their commit boundaries. +- **The terminal fact.** `step/model-output-end` with the outcome, the failure chain totals and the runtime's failure kinds. +- **Durable images.** Before the call, resolving a file-backed image for the Session the request names; the request that reaches Provider carries only what the model may receive. +- **Progress.** The active request's `ModelProgress` value: the open blocks, the text and thinking seen so far, the tools and the retry, which the App Server's notice is built from field for field. + +Callers keep as business: + +- Which model runs and with which credential: Provider. +- The request's messages, system and tools: ContextPreparation. +- What a failure means for the turn: Loop decides the turn's end and its one continuation. +- How a client renders the stream: the client. +- When to stop: the operator's stop is a `stop/interrupt` fact; Loop and ModelProvider settle their own parts. + +| Requirement (caller) | Can callers compose it from the operations below without breaking ModelProvider's invariants? | Handling | +| --- | --- | --- | +| A client or a Session method reads the active output and follows changes | No: the open blocks, offsets, tools and retry are the owner's transient state; a caller folding `step/*` events duplicates the stream | `progress`, `observe` | +| Loop learns how the call ended | Yes: the terminal fact | Business composition | +| A client follows the streamed text | Yes: `step/text` facts, ordered by the Timeline | Business composition | +| A caller stops the call | Not this owner: a stop is `stop/interrupt`; Loop writes it and ModelProvider settles | Business | + +An operation exists only where the row says No. + +## Caller example + +A Session method answers the active output of an open turn: + +```rust +let progress: ModelProgress = line_owner::(line)?.progress()?; +let text_total = progress.text_offset + progress.text.chars().count() as u64; +``` + +A client subscribes to progress for the rest of its connection: + +```rust +model_provider + .observe(&ctx, Arc::new(move |progress| notice(progress))) + .await?; +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| Provider (#2019, process) | `invoke` | One model request: selection, credential, transport, retries, recovery, streaming and the consumer callback. | +| SessionFiles (#2018, process) | `read` | The bytes of a file-backed image the request references; optional in profiles without the native store. | +| ContextPreparation (branch) | `validate` | The final request's budget check after image adaptation. | +| BranchScope | `timeline`, `dispatcher`, `timelineIdentity` | The line's facts, their order and its identity. | + +`Provider::invoke` adapts image references to the model's capability; ModelProvider resolves the durable bytes before the call and never sends a reference it cannot resolve. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `progress` | The active request's output so far | `{}` | `ModelProgress`: turn, request, open part ids, text and thinking with their offsets, tools and retry | None | `closed` | +| `observe` | The current progress, then every change, until the row unloads | the listener argument | `{}` | The row's unload ends the subscription; nothing is released by the caller | `closed` | + +The reply is the existing `dim_agent_runtime::ModelProgress` value, field for field; the App Server builds its `ModelProgressNotice` from it without another source. No block, stream or request object crosses. `listener` is a callback by reference, called outside the owner's locks and outside the Timeline's commit lock. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `closed` | `progress`, `observe` | The line is closing; the next generation serves a reloaded line | + +`progress` answers an empty value when no request is active; an absent request id is not an error. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `progress`, `observe` | Read the published value, or register the listener under the calling row and call it once, then on each change | The row's unload drops the listener | The generation stops calling and releases every listener | ModelProvider; the listener's work by the calling row | +| the model call | A `model/call` fact starts the call; resolve durable images, validate the final request, call `provider.invoke` with a consumer that writes `step/*` blocks; write one `step/model-output-end` with the outcome and the chain totals | The `stop/interrupt` fact cancels the call and drains Provider's stream; the terminal fact records the reason | An unended historical call settles failed without a model call; accepted output stays committed; no external effect is repeated | ModelProvider: the call, the output blocks and the terminal fact; Provider: the request, its credential and its stream; Loop: the turn | + +The owner writes no fact before the batch that carries it commits, and a failed output closes every started call with an error result in the same batch as the terminal, so no call of a failed output reaches a tool. + +## Exceptions with reasons + +- The failure chain and its retry display are Provider's execution data but the terminal fact is ModelProvider's: the fact is the branch's durable record of the call, and Provider has no Timeline. +- A terminal fact for a reload-settled call carries no Provider failure: no provider call ran, so the owner does not invent one. +- A request that fails before the model call is reached is settled with `step/model-output-end` by ContextPreparation; ModelProvider's rule check names that single exception and writes the terminal for every request it consumes. + +## Supersedes + +None: the contract adds the owner's first public read and keeps the provider and Timeline contracts as they are. + +## Verification + +- `progress` reports the open blocks and character counts, and is empty when no request runs; `observe` delivers the current value and each change, and stops at the row's unload or the owner's close. +- A `model/call` writes the `step/*` blocks in order and exactly one terminal fact; a failed output's started calls are closed with error results in the terminal's batch. +- A stop cancels the call and drains Provider's stream; an already committed block stays committed and the terminal names the cancellation. +- A reload fails an unended call without invoking Provider again; the request's messages and tools are not reconstructed. +- An unresolvable file-backed image fails the request instead of inventing a reference or silently omitting it. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds the call's facts and writes its own output facts. | +| §2 scopes | Branch: the call and its output belong to one line. Provider is the process owner it calls. | +| §3 orthogonality | No other owner's state is read; the request and the stream come through Provider. | +| §4 rule 1 | No command event of its own; `model/call` and `stop/interrupt` are the commands it consumes. | +| §4 rule 2 | The request handover is `model/call`; after it ModelProvider owns the call. | +| §4 rule 3 | Handlers register tasks; the provider stream runs in those tasks. | +| §4 rule 4 | No business meaning: which model and which credential are Provider's. | +| §4 rule 5 | A terminal fact and its error results commit in one batch. A request that never reaches this owner is the stated exception, settled by ContextPreparation. | +| §4 rule 6 | Output enters context only as committed blocks and the terminal result. | +| §4 rule 7 | Callers use the two reads; the owner uses Provider's operation. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Every block and terminal is published after its batch commits. | +| §7 values, ids and objects | The progress is a value; `observe` takes a callback; no stream or request object crosses. | +| §7 one interface | One name, `modelProvider`, on the `ModelProvider` type; the `StateCell` publication is removed. | +| §7 cross-language | Every operation is data or a callback. | +| ADR 002 D1 | Branch: one call is bound to a line and a turn. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | + +## Requirements raised to mechanism owners + +- #2019 (Provider): `invoke` must accept the branch consumer callback, the failure chain and the image-adapted request, as the Provider contract states; ModelProvider adds nothing to that request beyond durable image bytes. +- #2018 (SessionFiles): `read` must answer one file-backed image's bytes for the Session named in the request metadata, within the owner's limit. +- #2025 (Session access): `session.turn.get` reads `line_owner::(line)?.progress()`; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `ModelProvider` type; the wire name is `modelProvider`. + +```rust +use rutis::Ctx; +use std::sync::Arc; + +pub type ProgressListener = Arc rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; + +pub use dim_agent_runtime::ModelProgress; +pub type Progress = ModelProgress; + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ProgressError { + #[error("closed")] + Closed, +} + +#[rutis::service] +impl ModelProvider { + pub fn progress(&self) -> Result { /* .. */ } + pub async fn observe(&self, caller: &Ctx, listener: ProgressListener) -> Result<(), ProgressError> { /* .. */ } +} +``` diff --git a/docs/design/plugins/Prompt.md b/docs/design/plugins/Prompt.md index d5583edb8a..f026da7e4b 100644 --- a/docs/design/plugins/Prompt.md +++ b/docs/design/plugins/Prompt.md @@ -1,267 +1,44 @@ # Prompt -Status: Draft ([#548](https://github.com/arcships/dim/issues/548)). Requirements: [model-facing prompts §6 and §9.1](../model-prompts.md#6-the-input-guide). Rules: [design rules](../../architecture/rust-agent/principles.md) §1, §4 and §5, [ADR 002](../../adr/002-plugin-scope.md). Scope: branch, plus the entries table its Session holds. Language: Rust. The current capability is on [Prompt](../../architecture/rust-agent/plugins/Prompt.md)'s capability page. +This document is superseded. The owner is split between two contracts: -Prompt owns the input guide: the text every request carries about the model's own input. It owns the guide's frame, composes the frame and the entries in force into one text, and carries the entries each capability contributes. It owns none of the entries' words: the capability that writes a marker contributes the entry that explains it. The frame states the channels and their trust classes, the channel rule, escaping and the restatement after a summary, so the model can tell the operator's words from the runtime's, and both from material. +- The input guide — the frame, the entries in force and their composition — is [PromptGuide](https://github.com/arcships/dim/pull/2103) (#2026). +- The branch part that adopts a line's configuration and publishes the System is [Prompt adoption](PromptAdoption.md) (#2027). -## 1. Scope and non-goals - -Prompt owns: - -- **the frame** — the channels, the trust classes, the channel rule and the restatement after a summary ([model-facing prompts §6.2](../model-prompts.md#62-who-owns-which-part)); no scope removes or replaces it; -- **the entries table**, in the Session, and the route by which a loaded capability registers an entry (§2); -- **the composition** — the frame and the entries in force in one deterministic order (§3); -- **the channel rule's `[input ]` exception**, worded as a runtime guarantee and therefore protocol (§3.1). - -Not Prompt's: - -- an entry's words belong to the capability that writes the marker (§6); -- the request shape belongs to Loop, the adopted configuration to ContextPreparation, the summary path to ContextPolicy; -- the state and rule sources and the words the model reads in them belong to their source owners; the shared markers' guide entries belong to `PromptGuide` (§4). - -Not this design: each capability's list of model-facing texts with its protocol and policy marks, and the flow assertion in that writer's own flow ([#551](../model-prompts.md#92-every-capability-that-writes-model-facing-text), [#552](../model-prompts.md#94-timelinetree), [#553](../model-prompts.md#95-goal), [#554](../model-prompts.md#96-contextcompaction)); removing Prompt's two call sites ([#555](../model-prompts.md#97-loop-and-contextpreparation)). +The old sections remain only as pointers, so code comments and documents that link here keep their anchors. ## 2. The entry route -The route is a contract in the form [ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral) gives: identity, request and reply as data, errors, cancellation and unload. Rust is one binding of it ([§8](#8-binding-appendix)); a plugin contributed through the plugin bridge registers through the same contract (§6.1). - -**Identity.** A registration belongs to two things: the loaded part that makes it, and the markers its entry explains. The contributor is taken from the call — its `ctx` in Rust, the calling row through the bridge — and never from the payload, so no caller can register in another's name. The entry is in force exactly while that part is loaded ([rutis usage R6](../rutis-usage.md#r6-contributions-register-with-their-owner)). - -**Scope.** The table is the Session's, because contributors live at both Session and branch scope and the Session is their nearest common owner, the same reason its prompt sources are the Session's. Each registration states where its entry applies: `session` for every branch of the Session, or one branch id for that branch alone. A branch-scoped entry is in force exactly while that branch's part is loaded, so closing one line withdraws its entries and leaves the other lines' composition untouched. - -**Uniqueness is per composition.** For any one branch, a marker has at most one entry in force. A session-scoped entry therefore collides with every entry for the same marker; two branch-scoped entries for one marker collide only when they name the same branch. A registration is keyed by its scope and its first marker, so two branches each register their own copy of a branch-scoped entry without meeting. - -**Request.** One registration: the scope and one entry. - -| Field | Type | Meaning | -| --- | --- | --- | -| `scope` | `"session"` or `{ "branch": }` | Where the entry applies | -| `entry.markers` | list of strings, at least one | The marker element names this entry explains, e.g. `["dim-branch-line", "dim-branch-lines"]` | -| `entry.order` | integer | The entry's position among the entries ([§3.2](#32-the-order)) | -| `entry.text` | string | The entry, verbatim, as the model reads it | - -**Reply.** `null` when the entry is registered. The reply carries no identity of its own: the caller already knows what it registered, and the registry keeps no second key for it. - -**An entry from a writer that is not loaded cannot be made.** The registration is made by the loaded part itself, tied to its own generation, so there is no path by which a registration outlives its writer or arrives from one that never loaded. The one case in which the writer's identity is not available is a call from another language whose calling row cannot be resolved; that call fails with `no_caller_row` rather than registering in no one's name. - -**Errors** are data, `{code, message}`: - -| Code | When | -| --- | --- | -| `duplicate_marker` | Registering this entry would leave a branch with two entries for one marker: a marker it names already has an entry whose scope meets this one — a session-scoped entry for any branch, or a branch-scoped entry for the same branch. Changing an entry's text is a change to its writer's code, which registers again when it next loads | -| `invalid_entry` | No marker; a marker outside `[a-z][a-z0-9_-]{0,63}`; or an empty branch id | -| `too_large` | The entry's text is longer than 4096 bytes | -| `no_caller_row` | A call from another language whose calling row cannot be resolved, so the registration could not be tied to its contributor | -| `closed` | The part that holds the table is unloading, or the Session is closing; nothing is registered | - -**Cancellation and unload.** A registration is one atomic step under the table's lock: it has either taken effect or returned an error, and it is never half-written. It ends with its contributor's unload; each cleanup removes exactly the registration its generation made, so a reload replaces an entry instead of doubling it. A registration is not a call that can hang, so there is no separate cancellation signal. Withdrawal is invisible to a composition already made: a request being built sees the table before or after a withdrawal, never a mix. - -**Determinism.** The contract fixes neither load order nor registration order as an input: the entries in force are ordered by the entry's own `order` and then by its first marker's name (§3.2), so the same set composes the same text whatever order it registered in. - -## 3. The composition - -Prompt composes one text: the frame's head, the entries in force for the branch, and the frame's tail, in that order, paragraphs separated by one blank line and the text ending without a trailing blank line. The frame is Prompt's own text; the entries are the table's view for that branch. +The entry route is PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103) and [model-prompts §6](../model-prompts.md#6-the-input-guide). ### 3.1 The frame -The frame's head states what the guide is, that a tag never grants permission, and the channel rule. Its tail states that tool results are material, how content from outside the runtime is escaped, and that the state and rules after a summary restate what is still in force. - -The channel rule is protocol: it states a runtime guarantee. It reads, in force: - -> The operator is the person running this session. The operator's words always arrive in their own user messages. Everything the runtime adds arrives in separate user messages, wrapped in the tags below. The one exception is an input a compaction shortened: it ends with an [input ], and the recall tool opens that id for the input's full text. - -The exception is the handle a compaction appends to an input it shortened ([model-facing prompts §6.1](../model-prompts.md#61-what-it-covers)). A sentence saying that everything arrives in separate messages is false about that input, and a text that is false about the runtime is protocol and changes here, in the same change as the flow test that asserts it. - -### 3.2 The order - -Entries are ordered by their `order`, and entries with the same `order` by their first marker's name; both are data the contributor states, so the order never depends on which part loaded or registered first. The built-in entries use `10` to `130` in steps of ten (§4), leaving the numbers between them for a contribution that must sit inside a group. - -The entries at `10` to `90` compose, apart from the channel rule's exception, byte for byte the text the guide held while it was one file. Their order — exec, the two agent markers, the two branch entries, state, rule, summary, digest — is reproduced by the numbers in §4; no wording and no position changes, so this change carries no policy evaluation ([model-facing prompts §8](../model-prompts.md#8-judging-a-change)). The entries at `100` to `120` are new texts, for markers the one-file guide never explained. +The frame is PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103). ### 3.3 One composition, two paths -| Path | Who composes | When | What carries it | -| --- | --- | --- | --- | -| Adopted configuration | Prompt, through the configuration it publishes | At the adoption | `context/configured.system` of the branch | -| Host-prepared request | Loop, for the request it assembles | Per request | The request's own `system` field | - -Both call the same composition, so a host-prepared request carries the same frame and the same entries as the System an adopted configuration carries. The adopted path stores the composed text with the configuration it publishes; the host-prepared path composes when it builds the request, because that path has no adopted configuration to read ([model-facing prompts §6.2](../model-prompts.md#62-who-owns-which-part)). - -Prompt's own two call sites stay where they are: ContextPreparation places the System it publishes, and Loop places the System of the request it assembles. What changes is where the guide text comes from — the composition instead of a fixed file — not who places it. Removing the two placements is [#555](../model-prompts.md#97-loop-and-contextpreparation)'s. +The composition and its two paths are PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103). ### 3.4 Adopted when its writer loads -A guide entry takes effect when its writer loads and ends when its writer unloads. Prompt adopts the guide there: every open branch whose composition moved publishes one `context/configured` with its settings — the model, the tools and the source text — unchanged, and with the System composed over the entries in force; a branch whose composition did not move neither publishes nor reads its context for that change. Between those points the guide does not change, because an entry reaches the table only from its writer's `apply` and leaves with that writer's generation. - -A branch also adopts the guide once at its open: a fork inherits its parent's configuration and a restored branch carries the System it persisted, while the entries in force are the ones its writers registered at load. That adoption is part of the open: the branch reports itself open only after the adoption published, so the first request after an open carries the reconciled entries and none assembles from the inherited or the persisted System. It uses the adopted state owned by Prompt ([state reads](../prompt-state-read.md)) and publishes nothing when the composition already equals the adopted System. - -A closing branch adopts nothing: its writers withdraw because it is shutting down, and a configuration recorded then would carry a System the branch never ran with. - -The host-prepared path changes the guide at the same points without publishing anything, because it composes the guide into the request it assembles. A branch started after a load composes the entries in force at its open, and a request built from an adopted configuration carries the System that branch adopted. - -No request assembles a guide of its own, and no contributor appends text to a request. That is what keeps the guide from forking a cached prefix in the middle of a Session: the guide is part of the prefix, and it moves only when the prefix legitimately moves. +The adoption of a guide entry when its writer loads is PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103). ## 4. The built-in entries and their writers -Each built-in entry moves verbatim to the capability that writes its markers, and is registered from that part's `apply`. The registrar is the part whose lifetime the marker's presence follows. - -| Order | Markers | Registrar | Scope | Entry | -| --- | --- | --- | --- | --- | -| 10 | `dim-notification` | BackgroundExec | branch | The exec notification | -| 20 | `dim-agent-report` | Collaboration's Session part | session | The report of delegated work | -| 30 | `dim-agent-message` | Collaboration's Session part | session | A message from another agent | -| 40 | `dim-branch-line` | TimelineTree | session | Which line of the Session this is | -| 40 | `dim-branch-lines` | BranchLine | branch | The roster on `main`; the tie on `order` leaves the identity's entry first | -| 50 | `dim-branch-message`, `dim-branch-idle`, `dim-branch-ended` | BranchLine | branch | A message from another line, and the runtime's reports about a line | -| 60 | `dim-state` | PromptGuide | session | What a state block is | -| 70 | `dim-rule` | PromptGuide | session | What a rule block is, and how it ends | -| 80 | `dim-summary` | ContextCompaction's summary strategy part | session | What a summary is | -| 90 | `dim-digest` | ContextCompaction's context-preparation part | branch | What a digest is | -| 100 | `dim-shell-input` | ShellInput | session | The operator's own shell command and its output | -| 110 | `dim-scheduler` | Scheduler's Session part | session | The delivered prompt of a scheduled job, and a wakeup's prompt | -| 120 | `dim-workflow` | Workflow's Session part | session | The run's report and its stage markers | -| 130 | `dim-event`, `dim-event-guide` | EventHub's Session part | session | The delivered event, and the guide of the source that delivered it | - -For a plugin-specific marker, the registrar is the part that writes it, not the part that authors a source's words. `PromptGuide` owns the shared `dim-rule` and `dim-state` entries: Prompt writes those markers for its registered sources, and runtime parts may also append unkeyed `dim-state` snapshots through the input path. Profiles exposing either form include `PromptGuide`; snapshot writers reuse its entry and do not register competing entries. The state entry explains the latest observed value for a source, not a request or permission. It does not promise retention: the input key governs compaction replay ([model-facing prompts §3](../model-prompts.md#3-channels)). - -A compaction's replacement belongs to the policy every strategy is called through, not to a strategy: the policy composes the digest after any strategy returns ([ContextCompaction §5.10](ContextCompaction.md#510-class-3a-the-digest)). The entry therefore registers with the part that binds the policy, and only while a strategy is bound — a Session with no strategy compacts nothing and writes no digest. A Session with a strategy other than the product one still sends ``, and its guide explains it. - -A capability that writes a marker and registers no entry is a capability the guide does not explain; a capability that registers an entry for a marker nothing writes leaves a promise the runtime does not keep. Both are the writer's to fix, and [#551](../model-prompts.md#92-every-capability-that-writes-model-facing-text) makes each writer assert the pair in its own flow. +The built-in entries and their writers are PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103). ## 5. Facts that reproduce it -The entries in force are reproducible after a restart or a reload, as the other prompt sources are. - -| Fact | Where | What it reproduces | -| --- | --- | --- | -| The assembly | The loaded parts of the Session and its branches | Which capabilities are loaded, and so which entries each `apply` registers again | -| The adopted System | `context/configured.system` on the branch | The guide exactly as the branch adopted it, replayable without recomposing | - -The entries' text is code: each registrar states it in the commit that changes the marker. A restart reloads the same assembly, so the same entries register, and the branch's adopted System replays from the Timeline; a later adoption composes from the same registrations and produces the same text, because the order is the entries' own data. What a reload changes is a writer's availability, not the recorded text of an adoption already made. - -The state and rules a branch adopted are not facts about the guide: they are prompt entries, recorded by `prompt/changed` like any other source. The guide names them; it does not carry their content. - -## 6. Cross-module requirements +The facts that reproduce the entries are PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103). ### 6.1 The plugin bridge -A plugin contributed through the plugin bridge registers an entry the same way a Rust part does: from its `apply`, for as long as its row is loaded, through a call whose arguments and reply are serde data. The route reaches other languages in three parts: - -1. **The name, shared in the Session group.** A Rust registry of this shape reaches other languages only when its name is shared where it is provided; the host that runs foreign parts lists those names (`share_names` in the App Server), and `guideEntries` is shared there beside `toolRegistry`. -2. **A dispatch that ties the registration to the caller.** The Rust `register` takes its `ctx` from the caller; a foreign caller has no `ctx`, so the name is served through a `rutis_bridge` `HostDispatch` that reads `rutis_bridge::session::caller_row()` and registers under that row — the form `toolRegistry` uses. Without a caller row the call fails with `no_caller_row` rather than registering in no one's name. -3. **The TypeScript declaration.** The interface joins `npm/plugin.d.ts` beside `ToolRegistry`'s, naming the request, the reply and the error codes above: `register(scope, entry)` where `scope` is `"session"` or `{"branch": ""}` and `entry` is `{markers, order, text}`; the call resolves with no value; a refusal throws a `GuideEntryError` whose `code` is one of §2's codes, `closed` included, and `no_caller_row` for a call made outside a row. - -The capability itself — the table, the composition and the two placements — works in Rust alone, so the entries' route is complete for every built-in writer without the bridge, and the bridge makes it complete for the writers that live in another language. +Cross-language registration is PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103) and the [TypeScript authoring guide](../../typescript-plugin-authoring.md). ### 6.2 The writers -Each capability in §4 adds one dependency, its Session's `guideEntries`, and registers its entries from `apply` — Prompt's own `PromptGuide` part included. None of them needs a new service, event or configuration: the registration is a call to the owner, the way a tool registers with `toolRegistry` and a prompt source with `promptRegistry`. +The writers and their entries are PromptGuide's; see [PromptGuide](https://github.com/arcships/dim/pull/2103). ### 6.3 ContextPreparation: the entries and the published System -The target in §3.4 needs one change in [ContextPreparation](../../architecture/rust-agent/plugins/ContextPreparation.md)'s publisher ([#555](../model-prompts.md#97-loop-and-contextpreparation)) and one in Prompt. The publisher composes the guide at every adoption that publishes a System: a prompt change that renders the System composes the new source text with the entries in force, and a tools-only, model-only or guide adoption re-renders the guide over the source text the branch adopted. - -- The published configuration records that source text apart from the guide it carried (`context/configured.system_source`), so the source stays what the branch adopted even as the guide is composed again. -- A tools-only or model-only adoption, and a guide adoption, compose the guide as it reads now over the recorded source text: a writer that loads has its entry in force at the load itself, whether or not that load also adopts its tools, and one whose composition already reads so publishes nothing. -- A configuration written before the source was recorded has none to re-render from: it keeps its adopted System, guide included, and only a later adoption that renders the System replaces it. `restoring_a_session_keeps_its_adopted_system_and_model` (`tests/integration/tests/prompt_lifecycle.rs`) restores such a System from `context/configured`; recomposing it from the snapshot's prompt sources alone would put the guide where the adopted System stands. -- The request reads the adopted System as it is: Loop carries `context/configured.system` into a request built from it, and a host-prepared request carries the composition Prompt composes. Neither appends text of its own. - -The trigger is Prompt's. Its branch part declares a read of the table and subscribes to a `changes()` the table forwards from its registrations, so the watch stays with the registry the entries live in rather than crossing into ContextPreparation. The listener takes its version and the composition it starts from before the branch's own open adoption composes, and starts before that adoption runs: a registration made while the open runs therefore moves the composition the listener compares against and is adopted, instead of entering a baseline taken afterwards and marked as seen, and a change made while that adoption runs is adopted by an adoption queued behind the open's arm. Each change after it composes the branch's guide again in memory, which reads neither the Timeline nor the store, and enqueues one guide adoption on the same serial queue a model change and a tool adoption use only when that text moved. The open runs one more adoption itself, before it reports itself open, because the baseline is a composition and not the System the branch carries: it uses the same adopted state and publishes nothing when the two already agree. Running it on the open's path rather than as a later queue item is what makes a fork's and a restore's first request carry the entries in force. Nothing is recorded on a closing branch: the listener ends when the branch starts closing, and an adoption that already started reading refuses its append under the commit lock, so the item is dropped with the others rather than persisted as a System the branch never ran with. - -A writer's tools can reach a request one step before its guide. The tools arrive through the tool adoption as soon as their source loads, while the entry arrives through the listener and this queue, so a step in that window carries the new tools with the previous System and the next step replaces it: the prefix moves twice where §6.2 describes one move. The design accepts that step. Making Loop wait for a pending guide adoption would couple it to Prompt's queue for one step's prefix, and the guide still changes only at an adoption, never inside the request. - -## 7. Rule check - -| Rule | How this design complies | -| --- | --- | -| §1 Plugins and capabilities bounded | The frame is Prompt's; each entry is its writer's. The table is a carrier: Prompt holds the entries and owns none of their words | -| §3 Orthogonality | The route is one more contribution owner, of the shape already used by `toolRegistry`, `promptRegistry` and `sessionMethods`. It carries no marker's business meaning, and any capability uses it from Rust, and later from the bridge | -| §4 rule 1 Apply registers, cleanup releases | A contributor registers from `apply`; the registration ends with that part's generation | -| §4 rule 2 Facts and services | No new event and no new fact: the composition is carried by the adopted configuration and by the request, both existing | -| §4 rule 4 No business meaning in core | Timeline and Dispatcher gain nothing; the table is a capability's own state | -| §4 rule 6 Context from consumed events | The guide still reaches the model through the adopted configuration or the host-prepared request; this design adds no context path | -| §4 rule 7 Public events and services | `guideEntries` is a contribution owner in the Session, like `promptRegistry`; it is not a port, a checkpoint or an adapter | -| §4 rule 8 Infrastructure unchanged | None is changed. §6.1 raises what the bridge needs; it is not built here | -| §5 Ownership | Each text stays with its author, and each requirement sits inside one owner | -| ADR 002 D1 Scope | The frame is Prompt's; entries live where their writers live, and the table sits at the Session, the contributors' nearest common owner | -| D2 No wiring modules | None is added; the composition is Prompt's own code | -| D3 Scope dependencies | The table is Session-scoped and its contributors are Session and branch parts, which may depend on it; nothing depends on a narrower scope | -| D4 Configuration | None is added | -| D5 Language-neutral contracts | The route is stated as identity, data, errors, cancellation and unload, with Rust as one binding; §6.1 names what the bridge needs to be the second | -| ADR 008 D2 No delivery status | The document states the design only | -| ADR 008 D3 Own scope only | Each writer's own texts and their classes stay on that writer's page | - -## 8. Binding appendix - -Rust is one binding of §2 and §3. Names and semantics are above; this section is the spelling. - -```rust -/// One entry of the input guide: the markers it explains and its text. -pub struct GuideEntry { - /// The marker element names this entry explains, e.g. `dim-branch-line`. - pub markers: Vec, - /// Position among the entries; ties break by the first marker's name. - pub order: i32, - /// The entry, verbatim, as the model reads it. - pub text: String, -} - -/// Where a registration applies. -pub enum GuideScope { - /// Every branch of the Session. - Session, - /// One branch, by its timeline id. - Branch(String), -} - -/// The Session's guide entries, and the composition over them. Provided in -/// the Session by the Prompt plugin's `PromptGuide` part. -pub struct GuideEntries { /* registrations, keyed by (scope, first marker) */ } - -impl GuideEntries { - /// Registers `entry` for `scope` on behalf of the part that owns `ctx`, - /// until that part unloads. Fails when the registration would leave a - /// branch with two entries for one marker. - pub fn register(&self, ctx: &Ctx, scope: GuideScope, entry: GuideEntry) -> Result<(), Error>; - - /// The guide for `branch`: the frame, the entries in force, and the - /// frame's tail, paragraphs joined by one blank line. - pub fn compose(&self, branch: &str) -> String; - - /// The System for `branch`: `base` text followed by the guide. A missing - /// or empty base is the guide alone, and a `Parts` base gains the guide - /// as one more text part. - pub fn compose_system(&self, branch: &str, base: Option) -> SystemPrompt; -} -``` - -A refusal is a small error type, the source of the `PluginFailed` that `rutis::Error` carries, so a bridge reads its code from the downcast and never from the message: - -```rust -/// The codes the table decides (§2). -pub enum GuideEntryErrorCode { - /// `invalid_entry` - InvalidEntry, - /// `duplicate_marker` - DuplicateMarker, - /// `too_large` - TooLarge, -} - -impl GuideEntryErrorCode { - /// The code as §2 spells it. - pub fn as_str(self) -> &'static str; -} - -/// A refused registration: its §2 code and the message for the log. -pub struct GuideEntryError { - pub code: GuideEntryErrorCode, - pub message: String, -} -``` - -`invalid_entry`, `duplicate_marker` and `too_large` are the codes this binding produces. `no_caller_row` is produced only by the bridge: a Rust caller always has its `ctx`, and the registration is that caller's own effect. `closed` comes from the framework: when the caller's context is closing or unloading, the effect cannot be registered and the framework returns its own closed error, which a bridge maps to `closed`; the Rust binding returns it unchanged rather than dressing it as a `GuideEntryError`. - -Prompt composes through `GuideEntries::compose_system`, at the adoption it publishes and, for a host-prepared request, where Loop assembles its System: the composition is the `SystemPrompt` the request carries, placed over the source text the branch adopted. No caller appends text of its own. - -The foreign form of `register` is §2's data: the scope, the entry, and the error codes; `compose` is Rust-only, since no other language reads a composition — every language reaches the model through the same request. +Publishing the System is Prompt adoption's; see [Prompt adoption](PromptAdoption.md). diff --git a/docs/design/plugins/PromptAdoption.md b/docs/design/plugins/PromptAdoption.md new file mode 100644 index 0000000000..3915bff2d4 --- /dev/null +++ b/docs/design/plugins/PromptAdoption.md @@ -0,0 +1,240 @@ +# Prompt adoption + +Scope: branch. Issue: #2027. + +Prompt owns the configuration a line runs with: the prompt entries in force, the adopted model and tool set, and the System the line's requests carry. The input guide's frame, order and built-in entries are PromptGuide's design in [Prompt](Prompt.md); this document is the branch part's target contract. The current implementation is described in the [Prompt plugin page](../../architecture/rust-agent/plugins/Prompt.md). + +## Use and scope: responsibility split + +Prompt owns: + +- **The adopted configuration.** The entries in force per source and scope, the adopted model settings and tool set, the revisions and the System text, held under the branch's one projection. +- **The publication.** One atomic batch: the prompt changes, the delivery inputs and `context/configured` with the System composed over the entries in force. No other owner writes those facts. +- **Adoption order.** A tracked worker serializes loads and adoptions; an open or resume adopts the sources' current content before the line takes input; a superseded pending adoption answers without writing. +- **The tool part.** The adopted configuration's tool declarations and tool-source versions, merged from ToolBinding's current set. +- **The guide adoption.** When a guide entry loads or unloads, every open line whose composition moved publishes one configuration with its settings unchanged. +- **Recovery.** The latest effective references and revisions, then at most one committed adoption after them; no history replay for a missing legacy reference. + +Callers keep as business: + +- Which sources a client, a profile or a plugin loads, and their text: PromptHost and the contributing owners. +- The model a request runs: Provider and the Session's model methods. +- Which tools exist: ToolRegistry and ToolBinding. +- The System's frame and entries: PromptGuide and each entry's writer. +- What a publication failure means for a request: Loop ends the turn. + +| Requirement (caller) | Can callers compose it from the operations below without breaking Prompt's invariants? | Handling | +| --- | --- | --- | +| A Session language or Agent configuration call adopts sources and a model on one line | No: the entries, the System and the configuration commit in one batch, and only the owner holds the adopted projection across the decision | `configure` | +| PromptSources' branch part adopts changed source values after polling | Yes: the same `configure` with the loaded values | Business composition | +| ToolBinding adopts the registry's current tool set | Yes: the same `configure` with the tool set as data | Business composition | +| Skills adopts its list entry when the skill list changes | Yes: the same `configure` with source values | Business composition | +| A Session method, Report or a client reads the adopted configuration | No: the adopted settings and their revision are the owner's projection | `adoptedConfiguration` | +| PromptSources' branch part compares its checked sources with what was adopted | No: the effective entries per target are the owner's projection; reading a whole snapshot duplicates it | `adoptedEntries` | +| A caller waits until a publication is visible | Yes: the operation answers after the batch publishes; a publication that cannot be confirmed is an error kind | Business with the operation's reply | + +An operation exists only where the row says No. + +## Caller example + +The Session language update adopts the language source at the version the language owner returned, on the conversation line and on every loaded line: + +```rust +let outcome = line_owner::(line)? + .configure(ConfigureRequest::LanguageUpdate { version }, cancel.clone()) + .await?; +// Unchanged | Adopted { sequence } | Superseded +``` + +ToolBinding adopts the registry's current set on its own line: + +```rust +prompt + .configure(ConfigureRequest::Tools(tool_set), cancel.clone()) + .await?; +``` + +A Session method reads the adopted configuration: + +```rust +let Adopted { settings, through } = line_owner::(line)?.adoptedConfiguration()?; +``` + +The source poller compares only what it checked: + +```rust +let AdoptedEntries { entries } = prompt + .adopted_entries(AdoptedEntriesRequest { targets: checked.clone() })?; +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| PromptSources (#2026, Session) | `initial`, `load` | The Session's initial targets and model, and one source's current entry for a target. | +| PromptGuide (#2026, Session) | `compose`, `observe` | The System over the entries in force, and the subscription that reports the composition moved. | +| BranchScope | `timeline`, `dispatcher`, `timelineIdentity`, `branchLifecycle` | The line's facts, their order, its identity and its phase. | +| SessionScope (#2025, Session) | `reportFault` | A prompt or recovery failure that stops the line's own work. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `configure` | Adopt source values, a model and a tool set as one configuration | `{initial | loaded | languageUpdate | tools}` | `{outcome}`: `unchanged`, `adopted{sequence}` or `superseded` | The caller cancels before the batch commits; a committed adoption is not revoked, and a pending one that a newer adoption overtakes answers `superseded` | `invalid_scope` (an entry outside the line's ancestry, or a System entry not branch-scoped), `invalid_model` (a model without the snapshot the tools need), `source_failed` (a named source could not be loaded), `publication_unknown` (committed but publication unconfirmed), `cancelled`, `closed` | +| `adoptedConfiguration` | The adopted settings and the cutoff they were committed at | `{}` | `{settings?, through}` | None | `closed` | +| `adoptedEntries` | The effective entries for the named targets | `{targets?}` | `{entries}` | None | `closed` | + +`ConfigureRequest::Initial` carries the Session's initial targets and model; the owner loads each target through PromptSources and adopts the result. `Loaded` carries the entries the caller loaded; `LanguageUpdate` adopts the Session language entry at the given version. A tool-only adoption without a model configuration is `invalid_model`: the tool part is written into the configuration the line already adopted. `adoptedEntries` with no targets answers every effective entry; a target with no entry is absent; the caller compares an entry's `version` with the one it loaded. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `invalid_scope` | `configure` | Fix the request: a scope outside the line's ancestry, or a System entry that is not branch-scoped | +| `invalid_model` | `configure` | Adopt a model first, then the tool set | +| `source_failed` | `configure` (`Initial`) | A named initial source could not be loaded; fix or retry the source, then adopt again | +| `publication_unknown` | `configure` | The batch committed but publication was not confirmed; query the line's facts after recovery instead of retrying blindly | +| `cancelled` | `configure` | Nothing was committed by the cancelled call; a committed adoption is never revoked | +| `closed` | all | The line is closing; the next generation serves a reloaded line | + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `configure` | Admit the request into the serial adoption queue, load the sources, compute the changes, compose the System over the entries in force, commit the prompt changes, the delivery inputs and `context/configured` in one batch, then answer after publication | Before the commit: nothing is written. After the commit: the adoption stands | New adoptions are refused; the queue drains or ends cancelled; the adopted projection is republished from the committed facts | Prompt: the queue, the batch and the publication; the source work by the calling row | +| open or resume adoption | Adopt the sources' current content before the line reports open, then queue the existing receipt | A cancelled open abandons the adoption and settles the waiters | The line closes without the adoption; a restored line re-reads its committed configuration | Prompt | +| guide adoption | A composition change publishes one configuration with the settings unchanged, on every open line whose composition moved | The caller's cancellation stops its own wait | A closing line publishes nothing; the listener ends with the line | Prompt | +| `adoptedConfiguration`, `adoptedEntries` | Read the projection or the effective entries | Nothing to release | `closed` | Prompt | + +No request rebuilds the System from history: the System a line runs with is the one its last adoption published, and the entries reach the model only through that System or the request Loop assembles. + +## Exceptions with reasons + +- A guide adoption records the settings unchanged: a marker's writer loading must not make the line adopt a new model or tool set, so the adoption carries the adopted settings forward. +- A closing line publishes no guide change: its writers withdraw because it is shutting down, and a configuration recorded then would carry a System the line never ran with. +- The publication answer can be `publication_unknown`: the batch committed and publication confirmation is a separate read, and pretending either outcome would be wrong. + +## Supersedes + +- `docs/design/contracts/runtime-owner-operations.md`: the `prompt` rows (`configure`, `adoptedConfiguration`) and the `contextPreparation.publish` row. +- `docs/design/service-faces.md` section 3.5: the `prompt` and `configureControl` rows. +- The former one-file guide and publisher design in [Prompt](Prompt.md); the guide is PromptGuide's (#2103) and the adoption is this contract's. + +## Verification + +- `configure` commits the entries, the delivery inputs and `context/configured` in one batch; a second adoption that wins first makes the first answer `superseded` without writing. +- A model- or tool-only adoption re-renders the guide over the recorded source text; a prompt change that renders the System composes the new source text. +- A guide entry that loads or unloads publishes one configuration with the settings unchanged only on lines whose composition moved; a closing line publishes none. +- An open adopts the sources' current content before it reports open; the first request carries the composed System. +- `adoptedConfiguration` answers the last committed configuration; `adoptedEntries` answers only the requested targets. +- A publication that cannot be confirmed answers `publication_unknown`; the facts show the committed batch. +- A reload republishes the adopted projection from the committed facts without replaying history. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds prompt facts and writes the configuration facts. | +| §2 scopes | Branch: the adopted configuration belongs to one line; the guide table is the Session's, read through PromptGuide. | +| §3 orthogonality | No other owner's state is read; the sources and the guide arrive through their owners' operations. | +| §4 rule 1 | Configure requests are commands; the owner writes the result. | +| §4 rule 2 | The adoption's handover is the committed `context/configured`; after it the line runs with that configuration. | +| §4 rule 3 | Handlers schedule the adoption worker and return; loads run in that worker. | +| §4 rule 4 | No business meaning: what an entry says stays with its writer. | +| §4 rule 5 | The prompt change, the delivery inputs and the configuration commit in one batch. | +| §4 rule 6 | Entries reach the model only through the adopted System or the request Loop assembles. | +| §4 rule 7 | Callers use the three operations; the source loaders and the guide are other owners. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | The configuration and the prompt change are published after their batch commits. | +| §7 values, ids and objects | Source values, the model and the tool set are data; the configuration is a value; no object or callback crosses. | +| §7 one interface | One name, `prompt`, on the `Prompt` type; `configureControl`, the crate-private `adopt_tools` and the `ConfigurationPublisher` are removed. | +| §7 cross-language | Every operation is data. | +| ADR 002 D1 | Branch: the configuration is per line. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | + +## Requirements raised to mechanism owners + +- #2026 (PromptGuide): `compose` must answer the System for one line and a base System as data, and `observe` must deliver a callback the branch part can register; the current `compose_system` takes Rust values and the watch is Rust-only. +- #2026 (PromptSources): `initial` and `load` as the target contract states; `configure`'s `Initial` loads through them, and the branch part loads for its periodic checks. +- #2025 (Session access): the Session language and Agent configuration entries reach `line_owner::(line)?.configure(..)` and `line_owner::(line)?.adoptedConfiguration()` by line id; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `Prompt` type; the wire name stays `prompt`. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PromptSourceTarget; +use dim_agent_types::{ModelConfiguration, PromptEntry}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", content = "data", rename_all = "camelCase")] +pub enum ConfigureRequest { + Initial(dim_agent_runtime::ConfigureUpdate), + Loaded { sources: Vec }, + LanguageUpdate { version: u64 }, + Tools(ToolSetAdoption), +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ToolSetAdoption { + pub tools: Vec, + pub tool_sources: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "outcome", rename_all = "camelCase")] +pub enum ConfigureOutcome { + Unchanged, + Adopted { sequence: u64 }, + Superseded, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Adopted { + #[serde(skip_serializing_if = "Option::is_none")] + pub settings: Option, + pub through: u64, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AdoptedEntriesRequest { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub targets: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdoptedEntries { + pub entries: Vec<(PromptSourceTarget, PromptEntry)>, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case", rename_all_fields = "camelCase")] +pub enum PromptError { + #[error("invalid scope: {message}")] + InvalidScope { message: String }, + #[error("invalid model: {message}")] + InvalidModel { message: String }, + #[error("source {name} failed: {message}")] + SourceFailed { name: String, message: String }, + #[error("publication unknown")] + PublicationUnknown, + #[error("cancelled")] + Cancelled, + #[error("closed")] + Closed, +} + +#[rutis::service] +impl Prompt { + pub async fn configure(&self, request: ConfigureRequest, cancelled: CancelledFn) -> Result { /* .. */ } + pub fn adopted_configuration(&self) -> Result { /* .. */ } + pub fn adopted_entries(&self, request: AdoptedEntriesRequest) -> Result { /* .. */ } +} +``` diff --git a/docs/design/plugins/PromptSources.md b/docs/design/plugins/PromptSources.md index da515b33d8..657c98562b 100644 --- a/docs/design/plugins/PromptSources.md +++ b/docs/design/plugins/PromptSources.md @@ -68,7 +68,7 @@ The body states the setting itself, and asks for nothing: a state block is read **No selection, no block.** When the operator has chosen no language — the system default — the source produces no entry and the base sentence's rule stands. -**The carrier.** The client carries the operator's choice into the Session: `session.create {language?}` seeds it and `session.language.update` changes it, and the value is `SessionConfig.language`, an optional member of the Session's config record. The daemon never reads the client's interface-locale file. The PromptSources Session part provides the Session's live value as the `SessionLanguage` cell and reads it on every load; the cell's `get` is the `sessionLanguage` data face, which other languages read by name, and the branch part re-exposes that cell on each branch for the Session methods that change it, as the Skill list is re-exposed. The face has no write: an update also writes the Session record and has Prompt adopt the source. A Session created without a choice, including a record written by an older client, has no value and produces no entry. An update adopts the value on `main` and, before it replies, on every loaded branch, so that branch's next request carries it without a wake; a branch loaded later reads the current value when it loads, and each branch's periodic check remains the fallback. +**The carrier.** The client carries the operator's choice into the Session: `session.create {language?}` seeds it and `session.language.update` changes it, and the value is `SessionConfig.language`, an optional member of the Session's config record. The daemon never reads the client's interface-locale file. The PromptSources Session part provides the Session's live value as the `SessionLanguage` cell and reads it on every load; the cell's `get` is the `sessionLanguage` data face, which other languages read by name, and the branch part's target contract is [PromptSourcesBranch](PromptSourcesBranch.md): it no longer re-exposes the cell, and the Session methods read the Session value through the language owner. The face has no write: an update also writes the Session record and has Prompt adopt the source. A Session created without a choice, including a record written by an older client, has no value and produces no entry. An update adopts the value on `main` and, before it replies, on every loaded branch, so that branch's next request carries it without a wake; a branch loaded later reads the current value when it loads, and each branch's periodic check remains the fallback. ## 4. Dependencies diff --git a/docs/design/plugins/PromptSourcesBranch.md b/docs/design/plugins/PromptSourcesBranch.md new file mode 100644 index 0000000000..1a573a8e48 --- /dev/null +++ b/docs/design/plugins/PromptSourcesBranch.md @@ -0,0 +1,128 @@ +# PromptSourcesBranch + +Scope: branch. Issue: #2027. + +PromptSourcesBranch keeps a line's checked prompt sources level with what Prompt adopted: AGENTS.md instructions, the runtime environment and date, and the reply language. The sources themselves and their texts are PromptSources' Session part, designed in [PromptSources](PromptSources.md) and owned by #2026; this document is the branch part's target contract. + +## Use and scope: responsibility split + +PromptSourcesBranch owns: + +- **The check.** One tracked task per line: load the checked sources through PromptHost at the configured interval, compare each with Prompt's effective entry for its target, and collect the differences. +- **The adoption request.** Hand the changed values to Prompt's `configure` as data; the part decides nothing about entries, the System or the model. +- **The generation.** The task starts after the line is published, ends when closing starts, and a reload starts a fresh comparison from the current adopted entries. + +Callers keep as business: + +- The source texts and which sources are checked: PromptSources. +- The adoption, the System and the configuration facts: Prompt. +- The reply language's live value: the Session's language owner; the language source reads it through PromptSources. +- The polling interval: the assembly's factory configuration. + +| Requirement (caller) | Can callers compose it from the operations below without breaking PromptSourcesBranch's invariants? | Handling | +| --- | --- | --- | +| A line keeps its guide and environment entries current without a request rebuilding them | Not a caller requirement: the part is the reader itself | No operation; the part is the caller of Prompt and PromptSources | +| A client forces a refresh | Yes: Prompt's `configure` with the loaded values | Business composition by the client's own entry | + +The part has no public operation: it holds a task and a generation, not state another owner asks for. Removing the check from a profile removes the part; no caller substitutes for it. + +## Caller example + +The part's own loop, after the change; only PromptSources' load and Prompt's operations appear: + +```rust +let AdoptedEntries { entries } = prompt + .adopted_entries(AdoptedEntriesRequest { targets: checked.clone() })?; +let mut changed = Vec::new(); +for target in checked { + let LoadReply { entry } = prompt_sources + .load(target.source.clone(), target.scope, cancelled.clone()) + .await?; + let adopted = entries + .iter() + .find(|(source, _)| source == &target.source) + .map(|(_, entry)| &entry.version); + if entry.as_ref().map(|entry| &entry.version) != adopted { + changed.extend(entry); + } +} +if !changed.is_empty() { + prompt.configure(ConfigureRequest::Loaded { sources: changed }, cancelled).await?; +} +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| PromptSources (#2026, Session) | `load` | One checked source's current entry for a target. | +| Prompt | `adoptedEntries`, `configure` | The effective entries and the adoption of the differences. | +| BranchScope | `branchLifecycle` | Activation before the first check and the closing gate. | + +### Operations + +None. The part is a caller of Prompt and PromptHost; it exposes no service and registers no tool or method. + +### Errors + +The part has no caller-facing errors. A source load that fails is logged and retried at the next interval; an adoption that is `superseded` is not retried because a newer adoption already carries the values; a `closed` answer ends the task. + +### Flows + +| Flow | Normal path | The line closes | The part reloads | +| --- | --- | --- | --- | +| the check | Wait for activation; check immediately, then every configured interval; compare each checked source with Prompt's effective entry; adopt the differences in one `configure` | The task ends at closing; no adoption is written | A new generation checks immediately and compares against the current adopted entries; the old task is joined | +| a failed source load | Log the source and the error; keep the adopted entry; retry at the next interval | The task ends | The new generation retries | +| an adoption failure | Log it; the next interval sees the same difference and retries; a `superseded` answer is not retried | The task ends | The new generation compares again | + +The task runs outside the owner's locks; the part registers it in `apply` and cancels and joins it at unload, so no check outlives its generation. + +## Exceptions with reasons + +- The part polls instead of subscribing: prompt sources are files, environment values and a date, with no publication of their own; the interval is the only way to observe a change, and the current design keeps it. +- The comparison reads Prompt's effective entries rather than a snapshot of the whole projection: the part needs only the targets it checks, and the whole projection would duplicate Prompt's state. + +## Supersedes + +- [PromptSources](PromptSources.md): the PromptSourcesBranch section and its `PromptSourcesBranch::language` cell forwarding. +- `docs/design/service-faces.md`: the `promptSourcesBranch` catalog row and the section 4.8 statement that the branch re-exposes the Session language cell. + +## Verification + +- A change in AGENTS.md or the environment is adopted at the next check and appears in the line's System; an unreadable project file keeps the adopted version. +- A day change appends the date entry once; a language change is adopted for every open line through Prompt. +- The task starts only after activation, ends when closing starts, and a reload compares against the current adopted entries. +- A failed load writes no adoption and is retried; a superseded adoption is not repeated. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part; it writes no Timeline fact of its own and folds no state, so it is not a Capability. | +| §2 scopes | Branch: the check follows one line's adopted entries. | +| §3 orthogonality | No other owner's state is read; the sources and the entries arrive through their owners' operations. | +| §4 rule 1 | No command event: the adoption is Prompt's operation. | +| §4 rule 2 | No handover. | +| §4 rule 3 | The tracked task does the loads; no handler waits. | +| §4 rule 4 | No business meaning: the texts are the sources'. | +| §4 rule 5 | The differences go in one `configure`. | +| §4 rule 6 | The entries reach the model only through Prompt's adopted System. | +| §4 rule 7 | The part uses PromptHost and Prompt; it reads no Timeline state. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | The part writes no fact. | +| §7 values, ids and objects | The loaded values are data; no object crosses. | +| §7 one interface | No public name; the `promptSourcesBranch` forwarding service is removed. | +| §7 cross-language | The part exposes nothing; its dependencies are data faces. | +| ADR 002 D1 | Branch: the check belongs to one line. | +| ADR 002 D2 | No wiring plugin: the part is the feature's branch part. | + +## Requirements raised to mechanism owners + +- #2026 (PromptSources): the checked sources, their texts and the reply language's live value; the part loads them through `promptSources.load` and adds no second source path. +- #2026 (Session language): the live language value is read by the language source through PromptHost; the branch part no longer re-exposes a Session cell. + +## Binding appendix + +No service block: the part provides no public operation. The part is registered by the PromptSources feature as its branch part and is removed when the feature is not installed. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..225a8d3123 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -20,8 +20,16 @@ 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 | -| [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 | +| [ContextCompaction](ContextCompaction.md) (policy detail for ContextPreparation and ContextUsage) | — | — | the threshold, retention, cut and recovery rules ContextPreparation applies | P2 | +| [Prompt guide](https://github.com/arcships/dim/pull/2103) | — | `guideEntries`: the input guide's frame, the entries in force and their composition | — (the branch part is [Prompt adoption](PromptAdoption.md); the old [Prompt](Prompt.md) is a redirect) | #548 | +| [Prompt adoption](PromptAdoption.md) | — | — | the adopted configuration, its atomic publication, the tool part and the guide adoption | #2027 | +| [PromptSourcesBranch](PromptSourcesBranch.md) | — | — | the checked-source polling and the adoption request | #2027 | +| [Loop](Loop.md) | — | — | turns, steps, the compaction boundary and the run state | #2027 | +| [ContextPreparation](ContextPreparation.md) | — | — | the prepared request, the budget and the compaction step | #2027 | +| [ContextUsage](ContextUsage.md) | — | — | the context's numbers, the request baseline and recovery | #2027 | +| [ModelProvider](ModelProvider.md) | — | — | one model call, its output facts and its progress | #2027 | +| [InputQueue](InputQueue.md) | — | — | input application, withdrawal and the pending read | #2027 | +| [WaitBranch](WaitBranch.md) | — | — | arrivals and the one wait slot | #2027 | | [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 | | [EnvironmentSettings](EnvironmentSettings.md) | — (reads each setting module's read port) | — | settings snapshots as `` inputs at branch open and on a Settings change | #1020 | @@ -52,5 +60,5 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | | Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | -| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | -| Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | +| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, PromptGuide (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | +| Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt adoption, PromptSourcesBranch, Loop, ContextPreparation, ContextUsage, ModelProvider, InputQueue, WaitBranch, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/plugins/Recall.md b/docs/design/plugins/Recall.md index 3bc0c90dfe..7ba91909c8 100644 --- a/docs/design/plugins/Recall.md +++ b/docs/design/plugins/Recall.md @@ -535,7 +535,7 @@ configured. Rejected: | Situation | Behaviour | | --- | --- | | Later compactions | Nothing moves: recall covers the whole history and ids never change. Each compaction is one more line | -| Compaction during the call | Cannot happen on the calling branch: compaction runs in a request's preparation or as a Loop step, never while a tool batch runs ([ContextCompaction §5.4](ContextCompaction.md#54-manual-compaction)). The pinned head keeps the result consistent regardless | +| Compaction during the call | Cannot happen on the calling branch: compaction runs in a request's preparation or as ContextPreparation's manual step, never while a tool batch runs ([ContextCompaction §5.4](ContextCompaction.md#54-manual-compaction)). The pinned head keeps the result consistent regardless | | Branch fork inside a Session | The child recalls the inherited prefix with the same ids, then its fork line and its own events | | Session fork | The fork's `main` holds the copied facts with their event ids, then its `session/forked` line, then its own events; ids from the source Session open the same things. | | Session close, deletion | Closing a Session cancels calls in flight through the tool's cancellation token | diff --git a/docs/design/plugins/WaitBranch.md b/docs/design/plugins/WaitBranch.md new file mode 100644 index 0000000000..f3dfcd5554 --- /dev/null +++ b/docs/design/plugins/WaitBranch.md @@ -0,0 +1,171 @@ +# WaitBranch + +Scope: branch. Issue: #2027. + +WaitBranch owns one line's wake-ups: the steers and background-task notices released on the line during an open turn that the model has not read yet, and the one wait a caller may park on them. The `wait` tool that calls this owner is a Session part of #2026's registry group; this document is the branch part's target contract. The division is: the Wait document (the tool's owner, #2026) owns the tool declaration, its model-facing texts and the tool-result settlement, and registers no arrival table and no `wait` operation; the arrival table, the single slot and the `wait` operation are this contract's. + +## Use and scope: responsibility split + +WaitBranch owns: + +- **Arrivals.** The inputs released on the line during an open turn: a Steer, and a background task's tagged notice. An input the model has already read, or one deleted before it read, no longer counts. +- **The wait slot.** One wait per line; a second concurrent wait is refused. +- **The wait call's lifetime.** A caller-owned call bound to the owner's generation: the caller ends it with its cancellation, and the owner ends it at its close or reload; a reload does not answer `already_waiting`. +- **The timeout.** The caller's bound on this wait, not on the task it waits for. + +Callers keep as business: + +- Which task a caller waits for, and what to do after a wake-up: the tool and its model-facing texts. +- Which inputs are sent to the line: the operator entry and EventHub. +- The turn's run: Loop. + +| Requirement (caller) | Can callers compose it from the operations below without breaking WaitBranch's invariants? | Handling | +| --- | --- | --- | +| The `wait` tool parks until a matching arrival, a Steer, the timeout or its own cancellation | No: the arrival set, the single slot and the generation's settlement are the owner's, and a caller polling the Timeline would read state it does not own | `wait` | +| A caller wants the tasks that finished | Yes: the reply names the task ids | Business | +| A client reads whether the model already read a notice | Yes: the history read answers the consumed input | Business | + +An operation exists only where the row says No. + +## Caller example + +The `wait` tool, on the calling line, passes the line id, the optional task and its own cancellation: + +```rust +let WaitReply { reason, task_ids, waited_ms } = line_owner::(line)? + .wait(WaitRequest { task_id, timeout_ms }, cancel.clone()) + .await?; +let text = match reason { + Reason::Notification => format!("wait ended: notification ({})", task_ids.join(", ")), + Reason::UserSteer => "wait ended: steer".into(), + Reason::AlreadyNotified => already(&task_ids), + Reason::Timeout => "wait ended: timeout".into(), + Reason::Interrupted => "wait ended: interrupted".into(), +}; +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| BranchScope | `dispatcher`, `timeline`, `branchLifecycle` | The line's facts in order, its committed head and its phase. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `wait` | Wait for the next matching arrival, a Steer, the timeout or the caller's cancellation | `{taskId?, timeoutMs}` | `WaitReply {reason, taskIds, waitedMs}`: `notification`, `user_steer`, `already_notified`, `timeout` or `interrupted` | The caller's cancel ends the wait as `interrupted` and releases the slot; a dropped native future releases it too | `already_waiting` (another wait holds the line's slot), `closed` | + +`timeoutMs` is this wait's bound, from 1 to 300,000; the owner does not limit task execution. A wait that ends because the model already read the task's notice answers `already_notified` with the task ids instead of waiting for a notice that will not come again. A reload ends an accepted wait with `closed`; the tool maps that to the existing reload settlement, and the turn fails without a continuation. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `already_waiting` | `wait` | One wait runs on the line; end it or report that a wait is already running | +| `closed` | `wait` | The line is closing or reloading; the tool settles its call as a reload and the turn fails | + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `wait` | Admit under the slot, register the call in the generation's tracker, wait for an arrival, the timeout or cancellation, release the slot, answer | The cancellation ends the wait as `interrupted`; the slot is released before the tracking token | Admission stops; active calls end `closed` and the generation waits for their slots; a new generation starts with no old arrivals | WaitBranch: the slot and the arrival set; the tool: the result text and the tool-result fact | + +## Client-visible changes + +The `wait` data face takes one request object instead of positional arguments: `wait({taskId?, timeoutMs}, cancelled)` replaces `wait(taskId, timeoutMs, cancelled)` in the generated TypeScript declarations. The reply is `WaitReply {reason, taskIds, waitedMs}` with the existing reason values, and the error codes stay `already_waiting` and `closed`; a caller migrates by passing the two fields as one object. + +## Exceptions with reasons + +- A reload ends an accepted wait with an error rather than replaying an arrival: a cancelled background task emits no wake, and an arrival from the previous generation is not a wake the model can still act on. +- The wait's timeout belongs to the call, not to the owner: the owner has no policy on how long a caller may park, and the tool is the one place a model-facing bound is stated. + +## Supersedes + +None: the Wait document (#2103) keeps only the tool declaration, its texts and the tool-result settlement, and already calls this owner's `wait`; no old branch section remains to replace. + +## Verification + +- A Steer or a tagged notice released during an open turn ends a wait; an input the model read first does not end a later wait; the input that opened the turn never ends one. +- `wait` with a task id wakes only on that task's notice; without one it wakes on any matching arrival. +- A second concurrent wait answers `already_waiting`; the first releases its slot on cancellation, on timeout and on drop. +- A reload ends an accepted wait with `closed`; the tool writes the marked error result and the turn fails without continuing. +- An arrival from before a reload is not replayed; the new generation rebuilds only whether a turn is open. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds the line's input and turn facts; it writes no fact of its own. | +| §2 scopes | Branch: arrivals and the slot belong to one line. A Session part calls `wait` by line id. | +| §3 orthogonality | No other owner's state is read; the arrivals are the line's facts. | +| §4 rule 1 | No command event: the wait answers its caller and writes nothing. | +| §4 rule 2 | No handover. | +| §4 rule 3 | The wait is the caller's call, not a handler's; the handler only rebuilds the open-turn state. | +| §4 rule 4 | No business meaning: the model-facing texts are the tool's. | +| §4 rule 5 | No batch. | +| §4 rule 6 | The wait adds no context; its reply is a tool result. | +| §4 rule 7 | Callers use `wait`; the owner folds public facts. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact. | +| §7 values, ids and objects | The request and the reply are data; no handle or channel crosses. | +| §7 one interface | One name, `wait`, on the `WaitBranch` type; the private `arrival` path used by the tool is removed. | +| §7 cross-language | The operation is data, including the optional task id and the timeout. | +| ADR 002 D1 | Branch: the arrivals belong to one line's turn. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | + +## Requirements raised to mechanism owners + +- #2026 (`wait` tool): the tool calls `wait` by the calling line id and keeps the model-facing texts and the tool-result settlement; it no longer holds the branch `Wait` object or calls a private method. The Wait document keeps only the tool; the arrival table and the operation are this contract's, so the two documents do not both define a table or a reply shape. +- #2025 (Session access): the tool calls `line_owner::(line)?.wait(..)`; the route is [ADR 027](https://github.com/arcships/dim/pull/2029) D1 and the mechanism is [#2127](https://github.com/arcships/dim/issues/2127). + +## Binding appendix + +The service is marked on the `WaitBranch` type; the wire name stays `wait`. + +```rust +use crate::host::CancelledFn; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WaitRequest { + #[serde(skip_serializing_if = "Option::is_none")] + pub task_id: Option, + pub timeout_ms: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Reason { + Notification, + UserSteer, + AlreadyNotified, + Timeout, + Interrupted, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitReply { + pub reason: Reason, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub task_ids: Vec, + pub waited_ms: u64, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case", rename_all_fields = "camelCase")] +pub enum WaitError { + #[error("wait is already running in this session.")] + AlreadyWaiting, + #[error("closed")] + Closed, +} + +#[rutis::service] +impl WaitBranch { + pub async fn wait(&self, request: WaitRequest, cancelled: CancelledFn) -> Result { /* .. */ } +} +``` diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..b56da29a49 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -127,7 +127,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `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) | -| `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | +| `promptSourcesBranch` | 分支 prompt 装配 | 已删除:无公共操作,见 [PromptSourcesBranch](plugins/PromptSourcesBranch.md)。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 @@ -138,15 +138,15 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `toolHost` | `execute(call, caller, cancelled)` | ToolDriver、工具声明 | | `approval` | `pending()`、`decide(requestId, decision)` | 待处理请求、批次准入 | | `permission` | `check(call, risk, cancelled)` | 预设、权限状态、advisor | -| `inputQueue` | `submit(input)`、`withdraw(command)` | 排序、恢复、InputSnapshot | -| `wait` | `wait(taskId, timeoutMs, cancelled)` | 到达记录、单次等待槽 | +| `inputQueue` | `submit(input)`、`withdraw(input)`、`pending(request)` | 排序、恢复、待处理判断 | +| `wait` | `wait(request, cancelled)` | 到达记录、单次等待槽 | 形状与错误见所有者:[Permission](../architecture/rust-agent/plugins/Permission.md#permission-data-face)、 [Approval](../architecture/rust-agent/plugins/Permission.md#approval-data-face)、 -[InputQueue](../architecture/rust-agent/plugins/InputQueue.md#data-face)、 -[Wait](../architecture/rust-agent/plugins/Wait.md#data-face) 与 +[InputQueue](plugins/InputQueue.md)、 +[Wait](plugins/WaitBranch.md) 与 [toolHost](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面)。 -`inputQueue.withdraw` 只做普通撤回;Steer 必须走 `session.input.withdraw` 的校验与提交检查入口。 +`inputQueue.withdraw` 接受可选的 Steer 候选并在队列内运行 submit checks;见 [InputQueue](plugins/InputQueue.md)。 `mcpSession` 与 `backgroundExec` 的数据面以 id 加操作暴露: @@ -170,21 +170,21 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | 名字 | scope | provider | reason | 动作 | | --- | --- | --- | --- | --- | -| `agentLoop` | branch | Loop | hot-path | 待迁移;按 #1292 定义操作面 | -| `loopState` | branch | Loop | hot-path | 待迁移;按 #1292 定义操作面 | -| `prompt` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | -| `contextPreparation` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | -| `contextUsage` | branch | ContextUsage | hot-path | 本地请求计数器、请求引用与按序统计;`session.context.usage` 是 App Server RPC。按 #1292 确认是否需要独立插件操作。 | +| `agentLoop` | branch | Loop | hot-path | 目标契约:[Loop](plugins/Loop.md) | +| `loopState` | branch | Loop | hot-path | 并入 [Loop](plugins/Loop.md) 的 `state`/`observe` | +| `prompt` | branch | Prompt | hot-path | 目标契约:[Prompt adoption](plugins/PromptAdoption.md) | +| `contextPreparation` | branch | ContextPreparation | hot-path | 目标契约:[ContextPreparation](plugins/ContextPreparation.md) | +| `contextUsage` | branch | ContextUsage | hot-path | 目标契约:[ContextUsage](plugins/ContextUsage.md);`session.context.usage` 是 App Server RPC。 | | `toolBinding` | branch | ToolBinding | hot-path | 待迁移;按 #1292 定义操作面 | | `toolExecutor` | branch | ToolExecutor | hot-path | 待迁移;按 #1292 定义操作面 | -| `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | -| `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | +| `configurationPublisher` | branch | ContextPreparation | hot-path | 并入 [Prompt adoption](plugins/PromptAdoption.md) 的 `configure` | +| `configureControl` | branch | Prompt | hot-path | 并入 [Prompt adoption](plugins/PromptAdoption.md) 的 `configure` | | `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([#2093](https://github.com/arcships/dim/pull/2093)) | +| `contextModelHost` | session | SessionScope | hot-path | 目标契约:ContextFacts([#2093](https://github.com/arcships/dim/pull/2093)) | +| `prepareModelHost` | session | PrepareModelHost | hot-path | 目标契约:RequestSettings([#2093](https://github.com/arcships/dim/pull/2093)) | +| `prepareContextHost` | session | SessionScope | hot-path | 保留为模型 profile 的请求构建宿主端口;见 [ContextPreparation](plugins/ContextPreparation.md) | +| `compactionStrategyHost` | session | ProductSummaryStrategy | hot-path | 目标契约:SummaryStrategy([#2093](https://github.com/arcships/dim/pull/2093)) | ### 3.6 入口、凭据与宿主资源 @@ -317,7 +317,7 @@ store.associateWorktree {sessionId, repository, root, subtree} -> {} - `agentConfig` 在 runtime 的 catalog 注册 shared instance;`SessionScope` 已经提供值,`get` 返回同一个快照。 配置快照直接使用所有者的数据定义,接收端允许未知字段;公开类型名称的迁移见[插件配置类型兼容性说明](../release/README.md#plugin-configuration-type-compatibility)。 - `skillsConfig`、`collaborationConfig` 的注册从 typed 改成 shared instance;值仍由 `install_with_config` 的 `session_value` 提供。 -- `sessionLanguage` 只把读做成面;值由 PromptSources 的 Session part 提供,branch 通过 `PromptSourcesBranch::language()` 读同一个 cell。写入不暴露,避免绕过 Session 记录和 Prompt 的采用。 +- `sessionLanguage` 只把读做成面;值由 PromptSources 的 Session part 提供,branch 的分支部件通过 PromptSources 读取所检查的源,不再转交 Session 的 cell;见 [PromptSourcesBranch](plugins/PromptSourcesBranch.md)。 - FileAccess 通过 `store.associateWorktree` 调用 SessionStore;Rust 与跨语言调用共享同一写入操作。迁移调用方时移除 `worktreeAssociations`。路径校验和原子关联由 SessionStore 负责。 - 测试:`crates/dim-agent-capabilities/tests/legacy_session_faces.rs` 与 `crates/dim-app-server/tests/legacy_session_faces.rs` 比较 typed binding 与 wire 的同一操作。 diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index f636b2df77..0edf99db38 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -131,7 +131,7 @@ Ended display details read purpose/source and end data at their recorded positio ## 6. Messages between lines -A message is an `input/message` on the receiver's Timeline, written through `TreeCommands.input`. No new input path is added. A message carries one raw block, marked by its producer and without a key, and the mode of [InputQueue](../architecture/rust-agent/plugins/InputQueue.md): +A message is an `input/message` on the receiver's Timeline, written through the receiver line's `inputQueue.submit` ([InputQueue](plugins/InputQueue.md)). No new input path is added. A message carries one raw block, marked by its producer and without a key, and the mode of [InputQueue](../architecture/rust-agent/plugins/InputQueue.md): | Mode | Effect on the receiver | When to use it | | --- | --- | --- | diff --git a/docs/zh/design/plugins/Recall.md b/docs/zh/design/plugins/Recall.md index adc227f805..c4a4a22eb6 100644 --- a/docs/zh/design/plugins/Recall.md +++ b/docs/zh/design/plugins/Recall.md @@ -300,7 +300,7 @@ End of turn. Open one: open=. | 情况 | 行为 | | --- | --- | | 后续压缩 | 什么都不移动:Recall 覆盖整个历史,id 永不改变。每次压缩只是多一行 | -| 调用期间发生压缩 | 在调用方分支上不会发生:压缩只在请求的准备阶段或作为 Loop 的一步运行,从不在工具批次运行时发生([ContextCompaction §5.4](ContextCompaction.md#54-手动压缩))。无论如何,固定的 head 保证结果一致 | +| 调用期间发生压缩 | 在调用方分支上不会发生:压缩只在请求的准备阶段或作为 ContextPreparation 的手动步骤运行,从不在工具批次运行时发生([ContextCompaction §5.4](ContextCompaction.md#54-手动压缩))。无论如何,固定的 head 保证结果一致 | | Session 内的分支 fork | 子分支以相同的 id 回忆继承前缀,然后是它的 fork 那一行和它自己的事件 | | Session fork | fork 的 `main` 先是带原事件 id 的复制事实,然后是它的 `session/forked` 那一行,再是它自己的事件;源 Session 的 id 展开同样的内容 | | Session 关闭与删除 | 关闭 Session 通过工具的取消令牌取消进行中的调用 |