From f13fac3fb0bf3cd70f184402b09f57214d20b637 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 21:52:07 +0800 Subject: [PATCH 1/6] docs(2033): target contracts for Goal, SessionTitle, Web and Code Mode Goal writes a command input to the line and reads the goal owner's published value; the routing table, the Session-side re-fold and the pre-commit callback are removed. Code Mode keeps the process program slots as one callback operation and runs the program in the line's owner. SessionTitle writes titles through SessionStore's change callback and reads Goal's published value. Web names its two tool contributions and the Dim account's search operations. Refs #2033 Refs #2015 --- .../appserver/session-title-metadata.md | 19 +- .../contracts/resource-owner-operations.md | 2 +- .../contracts/runtime-owner-operations.md | 6 +- docs/design/plugins/CodeMode.md | 627 +++++------------ docs/design/plugins/Goal.md | 433 +++++------- docs/design/plugins/README.md | 6 +- docs/design/plugins/SessionTitle.md | 657 +++++------------- docs/design/plugins/Web.md | 384 ++++------ docs/design/resource-faces.md | 2 +- docs/zh/design/plugins/Goal.md | 1 + docs/zh/design/plugins/SessionTitle.md | 1 + docs/zh/design/plugins/Web.md | 1 + 12 files changed, 700 insertions(+), 1439 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 540bd28dd9..035e960224 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -5,8 +5,7 @@ The [target repository binding](../contracts/resource-owner-operations.md) moves Status: Implemented in roadmap item S5b ([#60](https://github.com/arcships/dim/issues/60), [#96](https://github.com/arcships/dim/pull/96)), after C6 ([#49](https://github.com/arcships/dim/issues/49), [#85](https://github.com/arcships/dim/pull/85)); the implementation follows this design. Review refined when a write -is admitted and how unload settles it (§6, D14). Requirement: [SessionTitle](../plugins/SessionTitle.md) §2, §4 and -[A.2](../plugins/SessionTitle.md#a2-depended-on-shapes-owners-define-them). Overview: +is admitted and how unload settles it (§6, D14). Requirement: [SessionTitle](../plugins/SessionTitle.md#own-contract). Overview: [Appendix B.2](../overview.md#b2-app-server-process-plugins), SessionStore and Rpc rows. Scope: [ADR 002](../../adr/002-plugin-scope.md) process scope, inside the existing SessionStore plugin, with three Rpc list fields. Consumer: SessionTitle. @@ -69,13 +68,13 @@ protocol version. | --- | --- | | `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write sets it to `expectedRevision + 1`: a new title, the same text again, a source change or a clear | | `title` | `{text, source}` or none | -| `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, enforced through the revision check ([SessionTitle §4](../plugins/SessionTitle.md#4-timing-and-conflicts)) | +| `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, enforced inside `setTitle`'s change callback ([SessionTitle](../plugins/SessionTitle.md#own-contract)) | - **A clear keeps the counter.** `title: null` leaves the Session's row with no title and the new revision. Were the row deleted, the counter would restart at 0, and a generation that read revision 0 before a rename and a clear would then commit an automatic title over the user's clear. - **Text as given.** SessionStore stores the text it receives. Title rules (trimming, length, a single line) are - SessionTitle's ([A.3](../plugins/SessionTitle.md#a3-configuration)): its method validates rename input and + SessionTitle's ([SessionTitle](../plugins/SessionTitle.md#own-contract)): its method validates rename input and normalizes generated text. The producer guarantees the contract, so SessionStore checks it again nowhere (AGENTS.md). - **Per Session.** Revisions of different Sessions are independent. A fork starts at 0. @@ -151,7 +150,7 @@ This settles the boundary that SessionTitle §0 left to S5b. | Before the call | The caller's own work. Cancelling it before the call writes nothing | | The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `storage` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | | After the call | SessionStore settles the write itself: it commits and announces, or fails and writes nothing. Dropping the call, unloading the calling row or losing the reply neither cancels nor undoes it. `setTitle` has no cancel action | -| Lost reply | The caller reads with `read`. It does not repeat the write blindly: a repeat at the old revision fails `conflict`, and one at the new revision would be a second change ([SessionTitle Appendix C](../plugins/SessionTitle.md#appendix-c-errors-and-recovery)) | +| Lost reply | The caller reads with `read`. It does not repeat the write blindly: a repeat at the old revision fails `conflict`, and one at the new revision would be a second change ([SessionTitle](../plugins/SessionTitle.md#errors)) | | SessionStore unload | Its disposer first stops admission: from then on a call fails `storage` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | Rejected: a cancel action that works until the transaction starts. It would only move the uncertainty, since a caller @@ -199,11 +198,11 @@ Protocol v3 `session.summaries` entries gain three fields: Rpc never calls `setTitle` and gains no method. How each error reaches clients: -| SessionStore | `session.summaries` | `session.rename` ([SessionTitle A.1](../plugins/SessionTitle.md#a1-sessionrename)) | +| SessionStore | `session.summaries` | `session.rename` ([SessionTitle](../plugins/SessionTitle.md#operations)) | | --- | --- | --- | | `storage` | The catalog read fails as it does today | `storage_failed` | | `not_found` | The Session is not listed | `session_not_found` | -| `conflict` | — | SessionTitle reads again and retries ([§3.2](../plugins/SessionTitle.md#32-manual-rename)) | +| `conflict` | — | SessionTitle reads again and retries ([SessionTitle](../plugins/SessionTitle.md#operations)) | ## 9. Lifecycle @@ -213,7 +212,7 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | Load, unload, close, restart | Unchanged: the title is stored with the Session's rows, not with its instance. `read` and `setTitle` work on a Session that is not loaded; their notices are dropped, as nobody listens | | `session.delete` (S5c) | Removed in S5c's single delete transaction, before the Session record. Afterwards `read` and `setTitle` fail `not_found` | | Creation rollback | The same transaction as a delete; it removes a row that a racing write committed | -| `session.fork` (S5c) | Not copied ([SessionTitle A7](../plugins/SessionTitle.md#appendix-e-assumptions)): the fork starts untitled at revision 0 | +| `session.fork` (S5c) | Not copied ([SessionTitle](../plugins/SessionTitle.md#exceptions-with-reasons)): the fork starts untitled at revision 0 | | SessionStore or SqliteStorage reload | Settles as in §6. Consumers of `sessionMetadata` reload with SessionStore ([ADR 002](../../adr/002-plugin-scope.md) D3), which SessionTitle §1 accepts. SessionStore reloads only with SqliteStorage, which has no dependencies | ## 10. Timing and conflicts @@ -227,7 +226,7 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | `setTitle` and Timeline appends | Independent rows; each uses its own transaction on the one store connection | | Notice and list read on one connection | §8: the higher `titleRevision` wins | | `setTitle` with no client attached | Committed; the notice is dropped; the next list shows the title | -| The same text written again | Commits a new revision and announces it ([SessionTitle Appendix B](../plugins/SessionTitle.md#appendix-b-full-conflict-table): a duplicate rename rewrites) | +| The same text written again | Commits a new revision and announces it ([SessionTitle](../plugins/SessionTitle.md#exceptions-with-reasons): a duplicate rename rewrites) | ## 11. Storage format @@ -281,7 +280,7 @@ after the upgrade commits (S5a's log line, with the version the store came from) | Identity | `dyn HostDispatch` at `host_key("sessionMetadata")`, provided by SessionStore; `register_shared("sessionMetadata")` in App Server's service catalog, beside `sessions` and `settings` | | Use | A C4 Session part declares `inject: ['sessionMetadata']` and calls `ctx.use('sessionMetadata')`, the path `settings` takes from a Session part ([settings-owner fixture](../../../runtime/fixtures/settings-owner.ts)). Types are in [npm/plugin.d.ts](../../../npm/plugin.d.ts) | | Modes | `read` and `setTitle` are both `async` | -| Writer | The service carries no caller identity, as for `settings` (AGENTS.md rule 11). SessionTitle is the title's one writer by design ([SessionTitle §2](../plugins/SessionTitle.md#2-data-and-state)); other packages only read | +| Writer | The service carries no caller identity, as for `settings` (AGENTS.md rule 11). SessionTitle is the title's one writer by design ([SessionTitle](../plugins/SessionTitle.md#own-contract)); other packages only read | | Reload | A consuming row reloads with SessionStore. SessionStore reloads only with SqliteStorage, so no directory part that never reloads is needed, unlike `sessions`, whose index reloads with Settings ([sessions D1](sessions-service.md#3-decisions)) | | Missing provider | A daemon without a native store has no SessionStore, so a row that injects `sessionMetadata` stays Pending under the existing rules; native Sessions continue | diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 8eca878f61..1335645c68 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -54,7 +54,7 @@ draining its admitted work before unloading. | --- | --- | --- | | Agents, Session catalog, grants and worktree clients → store → sqliteStorage | Reuse the store request/reply shapes for `createOwnedSession, fork, owner, creationRecord, hasRecords, sessionConfig, sessionConfigText, catalog, addGrant, removeGrant, grants, setSessionLanguage, associateWorktree, worktreeDirectories, worktreeUsages, sessionsUnderWorkspace, removeWorktreeDirectory`. | SQLite creates the Session, main branch, ownership and optional worktree association in one transaction. Fork uses bounded copy transactions on its own connection; only the final transaction inserts the Session row and makes the fork visible. Association commits the directory and Session link together. | | Session deletion and worktree removal → store | `store.delete` uses `sqliteStorage.hasRecords, removableOutputDirectories, touchWorktreeDirectories, rollbackSession`. `store.removeWorktree` uses the existing association/workspace checks and directory deletion; `store.removeUnregisteredDirectory` uses the existing directory-record and workspace checks and the caller's deletion. | SessionStore holds its ownership lock across the checks and the filesystem removal, including a recursive `--force` deletion with no time limit, so Session creation, fork, deletion and worktree association or removal wait for it. Dropping the caller does not release the lock while the removal runs. SQLite owns each database step. File deletion and Git removal run outside SQL transactions. | -| SessionTitle and Session rename → store → sqliteStorage | `readMetadata(sessionId)`, `setTitle(existing title request)`; existing metadata replies. FileAccess → `store.associateWorktree` with the existing association record. | SQLite checks the title revision and commits the write. SessionStore serializes title writes and publishes the committed notice before admitting the next one. | +| SessionTitle and Session rename → store → sqliteStorage | `title({id}) → {revision, title?: {text, source}}`, `setTitle({id}, change) → {revision}` ([SessionTitle](../plugins/SessionTitle.md#own-contract), target, pending [#2091](https://github.com/arcships/dim/pull/2091)); FileAccess → `store.associateWorktree` with the existing association record. | The change decides the next title under SessionStore's serialization; SQLite commits it and SessionStore publishes the committed notice before admitting the next write. | | Timeline clients → timelineStore; SessionStore → sqliteStorage | Bind existing `createSession, rollbackSession, releaseSession, sessionConfig, branches, head, batchEnd, batchEndAt, readPage, readSegments, query, trace, saveSnapshot, latestSnapshot` requests at the native boundary. `commitTimelineRound({batches: Append[]}) → {sessions: [{sessionId, result}]}` accepts ordered batches grouped by Session. | SessionStore admits appends synchronously, groups the existing writer round, and serves commit subscriptions and release/drain. SQLite owns encoding, the grouped transaction, per-Session fallback on failure and writer memo settlement. One accepted round produces the existing ordered batch outcomes after commit. Release or unload drops generation-local reader/writer state after drain. | | Session file put/import and read → sessionFiles → sqliteStorage | `reserveFile(sessionId,fileId,generation)`, `commitFile(sessionId,fileId,generation)`, `abandonFile(fileId,generation)`; ownership and path reads via `ownsFile, ownsOutput, ownedPaths`; `registerOutput(sessionId,path)`. | SessionStore reserves, writes or imports bytes through the file owner, then finalizes. SQLite verifies the Session and writer generation, clears the reservation and inserts ownership atomically. Bytes, path validation and fileId transfer stay with the file owner. | | Session file sweep → sqliteStorage | `releaseStaleFileWriters(generation), unownedFiles(), deleteIfUnowned(fileId), recordedFiles(names)`. | SessionStore removes files outside SQLite. SQLite rechecks ownership when deleting the row. Failed cleanup remains retryable. | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 3d36fd9d6d..f34abecf6a 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -18,11 +18,11 @@ | --- | --- | | Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | | Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Registered Session extension definitions must activate their instance rows. Host-added optional groups retain their optional rows. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | -| Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | +| Goal → the line's input owner ([Goal](../plugins/Goal.md#own-contract)) | Superseded: Goal writes one command input through `inputQueue.submit` and appends its business fact and state record with `timeline.append`, in that order. `timelineTree.inputs` is not used. | | Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | | History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | -| Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `query`; writes retain the ended/unknown errors. | +| Goal and Shell admission → timelineTree | `directory()` answers the lines and the default; `line({line})` answers one record or `unknown_branch`. Goal reads ended history through `read`; writes retain the ended and unknown errors. | | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | @@ -73,5 +73,5 @@ substitutes a newer head. | 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, ToolExecutor and Code Mode definition readers → `toolBinding` | `bind`, `bindCurrent`, `adopted({requestId}) → {adopted}`, `transfer`, `release`. ToolBinding retains the pinned handler generation; Code Mode reads `adopted` ([CodeMode](../plugins/CodeMode.md#own-contract)). | | 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/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index fd6ad89a50..677faace5d 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -1,488 +1,207 @@ -# Code Mode: bounded QuickJS tool orchestration +# Code Mode -Status: Draft. Phase: P3. Delivery status is tracked in [#1276](https://github.com/arcships/dim/issues/1276), not here. -Language: native Rust (`rquickjs`). The plugin is `crates/dim-codemode/`; it is not a TypeScript -package and runs no Node or TypeScript plugin runtime. Scope: process, Session and branch -([ADR 002](../../adr/002-plugin-scope.md)). +Scope: process, Session entry and branch run. Issue: #2033 (this contract); #1276 (delivery). The tool's contract, the child call batches, the approval rules and the client compatibility are unchanged and stay in [child tool batches](../appserver/child-tool-batches.md) and in this document's contract sections below. The current shape is the one #2033's scan report describes. -Code Mode lets a model submit one bounded program that invokes the request's adopted Session tools, -collects the results and returns one ordinary tool result. A program's tool calls are child tool -calls on the branch Timeline, not a second model batch. The design reuses `step/tool-call` and -`step/tool-result`; the only event-envelope addition is an optional `parent_call_id`. +Code Mode lets the model submit one bounded QuickJS program that invokes the request's adopted tools and returns one ordinary tool result. Three owners hold its state: the process owns the program slots, the branch owns the one-shot run, and the Session entry declares the tool. -The host installs the plugin with `dim_codemode::install`. The App Server product profile may -install the plugin, but only a protocol v4 Session is offered the `codemode` tool; v1–v3 -connections do not receive child events and cannot start a Code Mode program. The client boundary -is specified in [child tool batches](../appserver/child-tool-batches.md). A host that does not want -the tool omits the call. +## Use and scope: responsibility split -Issue: [#1276](https://github.com/arcships/dim/issues/1276). -Rules: [design rules](../../architecture/rust-agent/principles.md), [ADR 002](../../adr/002-plugin-scope.md), [plugin contract](../plugin-contract.md). +Code Mode owns: -## 1. Scope and ownership +- **The structural bounds.** `max_code_bytes`, `max_runtime_ms`, `max_calls`, `max_parallel_calls`, `max_memory_bytes`, `max_programs`, `max_output_bytes`, `max_single_result_bytes`. They are configuration, not tool parameters and not prompt text. +- **The process program slots.** At most `max_programs` programs run in one process at a time; the slot is held from the program's start to its settlement and released by the quota owner, including when the caller unloads. +- **The one-shot run.** One fresh QuickJS context per call with only `tools.list`, `tools.describe` and `tools.call`; the memory limit, the wall-clock interrupt and the program's cancellation; the outer result's text, effects and failure warning. +- **The tool declaration.** The `codemode` tool's name, description, schema, `session` risk and the v4 client gate. -### 1.1 Parts +Callers keep as business: -| Part | Scope | Owns | +- Which tools a request may call: ToolBinding pins the request's declarations, and the program sees only that snapshot without `codemode`. +- Whether a child call may run: Permission and Approval decide per child, with the tool's own risk. +- How child batches are shown: the client boundary and the TUI grouping. +- The prompt: the description states the contract the model acts on and nothing about host bounds. + +| Requirement (caller) | Can callers compose it from the owner's operations without breaking the owner's invariants? | Handling | | --- | --- | --- | -| `CodeMode` | Process | The structural `CodeModeConfig` bounds, the process `CodeModeRuns` map from `(session id, branch id)` to its runner, the program semaphore, and the registrations of the Session and branch parts. | -| `CodeModeSession` | Session | The `codemode` tool declaration and handler. The handler resolves the caller's `(session id, branch id)` in `CodeModeRuns`; it does not read Session state to find a branch. | -| `CodeModeBranch` | branch | The one-shot QuickJS program, the `tools` bridge, the parent gate use and the confirmed child effects copied onto the outer result. | -| ToolExecutor nested invocation | branch, mechanism owner | The pinned `ToolBinding` lookup, the child `step/tool-call` command, nested execution, Approval admission and the child terminal result. This is not Code Mode business state. | -| QuickJS runtime | branch | The execution boundary for model code. It receives only the serializable `tools` bridge. | - -`CodeMode` is a process plugin, not a `Feature`: it provides `CodeModeRuns` and registers the two -parts. `CodeModeSession` and `CodeModeBranch` are plain parts. `CodeModeBranch` is not a Capability -in this delivery: the part owns runtime-only execution state and the parent gate use, while -ToolExecutor owns the child `step/tool-call`/`step/tool-result` facts. - -The bounds are structural `CodeModeConfig` values. A user `codemode` Settings source is deferred; no -part invents defaults from another source. - -### 1.2 Goals - -- Allow one model tool call to run a bounded asynchronous program. -- Let the program invoke tools from the request's fixed `ToolBinding` snapshot. -- Keep every child invocation under the invoked tool's Permission and Approval policy. -- Record every child invocation as a child `step/tool-call` batch and one terminal - `step/tool-result`, with an explicit parent call. -- Return one bounded outer `ToolResult`; child results do not become model messages. -- Copy confirmed child effects onto the outer result for the existing compaction digest. -- Never replay a child side effect after cancellation, timeout or reload. - -### 1.3 Non-goals - -| Not done here | Why | -| --- | --- | -| Persistent REPL, cells or cross-turn JavaScript state | That is durable execution state and belongs in a separate design or Workflow. | -| A separate new event type for child calls | Child calls reuse `step/tool-call`/`step/tool-result`; `parent_call_id` carries the relation. | -| A separate OS-confined native host process | The first delivery runs QuickJS in the daemon process with memory, time and interrupt limits; process-level hardening is future work. | -| Direct access to ToolExecutor internals, handlers, ToolHost, file descriptors or host objects | Those would bypass the pinned binding and admission boundaries. | -| An implicit grant of all child permissions after approving `codemode` | Each invoked tool remains independently subject to Permission and Approval. | -| Recursive `codemode` calls | The allowed tool set excludes `codemode`; the first delivery has no nested Code Mode. | -| TypeScript type stripping | The first delivery evaluates JavaScript; a TypeScript front end is future work. | +| The model runs one program on the call's line | No: the QuickJS boundary, the memory limit and the interrupt must sit inside the run, on the line whose tools the program calls | `codeModeLine.run` at the call's line | +| At most `max_programs` programs per process | No: the cap is process state and must be settled when the run ends or the caller unloads | `codeMode.with_slot {work}` | +| Each child call is admitted on its own | No: admission, the child batch and the terminal result are ToolExecutor's | ToolExecutor's nested operation ([#2028](https://github.com/arcships/dim/issues/2028)); the program only names a tool and its arguments | +| A failed program returns a result the model reads | No: the failure text, the effects collected before it and the warning are the run's | the run's reply | +| Only v4 Sessions are offered the tool | No: the declaration is the entry's and the client's protocol version is SessionScope's record | the entry's declaration | + +An operation or parameter exists only where its row says No. + +## Caller example + +The entry's handler runs on the call's line and asks that line's run owner. No process table, no executor object, no slot handle. + +```rust +// CodeModeSession's handler: the call's line is a value on the execution context. +let line = execution.line.clone(); +let run = line_owner::(&line)?; +let result = run.run(RunProgram { + outer_call_id: call.id, + code: input.code, + context: execution, +}, cancelled).await?; +Ok(result) // one ToolResult for the outer call +``` -### 1.4 Tool exposure and eligibility +The line's run owner holds the slot around the program; the slot never leaves the quota owner. + +```rust +// CodeModeLine: one program inside one process slot. The gate is the executor's; +// the run closes it early to word the result, and the owner settles it again. +quota.with_slot(Arc::new(move |cancelled| Box::pin(async move { + let gate = executor.open(OpenRequest { parent_call_id: outer_call_id, context }, cancelled.clone()).await?; + let outcome = quick_js(code, gate.gate_id.clone(), cancelled.clone()).await; + let effects = executor.close(CloseRequest { gate_id: gate.gate_id }, cancelled).await?; + Ok(program_result(outcome, effects)) // the same effects appear once in the parent result +})), cancelled).await? +``` -`codemode` is declared beside the other adopted tools. The bridge exposes every ordinary tool in the -outer request's pinned `ToolBinding`, including eligible built-in, extension and MCP tools. -`codemode` itself is excluded. `tools.list` and `tools.describe` are projections of the same pinned -snapshot; `tools.call` rejects a name absent from it. A malformed or unknown call is a local program -error and writes no child Timeline fact. +## Own contract -## 2. Own contract +### Dependencies -### 2.1 The `codemode` tool +| Owner | Operation | Use | +| --- | --- | --- | +| Session access ([#2025](https://github.com/arcships/dim/issues/2025)) | the line's owner by line id | The entry reaches `CodeModeLine`; the run reaches the line's ToolExecutor | +| ToolExecutor ([#2028](https://github.com/arcships/dim/issues/2028)) | `open {parentCallId, context}` → `{gateId}`; `invoke {gateId, call}` → `{result}`; `close {gateId}` → `{effects}` | Child calls, admission, child facts; the run closes the gate to word its result, and the owner closes it again at parent settlement with the effects merged once | +| ToolBinding ([#2028](https://github.com/arcships/dim/issues/2028)) | `adopted {requestId}` → `{adopted}` | The request's pinned declarations for `tools.list`, `tools.describe`, `tools.call` | +| Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `toolRegistry.register` | The `codemode` contribution | +| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `config` | The Session's protocol version for the declaration | -`CodeModeSession` registers one tool named `codemode`: +### Operations -```json -{ - "code": "const listed = await tools.list(); return listed" -} -``` +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `codemode` | The model submits one program | `{code}` | the program's returned value as JSON text, or a terminal failure text, with the confirmed effects | The program is interrupted: a synchronous loop stops, a pending child is cancelled and new children are refused | `invalid_input` when the arguments or the code size are refused, returned as an error result | +| `codeModeLine.run` | Run one program on this line | `{outerCallId, code, context}` | `ToolResult` | Interrupts the program and closes the gate; committed children settle through ToolExecutor | `invalid`, `closed`, `cancelled` as the service error `{code, message}`; a failed program is the result's text | +| `codeMode.with_slot` | Run one program inside a process slot | `{work}` as a direct callback parameter, plus `caller: &Ctx` | `{}` | The work is cancelled and joined; the slot is released | `closed` as the service error `{code, message}`; a cancelled work is the callback's own result | -| Field | Meaning | -| --- | --- | -| `code` | Raw JavaScript async function body. It is rejected when absent, not a string or larger than `max_code_bytes`. | - -The tool has no model-facing timeout, call budget or concurrency parameter. Those are host -bounds; the model cannot raise or lower them. - -`CodeModeConfig` supplies the hard bounds: - -```text -max_code_bytes 256 KiB -max_runtime_ms 600 s -max_calls 4096 -max_parallel_calls 16 -max_memory_bytes 1024 MiB -max_programs 2 -max_output_bytes 16 MiB -max_single_result_bytes 4 MiB -``` +The program's own failure is a result, not an operation error: the reply carries the failure text, the warning that child calls may have completed, and the confirmed effects. `invalid` is a code body over the limit; `closed` is the owner unloading; `cancelled` is the caller's cancellation before or during the run. All three are the service error `{code, message}`; the child invocation's `gate_closed`/`interrupted`/`no_batch` are ToolExecutor's errors, which the run turns into a program failure or a cancellation. -`max_programs` bounds concurrent programs in one process. `CodeModeRuns` holds the program -semaphore; aggregate QuickJS memory is bounded by `max_programs * max_memory_bytes`. A program -waiting for a slot is cancelled by the outer call token. `max_parallel_calls` bounds child tool -tasks, and `max_single_result_bytes` bounds one child result before its full JSON string is -materialized. These bounds are host policy, not tool parameters and not prompt text. - -The outer tool is declared with risk `session`. The outer call enters the normal ToolExecutor -admission path under the Session's permission preset. Approving the outer call does **not** approve -child calls: each child uses the invoked tool's own risk. - -The model-visible description states only the contract the model must act on: the raw JavaScript -function body, top-level `await`/`return`, the `tools.list`/`tools.describe`/`tools.call` shapes, -`args` as an object, the whole child `ToolResult` (`content` and `structuredContent` together, -with the guidance to return `content` unless a program needs the structured fields), -`ToolCallError`, the exclusion of `codemode`, the absent host APIs, the JSON return value, and that -child results do not enter model context. Host bounds, engine name, memory, program count and -error-code tables are not prompt text. - -The outer result is a normal `ToolResult`. `content` is the program's returned value serialized as -JSON, or a stable terminal message on failure. `effects`, when present, are the confirmed effects of -child `ToolResult`s in child sequence order, including effects from an error result. A generated -timeout or failure result carries the effects that completed before it and warns that child calls -may have completed. - -### 2.2 QuickJS bridge - -The program sees only: - -```text -tools.list() -> [{name, description}] -tools.describe(name) -> declaration | undefined -tools.call(name, arguments) -> the whole child ToolResult -``` +### Flows -`arguments` is a JSON object. `tools.call` returns the child `ToolResult` as the program's value: -`content` (a string or content blocks) and `structuredContent` are both carried, so a program reads -the same content the model would read and the structured data the tool published. A child result -with `isError` throws `ToolCallError` with `code`, `message` and optional `data`. The error object is -data, not a second result shape. - -The context has no `process`, environment, filesystem, network, timer, console, child-process or -module loader. The host bridge is passed as the function argument; no host object is exposed as a -global. `tools.call` rejects a non-object argument and every name outside the filtered pinned set, -so `codemode` cannot recurse. - -The runtime enforces `max_code_bytes`, `max_runtime_ms` (a Rust `timeout_at` around the program and -a QuickJS interrupt handler), `max_memory_bytes` (QuickJS memory limit), `max_calls`, -`max_parallel_calls`, `max_single_result_bytes` and `max_output_bytes`. A synchronous loop is -interrupted by the QuickJS handler; cancellation also sets the interrupt and wins over the program -await. These bounds are not written into the prompt. - -## 3. Child calls on the Timeline - -### 3.1 Event model - -The Timeline keeps one call event type: - -- A top-level model request writes `step/tool-call` without `parent_call_id`. -- A child call writes `step/tool-call` with `parent_call_id` set to the outer `ToolCall.id`. -- The child result writes `step/tool-result` with `parent_call_id` set to the same outer - `ToolCall.id`; `call_event_id` points to the child `step/tool-call` event. -- A grandchild call writes `step/tool-call` with `parent_call_id` set to the child `ToolCall.id`. - -`parent_call_id` is an optional top-level property on `AgentEvent`, not a field inside -`ToolCallData`. The retrieval layer filters child batches without decoding `ToolCallData`; TUI and -App Server read the same property. - -Events produced while one child call executes carry `parent_call_id` set to the child -`ToolCall.id`. This includes asynchronous callbacks, background `task/*` results and child -`approval/*` events. A child `ask_user` call is itself a `step/tool-call`, so the child -`ask_user` batch carries the outer call id like every other child batch. The rule is: - -- For `step/tool-call` and its `step/tool-result`, `parent_call_id` is the call that spawned the - batch: the outer call for a child batch, the child call for a grandchild batch. -- For every other event produced by one call, `parent_call_id` is that call's `ToolCall.id`. - -The sequence is the commit order; `parent_call_id` is the structure. No reader infers a parent from -the open-batch order, so parallel children and grandchildren stay unambiguous. - -### 3.2 Normal sequence - -```text -step/tool-call (batch A, no parent_call_id) - calls: [codemode c1] - step/tool-call (batch B, parent_call_id = c1) - calls: [X c2] - step/tool-result (batch B result, parent_call_id = c1) - results: [c2] - step/tool-result (batch A result, no parent_call_id) - results: [c1, effects from c2] -``` +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `codemode` | The handler resolves the line's run owner and calls it; one result for the outer call | The program is interrupted; committed children settle through ToolExecutor; the result names the cancellation | The run is cancelled by the line's close; the outer call is settled by ToolExecutor | Reload settles the outer call as started but unfinished with the effect-may-have-happened warning; no child is replayed | ToolExecutor: the outer and child facts; the run owner: the QuickJS context | +| `codeModeLine.run` | Open the gate, evaluate the program, close the gate for the confirmed effects, answer the program's result | Interrupt, refuse new children; committed children record their own cancellation; the early close still answers the effects confirmed before it | The line's close cancels the run before the outer result | A closing or reloading line ends the run; ToolExecutor settles the gate, the child facts and the parent result | the run owner: the QuickJS context; ToolExecutor: the gate, every child fact, the effects and the outer result | +| `codeMode.with_slot` | Take a slot, run the work, release the slot | The work is cancelled and joined; the slot is released | The row's unload releases the slot it holds | New slots are refused once the process is unloading; held slots are released | the quota owner | -1. Loop writes batch A with `codemode` c1. ToolExecutor opens batch A. -2. The `codemode` handler starts the QuickJS program and opens the parent gate for c1. -3. The program calls `tools.call("X")`. The nested invocation service writes batch B with - `parent_call_id = c1` and `calls: [c2]`. -4. ToolExecutor runs c2 through the pinned binding, Permission and Approval. -5. ToolExecutor writes batch B's `step/tool-result` with `call_event_id = B`, - `parent_call_id = c1` and c2's `ToolResult`. -6. The program receives c2's result. Batch B is terminal. -7. The parent gate closes after every committed child is terminal. ToolExecutor writes batch A's - `step/tool-result` with c1's result and the confirmed child effects. -8. Loop continues with the next model request. - -Batch A stays open while child batches B, C and so on are open. The ordinary batch slot belongs to -batch A; child batches do not take a second model batch slot. - -### 3.3 Parallel and nested children - -- Batch A can open child batches B (c2) and C (c3) at the same time. -- Batch B and batch C both carry `parent_call_id = c1`. -- Child call c2 can open grandchild batch D (c4) with `parent_call_id = c2`. -- The parent gate for c1 waits for c2, c3 and their descendants. -- A child result closes the child batch it answers; a grandchild result closes the grandchild - batch. -- ToolExecutor never treats a batch with `parent_call_id` as a model batch. - -### 3.4 Parent gate and effects - -The parent gate is a branch-scoped contract of the nested invocation service: - -```text -open(parent_call_id) - -> invoke(...) // writes a child step/tool-call and returns its result - -> close(reason) // rejects new children and waits for every committed child -``` +The program's memory is bounded by QuickJS's own limit, its time by the wall-clock interrupt, and its output and each child's serialization by the configured byte limits. A child the program never awaits is still committed and joined before the outer result. Code Mode closes the gate once, after the program ends, to word the result with the confirmed effects; ToolExecutor closes it again at parent settlement without effect, and the same effects appear once in the parent result. -`close` runs for normal return, program failure, host timeout and cancellation. On reload, -ToolExecutor's rebuild applies the reload rule in §3.6 instead. `close` stops new admission, cancels -children that have not started or that the program no longer awaits, and waits up to a five-second -grace for a terminal `step/tool-result` for every committed child before the outer result is -written. A handler that ignores the cancellation token past the grace is outside the contract; its -terminal fact may settle after the outer result. A child waiting for Approval is cancelled through -the existing Approval contract. - -Child effects are collected from terminal child `ToolResult`s in child sequence order, including -effects from an error result, and appended to the outer `ToolResult.effects`. The gate records a -child's effects when its task writes the terminal result, so an unawaited child that completes -before `close` still contributes effects. `max_calls` bounds the number of child results; -`max_single_result_bytes` bounds one child serialization; each invoked tool remains responsible for -its own result bounds. ToolExecutor records the returned outer -result unchanged under the Session boundary contract. - -### 3.5 Cancellation and timeout - -- The parent gate closes admission. -- A child that has not started settles with an error `ToolResult` whose text names cancelled or not - executed; the design adds no separate status field. -- A started child receives the child cancellation token; ToolExecutor writes its terminal result. -- The outer result follows the parent gate; confirmed child effects are included. -- Every child call uses a per-program child `CancellationToken`; the token is cancelled whenever the - program returns, times out or is cancelled. A dropped Approval admission is removed and writes - `approval/cancelled`; a pending question is settled with the same child token. Approval admission - needs a drop guard: dropping the admission future removes the pending request and writes - `approval/cancelled`. -- A call the program starts and never awaits is still a committed child. The parent gate joins the - child; the program cannot finish with an unjoined child. - -### 3.6 Reload - -The reload rule is stated once, here: - -- A child `step/tool-call` with a matching `step/tool-result` uses the written result and effects. -- A child `step/tool-call` without a terminal result counts as started but not finished. ToolExecutor - writes an error `ToolResult` for the child and no confirmed effects. -- The outer `codemode` call counts as started but not finished when batch A has no terminal result. - ToolExecutor writes a failure result with an effect-may-have-happened warning and the confirmed - effects from terminal child results. -- No child is replayed after reload. -- The outer result is settled by ToolExecutor; CodeModeBranch does not write a competing outer - result. - -The existing `ToolExecutor` rebuild settles the outer batch. The child-batch work extends the same -rebuild to the child batches and their terminal results. - -## 4. Questions and TUI - -- A child `ask_user` call is a normal `step/tool-call` batch with `parent_call_id`. The batch is - visible only to v4 clients; v1–v3 clients receive only the outer result and are not offered the - `codemode` tool. -- `session.question.pending` queries every `step/tool-call` with an `ask_user` call and no - `step/tool-result` whose `call_event_id` is that batch. Top-level batches and child batches use - the same query. -- The pending reply returns the batch event id, `request_id` and each child call id. -- `session.question.respond` uses `request_id` and the child call id; the waiter key is unchanged. -- ToolExecutor writes the answer as the child batch's `step/tool-result`. -- TUI displays events in `sequence` order. A v4 TUI groups the child batch under - `parent_call_id`; a child event whose parent is outside the loaded window is hidden, never - promoted to a top-level row. -- A child batch may hold one or more calls; parallel child calls may be separate child batches. The - pending query returns each batch; TUI queues `ask_user` calls in batch order, as TUI already does - for a model batch. -- TUI must not treat a child batch as a model request. `parent_call_id` is the distinction. - -## 5. Branch and Hooks - -- A child `branch` call is in a child `step/tool-call` batch. `BranchSource::Tool.call_id` is the - child call id; the child batch exists on the Timeline. -- Hooks read every `step/tool-call` call, including batches with `parent_call_id`, and report the - child call id as `tool_use_id`. Recall is not extended to child calls in this delivery; its - current model tool-use projection is unchanged, and the child-grouping claim is removed. -- Query results and hooks payloads must not filter child batches out. -- `branch` default `at` keeps the existing request cut: the branch tool finds the outer request's - `step/tool-use` and the preceding `step/model-start`. The child batch provides the source call, - not the cut. - -## 6. Approval and Permission - -Two authorization decisions exist: - -```text -outer codemode call - -> Permission / Approval for codemode's declared `session` risk - -child tools.call(name) - -> Permission / Approval for name's declared risk -``` +### Errors -Child approvals reuse `approval/request`, `approval/respond` and cancellation. -`ApprovalRequestData.source` is `BranchSource::Tool { call_id: childCallId, turn_id, request_id }`. -The child call id is present in the child `step/tool-call`, so v4 clients and Hooks resolve the -source. `approval_id` remains the only key accepted by the response operation. A response authorizes -only that child call; a response never authorizes a sibling, a future call or the outer `codemode` -call. - -A child approval and background result carry `parent_call_id = childCallId` on the event envelope. -A child `ask_user` batch carries `parent_call_id = outerCallId`, like every child `step/tool-call`. -The outer approval (when the outer call asks) has no `parent_call_id`. - -## 7. Storage and client compatibility - -- `parent_call_id` is an optional top-level property on `AgentEvent`; `ToolCallData` and - `ToolResultData` keep their current shapes. -- The native store advances by one format step for the new optional event property and the child - batch semantics. The step number is the next free number at implementation time; the marker table - `CHECK` and its single row advance, while business tables, columns, indexes and rows do not. -- An older binary refuses the newer marker, preserves the store byte-for-byte and never downgrades. -- v1, v2 and v3 clients never receive child `step/tool-call`/`step/tool-result` events. The App - Server filters them at the wire boundary; their event allowlists and outer tool projection are - unchanged. They are also not offered the `codemode` tool, because a child `ask_user` or child - approval could not be surfaced. -- v4 clients receive child batches with `parent_call_id`. They must group the child under its - parent or hide it; rich child detail is optional. -- The upgrade/downgrade fixture includes a top-level batch, a child batch, a child result and a - child background result. The v3 projection fixture proves the child events are absent and the - outer events still reach the client; the v4 fixture proves the parent property is present. - -## 8. Dependencies - -| Dependency | Scope | Consumer | Purpose | -| --- | --- | --- | --- | -| `partRegistry` | Process | `CodeMode` | Register `CodeModeSession` and `CodeModeBranch`. | -| `CodeModeRuns` | Process | `CodeModeSession`, `CodeModeBranch` | Resolve the calling Session and branch's runner; the process plugin provides it. | -| `toolRegistry` | Session | `CodeModeSession` | Register the `codemode` tool. | -| `ToolExecutor` | branch | `CodeModeBranch` | Read the pinned declarations, submit child `step/tool-call` batches, run child calls and join the parent gate. | -| `TimelineIdentity` | branch | `CodeModeBranch` | The calling Session id and branch id. | -| `rquickjs` | library | `CodeModeBranch` | The QuickJS runtime and the `tools` bridge. | - -The plugin does not depend on `ToolHost`, a handler registry, a second event bus, direct Session -facade access or a Node/TypeScript runtime. - -## 9. Requirements raised to mechanism owners - -### R1. ToolExecutor child batches and parent gate - -| Field | Content | +| Kind | What the caller does next | | --- | --- | -| Problem | A branch part must run an adopted tool while its own outer tool call is current. Calling a handler or `ToolHost` directly bypasses the pinned binding and Permission. A second top-level `step/tool-call` makes Loop and ToolExecutor treat the child as a model batch. | -| Existing mechanisms considered | `ToolBinding.handler` alone bypasses Approval; a second top-level `step/tool-call` fails with "concurrent tool batches"; a Session-side registry read is not the request snapshot. | -| Generic capability | A branch-scoped nested invocation service that writes child `step/tool-call` batches with `parent_call_id`, executes the child calls through the request-pinned binding, Permission and Approval, writes child `step/tool-result` events, and exposes `open`/`invoke`/`close` to the caller. The service refuses a call when the outer batch is closed, interrupted or not the current batch; a closed or interrupted executor never exposes the nested surface. | -| Sequence, batch, interruption and reload | Child batches do not take a model batch slot. The parent gate closes admission and waits for every committed child before the outer result. Cancellation uses a per-program child token; Approval admission has a drop guard that removes a pending request and writes `approval/cancelled`. Reload uses the rule in §3.6: terminal child results are used; started-but-unfinished children fail; the outer call fails with the effect-may-have-happened warning and confirmed child effects. | -| Owner and issue | Dim runtime / ToolExecutor mechanism owner; [#1276](https://github.com/arcships/dim/issues/1276). | +| `invalid` | Fix the program: it exceeds the code byte limit | +| `closed` | The line's run owner, the executor or the process quota is unloading; the next generation serves the next call | +| `interrupted` | The turn was interrupted before the gate existed; the run answers a cancellation result | +| `gate_closed` | The parent call settled or the batch was interrupted before the run closed the gate; the program's next child call fails and the run ends with the effects the parent already carries | +| `cancelled` | The call stopped where the caller cancelled; committed children are reported in the effects | +| a failed program (a result, not an error) | The model reads the failure text and the warning; it checks the effects before retrying | -### R2. QuickJS execution boundary +## Exceptions with reasons -| Field | Content | -| --- | --- | -| Problem | A model-supplied program cannot be safely run with `eval`, Node or the trusted plugin process. The engine must have no host capability except the tool bridge. | -| Existing mechanisms considered | The `rquickjs` native QuickJS binding, `AsyncRuntime`/`AsyncContext`, `Promise`-wrapped host functions, `set_memory_limit` and `set_interrupt_handler`. | -| Generic capability | One fresh QuickJS context per call with only `tools.list`, `tools.describe` and `tools.call`, a hard memory limit, a wall-clock interrupt and a child cancellation token. A separate native host process is a future hardening. | -| Sequence, batch, interruption and reload | The context is dropped after the program's promise settles. A dropped child token settles a child Approval or question. Reload settles the outer call through ToolExecutor; no child is replayed. | -| Owner and issue | Runtime/host mechanism owner; [#1276](https://github.com/arcships/dim/issues/1276). | +- One QuickJS context per call, in the line's scope: the program is model-supplied code, and the line is the smallest scope that still holds the request's pinned tools. +- The child gate stays inside ToolExecutor: admission, child facts, effects and the terminal result are that owner's; Code Mode opens the gate, invokes by id and closes it once for its result text, and the owner's settlement remains the backstop. +- The program's failure is data on the tool result, not an operation error: the model must read it and decide, and the outer result is the only model-visible outcome. +- A recursive `codemode` call is refused by the pinned set, not by a second check: the program's tool list excludes the tool itself. +- The v4 client gate is the entry's declaration: v1–v3 clients could not surface a child `ask_user` or a child approval. -### R3. Questions child batches +## Verification -| Field | Content | -| --- | --- | -| Problem | The TUI question path assumes every `step/tool-call` with `ask_user` is a model batch. A child `ask_user` call is a `step/tool-call` batch with `parent_call_id`; the current TUI does not receive or group child batches, so the prompt cannot be shown or answered reliably. | -| Existing mechanisms considered | The existing pending query already selects `step/tool-call` rows; the waiter table and `session.question.respond` key already use `request_id` + `call_id`. | -| Generic capability | The pending query includes child batches; the reply returns the child call id; TUI receives child batches, displays them in sequence order and queues `ask_user` calls. | -| Sequence, batch, interruption and reload | The child batch is visible only to v4 clients, and only v4 Sessions are offered `codemode`. The waiter key is `(branch, request, child call id)`. The child result closes the batch. Reload settles a waiting child through ToolExecutor's failure rule. | -| Owner and issue | Questions owner; [#1276](https://github.com/arcships/dim/issues/1276). | +Flow tests through the public interfaces: -### R4. Branch and Hooks child batches +- A program calls a pinned tool and the outer result carries its value; a child result reaches the program whole. +- A child `ask_user` waits and returns the answer; a child approval names the child call; a denied child is a catchable program error. +- A completed child's effect survives the parent's reload; an open child fails when ToolExecutor reloads; no child is replayed. +- A synchronous loop is interrupted; a never-settling promise times out; the call budget, the parallel limit, the code limit and the single-result limit are enforced. +- Two Sessions with `main` lines keep their own runs; a third program waits for a slot and is released by cancellation. +- The `codemode` tool is declared only to v4 Sessions, and a program cannot call `codemode`. -| Field | Content | -| --- | --- | -| Problem | Branch source lookup and Hooks `tool_use_id` assume every call is in a top-level model batch. Recall keeps its separate model tool-use projection. | -| Existing mechanisms considered | The child call is a normal `step/tool-call` batch with `parent_call_id`; the call id is unchanged. | -| Generic capability | Branch and Hooks read every `step/tool-call`, including child batches; `BranchSource::Tool.call_id` and `tool_use_id` use the child call id. Recall keeps its model tool-use projection; child Recall is a separate design. | -| Sequence, batch, interruption and reload | Child batches are terminal before the outer result; reload uses the child result written by ToolExecutor. | -| Owner and issue | Branch and Hooks owners; [#1276](https://github.com/arcships/dim/issues/1276). Recall child grouping is a separate design. | +## Supersedes -### R5. Event envelope, storage and v1 projection +- This document's earlier shape sections: the process runner map, the runner trait and the executor wrapper are replaced by `codeMode.with_slot` and `codeModeLine.run`. The tool contract, the child batches, approval and the client boundary remain as described in [child tool batches](../appserver/child-tool-batches.md) and in this document's contract sections. +- [runtime-owner-operations.md](../contracts/runtime-owner-operations.md): the Code Mode row that reads `toolBinding.definitions`; the run reads `toolBinding.adopted`. -| Field | Content | -| --- | --- | -| Problem | `step/tool-call` and `step/tool-result` need a parent relation; the retrieval layer must distinguish child batches without decoding `ToolCallData`; v1 and v2 projections must not expose the new envelope property. | -| Existing mechanisms considered | An optional top-level `AgentEvent.parent_call_id`; the existing `step/tool-call`/`step/tool-result` shapes. | -| Generic capability | The event envelope carries optional `parent_call_id`; the native store advances one format step; v1–v3 projections omit parented events at the wire boundary; v4 clients and TUI read the property. | -| Sequence, batch, interruption and reload | The property is written at commit time with the event; the upgrade/downgrade fixture covers a top-level batch, a child batch, a child result and a child background result. | -| Owner and issue | Timeline/event and App Server owners; [#1276](https://github.com/arcships/dim/issues/1276). | +## Client-visible changes + +None. The `codemode` tool keeps its name, description, schema, risk and v4 gate; child batches and the outer result are unchanged; the gate is still opened and closed by ToolExecutor. -## 10. Rule check +## Rule check -| Rule | How this design complies | +| Rule | Application | | --- | --- | -| §1 Capability boundary | `CodeModeBranch` is a branch part with runtime-only execution state, not a Capability in this delivery. `CodeModeSession` only registers a tool; `CodeMode` only owns process configuration and registrations. | -| §4.1 split by state owner | Process owns `CodeModeRuns`, the program semaphore and the bounds; Session owns the tool declaration; Branch owns the one-shot QuickJS execution and parent gate use; ToolExecutor owns child batches, admission and terminal facts. | -| §4.2 command and handoff | A child `step/tool-call` with `parent_call_id` is the durable handoff command. The parent gate closes admission and joins every committed child before the outer result. | -| §4.3 handlers register work and return | The `codemode` handler awaits the QuickJS program and the parent gate; the branch owns runtime waiters and settles them before returning. | -| §4.4 core mechanism has no business meaning | The nested invocation service and `parent_call_id` are generic; the contract names no Code Mode type. | -| §4.5 atomic batches and ordered dispatch | Child batches are committed and dispatched in sequence. The outer batch stays current; child batches do not take the model batch slot; the outer result is committed once. | -| §4.6 context boundary | Child results never enter context. Only the outer `step/tool-result` is model-facing; a value the model needs is in the outer `content`. | -| §4.7 public interaction | The plugin uses `ToolExecutor`, `ToolRegistry`, `CodeModeRuns` and `rquickjs`; it receives no handler or ToolExecutor internals. | -| §4.8 infrastructure requirements | R1–R5 state the existing mechanisms, the generic additions, cancellation/reload behavior and the owners. | -| §4.9 facts in Timeline | Every child call has a durable `step/tool-call` command and a terminal `step/tool-result`; child effects travel on the child result and the outer result. | -| ADR 002 D1 | Process `CodeMode`, Session tool, Branch execution and ToolExecutor each own their own state. | -| ADR 002 D2 | No wiring plugin, second bus or lifecycle manager is added. | -| ADR 002 D3 | Dependencies point from Code Mode to existing core contracts and ToolExecutor; core does not depend on the optional crate. | -| ADR 002 D4 | Bounds are structural `CodeModeConfig`; a user Settings source is deferred. | -| ADR 002 D5 | The child-batch, nested invocation and QuickJS contracts are Rust data/error shapes; the binding does not leak into the design. | - -Ablation: this design keeps the existing `step/tool-call`/`step/tool-result` shapes, adds only the -optional envelope property, reuses the existing Approval and Questions waiters, and gives child -effects one path: the child result. A separate child event type, a second tool registry, a -persistent REPL, a separate host process and a user settings source are not part of this delivery. - -## 11. Binding appendix - -The following is semantic pseudocode, not a committed spelling. - -```text -CodeMode::apply(ctx): - runs = Arc - ctx.provide(runs) - partRegistry.register(Session, "CodeModeSession", |names| CodeModeSession::new(names)) - partRegistry.register(Branch, "CodeModeBranch", |names| CodeModeBranch::new(names, config)) - -CodeModeSession::apply(ctx): - session_id = sessionIdentity.session_id - tools.register(declaration = { - name: "codemode", - risk: "session", - inputSchema: { code } - }, handler = |call, context, cancel|: - runner = runs.get(session_id, context.branch_id) or error - runner.run(call.id, call.code, context, cancel)) - -CodeModeBranch::run(outer_call_id, code, context, cancel): - child_cancel = cancel.child_token() - program_slot = runs.acquire_program(child_cancel) or error - runtime = AsyncRuntime::new(); runtime.set_memory_limit(max) - runtime.set_interrupt_handler(deadline || child_cancel) - quickjs = AsyncContext::full(runtime) - gate = toolExecutor.open(outer_call_id) - result = try: - quickjs.async_with(|ctx|: - install tools.list / tools.describe from executor.definitions(context.request_id) - install tools.call = Async(|name, args| gate.invoke(ToolCall{name, args}, context, child_cancel)) - promise = ctx.eval(async function body) - return promise.into_future()) - finally: - child_cancel.cancel() - gate.close(reason) - drop(program_slot) - return ToolResult { content: JSON(result), effects: collected_effects } +| §1 parts and Capabilities | The process part owns the bounds and the slots and registers the two parts; the Session part registers the tool; the branch part runs the program. No part folds state, so none is a Capability. | +| §2 scopes | The bounds and slots are process state; the declaration is Session state; the QuickJS context is the line's. | +| §3 orthogonality | Code Mode reads the pinned declarations and invokes tools through ToolExecutor; it returns no other owner's data. | +| §4 rule 1 (commands) | Child calls are ToolExecutor's commands; Code Mode writes no Timeline fact. | +| §4 rule 2 (handover) | The gate is ToolExecutor's; Code Mode holds it only for the run and closes it before answering. | +| §4 rule 3 (before callbacks) | None registered. | +| §4 rule 4 (no business meaning in core) | The tool, the bounds and the program text are Code Mode's; ToolExecutor's nested operation names no Code Mode type. | +| §4 rule 5 (batches) | The outer batch stays current; child batches do not take a model batch slot. | +| §4 rule 6 (context) | Only the outer result is model-visible; child results reach the program. | +| §4 rule 7 (public events and services) | The registry, the line's owners and ToolExecutor's operations; no handler or executor internals. | +| §4 rule 8 (requirements) | The line-id provider is the open one; #2028's contract covers the nested invocation. | +| §4 rule 9 (facts) | Child calls and their terminal results are facts; effects travel on the child result and the outer result. | +| §7 values, ids and callbacks | The run takes data and a callback; the quota takes the caller's work as a callback; the gate is an id for `invoke` and `close`, and the owner closes it at settlement; no object crosses. | +| §7 no proxy lookup | The entry does not hold a run table; it asks the call's line. | +| §7 one interface | One tool contribution, one run operation, one quota operation; no adapter, no runner trait. | +| §7 cross-language | The tool, the run and the quota are data and callbacks; the program's bridge is `tools.list/describe/call`. | +| §7 one change | Deleting the process runner table, the runner trait and the executor wrapper happens in the same change that adds the quota operation and the line's run operation. | +| ADR 002 D1 | Slots are process state; the run is line state; the declaration is Session state. | +| ADR 027 D1–D3 | The tool handler reaches `codeModeLine` and the line's ToolExecutor by the line id on its execution context; the resolution is not a dependency and is not kept across calls. | +| ADR 027 D2 | `codeModeLine` and ToolExecutor are branch data faces; no registration point or lifecycle service is resolved by id. | +| ADR 002 D2 | No wiring plugin: both operations are on their owners' types; the mechanism resolves the line. | +| ADR 002 D3 | Dependencies point from Code Mode to the registry, the mechanism and ToolExecutor. | +| ADR 002 D4 | The bounds are structural configuration; no business setting is read. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +- [TimelineTree #2024](https://github.com/arcships/dim/issues/2024): the cross-cutting decision names this owner's contract as the place that fixes who provides the line-id operations to Session parts. Code Mode needs two: a Session-registered tool handler resolving `codeModeLine` by the line id on its execution context, and the run resolving the line's ToolExecutor. SessionScope's contract has no such operation. +- [The branch tool chain #2028](https://github.com/arcships/dim/issues/2028): none open; `open`/`invoke` and `toolBinding.adopted` are what this contract calls ([#2100](https://github.com/arcships/dim/pull/2100)). +- The line's timeline owner (runtime): child `step/tool-call` and `step/tool-result` batches carry `parent_call_id`; the v1–v3 projection omits them. + +## Binding appendix + +The process part provides `codeMode`; the branch part provides `codeModeLine`; the Session part registers the tool. Request, reply and error types are data; `cancelled` is the binding's cancellation argument. + +```rust +use rutis::host::BoxFuture; + +#[rutis::service] +impl ProgramSlots { + /// Run `work` while holding one process program slot; `caller` binds the + /// slot to the calling row, so the owner releases it at that row's unload. + pub async fn with_slot( + &self, + caller: &Ctx, + work: impl Fn(CancellationToken) -> BoxFuture<'static, Result<(), ServiceError>> + Send + Sync, + cancelled: CancellationToken, + ) -> Result<(), ServiceError>; +} + +/// The service error shape of every data face: `{code, message, data?}`. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{message}")] +pub struct ServiceError { + pub code: String, // "closed" + pub message: String, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunProgram { + pub outer_call_id: String, + pub code: String, + pub context: ToolExecutionContext, +} + +/// `RunError` is the same `{code, message}` shape: `invalid`, `closed`, `cancelled`. ``` -The host adds the process row with `dim_codemode::install`; `install_required` also makes both -parts required for a Session that must publish only after the tool is registered. The product -profile may install the plugin by default once the v4 protocol, TUI/web grouping and the -`AgentLoop` rebuild filter in [child tool batches](../appserver/child-tool-batches.md) land. The -Session gate keeps `codemode` out of v3 connections even when the plugin is installed. +`ToolExecutionContext` and `ToolResult` are `dim_agent_types`' types; `ServiceError` is the same `{code, message}` shape every data face uses; the child operations are ToolExecutor's ([#2028](https://github.com/arcships/dim/issues/2028)). diff --git a/docs/design/plugins/Goal.md b/docs/design/plugins/Goal.md index f44b2a1eb8..1a43b81368 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -1,274 +1,227 @@ # Goal -Status: Draft. -Scope: 既有 Goal Session/branch 部件的目标、命令、续行、模型输入和终止。 -Issue: [#1320](https://github.com/arcships/dim/issues/1320)。 +Scope: branch state with a Session entry. Issue: #2033 (this contract); #1320 (the goal feature). Evaluator judgement is a mode of this owner, described in [Pursuit](Pursuit.md); the state object and its reload mapping are in [Goal-state-read.md](Goal-state-read.md), and the two places where this contract supersedes that document are named below. -[业务状态与重载](Goal-state-read.md)唯一规定完整状态数据、内存与持久化边界、加载映射、原子提交、成本和验收。[读取与输入删除](Goal-property-queries.md)规定旧历史不恢复及输入删除不回滚的边界。本文规定 Goal 的入口、执行规则和模型协议;[Pursuit](Pursuit.md)规定 evaluator 判定方式。当前代码和生成装配图不因设计更新而宣称已实现目标。 +Goal owns the goal of one line: the objective, the judge, the status and the reason it changed, the decisions that follow, and the model-visible texts that state them. A Session part registers the commands; a branch part holds the state. The current shape is the one #2033's scan report describes. -## 1. Structure +## Use and scope: responsibility split -Goal 属于一条分支。Session 部件注册命令和工具,branch 部件拥有目标、当前执行和异步任务。依赖及作用域遵守 [ADR 002](../../adr/002-plugin-scope.md)、[插件合同](../plugin-contract.md)和 [rutis](../rutis-usage.md)。 +Goal owns: -| 部件 | 依赖和职责 | -| --- | --- | -| GoalSession | TreeCommands、ToolRegistry、SessionMethods、GuideEntries、SessionIdentity;注册 goal_update、session.goal 和模型 guide。入口按 Session 与 branch 身份路由本插件拥有的 branch 处理句柄,不持有分支业务状态。 | -| GoalBranch | Dispatcher、Timeline、TimelineIdentity、BranchLifecycle、SessionLifecycle、TreeCommands、Settings;拥有状态、决定、业务事件和自己的任务。 | - -分支内写业务状态用声明的 timeline;普通 continuation 和评估分支操作沿用原输入/TreeCommands 服务。没有新公共分支服务、Store 依赖或恢复协调模块。部件在 apply 注册清理及服务,实际消费和任务遵守 activated/closing;关闭完成必要终态后才移除服务。 - -maxContinuations 仍是 Settings 的 goal 源中的可选业务字段,范围 1..=1000,缺失表示无限额。每次决定通过 Settings 读取;不增加默认限额、缓存或重载配置机制。 - -## 2. Data and state - -Goal 有两个不同的对象: - -- 持久业务状态:一个完整目标、判定方式、active/paused/completed/blocked/none 及原因或说明。每次真实业务变更写一个 goal/state。 -- 本实例执行:次数、轮次、当前输入/任务、评估配对、待执行决定和写入协调;全部在内存。它们不因每个事件到达而保存。 - -业务事件结构和加载映射见 [状态设计 §2](Goal-state-read.md#2-保存对象)与[§4](Goal-state-read.md#4-get-与冷恢复)。active 是持久记录中的状态,running 是当前实例实际在执行;重载可使最后记录仍为 active、当前状态已经 paused。 - -| 命令或结果 | 本次有效业务变化 | -| --- | --- | -| set | 新目标与 judge,active;开始新执行,次数归零。 | -| edit | 替换目标,保留有效状态和 judge;不启动暂停中的目标。 | -| pause | paused,reason=user;停止后续自动推进。 | -| resume | active,开始新的执行;不复活旧轮次、计数、评估或决定。 | -| clear | objective=null,state=none;终止当前 Goal。 | -| goal_update completed / blocked | model judge 下完成/阻塞;evaluator judge 下 completed 只是本次执行的评估请求,状态保持 active。 | -| evaluator 的有效 done / blocked | 完成/阻塞当前目标。 | -| 中断、失败、取消、限额、无进展、评估失败、可控卸载 | 结束正在执行的 Goal,写 paused 和原因。 | -| continuation、普通输入、任务和轮次变化 | 本实例内存变化,不写 Goal 状态事件。 | - -Goal 命令的模型状态输入与 trigger 仍紧邻,状态输入在前;结构化业务事件同批置后。状态只在提交成功且按序消费后可见;后一个命令等待先前本插件写入已消费,不能对旧目标组成下一条状态。设置和恢复的 Queue 输入仍驱动第一轮;evaluator 完成申请不产生假的目标状态变更。 - -## 3. Flows - -### 3.1 Set and continue - -~~~mermaid -sequenceDiagram - actor U as 用户 - participant S as Goal Session 入口 - participant G as Goal branch - participant T as Timeline - participant L as InputQueue / Loop - U->>S: session.goal.set - S->>G: 校验并路由到本 Session 的 branch - G->>T: append_batch:模型状态输入、trigger、goal/state - T-->>G: 提交成功并按序派发 - G->>G: running,初始化本次执行 - T-->>L: 采用输入并执行 - L->>T: turn/end - T-->>G: 当前轮次完成 - G->>G: 检查本实例状态、Settings、进展 - G->>T: 原 continuation 输入 - Note right of G: 次数变化只在内存,不写恢复事件 -~~~ - -### 3.2 Completion through goal_update - -工具先校验外部参数,再由 Goal branch 组成目标变化。model judge 下,模型状态输入、completed trigger 和完整 completed 业务事件原子提交。evaluator judge 下只登记本次执行的完成申请;创建评估、等待报告不写恢复快照。只有有效评估结果才决定 completed/blocked,见 [Pursuit](Pursuit.md)。 - -### 3.3 Interrupt pauses the goal - -turn-scope stop/interrupt、执行失败或取消使正在运行的 Goal 停止新的自动决定。Goal 的 owned task 取消并结算自己发起的工作,写 paused 与必要模型状态输入。已经交接的输入和已经开始的模型/工具工作按各自所有者规则结算;Goal 不直接撤回它们。 - -### 3.4 A new branch clears the inherited goal - -子分支和 fork 从本地 branch/start 或 session/forked 开始,不能继承父分支/复制前缀的 Goal 执行或目标。继承 key 仍存在时,沿用原 start clear 退休这些模型可见 key。清理在 publication 后作为 Goal 自己的任务完成;它不是恢复父分支执行。 - -## 4. Timing and conflicts - -### 4.1 Interrupt committed before the continuation (at most one extra turn) - -决定只使用已消费事实,写入前重查同一轮次和执行。中断与已经提交的 continuation 交错时,不抹去已提交事实;后续暂停阻止新续行。已经交接的工作允许按原交接规则完成结算,不为了保证零额外调用而改变 InputQueue/Loop。 - -### 4.2 Reload - -加载行为唯一见 [Goal 状态设计](Goal-state-read.md#4-get-与冷恢复):最后 active 映射为内存 paused,不写回、不读取旧轮次和次数、不补答旧决定、不恢复旧评估。set/resume 才开始新执行。 - -Session/branch 部件的可控关闭会结束其正在运行的 Goal 并写 paused;进程直接崩溃或存储不可写时无法保证终态提交,由加载映射覆盖这一情况。客户端 detach、重连和查询不关闭原实例。 - -### 4.3 Other key rows - -| 场景 | 结果 | -| --- | --- | -| 普通操作员输入 | 仅在本实例内重置 count/idle,使旧延后评估失效;不写归零事件。 | -| 待消费 Queue/Steer 输入 | 暂不自动续行;不将其列表写进 Goal 状态。 | -| 有未结束后台任务 | 在本实例等待,取消结束可唤起一次仍有效的决定;重载后不重建这项等待。 | -| Goal 命令输入被删除 | 仅移除本实例待输入 ID;已提交目标不变,零查询、零补偿写入。 | -| 重载后到达旧评估报告 | 不在当前执行的配对表中,不能完成或续行目标。 | -| paused 后 edit | 仍 paused;必须显式 set/resume 才运行。 | -| clear 后加载 | 没有目标,不读取更早目标复活它。 | -| 未知或损坏新状态 | 返回错误,不冒用更旧状态。 | - -## 5. Context mapping - -goal/state 不进入模型上下文。Goal 仍通过采用输入提供模型文本,不能通过请求准备注入内存状态。 - -| 对象 | 模型含义 | -| --- | --- | -| goal:state | 完整目标及这次业务变更时的状态。历史 active 只证明当时开始过执行。 | -| 新 set/resume trigger | 当前输入中的明确开始/恢复请求。 | -| 新 continuation | 当前执行驱动下一轮的请求。 | -| completed/blocked/paused 记录 | 当时已经确认的结束/暂停状态。 | -| 子分支的 start clear | 继承目标不属于本线,不在本线继续或完成它。 | +- **The goal of a line.** One objective, the judge that decides completion, the status (`active`, `paused` with a reason, `completed`, `blocked`, or none) and the moment it last changed. The state belongs to the line and ends with it. +- **The decisions that follow a fact.** After a turn ends: continue, stop at the optional continuation limit, stop after three turns without progress, or ask for an evaluation. On an interrupt, a failed or cancelled turn, or an unload: pause with the reason. When a child line starts: retire the keys of an inherited goal. +- **The texts the model reads.** The `dim-goal` marker's command block, state block and continuation, and the guide entry that explains them. +- **The commands' vocabulary.** `set`, `edit`, `pause`, `resume`, `clear` and the completion report, their parameter rules, and the two entry points that carry them (`session.goal.*` and the `goal_update` tool). +- **The evaluator line's purpose.** Goal asks TimelineTree to open a child line cut at the turn end and closes it with the operation id it wrote. -guide 和 active 文本不能把历史 active 解释为当前实例的运行授权。当前状态来自 Goal owner;历史页和模型历史保留当时事实。重载只在内存暂停,不补造一条模型上下文输入。 +Callers keep as business: -## 6. Interfaces (summary) +- Which line a command names; a client that names none means the conversation line. +- Which command and its parameters; the operator's presentation of the goal. +- History: a client that shows the goal of an ended line reads that line's facts and folds them itself. -公开入口仍为 session.goal.set/edit/pause/resume/clear/get 和工具 goal_update;参数、GoalRead 和命令 sequence 返回保持原接口。[Appendix A](#appendix-a-interface-details)列出合同。无 Goal 数据库或专用查询机制。 - -## 7. Security - -所有入口按 Session 身份及分支校验路由,不能通过参数切换到其他 Session。Goal 不授予执行权限,实际模型/工具仍遵守 Session 的 Permission/Approval。普通用户不能提交任意 raw Goal 块;生产者转义目标和说明。诊断不记录目标正文或凭据。 - -## 8. Rule check - -| 规则 | 本设计 | -| --- | --- | -| principles §1 | Goal branch 是 Capability;Session 部件是入口,不把所有部件统称 Capability。 | -| §4.1、§4.2 | 不写别的所有者的结果,不回收已交接输入;删除按 InputQueue 的事实。 | -| §4.3、§4.4 | 无 before I/O;核心不解释 Goal。 | -| §4.5 | 业务状态和必要输入同批提交,Dispatcher 按序消费,任务写前重查。 | -| §4.6 | 模型内容只经采用输入,不注入内存状态。 | -| §4.7、§4.8 | 已声明的现有服务,无核心机制新增。 | -| §4.9 | 业务状态及实际驱动输入持久化,执行进度不落盘。 | -| ADR 002 D1 | Session 注册工具/方法;目标、执行和任务归 branch。 | -| ADR 002 D2 | 不增加接线模块或全局隐式资源。 | -| ADR 002 D3 | 扩展依赖核心,Session 不持有分支业务状态。 | -| ADR 002 D4 | goal Settings 是业务配置,不触发部件重载。 | -| ADR 002 D5 | 事件、状态、入口和错误为语言中立合同;Rust 名字在绑定附录。 | - -## 9. Requirements raised to mechanism owners - -无。Goal branch 使用已有 append_batch、Dispatcher、生命周期及属性查询。完整业务事件是扩展数据,不新增核心事件类型、查询字段或 native 格式版本。 - -## 10. Implementation - -修改对象和验收见[状态设计 §6–§7](Goal-state-read.md#6-成本和修改落点)。保留既有 GoalSession/GoalBranch 装配、Settings、参数校验、文本编码及产品流程;移除运行对象序列化、逐事件 checkpoint、恢复节点、源后缀重放和每输入删除边界。当前实现状态由 issue 和实际代码记录,本文不把旧测试通过等同于新状态机完成。 - -## Appendix A. Interface details - -### A.1 Tool goal_update - -Session 的 ToolRegistry 注册 goal_update,risk=session;参数为 status=completed|blocked、summary,summary 长度 1..=2000。调用方分支由 ToolCall 身份确定。返回 ToolResult.content 为 goal_update recorded: completed. 或 goal_update recorded: blocked.;确认提交,不把评估请求误报为目标已完成。取消发生在提交前不写入,提交后事实保留。 - -### A.2 Session methods - -namespace 为 session.goal,mutating 方法 interruption=report、progress=false;get 的 mutating=false。branchId 默认 main。 - -| 方法 | 参数 | 结果 / 行为 | +| Requirement (caller) | Can callers compose it from the owner's operations without breaking the owner's invariants? | Handling | | --- | --- | --- | -| set | sessionId、branchId?、objective、judge? | {sequence};judge=model(默认)或 evaluator,目标 1..=4000 字符。 | -| edit | sessionId、branchId?、objective | {sequence};保留当前有效状态及 judge,不启动暂停目标。 | -| pause | sessionId、branchId? | {sequence};用户暂停,Append。 | -| resume | sessionId、branchId? | {sequence};Queue,新的执行、次数归零。 | -| clear | sessionId、branchId? | {sequence};清除并终止当前执行。 | -| get | sessionId、branchId? | 原 GoalRead,见 A.3。 | - -Session 入口校验参数和 Session 身份,Goal branch 决定状态并提交原子批次。sequence 仍是命令 trigger 的位置;结构化业务事件不改变它。没有目标时保持原命令的空目标结果,不凭空创建目标;没有生效变化不写伪造的业务状态。 - -### A.3 Reading the goal - -返回 {branchId, through, goal};goal 为 null 或 {objective, status, evaluator}。status 为 {kind:active|completed|blocked|none} 或 {kind:paused,reason},保持 GoalRead 的既有外部类型。 - -活分支等待本次入口固定位置已消费后返回内存;不因 source_through 或新的持久事件等待。重载后的 active 记录返回有效 paused,reason=interrupted_reload;不能把持久历史页当作当前状态。无活 owner 时读取最后本地业务状态并应用加载映射。普通路径读取一个 Goal 状态对象;没有 goal/state 就没有当前 Goal,删除输入不改变已提交状态。 +| A client submits a goal command for a line | No: the command must reach the line's input owner in order, and the resulting state is the owner's | the Session entry writes one command input to the line | +| The model reports completion or blockage | No: the report changes the goal, and its line is the call's line | the tool handler writes one command input to that line | +| A client reads the goal of a line | No: the goal is the line owner's state and nothing else publishes it | `goalLine.read` at the line id | +| The owner states the state to the model | No: the state block restates the whole goal and the live keys when it changes | the branch owner writes the state record input | +| A command is retried after a lost reply | No: accepting a command once is the input owner's rule | the submission id on `submit` | +| A client shows the goal of an ended line | Yes: the line's facts stay readable at its fixed head and the fold is the client's projection | business composes with TimelineTree's `read` | +| A client reads the conversation line's goal without naming it | Yes: the line record carries the Session's current line | business composes with TimelineTree's `directory` | +| The owner continues a goal after a turn | No: the decision uses the owner's fold, counters and tasks | branch-internal | + +An operation or parameter exists only where its row says No. + +## Caller example + +`session.goal.set` writes one command input to the named line; the branch owner decides and states the result. No object, no sequence, no wait. + +```rust +// The entry checks its own parameters and resolves the line a client left unnamed. +let line = match command.line { + Some(line) => line, + None => tree.directory()?.default, // TimelineTree's shape (#2092) +}; +let _ = tree.line(LineRequest { line: line.clone() })?; // unknown_branch for a line that does not exist +// Goal's own text: the command block carries the operation, the objective and the judge. +let input = goal_command(&line, &command); +line_owner::(&line)? + .submit(input, cancelled) + .await?; +// The reply is the input's position; nothing else is returned and nothing is released. +``` + +`session.goal.get` reads the line owner's published value; the caller decides what "no owner" means for its screen. + +```rust +let goal = match line_owner::(&line) { + Ok(owner) => owner.read().await?, + Err(NoInstance) => return Err(AgentError::Reloading("Goal".into())), // service_reloading +}; +// `goal.objective`, `goal.status`, `goal.evaluator`, `goal.through`; history is read from facts instead. +``` + +`goal_update` writes a report input to the call's line: + +```rust +let line = execution.line.clone(); // the call's line, a value +line_owner::(&line)? + .submit(goal_report(&line, status, summary), cancelled) + .await?; +``` + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| TimelineTree ([#2024](https://github.com/arcships/dim/issues/2024)) | `directory`, `line`, `read`, `create`, `end` | The conversation line; one line's record for the named line; an ended line's facts; opening and closing the evaluator line | +| The line's input owner ([#2027](https://github.com/arcships/dim/issues/2027)) | `submit` | The command input and the state record input | +| The line's timeline (branch runtime) | `append` | The business fact recovery reads | +| Dispatcher, BranchLifecycle, TimelineIdentity (branch runtime) | facts, activation, closing | Folding the line's facts and the branch part's lifetime | +| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `phase` | Not ending evaluator lines while the Session is closing | +| Settings ([#2017](https://github.com/arcships/dim/issues/2017)) | `register`, `read` | The `goal` source's optional `maxContinuations` | +| Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `sessionMethods.register`, `toolRegistry.register`, `guideEntries.register` | The commands, the tool and the guide entry | -缺失分支、存储失败和未知 schema 仍是错误;取消读取返回 operation_interrupted,不取消已经接受的命令。详细范围见[状态读取](Goal-state-read.md#4-get-与冷恢复)。 +The line-id operations that `line_owner` names are the ones the cross-cutting decision puts in TimelineTree's contract ([#2024](https://github.com/arcships/dim/issues/2024)); SessionScope's contract has no such operation. -### A.4 Continuation decision +### Operations -只在本实例 running 时对新事实做决定;计数、轮次、去重和等待仅存在内存。 +The entry's operations are the five commands, the read, the tool and the guide entry; the branch owner's operation is one read. -| 条件 | 不满足时 | -| --- | --- | -| C1:当前有效目标存在且在运行 | 不自动工作。 | -| C2:本次执行未被中断 | 终止并写 paused(interrupted)。 | -| C3:本轮正常完成 | 失败/取消时终止并写 paused(turn_failed / turn_cancelled)。 | -| C4:这是本实例当前待决定轮次,尚无决定且无新轮次打开 | 不重复决定。 | -| C5:无待消费驱动输入,且无未结束后台任务 | 在本实例等待,不写恢复状态。 | -| C6:未达到可选 maxContinuations | 暂停,reason=limit。 | -| C7:本轮非自动续行驱动,或调用过工具,或连续无进展轮数仍小于 3 | 暂停,reason=no_progress。 | +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `session.goal.set` | Start a new execution of a goal on a line | `{sessionId, branchId?, objective, judge?}` | `{sequence}`: the accepted input's position | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.edit` | Replace the objective, keeping status and judge | `{sessionId, branchId?, objective}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.pause` / `resume` / `clear` | Pause, resume or clear the goal | `{sessionId, branchId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.get` | The goal of a line now | `{sessionId, branchId?}` | `{branchId, through, goal?}`; the goal carries `{objective, status, evaluator}` | The wait for the owner's fold stops | `invalid_params`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `goal_update` | The model reports completion or blockage | `{status, summary}` | text in `ToolResult.content` | Before the input is submitted | the commands' codes, returned as an error result | +| `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | While the fold reaches the head | `closed` as the service error `{code, message}` | -满足条件时只写原 continuation 输入,更新内存 count/idle。count 在 set、resume 和操作员输入时在内存归零;操作员输入是有 user 内容且首 raw 块不带来源标记的输入。其它插件自动输入不重置。 +`invalid_params` covers what Goal itself checks: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `unknown_branch` is TimelineTree's `line` refusal; `branch_ended` is the input owner's refusal; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. Every code above is one the client already receives today. -C7 沿用一次本轮 step/tool-call 存在性查询;仅自动续行驱动且没有未结束任务时需要。没有工具调用则 idle+1,有工具调用或非自动续行驱动则为零。Pursuit 的 continue 已由评估判断,idle=0,不额外执行 C7。 +`goalLine.read` takes no request parameter: the line is the instance the mechanism resolved. Requests, replies and errors are data; `cancelled` is the binding's cancellation argument. -handler 只登记自己的任务后返回;网络、Settings 和查询等待在 owned task。写前重查当前执行/轮次。取消后台任务后本实例仍 running 时可以处理延后决定;部件重载不再恢复它。 +### Flows -### A.5 Model-visible texts +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `session.goal.*` write | Check parameters, resolve the line, compose the command input, submit it; the input owner commits it in order | Before submission nothing is written; after submission the input stays and the branch owner decides | Nothing to release: no id crossed | `closed` once the Session or the input owner is closing | the input owner; the entry holds nothing | +| `goalLine.read` | Wait for the branch part's fold to reach its head, answer the value | The wait stops; the value is unaffected | Nothing to release | `closed` when the part is closing | the branch part | +| Branch decision | Consume a command input, decide from the fold, append the business fact, append the state record, then write the continuation or ask for an evaluation | The line's closers end the branch part's tasks; an admitted input is not withdrawn | — | Closing cancels the tasks, writes `paused` with its reason, then the services are withdrawn | the branch part: its own tasks, the fact and the record; the input owner: the continuation it accepted | +| Evaluator line | Open a child line at the turn end with Goal's operation id; the evaluator reports a conclusion; Goal closes the line | The line's close stops the decision that would open it | — | On rebuild and on close Goal closes the evaluator lines it opened, before the Session closes | the branch part asks; TimelineTree creates, holds and closes the line | -沿用 dim-goal 标记、goal:state key、命令和 continuation 的原编码。状态输入 Append,set/resume/continuation 的驱动输入 Queue,其余命令 Append。命令状态输入仍在 trigger 前且原始序号紧邻,goal/state 置于两者之后;完成申请不改变状态时不伪造新的状态记录。 +The business fact precedes the state record: the fact is what recovery reads, the record is model-visible text. A crash between the two leaves the goal correct in recovery and one state block missing from history; the next change restates the whole state. This supersedes [Goal-state-read.md](Goal-state-read.md)'s one-batch command write; the state object, the load mapping and the property queries in that document stay. -目标及所有说明/属性仍转义 &、<、>、双引号;目标放在 objective 标签内,完成/阻塞说明分别放在 result/blocker 标签内。读取按标签边界逆向转义,不按正文标题拆分。沿用 4000/2000 字符限制,旧历史不重建当前 Goal,不修改冻结事件样本。 +### Errors -| 文本 | 合同 | +| Kind | What the caller does next | | --- | --- | -| 状态记录 | kind=state、key=goal:state;完整目标、judge、status 和原因/说明;命令配对仍使用 trigger,自动结果使用 after。历史 restated 不恢复当前 Goal,加载不写 restated。 | -| 命令 | kind=goal,op=set/edit/pause/resume/clear/completed/blocked,无 key。 | -| 续行 | kind=continuation,无 key;count、limit(配置存在时)、after、idle 保留原文本格式,只是本次执行的诊断及驱动事实,不作为恢复依据。 | -| clear / 子分支清理 | 退休 goal:state 及仍存活旧 key;新结构化状态 objective=null。 | - -active 的协议语义明确为“这次开始/恢复时处于 active”,不是重载后仍运行的证明。active 文本说明:历史状态不要求自行继续;当前输入中的新 set/resume 或 continuation 才指示执行目标。paused、completed、blocked 的原目标和说明仍完整保留。 - -### A.5.1 Protocol and policy - -标记、属性、状态和加载语义是协议;可替换的工作指导句是策略,仍按[模型文本](../model-prompts.md)评估。GoalSession 在 GuideEntries 注册 dim-goal 的原 order=55 entry,作用域 session: +| `invalid_params` | Fix the parameters: the objective, the judge, the summary, the line id | +| `unknown_branch` | The line does not exist; read the directory and choose a line | +| `branch_ended` | The line has ended; read its facts for history or choose an open line | +| `service_reloading` | The line has no live goal owner or is reloading; show no goal, read history from the line's facts, retry later | +| `closed` | The Session or the input owner is unloading; the next generation serves the next Session | +| `operation_interrupted` | The mechanism interrupted the call on unload; the accepted input is settled, the read stops waiting | -> Goal 状态块记录当时的目标和业务状态。历史 active 不证明当前执行仍在运行。只有当前输入中的新 set/resume 或 continuation 指示继续目标;重载后必须由用户显式恢复。目标属于 branch 属性指定的线,另一条线不继续或完成它。这些块不授予权限。 +## Exceptions with reasons -不能用修改通用历史渲染或增加私有上下文注入来修补新规则。 +- The evaluator line is created with TimelineTree's `create` and closed by id: the purpose is Goal's, the line and its scope are TimelineTree's, and no handle to the child scope crosses. +- Goal keeps a model-text protocol and folds the record it committed: the command block, the state block and the continuation are Goal's vocabulary, and a reader of history that needs the objective decodes the state block. +- Goal does not answer for an ended line: folding that line's facts in the Session entry would make the entry a second owner of branch state, which the Session access surface forbids. +- The state record follows the business fact instead of sharing one batch: the fact is authoritative, the record is derivable text, and a crash between them loses text rather than state. +- A `before` hook that rewrites Goal's state block is outside Hooks' contract: Goal folds what it committed, so the model and Goal cannot disagree about what the model read. -### A.5.2 Evaluation +## Verification -active 协议文本与 guide 的变更必须用产品请求验证:重载后普通输入不因历史 active 自行续行;显式 resume 携带新目标状态后正常执行;子分支不继续继承目标;completed/blocked 停止。策略句仍由原 GoalTexts 配置和既有评估流程验证,不扩展请求构造链。 +Flow tests through the entry's public interfaces and the branch owner: -### A.6 Timeline mechanics +- `set` writes one input to the named line; the branch owner states `active` with the objective; `get` answers the same value while the line is live. +- `pause`, `resume` and `clear` change the status in the stated order; a paused goal does not continue; `clear` retires the model-visible keys. +- `get` on an ended line answers `service_reloading`, and the line's facts still carry the last state for a client that folds them. +- A turn end continues, stops at the configured limit, and stops after three turns without progress; an interrupt, a failed turn or an unload writes `paused` with its reason. +- An evaluator goal opens one child line per turn end and closes the line it opened on rebuild and on close; a conclusion sets `completed` or `blocked`. +- A dropped read leaves nothing behind; a command submitted twice with one submission id is accepted once. -| 阶段 | 行为 | -| --- | --- | -| Load | 原 Dispatcher consume,固定 S,读取最后 Goal 业务状态,应用重载暂停,返回 S。旧源不重放。 | -| Consume | 只处理 S 后新事实。goal/state 改业务状态;普通输入/轮次/任务只更新本实例内存。 | -| Write | Goal branch 经 timeline.append_batch 提交状态与必要输入;原 continuation 和评估操作走已声明服务。 | -| Adoption | InputQueue 决定 applied/deleted,Loop 写 consumed;Goal 不代写。 | -| Closing | 禁止新决定,取消/释放自有资源,运行中写 paused,再移除服务。 | -| Crash | 不能保证终态提交;下一次加载只在内存暂停。 | -| Reconnect | 原实例仍活着则继续,不执行加载映射。 | - -## Appendix B. Full conflict table - -执行冲突见 §4.3、A.4;加载和终止冲突由[状态设计 §4–§5](Goal-state-read.md#4-get-与冷恢复)唯一规定。原“重载恢复计数、重做未决定 turn-end、重发评估”规则全部取消。分支来源标记仍使其开启输入不被认作操作员输入。 - -## Appendix C. Errors and recovery +## Supersedes -参数、身份、分支缺失、取消及存储错误沿原公开错误合同。业务状态提交失败不报告成功,未知/损坏 schema 报错,不取更旧事件掩盖。异常可写 paused 时必须写,不能写时由下次加载映射暂停,不能声称已经持久化。读到 active 不触发网络、工具、评估或 continuation。 +- [Goal-state-read.md](Goal-state-read.md): the one-batch command write and its ordering rule. The state object, the load mapping and the property queries in that document stay; the record now follows the business fact. +- [runtime-owner-operations.md](../contracts/runtime-owner-operations.md): the Goal rows — `inputs(id, inputs)` as one atomic record-and-trigger batch, and `directory({id})` returning one branch's record. Goal writes one command input through the input owner and reads `directory()`/`line`. +- The Chinese mirror `docs/zh/design/plugins/Goal.md` describes the pre-contract shape; its target is this document. +- The `session.goal.*` reply field `sequence` stays; the routing table, the Session-side re-fold and the pre-commit callback are deleted. -## Appendix D. Acceptance +## Client-visible changes -[状态设计 §7](Goal-state-read.md#7-requirements-raised-to-mechanism-owners验收与-rule-check)定义新状态机验收。既有命令、参数、Session 隔离、原子配对、模型转义、Settings 和正常续行产品测试保留;旧的重载继续执行断言替换为 paused、零快照写入、显式 resume 后重新执行。 +The `goal:state` record no longer shares one batch with the command. The model sees the command input first and the state record from the next request; the record's text format is unchanged. No client field, code or notification changes: `session.goal.*` keeps `{sequence}` and `{branchId, through, goal?}` with `{objective, status, evaluator}`, and every error code above is one the client already receives. Affected: the prompt-evaluation tests that assert the command and record order, and `Goal-state-read.md`'s ordering rule. -## Appendix E. Assumptions +## Rule check -| 约定 | 决定 | +| Rule | Application | | --- | --- | -| A1 / A2 | Queue/Append 和模型标记沿 A.5,结构化业务状态不成为另一条上下文输入路径。 | -| A3 / A11 | 目标只属于本地分支,子分支和 fork 不继承执行。 | -| A4 / A5 | 可选限额、三次无进展、操作员输入在内存归零;重载不恢复计数。 | -| A6 / A7 | 执行异常终止写 paused;用户 pause 阻止后续自动推进,不直接撤回已经交接的工作。 | -| A8 | 当前状态通过 session.goal.get 读内存;历史块不代替重载后的有效 paused。 | -| A9 / A10 | goal_update 的 session 风险与 4000/2000 字符限制不变。 | -| A12 / A13 | 显式 set/resume 开始新执行,branchId 默认 main。 | -| A14 | 命令批次保留配对顺序;删除命令输入不撤销已经生效的目标。 | -| A15 / A16 | completed 在 model judge 下完成,在 evaluator judge 下是申请;当前状态还受重载暂停规则约束。 | -| A17 | 本实例等待当前后台任务,不在新实例恢复等待。 | - -## Appendix F. Open questions - -本方案没有留给实现选择的恢复模式:旧执行终止,重载暂停,显式 set/resume 开始新执行。 - -## Appendix G. Rust binding - -沿用 GoalSession/GoalBranch、原 Changes 身份路由、TypedPlugin、ctx.effect、TaskTracker、CancellationToken、Settings、Dispatcher::consume 和现有 TimelineQuery。一个 Goal 业务状态定义用于生产与读取;text.rs 负责唯一模型文本转换。append_batch 构造的内部输入在 Goal 边界校验并赋予 submission ID,不新增通用写入包装或数据库能力。具体文件拆分不构成新增需求。 +| §1 parts and Capabilities | `GoalBranch` injects the Dispatcher and the Timeline, writes and folds facts, so it is a Capability. `GoalSession` registers a tool, a method namespace and a guide entry: an entry point, not a Capability. | +| §2 scopes | The goal belongs to the line; the commands belong to the Session entry; nothing about the goal is held at the process scope. | +| §3 orthogonality | Goal reads TimelineTree's line record and its own facts, writes through the input owner and its own timeline, and returns no other owner's data. | +| §4 rule 1 (commands) | A client's command is an input to the line's input owner; Goal never writes another owner's state. | +| §4 rule 2 (handover) | The evaluator line is opened by TimelineTree and closed by id; no branch scope or object crosses. | +| §4 rule 3 (before callbacks) | Goal registers no `before` callback and folds what it committed. | +| §4 rule 4 (no business meaning in core) | The marker, the state block and the guide entry are Goal's; the core carries none of them. | +| §4 rule 5 (batches) | The fact and the record are separate appends in that order, so recovery never reads state that was not committed. | +| §4 rule 6 (context) | The model reads goals only through adopted inputs; `goalLine.read` serves callers, not context preparation. | +| §4 rule 7 (public events and services) | The branch part uses the Dispatcher, its timeline, TimelineTree and the input owner; the entry uses the registration points and the mechanism. | +| §4 rule 8 (requirements) | Two requirements are listed below; no core change. | +| §4 rule 9 (facts) | The goal is a line fact plus the model-visible record; execution counters stay in memory. | +| §7 values, ids and callbacks | The entry writes an input (data) and reads a value at a line id; the mechanism resolves the line's owner; no object crosses. | +| §7 no proxy lookup | The entry neither folds the line's state nor answers from Goal's facts; the branch owner answers its own value. | +| §7 one interface | The commands are one method namespace and one tool contribution; the branch owner's face is one read; no adapter exists beside either. | +| §7 cross-language | Commands, parameters, replies and errors are data; the tool result is text in `ToolResult.content`. | +| §7 one change | The implementation task deletes the routing table, the re-fold path and the pre-commit callback in the same change that adds `goalLine.read` and migrates the entries. | +| ADR 027 D1–D3 | The entry reaches `GoalLine` and the line's `InputQueue` by line id; the resolution is not a dependency and is not kept across calls. The registration points it uses (`sessionMethods`, `toolRegistry`, `guideEntries`) are its own Session's, not resolved by id. | +| ADR 027 D2 | No registration point and no lifecycle service is resolved by line id: `GoalLine` and `InputQueue` are data faces of the branch group. | +| ADR 002 D1 | The goal, its decisions and its tasks live in the branch; the Session entry registers the commands. | +| ADR 002 D2 | No wiring plugin: the branch part provides `goalLine` on its own type; the mechanism resolves the line. | +| ADR 002 D3 | Dependencies point from Goal to TimelineTree, the input owner, Settings and the runtime; nothing depends on Goal. | +| ADR 002 D4 | `maxContinuations` is business configuration read at use; no reload. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +- [TimelineTree #2024](https://github.com/arcships/dim/issues/2024): the cross-cutting decision names this owner's contract as the place that fixes who provides the line-id operations to Session parts. Goal needs two: a Session part resolving `GoalLine` for the read and the line's `InputQueue` for the command. SessionScope's contract has no such operation. +- [The line's input owner #2027](https://github.com/arcships/dim/issues/2027): `submit` accepts one validated input with its submission id, commits it in order and answers its position; an ended line and a closing owner are data. +- The line's timeline owner (runtime, outside the #2015 scan): `append` accepts an input-message draft and an extension fact; Goal appends the fact and then the record. + +## Binding appendix + +The branch owner's face is marked on its own type and provided inside the line's scope; the mechanism resolves it by line id. The entry uses the existing registration points. `cancelled` is the binding's cancellation argument, not a request field. + +```rust +use rutis::host::BoxFuture; + +/// The value the branch part publishes; `through` is the head the fold reached. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GoalValue { + pub objective: Option, + pub status: GoalStatus, // dim_agent_types::GoalStatus: active | paused{reason} | completed | blocked | none + pub evaluator: bool, // the judge; `GoalView` uses this field name on the wire + pub through: u64, +} + +#[rutis::service] +impl GoalLine { + /// The goal of this line now; waits until the fold reaches the head. + pub async fn read(&self) -> Result; +} + +/// The service error shape of every data face: `{code, message, data?}`. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{message}")] +pub struct ServiceError { + pub code: String, // "closed" + pub message: String, +} +``` + +`GoalStatus` and `GoalView` are the existing types in `dim_agent_types`; the command input's text and its `dim-goal` marker are the existing ones in `crates/dim-goal`, and their wire spelling is unchanged. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..1a2755ca49 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -14,9 +14,9 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [ShellInput](ShellInput.md) | — | `shell.*` methods, command runs | — | P1 | | [Attachments](Attachments.md) | — | `attachment.put`, Session files | — | P1 | | [Report](Report.md) | error-only `report.*` and its connection-bound drafts | `session.report.*` and its connection-bound drafts | — | [#1319](https://github.com/arcships/dim/issues/1319) | -| [SessionTitle](SessionTitle.md) | — | observes adoption of the first user input, `session.rename` | — | P1 | +| [SessionTitle](SessionTitle.md) | — | observes the first adopted input, `session.rename`; writes through SessionStore, generates through Provider | — | P1 | | [PromptSuggestion](PromptSuggestion.md) | `PromptSuggestionSettings` in App Server: the `prompt-suggestion` Settings source | observes the completed turn's events, `session.suggestion.request` and `session.suggestion.respond`, the offer in flight and the shown offer; no events | — | P1; [#943](https://github.com/arcships/dim/issues/943) | -| [Goal](Goal.md) | — | `goal_update` tool, `session.goal.*` | goal state folded from `goal:objective` and `goal:status` blocks, continuation | P2 | +| [Goal](Goal.md) | — | `goal_update` tool, `session.goal.*`, the `dim-goal` guide entry | the goal of a line, its continuation and evaluator decisions; publishes `goalLine.read` by line id | P2 | | [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 | @@ -34,7 +34,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [Notifications](Notifications.md) | — | Session observer, `notify` tool | — | Withdrawn | | [Scheduler](Scheduler.md) | triggers, run history (jobs in Settings) | `schedule` tool | — | P2 | | [Workflow](Workflow.md) | runs (definitions in Settings or project files) | `workflow` tool | — | P2 | -| [Code Mode](CodeMode.md) | `CodeMode`: structural bounds, the branch runner map, the program semaphore and part registrations (when installed) | `codemode` tool (v4 clients only) | one-shot QuickJS program execution, child call batches, effects and cancellation; client boundary in [child tool batches](../appserver/child-tool-batches.md) | Draft P3; native crate `crates/dim-codemode/`; [#1276](https://github.com/arcships/dim/issues/1276) | +| [Code Mode](CodeMode.md) | `codeMode`: the structural bounds and the process program slots (when installed) | `codemode` tool (v4 clients only) | `codeModeLine.run`: one-shot QuickJS execution, the child gate use, effects and cancellation; client boundary in [child tool batches](../appserver/child-tool-batches.md) | Draft P3; native crate `crates/dim-codemode/`; [#1276](https://github.com/arcships/dim/issues/1276) | | [Collaboration](Collaboration.md) | member relations and temporary agents | `agent` tool, including the `models` action that lists the models a new member can run; reports and messages; the two markers' guide entries | the delegation's facts, wake inputs and settlement | #551 | | [ExternalAgent](ExternalAgent.md) | external conversations, Collaboration member kind `external-agent`; bridge row per node | — (delegation and decisions are Collaboration's) | — | P3 | | [AcpGateway](AcpGateway.md) | client-host plugin: ACP/RPC connections, requests and cleanup; outside the daemon | — | — | #436; PR #441; [acceptance](../acp-gateway-acceptance.md) | diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 1db4af1c80..251462fd35 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -1,522 +1,221 @@ # SessionTitle -Overall design: [overview](../overview.md) (SessionTitle). Scope: [ADR 002](../../adr/002-plugin-scope.md) (Session). - -SessionTitle is a Session plugin that gives an interactive leader Session a title stored through SessionStore metadata. It observes its own Session through the existing Session broadcast; when the first eligible input on `main` is adopted (`input/applied`) — an operator input with `user` content, or Goal's applied objective (A10) — it generates a title from that input's text alone through the routing policy in §3.3. The title is SessionStore state: SessionTitle writes it only through SessionStore's typed `setTitle` operation, and SessionStore announces each change with a Session broadcast notice that clients consume (the delivered C6 notice record is described in [§9](#9-requirements-raised-to-mechanism-owners); the SessionStore title metadata and the Rpc forwarding are supplements in [overview Appendix B.2](../overview.md#b2-app-server-process-plugins)). It serves `session.rename` by registering the namespace `session.rename` with its Session's `sessionMethods` ([methods and tool contributions](../contracts/session-boundary.md)), and it writes the title a Session's creation requested, once, as the first manual title (§3.4). It writes no Timeline event and has no model-visible effect. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is in Appendix G. - -## 0. Implementation boundary - -The base CLI provides `session-title` from the independent `dim-session-title` Rust crate. -The `dimcode` product profile installs it through `AgentBuilder::plugin`; the App Server -provides only its generic CLI profile callback and existing owner services. The plugin owns -its public generation contract. DimOAuth imports that contract from this crate. Its process row registers -the Settings source and the Session part through the existing part registry; every Session -mounts one copy. Availability does not depend on `--defaults`, a staged TypeScript package, -Node/Python installation or language-runtime acquisition. The owner of model selection in the -profile and storage remain the owners of auxiliary calls and title metadata. - -The shipped plugin retains the `session-title` identity, Settings document and metadata format. -PluginManager's source selection owns the transition from the former default package to the -built-in implementation, preserving explicit disablement and installed replacement selections. -Only the selected implementation may register the Settings source or `session.rename`. - -Public behavior tests belong to this plugin crate and use `dim-client` and the App Server -public APIs; fixtures install the plugin explicitly. App Server tests have no dependency on -SessionTitle and cover generic host behavior. Verification uses the native flow -[`native_flow.rs`](../../../crates/dim-session-title/tests/native_flow.rs) without -language runtimes. It exercises fixed-cut property queries, settings validation, RPC, HTTP auxiliary -execution, Unicode bounds, concurrent adoption, title notices, manual-over-auto conflicts, -restore, fork and closing settlement. -[`appended_context_flow.rs`](../../../crates/dim-session-title/tests/appended_context_flow.rs) -covers context appended after the operator's text (Hooks A.6.2, Skills §9) staying out of the -title. The Node-backed -[`scheduler_flow.rs`](../../../crates/dim-session-title/tests/scheduler_flow.rs) exercises -scheduled report provenance without letting reports supply title text. Diagnostics contain -only outcome and duration. - -| Boundary | Current contract and Ready decision | -| --- | --- | -| Observation | Read the Session id from `sessionIdentity`, the creation configuration from `sessionConfig` and closing from `sessionLifecycle` ([plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | -| Timeline reads | Use the Session’s branch query facade on `main`, with a fixed published cutoff. Read only the adopted input identity, its user content or Goal objective, and the adopted model fields (§0.1). | -| Configuration | Existing named Settings and row source declaration, user scope only (A.3/A12). Read settings.read({source:"session-title",scope:"user"}) at each decision and use its validated/defaulted document directly. | -| Metadata/notice | S5b #60/#96 defines the process service `sessionMetadata` (`read` and `setTitle`, both async), its errors `conflict`/`not_found`/`storage`, the handover and the v3 list fields `title`/`titleSource`/`titleRevision` ([title metadata](../appserver/session-title-metadata.md)); A.2 restates that contract. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). Names, modes, handover and errors follow S5b. | -| Auxiliary request | The profile's model-selection owner implements AuxiliaryModel and its named `auxiliaryModel.complete` HostDispatch/catalog binding: Provider in the product profile, ConfiguredModels in the model-config profile. Inject it through ordinary C4 dependencies; credentials stay with that owner ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)). | -| Policies | A1–A12 define the first implementation. Appendix D requires public-flow acceptance; documentation CI alone is not runtime acceptance. | - -C7 #50 is already unnecessary (#86). S4 owns its own credential/connection resolution. Missing -required providers keep the Session part Pending under existing rules, including rename; native -Session use continues. Only `sessionTitleGenerator` is optional (§3.3); rename retains its required owner services. - -The C4 leaf callback filters `main` adoption on its own Session's channel, registers an owned task and returns; -it does not await Settings, queries or model work. SessionBroadcast forwards published Dispatcher events. -The first query captures published T; T must include the triggering adoption N. Subsequent queries use that -same T. Queries use the Session's public branch facade; SessionTitle does not inject a branch service or -read the store directly. - -### 0.1 Fields read for one title attempt - -1. Check the triggering input by id and capture published T. It must be an `input/message` with `data.user`, or Goal's applied `goal:state` record stating an objective (A10). Return only its id. If it does not qualify, stop here without querying earlier inputs. Other raw-block inputs, including runtime notifications, Goal's triggers and continuations, do not trigger generation. -2. At T, select the first `input/applied` whose `data.input_id` names such an eligible `input/message`. Return only `data.input_id`. The adoption's position defines “first”; creation order does not. -3. Read the selected first input's `data.user` by id, or its `data.blocks` when it is Goal's record; take the text blocks or the `` element. This is the message body used for generation; eligibility predicates also inspect the referenced input. A text block after the first that starts with a runtime marker is context a capability appended, not the operator's words (Hooks A.6.2, Skills §9), so the title leaves it out; the first block is the operator's whatever it opens with. -4. Select the last `context/configured` at T and read its adopted provider/model identifiers. With no adopted configuration, use the existing excerpt fallback. - -Each query returns at most one row. No full-history page or input map is retained. The user content or -objective is still bounded to the existing 2,000-character excerpt before generation. Query results are -released after the attempt. - -Use the [plugin binding contract](../rutis-usage.md): the plugin's one row injects `partRegistry` -and registers the Session part; each Session mounts a copy. The part injects -`sessionMethods` and registers `session.rename` with it from `apply`; it provides no service. -`apply` reads the Session identity and creation configuration and registers observation/cleanup; -it does not start an asynchronous initialization job. Its creation configuration is immutable. -The plugin depends on the existing public Rust Settings and sessionMetadata bindings; it does not expose or alter their implementations. Plugin behavior and cross-plugin title flows live in this crate's tests and use the public client and host APIs. App Server tests have no dependency on this crate and install no title plugin implicitly. - -The part injects its required dependencies: the process services -`settings`, `sessionMetadata` and `auxiliaryModel`, and the Session services branch queries, `sessionIdentity`, -`sessionConfig`, `sessionLifecycle` and `sessionMethods`. The optional `sessionTitleGenerator` -is read by name when used, without injection or a readiness gate, under the -[required/optional binding contract](../rutis-usage.md#3-services-by-name). -The product assembly installs the native -plugin independently of foreign plugin rows. Missing required service providers affect only SessionTitle's -availability under the existing dependency rules, not the Session's execution capabilities. - -The fixed snapshot ends at returned T, not necessarily at N. Its first adopted eligible input -supplies text. With model=null, the latest ContextConfiguredData.settings in that snapshot supplies -providerId/modelId; without an adopted model, generation uses the excerpt fallback in §3.3 instead of the profile's current default. - -Cancellation before setTitle handover stops work without writing. The handover is the setTitle call -itself: from then on SessionStore settles its own atomic operation, and a lost reply does not authorize -repeating or undoing it ([S5b §6](../appserver/session-title-metadata.md#6-handover-cancellation-and-settlement)). No rollback or -coordination mechanism. -Generation takes no Session activity hold ([idle unload D10](../appserver/idle-unload.md#3-decisions)); -idle unload follows the same cancellation and store-handover rules. - -## 1. Structure - -```mermaid -flowchart LR - subgraph PROC["Process"] - AUX["AuxiliaryModel (model-selection owner)"] - META["SessionStore title metadata"] - Settings["Settings source session-title"] - Rpc["Rpc"] - end - subgraph SESS["Session"] - ST["SessionTitle"]:::new - SB["Session broadcast"] - TT["Session branch queries: published main properties"] - CFG["SessionConfig"] - end - ST -->|"listen: input/applied on main"| SB - ST -->|"query required fields at T >= N"| TT - ST --> CFG - ST -->|"optional generate(providerId, text)"| GEN["sessionTitleGenerator (DimOAuth)"] - ST -->|"complete(model, text)"| AUX - ST -->|"setTitle with revision"| META - META -->|"title notice"| SB - ST -->|"read at use"| Settings - Rpc -->|"session.rename dispatched through the Session"| ST - Rpc -->|"session.summaries reads title fields"| META - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -| Part | Scope | Depends on | Provides | -| --- | --- | --- | --- | -| `session-title` | Process | Settings and part registry | Registers the Settings source and Session part | -| `SessionTitle` | Session | Session services `sessionIdentity`, `sessionConfig`, `sessionLifecycle` and `sessionMethods`; Session branch queries; process Settings, title metadata `sessionMetadata` (S5b) and required `auxiliaryModel` (a profile without an owner of model selection keeps the row Pending); optional `sessionTitleGenerator` read at use | Registers session.rename with sessionMethods | - -Dependencies stay in the Session or enclosing process. Session observation, branch queries and Settings supply observation, field reads and configuration; S5b supplies title metadata and C6 the notices; the profile's model-selection owner supplies the named auxiliary operation. The plugin's row registers its source in its `apply`. Real provider reloads cancel the row's work (ADR 002 D3); SessionStore index reload does not. Business data changes never reload the plugin (D4). - -## 2. Data and state - -```mermaid -flowchart TB - subgraph TLM["main branch Timeline"] - FUI["first adopted eligible input (input/message, input/applied)"] - CC["context/configured (adopted model)"] - end - subgraph STORE["SessionStore metadata (persistent)"] - MD["revision, title text, source auto or manual"] - end - CONF["SessionConfig: interactive, collaborationRole, initialTitle"] - CFG["session-title: enabled, maxLength, model"] - MEM["in-flight generation, failed attempts (memory)"]:::new - FUI -->|"text only"| MEM - CC -->|"Session model"| MEM - CONF --> MEM - CFG --> MEM - MEM -->|"setTitle, expected revision"| MD - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -SessionStore owns the title: it keeps the text, source and revision counter and accepts changes only through its typed `setTitle` operation, which SessionTitle alone calls. After each committed change SessionStore emits a title notice on the Session broadcast (A11); the title never enters the Timeline. Each decision reads Settings first and skips disabled generation before metadata or Timeline queries; otherwise it reads metadata and the required fields at a fixed cutoff. An image-only first input is remembered for the loaded generation. In-memory state is lost on reload or Session unload, which only allows another attempt. - -## 3. Flows - -### 3.1 Automatic title from the first eligible input - -```mermaid -sequenceDiagram - participant TL as main Timeline - participant SB as Session broadcast - participant ST as SessionTitle - participant Settings as Settings - participant Meta as SessionStore metadata - participant Queries as Session branch queries - participant Gen as Generation path (§3.3) - TL-->>SB: input/applied at N, branch main - SB-->>ST: Event - Note over ST: interactive leader, none in flight - ST->>Settings: read session-title; skip if disabled - ST->>Meta: metadata: no title, revision r - ST->>Queries: select first adopted eligible id, its text and model at fixed T >= N - ST->>Gen: generate from adopted input - Gen-->>ST: title or excerpt fallback - ST->>Meta: setTitle(expected r, auto) - Meta-->>SB: title notice -``` +Scope: Session. Issue: #2033 (this contract). The generation policy, the operator's text rules and the acceptance list are the ones in the previous version of this document; this contract states the owner's shape and the calls it makes. -Generation starts when the input is adopted, not after the turn. Only the text of the first adopted eligible input on `main` is sent — an operator message's text, or Goal's applied objective (A10). A deleted input is never adopted, so it never titles the Session and its text never reaches the auxiliary model. -The main turn never waits for title completion; the title task follows its own budget. - -### 3.2 Manual rename - -```mermaid -sequenceDiagram - participant CLI - participant Rpc - participant ST as SessionTitle (in the Session) - participant Meta as SessionStore metadata - CLI->>Rpc: session.rename sessionId, title - Rpc->>ST: resolve Session, sessionMethods call - ST->>Meta: metadata, revision r - ST->>Meta: setTitle(expected r, manual) - Meta-->>ST: revision r+1 - Note over Meta: title notice on the Session broadcast - ST-->>Rpc: title, titleSource manual, revision -``` +SessionTitle owns a Session's title policy: when a title is generated, what text is acceptable, when the operator's text replaces it, and the title a Session's creation requests. The title value itself belongs to SessionStore, which serializes the writes and announces each commit. The current shape is the one #2033's scan report describes. -Rpc resolves the Session as for any Session method, loading it if needed. On `conflict` SessionTitle rereads and retries up to 3 times. +## Use and scope: responsibility split -### 3.3 Generation routing and optional service +SessionTitle owns: -SessionTitle owns routing. An explicit Settings `model` goes directly to `auxiliaryModel`. -Otherwise it reads the process service `sessionTitleGenerator` at use time, without a required -dependency, and passes the provider of the latest adopted model in the fixed history prefix. -It never routes from a global default or from the existence of account credentials. A missing, -failed or reloading optional provider does not gate SessionTitle or manual rename. +- **The moment of generation.** The first adopted input on the Session's conversation line — an operator input with user content, or Goal's applied objective — triggers one attempt; a Session that already has a title never generates one. +- **The text rules.** The instruction sent to the model, the 2000-code-point excerpt, the output normalization (one line, no quoting, collapsed whitespace) and the length bound from the `session-title` source. +- **The routing.** An explicit model from the source, otherwise the account owner's title operation when the adopted provider belongs to it, otherwise the adopted model, otherwise the excerpt fallback; one 30 s budget across the paths; three failed attempts end the attempts for this generation. +- **The manual rename.** `session.rename`'s parameter rules and the text it accepts or clears. +- **The requested initial title.** The title a launch carried is written once, as the first manual title, after the Session is published. -The service contract belongs to SessionTitle; a provider implements only generation, not Session -selection, persistence or fallback. Its only method is async `generate(request, cancelled?)`: +Callers keep as business: -| Item | Contract | -| --- | --- | -| Request | `{providerId: string, text: string}`; nonempty provider id and text, at most 2000 Unicode code points | -| Generated | `{kind: "generated", title: string}`; nonempty text, normalized by SessionTitle | -| Unavailable | `{kind: "unavailable", reason: "unsupported_provider" \| "account_unavailable" \| "disabled" \| "not_entitled" \| "quota_exhausted" \| "service_reloading"}` | -| Failed | `{kind: "failed"}`; transport, invalid upstream response or transient rejection | -| Cancelled | `{kind: "cancelled"}`; terminal for this title task, with no alternate request or metadata write | -| Invalid request | Reject with `invalid_request`; validate external arguments at the service boundary | -| Cancellation | Optional function returning a promise that resolves on cancellation. The caller resolves it and awaits the original call; the provider cancels its I/O and settles accepted work before unloading | - -After an unavailable or failed service call, SessionTitle uses the adopted model through -`auxiliaryModel`. A missing model, auxiliary error, empty normalized output or the shared 30 s -generation deadline uses the input excerpt as a fallback title: collapse whitespace, trim and apply the configured Unicode length bound while preserving punctuation, and write through the same revision-checked -metadata operation with source `auto`. Account-service failure alone does not consume one of -the three failed attempts that cannot complete a metadata write. Session closing or explicit cancellation never falls back. -The deadline includes both generation paths; timing out cancels and joins the active call before -the fallback write. Whitespace-only text has no title and is treated as no text. A model reply -that completes with no non-whitespace text and no tool call is a `malformed_response` -([model failures §4](../model-failures.md#4-retry)); the auxiliary model retries it once, so a -single empty answer costs one more request, and a repeated one is an auxiliary error that falls -back to the excerpt. - -DimOAuth implements this optional service for its own provider; its endpoint, authentication, -refresh and rejection classification belong to its [runtime contract](../../../crates/dim-oauth/docs/runtime-contract.md). -SessionTitle receives neither credentials nor an issuer. The model-selection owner, AuxiliaryModel, -model execution, Timeline and Dispatcher have no title routing policy. No additional registry or wiring plugin is used. - -### 3.4 The title a Session's creation requested - -`sessions.launch` may carry `title`, the label its caller already knows for the Session -([sessions service §6.1](../appserver/sessions-service.md#61-launch)). Agents stores it in the new Session's -fixed configuration as `initialTitle`; SessionTitle is still the title's one writer, so the store never receives a -title written by the caller. - -```mermaid -sequenceDiagram - participant L as sessions.launch - participant A as Agents - participant ST as SessionTitle (in the Session) - participant Meta as SessionStore metadata - L->>A: launch {title} - A->>A: SessionConfig.initialTitle = title - Note over ST: apply, Session published - ST->>Meta: metadata: revision 0? - ST->>ST: rename's text rule, then maxLength - ST->>Meta: setTitle(expected 0, manual) - Meta-->>ST: revision 1 - Note over Meta: title notice on the Session broadcast -``` +- The title UI and when the operator renames. +- Which Session is shown; SessionTitle never names another Session's row. +- The creation configuration and whether the Session is interactive or a leader: SessionScope owns the record, SessionTitle reads it. -- **Once.** The write happens only while the stored revision is 0. A later rename or clear is therefore never undone - by a reload: the configuration keeps `initialTitle`, and the part skips the write once anything has titled the - Session. A `conflict` at `setTitle` means another writer titled it first, and that title wins. -- **The text rule.** It is `session.rename`'s: trim the text, and write nothing for an empty one or one with a control - character or a line separator. The length is bounded to the operator's `maxLength` the way a fallback title is, and - punctuation stays: `title_text` strips it because it is for model output, and this text is the caller's. -- **When.** The write runs after `apply` and after the Session is published, in the part's own task, so the launch's - reply may arrive first. The row shows the title once the title notice is sent, which is the same path a rename takes. -- **For every Session.** Interactive and non-interactive alike: the initial title needs no model and no eligibility - gate. Generation keeps its gate ([§4](#4-timing-and-conflicts)); a Session with an initial title is already titled, so - generation would skip it anyway. - -## 4. Timing and conflicts - -```mermaid -sequenceDiagram - participant G as generation - participant R as rename - participant Meta as SessionStore metadata - G->>Meta: metadata, revision r, no title - R->>Meta: setTitle(expected r, manual) - Meta-->>R: r+1 - G->>Meta: setTitle(expected r, auto) - Meta-->>G: conflict - Note over G: automatic title discarded -``` +| Requirement (caller) | Can callers compose it from the owner's operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The operator sets or clears a title | No: the accepted text, the length bound and the precedence over a generated title are the owner's rules | `session.rename` | +| The title appears when the first input is adopted | No: the observation, the routing and the fallback are the owner's decisions | the owner's own task; no caller | +| A generated title never overwrites a title the operator set | No: the decision must run while the store holds the title, or a write in between is lost | `store.setTitle` with a `change` callback that refuses when a title exists | +| The title a launch requested is written once | No: the condition must be decided under the store's exclusion, and the text rule is the owner's | `store.setTitle` with a `change` that refuses unless the title is untitled | +| The title of a Session that was never titled is shown as absent | Yes: `store.title` answers the revision and the value, with its source | business composes | +| Which input the title came from | Yes: the line's facts are readable; the owner's choice is one input by id | business reads the line, the owner composes nothing new | -The revision check is the recheck: a manual title always wins. +An operation or parameter exists only where its row says No. -| Scenario | Order | Outcome | Owner | -| --- | --- | --- | --- | -| Member Session (`collaborationRole`), or a non-interactive Session | `SessionConfig` | Never generated; rename allowed | SessionTitle | -| Session whose creation requested a title (`initialTitle`) | `SessionConfig`, revision 0 | Written once as a manual title under rename's text rule and `maxLength`; a later rename or clear wins on reload (§3.4) | SessionTitle | -| Second input before generation finishes | — | Skipped (in flight) | SessionTitle | -| First input deleted | input < `input/deleted` | Never adopted: no title from it; the next adopted eligible input triggers (A9) | SessionTitle | -| Generation paths failed | — | Input-excerpt fallback (§3.3); storage failure may retry while untitled (A5) | SessionTitle | -| Reload or Session unload mid-generation | — | Cancel before store handover; the next adopted main input may trigger. An admitted mutation settles with SessionStore | Lifecycle / SessionStore | +## Caller example -Full table: [Appendix B](#appendix-b-full-conflict-table). +`session.rename` checks the text, then writes it through the store's `change`; the store holds the title across the decision, so no concurrent writer can be lost. -## 5. Context mapping +```rust +let text = title_text(params.title.as_deref(), &document)?; // owner rules: trim, no control characters, length +let change = TitleChange::new(move |current: Option| { + // A manual rename always wins: the operator's text replaces whatever is stored. + Ok(text.clone().map(|text| Title { text, source: TitleSource::Manual })) +}); +let written = store + .setTitle(SetTitle { id: session }, change, cancelled) + .await + .map_err(|error| match error { + StoreError::Rejected { code, message } => wire_invalid(code, message), // the change refused the write + StoreError::NotFound => session_not_found(), + other => storage_failed(other), + })?; +``` -No model-visible effect: SessionTitle writes no input, tool, prompt source or event. The auxiliary request is a separate one-shot call: +A generation attempt: the adopted input's text, the model, and one write whose `change` refuses once any title exists. -| Part | Content | -| --- | --- | -| System | `Write a short title for this conversation: at most 8 words, in the language of the user's message, no quotes, no trailing punctuation. Reply with the title only.` (A2) | -| User message | The text blocks of the first adopted operator `input/message` on `main` (one with `input/applied`) that carry the operator's words, joined by newlines, or the `` element of Goal's first adopted `goal:state` record, cut to 2000 characters (A2, A10) | +```rust +let input = tree.read(ReadLines { line: ROOT, scope: None, from: None, through: Some(adopted_at), fields: INPUT_FIELDS, limit: None }).await?; +let text: String = eligible_text(&input).chars().take(2000).collect(); +let title = match route(&document, &adopted_model) { + Route::Account(account) => match account.title(TitleRequest { provider, text }, cancel.clone()).await { + Ok(reply) => reply.title, + Err(TitleError::UnsupportedProvider | TitleError::Unavailable { .. }) => generate_with_model(&provider, &text).await?, + Err(error) => return Err(error.into()), + }, + Route::Model(model) => generate_with_model(&model, &text).await?, + Route::Excerpt => excerpt_title(&text, document.max_length), +}; +let change = TitleChange::new(move |current: Option| match current { + Some(_) => Err(Rejected::new("titled", "the Session already has a title")), // the operator's title wins + None => Ok(Some(Title { text: title.clone(), source: TitleSource::Auto })), +}); +store.setTitle(SetTitle { id }, change, cancel).await?; +``` -Never sent: images, raw input blocks, deleted inputs, later inputs, assistant output, system prompt, tool calls and results, child-branch events. Diagnostics record outcome and duration only. +## Own contract -## 6. Interfaces (summary) +### Dependencies -| Interface | Kind | Purpose | +| Owner | Operation | Use | | --- | --- | --- | -| `session.rename {sessionId, title \| null}` | `sessionMethods` namespace `session.rename` | Set or clear a manual title | -| `session-title` source: `enabled`, `maxLength`, `model` | Business configuration (Settings source) | Turn generation off; title length; explicit title model or automatic routing (§3.3) | -| `title`, `titleSource`, `titleRevision` in v3 `session.summaries` | Rpc protocol fields read from SessionStore ([S5b §8](../appserver/session-title-metadata.md#8-session-lists)) | Display; the revision orders a list against notices | -| Title notice, `data: {title, titleSource, titleRevision}` | Session broadcast notice emitted by SessionStore (C6 record, §9; [S5b §7](../appserver/session-title-metadata.md#7-the-title-notice)) | Live title update for subscribed clients | +| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `config`, `identity`, `activated`, `closing` | The creation record (`initialTitle`, `interactive`, `collaborationRole`), the Session id, publication and close | +| SessionStore ([#2018](https://github.com/arcships/dim/issues/2018)) | `title`, `setTitle` with a `change` callback | The current title (text, source, revision) inside the decision; the write, its announcement and the new revision | +| TimelineTree ([#2024](https://github.com/arcships/dim/issues/2024)) | `read` | The first adopted input's text and the adopted model at a fixed cutoff | +| Provider ([#2019](https://github.com/arcships/dim/issues/2019)) | `invoke` with `Once` | One title request on an adopted model | +| The Dim account owner ([#2019](https://github.com/arcships/dim/issues/2019), optional) | `title` | The relay's title endpoint when the adopted provider belongs to it | +| Settings ([#2017](https://github.com/arcships/dim/issues/2017)) | `register`, `read` | The `session-title` source: `enabled`, `maxLength`, `model` | +| Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `sessionMethods.register` | Publishing `session.rename` | -## 7. Security +The account owner is read by its face name when generation needs it, so a profile without that owner generates through the model or the excerpt; this document does not require the account owner to exist. -The first eligible input's text is sent only to the generation paths selected by §3.3: an explicit model, or the optional service and adopted model. Titles may contain user content and are returned to every client that can list Sessions. No credentials, host settings or tool output enter the request. Rename input is validated by SessionTitle's method (A.1). +### Operations -## 8. Rule check +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `session.rename` | Set or clear the manual title | `{sessionId, title: string \| null}` | `{title, titleSource, revision}` | Before the write is admitted; after admission the store settles it | `invalid_params`, `session_not_found`, `storage_failed`, `service_reloading`, `operation_interrupted` | +| generation (internal) | Title the Session from its first adopted input | — | — | The 30 s budget or the Session's close; before the write is admitted nothing is written | none is returned to a caller; failures reach the fallback or end the attempt | -| Rule | How this document complies | -| --- | --- | -| Principles §4 rule 1 (commands for others' state) | The title is SessionStore's process-level state with no Timeline; SessionTitle changes it only through SessionStore's typed `setTitle`, and SessionStore decides through its revision check (principles §4 rule 9). | -| Principles §4 rule 2 (handover) | SessionTitle reads an input only after its handover (`input/applied`) and never acts on the input itself. | -| Principles §4 rule 3 (before callbacks only) | No intervention before a write; rename rules are checked by SessionTitle's own method, not at an entry. | -| Principles §4 rule 4 (no business meaning in core) | The delivered C6 Session broadcast notice in §9 is a generic record for any owner of process-level Session state. | -| Principles §4 rule 5 (batch) | The trigger acts on `input/applied` when it is consumed, in sequence order. | -| Principles §4 rule 6 (context from handed-over events) | SessionTitle adds nothing to model context; the auxiliary request contains only adopted input text. | -| Principles §4 rule 7 (public events and services only) | It uses the Session broadcast, fixed-prefix read, SessionStore `setTitle`, `AuxiliaryModel`, optional `sessionTitleGenerator` (§3.3) and Settings, all public. | -| Principles §4 rule 8 (requirements to mechanism owners) | C6 and S5b deliver the notice and metadata contracts in §9. None for #4: SessionTitle uses the Session services, the Session channel and named process services through existing owner contracts. Requirements to other plugins (SessionStore title metadata and notice emission, Rpc forwarding of notices) are listed in [overview Appendix B.2](../overview.md#b2-app-server-process-plugins). | -| Principles §4 rule 9 (only facts later decisions use) | The title is process-level SessionStore state: it never enters the Timeline, changes through `setTitle` and reaches UIs as a Session broadcast notice. | -| Principles §1 (Capability and App Server boundary) | SessionTitle is a Session part, not a Capability: it injects neither Dispatcher nor Timeline; Rpc only dispatches `session.rename` and reads title fields from SessionStore. | -| ADR 002 D1 (scope follows state) | Session scope: the title belongs to the Session; the stored title is SessionStore's. | -| ADR 002 D2 (no wiring modules) | No wiring module; required services are injected, and the optional generator is read at use under the binding contract. | -| ADR 002 D3 (dependencies follow scope) | Dependencies are in the Session or enclosing process scope; their reload cancels a generation, which is accepted. | -| ADR 002 D4 (structural vs business configuration) | Plugin enablement and source selection are structural; the user-only `session-title` source in A.3 owns business configuration, read at use without reloading the row. | -| ADR 002 D5 (language-neutral contracts) | Contracts are neutral; the Rust form is Appendix G. | - -## 9. Requirements raised to mechanism owners - -**R1. Session broadcast notice for process-level state — delivered.** - -C6 #85 supplies the notice record and Rpc forwarding; S5b #96 supplies title metadata and -post-commit title notices. SessionTitle consumes these delivered contracts. - -| Item | Content | -| --- | --- | -| Blocked by | Principles §4 rules 9 and 4: process-level state such as the SessionStore title must not enter the Timeline, yet clients must see title changes live; the delivered C6 `Notice` record carries these post-commit changes ([session_broadcast.rs](../../../crates/dim-agent-capabilities/src/session_broadcast.rs)). | -| Existing mechanisms considered | A `session/titled` Timeline event (puts process state on the Timeline; rejected in overview §7); client polling of `session.summaries` (no live update); a title-specific channel (a business-specific port, rule 8). | -| Generic capability | A notice record `{source, kind, data}` on a Session's broadcast channel, emitted by the owner of process-level state about that Session after a committed change; no business meaning. The title notice is this record with `source: "SessionStore"`, `kind: "title"`, `data: {title, titleSource, titleRevision}` ([S5b §7](../appserver/session-title-metadata.md#7-the-title-notice)). Rpc forwards that record unchanged as `session.notice`, adding the channel's `sessionId` ([C6 D4](../appserver/session-notices.md#10-decisions)), so `data` does not repeat it. | -| Effect on sequence, batch, interrupt, reload | No sequence number and no batch; not replayed: a client that resubscribes reads current state through the owner's query (`session.summaries`); interrupts do not apply; a reload of the emitter only stops notices. | -| Owner and issue | Runtime C6 [#49](https://github.com/arcships/dim/issues/49), implemented in [#85](https://github.com/arcships/dim/pull/85): the record, `session_broadcast::notify` and Rpc's `session.notice` ([Session broadcast notices](../appserver/session-notices.md)). SessionStore emits the title notice ([S5b](../appserver/session-title-metadata.md), the supplement in [overview Appendix B.2](../overview.md#b2-app-server-process-plugins)). | +`invalid_params` is the owner's own rule: an empty title, a control character or a line separator, a title longer than `maxLength`, a parameter that is neither a string nor `null`. `session_not_found` and `storage_failed` are SessionStore's answers; `service_reloading` is the part unloading; `operation_interrupted` is the mechanism's report. Every code is one the client already receives. The store's `change` runs under its exclusion with the current title, so a lost update cannot happen and the caller keeps no retry: a manual rename returns its text, an automatic or requested title returns `Rejected` when a title exists, and the owner's serialization decides the order. -**#4: None.** Observation uses the Session services and the Session channel; branch queries are Session services; Settings, `sessionMetadata` and the auxiliary model are process services. SessionTitle injects no branch service. +### Flows -**The model-selection owner (S4): the named `auxiliaryModel` binding.** Provider (product) and ConfiguredModels (model-config) bind their existing `AuxiliaryModel` operation for C4 injection ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)). A profile without such an owner keeps SessionTitle's row Pending through its ordinary required dependency. No core mechanism is needed. +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `session.rename` | Check the text, call `setTitle` with a `change` that returns the manual text, answer the new revision | Before admission the call ends `cancelled`; an admitted write is not undone | Nothing to release | `closed` once the Session is closing; an admitted write settles in the store | SessionStore for the write and the exclusion; SessionTitle for nothing | +| Generation | Observe adoption, read the input and the model at a fixed cutoff, generate within the budget, fall back to the excerpt, write with a `change` that refuses when a title exists | Cancelled before admission: nothing is written; the in-flight model call is cancelled and joined | The task is cancelled; nothing is written | Cancelled before the store handover; an admitted write settles in the store | SessionTitle for the model call; SessionStore for the write and the exclusion | +| Initial title | After publication, call `setTitle` with a `change` that returns the requested text only while the title is untitled | Before the write nothing is written | Cancelled with the part | A later rename or clear is never undone by a reload: the `change` sees the stored title and refuses | SessionStore | -**DimOAuth:** implement the optional generation service defined in §3.3; account requests and settlement remain in its runtime contract. No Provider or Core mechanism change is required. +The generation task takes no Session activity hold: an idle release cancels it like any other close. A deleted or withdrawn input never triggers generation; the first adopted eligible input decides. -## Appendix A. Interface details +### Errors -### A.1 `session.rename` +| Kind | What the caller does next | +| --- | --- | +| `invalid_params` | Fix the title: its length, a control character, a line break, the parameter type | +| `session_not_found` | The Session row does not exist; the client drops the rename | +| `storage_failed` | The store could not commit; retry later or report the failure | +| `service_reloading` | SessionTitle is unloading; the next generation serves the next call | +| `operation_interrupted` | The mechanism interrupted the call on unload; an admitted write settles in the store | -Registered with `sessionMethods` (Session, namespace `session.rename`) with one declaration `{name: "session.rename", mutating: true, interruption: "report", progress: false}`; its `call(MethodCall, cancelled, progress): async -> MethodReply` handles it. A dropped call is cancelled before `setTitle` or completes atomically after it. +## Exceptions with reasons -| Params | Result | Errors | -| --- | --- | --- | -| `{sessionId, title: string \| null}` | `{title: string \| null, titleSource: "auto" \| "manual" \| null, revision}` | `invalid_params`, `session_not_found`, `service_reloading`, `storage_failed`; dispatch errors per [session-boundary](../contracts/session-boundary.md) | +- The account owner is an optional name, not a required dependency: generation falls back to the model and then to the excerpt, so a profile without an account owner still titles Sessions and still renames. +- A generation attempt reads the adopted input at a fixed cutoff instead of subscribing to later facts: the title is decided once from the first eligible input, and later inputs never retitle. +- The model call is one `invoke` with `Once`: a title is a single request with no retry and no model substitution, which is the mode Provider's contract names for one paid request. +- The requested initial title is written only while the title is untitled, decided inside the store's `change`: the configuration keeps the requested text, so a reload would otherwise resurrect a title the operator cleared. +- The `change` only computes: waiting on another owner or on I/O inside it holds the title's exclusion for that wait, the same rule FileStorage's `update` states. -`title` is trimmed; 1..=`maxLength` (source `session-title`) characters, no line breaks or control characters (A3). `null` clears the title (A6). +## Verification -### A.2 Depended-on shapes (owners define them) +Flow tests through `session.create`, `session.submit`, `session.rename`, `session.summaries` and `settings.*`: -| Service | Method | Kind | Request | Reply and errors | -| --- | --- | --- | --- | --- | -| SessionStore `sessionMetadata` (S5b) | `read` | async | `{sessionId}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`; errors `not_found`, `storage` ([S5b §4](../appserver/session-title-metadata.md#4-operations)) | -| SessionStore `sessionMetadata` (S5b) | `setTitle` | async | `{sessionId, expectedRevision, title: {text, source} \| null}` | `{revision}`; errors `conflict`, `not_found`, `storage`. The call is the handover; after a commit SessionStore emits the title notice | -| SessionStore (S5b) | title notice | Session broadcast notice (C6 record, §9) | — | `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}` on the Session's broadcast channel; no sequence number, not replayed | -| `AuxiliaryModel` (the profile's model-selection owner) | `complete` | async | `{model: {providerId, modelId}, request: {system, messages: [{role: "user", content: text}]}}`, optional `cancelled: () => Promise` ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)) | `{text, stopReason, usage}`; rejects with the existing error code/message. Resolve the cancellation reference on timeout or closing and await the original call's settlement | +- The first adopted input starts one attempt; the title appears while the turn is still running; a second input does not retitle. +- A manual rename during generation wins; the automatic write's `change` sees the title and refuses, so the attempt is discarded. +- An image-only first input yields no title and does not rescan later inputs; a withdrawn input never triggers. +- A Goal-first Session titles from the goal's published value, not from the model text; a later operator turn does not retitle. +- No account owner: generation uses the model; no model: the excerpt; a failing relay falls back without consuming an attempt. +- Reload before the store handover writes nothing; an admitted write settles in the store and is not repeated. +- A launch's requested title is written once while untitled; a later rename or clear survives a reload because the `change` refuses. -### A.3 Configuration +## Supersedes -Settings source `session-title`, one document: `enabled: bool` default `true`; `maxLength: u32` default 80, range 10..=200 (A3); `model: {providerId, modelId} | null` default `null`, enabling optional service routing before the latest adopted model in the prefix (§3.3). The schema SessionTitle declares carries the defaults and the range (`minimum`/`maximum`), so Settings rejects an out-of-range value on write and when reading a persisted file, and SessionTitle uses the delivered document without checking it again. Read at each decision. SessionTitle has no tool that writes configuration, so the document is written only through the client methods `settings.read`/`settings.update` (S8b named Settings delivered). A change is a data update with notification, never a reload. Enabling the plugin is structural configuration. An unselectable explicit `model` uses the excerpt fallback (§3.3), without consulting the optional service. +- [session-title-metadata.md](../appserver/session-title-metadata.md): the paragraph describing SessionTitle's calls on the old metadata service (`sessionMetadata.read`/`setTitle`, revision compare). The title value, the source and the notice stay that document's; this contract's dependency table replaces the calls. +- [resource-owner-operations.md](../contracts/resource-owner-operations.md): the SessionTitle row (`store.readMetadata`, `setTitle` with an existing title request). SessionTitle calls `store.title` and `store.setTitle` with a `change`. +- [resource-faces.md](../resource-faces.md): the sentence that SessionTitle uses the process repository operations. +- The Chinese mirror `docs/zh/design/plugins/SessionTitle.md` describes the pre-contract shape; its target is this document. +- This document's earlier 522-line design: its generation policy, limits, acceptance and appendices remain in force; its shape sections are replaced by this contract. -The original row owns the source declaration: `source: "session-title"`, -`userFile: "session-title.json"`, no `projectFile`, and `userOnly: []`. This selects user scope -only; no project document is merged. The file-backed profile uses that user filename; the native -profile uses the existing Settings row `user/session-title`, not a second file or store -([Settings §3–4](../appserver/settings-service.md#3-data-and-state)). The schema rejects unknown -members; `model` is either null or an object requiring nonempty `providerId` and `modelId` strings -and no other members. Missing documents receive the stated defaults at the Settings boundary. -No credentials or model-connection configuration belong in this source. +## Client-visible changes -Character limits for the excerpt and titles count Unicode code points. The auxiliary request -omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remains SessionTitle's. +None. `session.rename` keeps its parameters, its `{title, titleSource, revision}` reply and every error code it publishes; no conflict retry is visible because the store's `change` runs under its own exclusion. A title written by the operator still always wins, now decided inside that callback. -### A.4 Mechanics +## Rule check -| Step | Path | -| --- | --- | -| Listen | The Session's copy of the part listens to its Session's `session/{sessionId}` from `apply`, filters main input/applied, registers an owned task and returns; `sessionLifecycle.closing()` or copy cleanup ends owned work | -| Eligibility | C4 creation snapshot: `interactive !== false && collaborationRole === "leader"` for generation; native omission means true. A requested initial title (`initialTitle`, §3.4) is written for interactive and non-interactive Sessions alike: it needs no model, and it is the caller's own text | -| Trigger | On `input/applied` at `N`: skip if not eligible, disabled, in flight or failed attempts ≥ 3 (A5); otherwise start a generation task owned by the plugin's lifetime | -| Check | `sessionMetadata.read({sessionId})`: skip if any title exists; keep revision `r` | -| Read | The four field queries in §0.1 share published T >= N. No adopted eligible input/text means no title (A8/A10). | -| Generate | Route and fall back under §3.3 within the shared 30 s budget (A4); normalize the first line, remove quotes and trailing punctuation, collapse whitespace, cut at `maxLength`, trim again | -| Write | `setTitle({sessionId, expectedRevision: r, title: {text, source: "auto"}})`; `conflict` or `not_found` discards | -| Timeline | No writes, no Dispatcher registration, no `StateCell` | -| Reload / unload | Cancel before store handover; the owner settles an admitted mutation. Events in the gap are not replayed | - -## Appendix B. Full conflict table - -| Scenario | Sequence order | Outcome | Owner | -| --- | --- | --- | --- | -| First input's turn interrupted or failed | input < `stop/interrupt` | Generation proceeds | SessionTitle | -| Goal's applied `goal:state` record stating an objective | — | Eligible: titles the Session from `` (A10); a later user turn does not retitle | SessionTitle | -| Other inputs without `user` content (Goal's triggers and continuations, source markers) | — | Never trigger, never used | SessionTitle | -| First input withdrawn (`session.input.withdraw`) before it is applied | input < withdraw < `input/deleted` | Never applied: no generation, text never sent; the first applied eligible input triggers | SessionTitle | -| First user input carries only images | — | No automatic title (A8) | SessionTitle | -| Rename before the check | rename < check | Title present: skip | SessionTitle | -| Rename during generation | check (r) < rename (r+1) < write | `conflict`: automatic title discarded | SessionStore revision | -| Concurrent renames | revision order | Last committed rename wins | SessionStore | -| Duplicate `session.rename` | — | Rewrites the same text | SessionTitle | -| Steer/Queue/Append inputs after the first | — | Never in the excerpt | SessionTitle | -| Tool batch, compaction | — | Irrelevant: only the input fact is read | — | -| Child branch inputs | branch filter | Never trigger | SessionTitle | -| Member, stage or scheduled Session | `SessionConfig` | Never generated | SessionTitle | -| Session close during generation | — | Cancel before store handover; an admitted mutation remains owned by SessionStore | Lifecycle / SessionStore | -| Session fork | metadata not copied (A7) | Fork untitled; the next adopted eligible input on `main` triggers generation from the first adopted eligible input in its prefix | SessionTitle | -| SessionTitle, the model-selection owner, SessionStore or Settings reload | — | Before handover, cancel generation; an admitted store mutation follows S5b settlement (D3) | Lifecycle / SessionStore | -| Model or policy unavailable | — | Failure counted; after 3 no further attempts until reload (A5) | SessionTitle | -| Resource node offline | — | No effect | — | -| Client detach | — | No effect | — | - -## Appendix C. Errors and recovery - -| Case | Result | +| Rule | Application | | --- | --- | -| Model error, timeout, empty output, unavailable policy | Input-excerpt fallback (§3.3); cancellation never falls back | -| Settings read fails | Automatic: no write, diagnostic, failure counted; rename: `storage_failed`. No fallback document | -| `setTitle` `conflict` on automatic write | Discarded (diagnostic) | -| `setTitle` `storage` | Automatic: failure counted; rename: `storage_failed` | -| Unknown Session on rename | `session_not_found` | -| SessionTitle reloading | Before handover: service_reloading, no rename. After handover/lost reply: read metadata; do not infer no commit or repeat the write | -| Cancellation | Before handover abort the auxiliary call and discard; after store admission, S5b owns the atomic outcome | - -## Appendix D. Acceptance - -Flow tests through the default native product assembly without language runtimes, -`session.create`/`session.submit`, `session.rename`, -`session.summaries`, `settings.read/update` and a fake auxiliary model: - -1. Hold the main turn open with the existing model fixture. The first `session.submit` on an interactive leader Session starts generation after adoption and produces an `auto` title while that controlled turn is still active; the request contains only the system text and that input's text, and one title notice reaches subscribed clients. Completion before turn end is not a production ordering guarantee. -2. Interrupting or failing the first turn does not prevent the title. -3. Member Sessions and `interactive: false` Sessions get no title; rename works on them. -4. Rename during generation (fake model held): manual kept, automatic discarded. -5. A titled Session is never regenerated; clearing allows regeneration at the next adopted input, still from the first adopted input's text. -6. Rename of an unloaded Session loads it through Rpc and succeeds. -7. Child-branch inputs and inputs without `user` content never trigger; image-only first input yields no title and later inputs do not scan history again. -8. Reload before store handover cancels generation without writing; the next adopted input may trigger. Reload after admission leaves settlement to SessionStore; reread metadata after a lost reply without repeating the write. Three failed attempts to obtain settings or commit metadata stop attempts; generation failure uses the excerpt fallback (§3.3). -9. Invalid rename method/type, empty text and control characters return `invalid_params` even when Settings cannot be read; the length check uses the validated Settings document. -10. A first input withdrawn before it is applied (`session.input.withdraw`) produces no title and is never sent to the auxiliary model; the next adopted input titles the Session from its own text. -11. Missing Settings documents yield the declared defaults; invalid persisted settings fail without rewriting them. Updates use existing Settings CAS, reject invalid ranges/shapes, and affect the next title/rename decision without reloading the row. Project scope is rejected. Disabled generation reads neither metadata nor Timeline queries across repeated inputs. Cover non-BMP text at the excerpt/title limits, punctuation before first-line trailing spaces and whitespace at the truncation boundary in the title flow. - -12. Optional generation service absent or withdrawn: ordinary model generation and rename remain available. Nonmatching provider uses only the model; a matching service success avoids a duplicate model request. Explicit model bypasses the service. Unavailable, failed and invalid responses fall back to the model; model failure or deadline uses the excerpt. Closing while the service is pending cancels and settles it without model fallback or metadata writes. - -13. A Goal-first Session is titled from the applied objective with no operator input: the request carries the `` text alone and one title notice arrives. A later user turn does not retitle it; a user-first Session keeps its turn's title when a goal is applied afterwards; a non-interactive Session with a goal stays untitled while `session.rename` works; and a failing auxiliary call falls back to the objective excerpt. - -## Appendix E. Assumptions - -A1–A12 are the policies for the first implementation. - -| # | Assumption | Basis | Effect if rejected | -| --- | --- | --- | --- | -| A1 | Explicit title model first; otherwise optional service then the adopted model (§3.3) | Maintainer decision | Different routing | -| A2 | Instruction text, 8-word target, 2000-character excerpt | Judgment | Different prompt or excerpt | -| A3 | Title length default 80 (10..=200), single line | Judgment | Other limits | -| A4 | 30 s generation budget | Judgment | Other timeout | -| A5 | At most 3 failed attempts per Session per plugin generation | Judgment | More retries, or none | -| A6 | `session.rename` with `null` clears the title | Judgment | Manual title permanent | -| A7 | Session fork does not copy the title | Judgment | Fork shows the source title | -| A8 | A first user input without text produces no automatic title | Decision: title from first user input | Later inputs or a placeholder | -| A9 | Generation waits for adoption (`input/applied`); a deleted input never titles the Session | Maintainer decision | Deleted text could reach the auxiliary model | -| A10 | "User input" means an operator input with `user` content, or Goal's applied `goal:state` record, which states the objective. The record's format is Goal's ([Goal A.5](Goal.md#a5-model-visible-texts)): SessionTitle decodes it and owns no second contract, so a format change is Goal's and updates this reader in the same change. Collaboration and ShellInput write raw blocks only; Scheduler and Workflow inputs carry `user` content but run in non-interactive Sessions, which SessionTitle does not title. A Goal-first Session titles from its objective, and a later user turn does not retitle it. A Goal-first Session whose history predates the record (only the old `goal:objective`/`goal:status` keys) keeps the earlier behaviour: it stays untitled until its first operator turn, or until a later Goal change writes a record; Goal backfills none at load ([Goal A.3](Goal.md#a3-reading-the-goal)). | Judgment | A Goal-created Session stays untitled, and clients need a second title source | -| A11 | SessionStore announces title changes with a Session broadcast notice; a client that is not subscribed sees the change at its next `session.summaries` | Principles §4 rule 9 | Clients poll `session.summaries` | -| A12 | User-only source file session-title.json, no project merge; native Settings row user/session-title | Existing S8b row source mechanism, A.3 | Different source/scope requires explicit confirmation | - -## Appendix F. Open questions - -None. Session list fields follow S5b; observation, Timeline queries, Settings, metadata and the named -auxiliary binding use the owner contracts in §0. The optional service contract is owned here (§3.3); no Core change is required. - -## Appendix G. Rust binding - -| Neutral | Rust | -| --- | --- | -| Namespace `session.rename` registered with `sessionMethods` | The Session part calls `methods.register(ctx, "session.rename", Vec, handler)` on a `Key` dependency | -| Published branch properties | Required `Key`; `TreeCommands::query("main", TimelineQuery)` with branch scope, `include_publishing: false` and one-row `QuerySelect::Fields` results. Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | -| Title metadata | `SessionMetadataService::read` and `SessionMetadataService::set_title` | -| Auxiliary call | `AuxiliaryModel.0.complete` with its cancellation token | -| Optional generation | `ctx.get_at(&host_key("sessionTitleGenerator"))` at use; `HostDispatch.generate` with a cancellable callback promise, using the request/reply types exported by `dim-session-title` | -| Session broadcast listener | Listener on `session_channel(session_id)` for `Event` records, removed by `ctx.effect` | -| Generation task | Spawned under `ctx.effect` | +| §1 parts and Capabilities | One Session part. It writes no Timeline event and folds no state, so it is not a Capability. | +| §2 scopes | Session: the policy and the in-flight attempt live with the Session; the title value lives in SessionStore. | +| §3 orthogonality | The part reads the line's facts and the account's answer and returns only its own decisions; the title value is the store's. | +| §4 rule 1 (commands) | The title is written through the store's operation; no other owner's state is written. | +| §4 rule 2 (handover) | The write is the handover; after admission the store owns the outcome. | +| §4 rule 3 (before callbacks) | None registered. | +| §4 rule 4 (no business meaning in core) | The instruction, the excerpt rule and the routing are SessionTitle's. | +| §4 rule 5 (batches) | No batches. | +| §4 rule 6 (context) | No model-visible text is added to the Session's context; the title request is a separate one-shot call. | +| §4 rule 7 (public events and services) | The Session broadcast, the line's read, the store's operations, Provider's `invoke`, the optional account face and Settings. | +| §4 rule 8 (requirements) | One requirement on SessionStore, listed below. | +| §4 rule 9 (facts) | The title never enters the Timeline; the store announces each commit. | +| §7 values, ids and callbacks | The Session id, the title value and the revision cross; `setTitle` takes the caller's `change` by reference and the model request takes Provider's consumer; no object crosses. | +| §7 no proxy lookup | SessionTitle returns only its own decisions; the title value comes from the store and the account answer from the account owner. | +| §7 one interface | One method namespace; no service of its own; no adapter. | +| §7 cross-language | The rename is data; the internal generation has no cross-owner caller. | +| §7 one change | Deleting the optional generator name, the required auxiliary dependency and the model-text decode happens in the same change that adds the store precondition and the account call. | +| ADR 002 D1 | The policy is Session state; the title value is the store's. | +| ADR 002 D2 | No wiring plugin: the part registers one namespace and calls owners' operations. | +| ADR 002 D3 | Dependencies point from SessionTitle to SessionScope, SessionStore, TimelineTree, Provider, Settings and optionally the account owner. | +| ADR 002 D4 | `enabled`, `maxLength` and `model` are business configuration read at use; enabling the plugin is structural. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +- None open. SessionStore's current contract ([#2091](https://github.com/arcships/dim/pull/2091)) has `setTitle {id} + change` running the change under the owner's serialization with `rejected` as a kind, and `title` answering `{text, source}`; this document depends on exactly that. + +## Binding appendix ```rust -// SessionMetadataService (S5b; named service `sessionMetadata`) -async fn read(&self, session_id: &str) -> Result; -fn set_title(&self, session_id: &str, expected_revision: u64, title: Option) - -> impl Future<Output = Result<u64, MetadataError>>; // Conflict | NotFound | Storage; the call is the handover -pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } -pub struct Title { pub text: String, pub source: TitleSource } // Auto | Manual -// AuxiliaryModel (the profile's model-selection owner) -async fn complete(&self, model: ModelId, request: AuxiliaryRequest, - cancel: CancellationToken) -> Result<AuxiliaryReply, AuxiliaryError>; +use dim_app_server::storage::{MetadataError, SessionMetadata, Title, TitleSource}; + +/// The Session part reads and writes the store's own types; `set_title` takes the +/// caller's `change`, and the reply carries the committed revision. +async fn rename(&self, request: RenameRequest, cancelled: CancellationToken) -> Result<RenameReply, RenameError>; + +pub struct RenameRequest { + pub session: String, + pub title: Option<String>, +} + +pub struct RenameReply { + pub title: Option<String>, + pub title_source: Option<TitleSource>, + pub revision: u64, +} + +/// The method's wire errors are the ones already published; the enum only names them. +pub enum RenameError { + InvalidParams(String), + SessionNotFound, + StorageFailed(String), + ServiceReloading, + OperationInterrupted, +} + +/// One title decision inside the store's exclusion. `StoredTitle` carries the +/// text, the source and the revision the store holds now; `Rejected` is the +/// store's kind for a change that refuses, and SessionTitle treats it as +/// "discarded" for an automatic title and as `invalid` for a rename. +pub type TitleChange = Arc< + dyn Fn(Option<StoredTitle>) -> Result<Option<Title>, Rejected> + Send + Sync, +>; ``` + +The store's `title` and `setTitle` shapes are SessionStore's contract ([#2091](https://github.com/arcships/dim/pull/2091)); this appendix restates none of them. diff --git a/docs/design/plugins/Web.md b/docs/design/plugins/Web.md index 7aa51e4ad8..37a4ba9511 100644 --- a/docs/design/plugins/Web.md +++ b/docs/design/plugins/Web.md @@ -1,262 +1,172 @@ # Web -Status: Implemented as a built-in Rust plugin in `dim-app-server`. Overall design: [overview](../overview.md) (Web). Phase: P2. Language: Rust. Scope: [ADR 002](../../adr/002-plugin-scope.md) (Session). - -Web is a Session plugin with two tools. `web_fetch` is always declared while the part is Active; `web_search` is offered by a dynamic tool source the part registers with the Session's `toolRegistry`, only while a search service is usable ([tool contributions §7](../../architecture/rust-agent/tool-contributions.md#7-动态工具来源); [session-boundary A.5](../contracts/session-boundary.md#a5-tool-contribution), [ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)). Search goes to a configured built-in search adapter; fetch downloads one public page and returns bounded text. Web holds no state shared across Sessions, writes no Timeline event (every call and result is already a tool call fact) and reads its business configuration from its Settings source `web` at use time, so editing it never reloads anything ([ADR 002 D4](../../adr/002-plugin-scope.md#d4-structural-configuration-and-business-configuration-are-separate)). The offered `web_search` set follows committed writes of that source and the managed account's sign-in state; when managed search first becomes necessary for a Session, Web asks the account owner for one provider-owned observation of its store, so a sign-in or sign-out another process wrote is visible without an account RPC. A branch adopts the set as its tool part, and each request's declaration is fixed when the request is built, so a change reaches the first request built after that adoption (A3). - -## 1. Structure - -```mermaid -flowchart LR - subgraph PROC["Process"] - Settings["Settings: web business source"] - Managed["managedSearch: search"] - end - subgraph SESS["Session"] - Web["Web: web_fetch, web_search source"]:::new - ToolRegistry["ToolRegistry"] - end - subgraph BR["Branch"] - Exec["ToolBinding, ToolExecutor, Approval, Permission"] - end - Web -->|"read source web at use"| Settings - Web -->|"default / dim-oauth search"| Managed - Web -->|"registers its tools"| ToolRegistry - Exec --> ToolRegistry - Exec -->|"execute(ToolCall), cancel request"| Web - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -| Part | Scope | Depends on | Provides | -| --- | --- | --- | --- | -| `web` | Process, when a home exists | `settings`, `partRegistry` | Registers the `web` Settings source and the Session part `Web` | -| `Web` | Session | `settings`, `toolRegistry`, `managedSearch`, the Session config and lifecycle | Registers `web_fetch` and the `web_search` tool source; owns the Session fetch cache; provides no name | +Scope: Session. Issue: #2033 (this contract). The tool parameters, result formats, address policy, error codes and acceptance list are Appendix A–E below and are unchanged; this part states the owner's shape and the calls it makes. The current shape is the one #2033's scan report describes. -**Contracts depended on:** the implemented [C4 tool binding](../session-typescript.md), [named Settings/source declarations](../appserver/settings-service.md), [managed provider contract](../../../crates/dim-app-server/README.md#managed-provider-contract), and Permission's existing `network` risk. #150 supplies tools, #166/#175 supply Settings, and #177 supplies Settings events. Web consumes the `web` source's change events and the managed account's availability, and no Session broadcast; it does not wait for #168. **Contracts defined here:** the two tools, result formats and the `web` document. +Web owns two network call intents — read one public page, search once — the policy they run under, the converted text one Session keeps between page calls, and the rule that decides whether `web_search` is declared. Web provides no service: its public surface is the two tool contributions. -Web is a built-in process row in the App Server. That row registers the `web` Settings source and the Session part; it adds no Web-specific registry or host port. When `searchService` is absent (default) or `{"kind": "dim-oauth"}`, `web_search` delegates the authenticated relay query to `managedSearch` so OAuth tokens stay inside the Rust managed provider; when `searchService` names an explicit adapter such as `brave`, Web queries that adapter directly. Calls read Settings at use time. The part also subscribes, before its first read, to committed writes of the `web` source and to the managed account's availability, and re-evaluates the `web_search` source after either changes, so the declarations follow without a reload: the branch adopts the offered set as its tool part, and a request declares what the branch had adopted when the request was built (A3, [tool contributions §7](../../architecture/rust-agent/tool-contributions.md#7-动态工具来源)). When managed search first becomes necessary for a Session — its assembly, or a Settings change from an explicit adapter to the default — the part asks the account owner for one provider-owned observation of its store before deciding the declaration, so a sign-in or sign-out another process wrote reaches a new or switched Session without an account RPC; afterwards the provider's watch is the source. Non-fatal configuration diagnostics use existing `ToolResult.structuredContent`. +## Use and scope: responsibility split -The search API key is `searchService.apiKey`, a user-only field in Web's Settings source ([settings-service §1.2](../appserver/settings-service.md#12-decision-secrets-belong-to-their-owner)). On Unix, the file-backed profile writes the user document with mode 0600. The native profile stores it as `user/web` in SQLite; its boundary is the product home, created with mode 0700 for a new directory on Unix (Windows inherits the parent DACL). Existing home permissions are preserved, and the database has no separate 0600 guarantee. `userOnly` restricts writes, not local reads: the field is written through the client method `settings.update`, never by Web, and local clients can read it through `settings.read`; remote and paired clients cannot. Web reads it with the document at each call, never keeps it, and never places it in definitions, results, `structuredContent`, diagnostics, errors or logs. +Web owns: -**Reload.** PluginManager owns the built-in `web` row's on/off state; see §6. Explicit `plugin.reload` returns `not_reloadable`. Web depends on the process service Settings and on the Session's `toolRegistry`, which it registers with, and reads the Session's configuration (its mount list) and lifecycle. A Settings reload reloads its dependent Web parts: ToolRegistry does not depend on Web (session-boundary A.5), so the Session keeps running: Web's registrations are withdrawn while Web reloads and its tools are offered again from the next request once it registers them again, without a Session reload (#241); an in-flight call is settled by ToolExecutor as reloaded. This follows the dependency lifecycle ([ADR 002 D3](../../adr/002-plugin-scope.md#d3-dependencies-follow-scope-and-point-from-extensions-to-the-core)). Configuration edits never reload; they change the offered `web_search` set, which the branch adopts, and the first request built after that adoption declares it (A3). +- **The two calls.** A page read under the address and content policy (Appendix A.3, A.4) and a search under the query rules (A.2), each with its own time limit and cancellation. +- **The declaration.** `web_fetch` is always declared while the part is Active; `web_search` is offered only while a search service is usable, composed from the `web` Settings source and the account owner's availability subscription (A.1, A.3 of the tool contributions page). +- **The converted-text cache.** One Session's converted pages, keyed by final URL, bounded by age and bytes, so a later page of the same text needs no second request (A9). +- **The result text.** Headers, truncation notices, redirect notices and error codes the model acts on (Appendix A.2, A.3, C). -**Node.** Requests leave from the App Server process that hosts the Session, not from the Session's resource node (A2). +Callers keep as business: -## 2. Data and state +- Whether a call may run: Permission and Approval decide, and Web never admits anything itself. +- What a result means for the conversation; Web returns tool results only. +- Which tools a Session mounts: `SessionConfig.tools` is SessionScope's record and ToolRegistry's rule. +- The search service and its key: the operator writes them through `settings.*`; Web reads and never writes them. -```mermaid -flowchart TB - subgraph CFG["Business configuration (Settings source web)"] - WebCfg["searchService, allowPrivateHosts, proxy, proxyDns"] - Secret["searchService.apiKey (user-only)"] - end - subgraph MEM["Web memory per Session (not persisted)"] - Cache["Fetch cache, bounded (A9)"] - Inflight["In-flight calls: abort handle each"] - end - subgraph TL["Branch Timeline (written by others)"] - Calls["step/tool-call ... step/tool-result, approval/*"] - end - WebCfg -->|"read at call start"| Inflight - Secret -->|"read with the document per call"| Inflight - Inflight -->|"one ToolResult per call, written by ToolExecutor"| Calls +| Requirement (caller) | Can callers compose it from the owner's operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Read one public page as bounded text | No: the address policy, the conversion and the byte limits are the owner's | `web_fetch` tool contribution | +| Search once, with domain filters | No: the query rules, the service selection and the account fallback are the owner's | `web_search` tool contribution | +| Continue a long page without fetching it again | No: only the owner keeps the converted text across calls | the owner's cache; `start_char` on the next call | +| Declare `web_search` only while a service is usable | No: the availability subscription is the account owner's and the declaration is this owner's | the part's tool source, re-evaluated on a committed `web` write and on an availability change | +| Read the current configuration | No: the source and its defaults are Settings' | Settings' `read` at use | +| Decide whether a call may run | Yes: Permission and Approval decide | business, in ToolExecutor | +| Show or judge a result | Yes: the result is text on the call's fact | business | + +An operation or parameter exists only where its row says No. + +## Caller example + +A tool call is one contribution; the handler receives data and a cancellation and returns the model-visible result. No other owner's object appears. + +```rust +// Registered from the part's apply: a fixed tool. +tools.register(ctx, ToolContribution { + definition: fetch_definition(), // name, description, schema, risk network + handler: Arc::new(WebFetch { settings: settings_id.clone(), cache: cache.clone() }), +})?; +// And the dynamic source: one set holding web_search while a search service is usable. +tools.register_source(ctx, "web", Arc::new(SearchSource { /* ... */ }))?; ``` -Web owns no Timeline state and no `StateCell`. The cache starts empty when Web is applied; nothing is rebuilt from the Timeline. - -## 3. Flows - -### 3.1 A `web_fetch` call - -```mermaid -sequenceDiagram - participant L as Loop - participant TL as Timeline - participant X as ToolExecutor - participant A as Approval and Permission - participant W as Web handler - participant N as Remote site - L->>TL: step/tool-call - TL-->>X: Dispatcher delivers, X registers batch task and returns - X->>TL: append step/tool-start - X->>A: admit risk network - A-->>X: allow (or ask, deny) - X->>W: execute(ToolCall) - W->>W: validate URL, select resolution and address policy (A.4) - W->>N: GET via validated IP or proxy-resolved hostname (A.4) - N-->>W: body up to 5 MiB - W-->>X: ToolResult header plus text slice - X->>TL: step/tool-completed, then one step/tool-result for the batch +```rust +// One fetch: read the source, apply the policy, convert, answer a slice. +let document: WebDocument = settings.read(settings_id.clone(), Scope::User, cancelled.clone()).await?.document; +let page = self.cache.page_or_fetch(&request.url, &document, cancelled).await?; +Ok(page.slice(request.start_char, request.max_chars)) ``` -The handler runs on ToolExecutor's task and decides only from its arguments and the configuration read at call start. Longer pages are read with further calls using `start_char`; a cross-host redirect is returned as a notice so the new host gets its own admission (A10). - -### 3.2 A `web_search` call - -```mermaid -sequenceDiagram - participant X as ToolExecutor - participant W as Web handler - participant S as Settings - participant M as managedSearch - participant Q as Search service - X->>W: execute(ToolCall: query, filters) - W->>S: read searchService - alt absent (default) or dim-oauth - W->>M: search({query, count}) - alt signed in and available - M->>Q: authenticated POST /web-search - Q-->>M: hits - M-->>W: hits - W-->>X: numbered result list, domain filters applied by Web - else not signed in or no managed provider - M-->>W: unavailable - W-->>X: error search_unavailable - end - else configured adapter (e.g. brave) - W->>Q: query over HTTPS - Q-->>W: hits - W-->>X: numbered result list, domain filters applied by Web - else no usable service - W-->>X: error search_unavailable - end +```rust +// One search: the account owner's search when the source names no adapter. +let reply = account.search(SearchRequest { query, count }, cancelled).await?; +Ok(numbered(&reply.results, &request)) ``` -While a Session's Web part is Active, `web_search` is declared only while a search service is usable: an adapter configured with its API key, or, for the default (when `searchService` is absent or `{"kind": "dim-oauth"}`) a signed-in Dim account used through `managedSearch`. The part offers the tool as a dynamic source and withdraws it when the configuration or the account makes the service unusable; the change applies to the first request built after the branch adopts the new set, without a reload, and a request built before that adoption keeps the declaration it was built with (A3). A call-time failure of a usable service — network, service error or invalid response — does not withdraw the tool; it returns the call error (Appendix C). A Session whose mount list (`SessionConfig.tools`) does not name `web_search` never declares it. - -## 4. Timing and conflicts - -```mermaid -sequenceDiagram - participant TL as Timeline - participant X as ToolExecutor - participant W as Web - Note over TL,W: Turn interrupt during a request - TL->>X: step/tool-start - X->>W: execute - TL-->>X: stop/interrupt (seq after tool-start) - X->>W: cancel request - W-->>X: error result cancelled (socket closed) - X->>TL: step/tool-result for the batch -``` +## Own contract + +### Dependencies -| Scenario | Outcome | Owner | +| Owner | Operation | Use | | --- | --- | --- | -| Configuration edit during a call | Call continues with values read at its start; next call uses the new values | Web | -| Service removed or account signed out between calls | The first request built after the branch adopts the withdrawal no longer declares `web_search`; a request built before that adoption keeps the declaration it was built with, and a call from it returns `search_unavailable` | Web | -| Web or Settings reload mid-call | The call is settled as reloaded; ToolRegistry and Loop keep running, and Web's tools are absent until Web registers them again, then offered from the next request (D3, #241) | ToolExecutor | -| Process restart mid-call | ToolExecutor settles the committed call as not surviving recovery; Web never repeats a request | ToolExecutor | -| Compaction after a result | Fetched text survives only through the summary | ContextPreparation | +| Settings ([#2017](https://github.com/arcships/dim/issues/2017)) | `register`, `read` | The `web` source: search service, private-host exceptions, proxy, proxy DNS; read at each call | +| `dimAccount` (DimOAuth, [#2019](https://github.com/arcships/dim/issues/2019), optional) | `availability`, `subscribe`, `search` | The relay's sign-in state, its changes, and the relay search when the source names no adapter | +| Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `toolRegistry.register`, `toolRegistry.register_source` | The fixed `web_fetch` contribution and the dynamic `web_search` source | -Full table in Appendix B. +The account owner is read by its face name when the source names no search adapter. A profile without an account owner declares `web_fetch` only; a profile with one declares `web_search` while that owner reports a usable account. -## 5. Context mapping +### Operations -| The model sees | Form | Position | -| --- | --- | --- | -| `web_search`, `web_fetch` name, description, input schema | Tool declarations | Adopted `context/configured.tools` when the Session mounts them: always without a mount list (`SessionConfig.tools`), and those its list names with one. `web_search` only while a search service is usable | -| Search results, fetched text, errors, redirect notices | `ToolResult.content` (text only) | Tool result position of the call's batch | +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `web_fetch` | Read one public `http(s)` page as bounded text | `{url, start_char?, max_chars?}` | `ToolResult.content`: the header block and the text slice; `structuredContent` for clients (A.3) | The call stops: the request is aborted and the socket released before the result is written | error codes as `ToolResult.isError` (Appendix C) | +| `web_search` | Query the configured service | `{query, max_results?, allowed_domains?, blocked_domains?}` | `ToolResult.content`: the numbered result list; `structuredContent` for clients (A.2) | As `web_fetch` | error codes as `ToolResult.isError` (Appendix C) | +| declaration | Offer `web_search` while a service is usable | — | the tool source's current set and its version | — | — | -- Compaction: declarations survive as configuration; results only through the summary. -- Child branches inherit results in their ancestor prefix. -- Non-interactive Sessions see the same declarations for the same configuration and can use them; the tool set stays the same across Sessions (#30). -- Never visible: `structuredContent`, the service name, configuration, the API key, private-host exceptions, diagnostics. -- Fetched page text is untrusted third-party content placed in a tool result without instruction framing (A14). +The tool error codes are business results the model reads and acts on: `invalid_input`, `blocked_address`, `dns_failed`, `connect_failed`, `timeout`, `http_status`, `too_many_redirects`, `unsupported_content_type`, `search_unavailable`, `search_failed`, `settings_unavailable`, `cancelled` (Appendix C). A failed call changes nothing else and affects no other call. -### 5.1 Model-facing texts +### Flows -The two declarations are built-in and protocol throughout ([model-facing prompts §4](../model-prompts.md#4-protocol-and-policy)): both schemas, and both descriptions, which state what each call does and returns — "Search the web. Returns numbered titles, URLs and snippets." and "Read a public web page as text. Use start_char to continue at the returned final URL.", the second naming the continuation argument and the final URL the result carries. Both result texts are protocol: +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `web_fetch`, `web_search` | Read the source, run the call under the policy, convert, answer one result | The request is aborted, the socket released, the call answers `cancelled`; a response fully converted before the abort is returned as it is | The part's tracker stops and joins the in-flight call before the part unloads | The part's close aborts in-flight calls; ToolExecutor settles them as reloaded; the next generation registers the tools again | the calling row: the converted text and the socket; ToolExecutor: the call's terminal fact | +| Declaration | The source offers `web_search` while the account reports a usable service; a committed `web` write or an availability change re-evaluates it | — | The registration goes with the part | Reload withdraws the registrations and the next generation offers the current set | Web: the offer; ToolBinding: which declaration a request adopts (A.1) | -| Text | Class | -| --- | --- | -| `web_fetch failed: <code>: <message>` and `web_search failed: <code>: <message>` | Protocol: the result format and its codes (Appendix C); the model reads the code and acts on it | -| The `web_fetch` header's `URL:`, `Title:`, `Content-Type:` and `Characters: <start>-<end> of <total>` lines | Protocol: the result format | -| `[Truncated: call web_fetch again with start_char=<end> to continue.]` and `Redirected to <url>; call web_fetch with that URL to follow it.` | Protocol: the handles that continue a read; the model passes them back | -| The search result list, the fetched text slice and the redirect notice's URL | The service's and the page's own content, carried as material | +### Errors -Web writes no marker and contributes no guide entry; its declarations have no policy text. +The tool result codes are listed above and detailed in Appendix C. Web has no operation-level errors: it provides no service, and every failure is a result the model reads. -## 6. Interfaces (summary) +## Exceptions with reasons -| Interface | Kind | Purpose | -| --- | --- | --- | -| `web_search` | Tool offered by Web's dynamic source to `toolRegistry` (Session), risk `network` | Query the configured service; numbered result list | -| `web_fetch` | Tool registered with `toolRegistry` (Session), risk `network` | Fetch one public `http(s)` URL; bounded text slice with pagination | -| `web` source | Business configuration in Web's Settings source, read at use | Search service, private-host exceptions, proxy | - -No Session methods, `managementMethods` or CLI subcommand: protected client configuration uses the implemented `settings.read`/`settings.update`. No `/settings` UI is assumed. Details in Appendix A. - -### 6.1 Registration and source - -The process row `web` is registered with the App Server when a home exists. Its apply registers the Settings source `web` (user file `web.json`, no project file) and the Session part `Web` with `partRegistry`. Each Session mounts that part. The part injects `settings`, `toolRegistry` and `managedSearch`, and reads the Session's configuration (its mount list) and lifecycle. Its apply registers cleanup, `web_fetch`, and the `web_search` source; when the configuration needs the managed account, it asks the owner for one provider-owned observation of the account store while assembling the source, then re-evaluates the source on each committed write of the configuration and each account change, observing the account once more when a later configuration starts needing it. The Rust spelling is Appendix G. - -The source schema the row registers, with `userOnly` paths `/searchService`, `/allowPrivateHosts`, `/blockPrivateAddresses` and `/proxyDns`: - -```json -{ - "type": "object", - "additionalProperties": false, - "properties": { - "searchService": { - "type": "object", - "required": ["kind"], - "additionalProperties": false, - "properties": { - "kind": { "type": "string", "minLength": 1 }, - "endpoint": { "type": "string", "format": "uri" }, - "apiKey": { "type": "string", "minLength": 1, "writeOnly": true } - } - }, - "allowPrivateHosts": { - "type": "array", - "items": { "type": "string" }, - "default": [] - }, - "blockPrivateAddresses": { "type": "boolean", "default": false }, - "proxy": { "type": "string", "format": "uri", "writeOnly": true }, - "proxyDns": { "type": "boolean", "default": true } - } -} -``` +- Web reads the account owner's availability and follows its changes instead of failing the model's call: the declaration must follow a sign-in another process wrote, and a subscription is the account owner's own value. +- The converted-text cache is Web's own projection with its own freshness bound (15 minutes, 50 MiB, final URL): pagination is the only reader, and no other owner can answer for a page Web converted. +- A tool registration is a callback by reference on the mechanism's registration point, which §7 names as not a forwarding facade; Web keeps no second interface beside it. +- `web_fetch` is declared even when no search service is usable, and stays declared while the page path works: the two tools have independent availability. + +## Verification + +The acceptance list is Appendix D. It covers the declaration following a service change without a reload, the result formats and domain filters, pagination and the download limit, redirects, the address policy, permission, interrupt settlement, restart settlement, non-interactive Sessions and secret redaction. -Execution follows the tool handler with the call's cancellation token. Every call reads the user-scoped `web` source. A read failure, or a stored document that does not deserialize into the web document, fails the call with `settings_unavailable` and opens no connection. Web does not substitute defaults for that document. When an API-key adapter is configured, the key is `searchService.apiKey`. When `searchService` is absent or `{"kind":"dim-oauth"}`, `web_search` calls `managedSearch` and does not read OAuth tokens. +## Supersedes -Settings treats `format: "uri"` as an annotation. Web parses `searchService.endpoint` and `proxy` when constructing an HTTP request, rather than revalidating the Settings document. An unparsable endpoint fails `web_search` with `search_unavailable`. An unparsable proxy fails `web_search` with `search_unavailable` or `web_fetch` with `connect_failed`. No connection is attempted, no direct-connection fallback is used, and diagnostics omit configuration values. Web's proxy settings apply to fetches and directly configured search adapters; account-backed search follows the managed provider contract. +The Chinese mirror `docs/zh/design/plugins/Web.md` describes the pre-contract shape; its target is this document. -The initial source is the user file `web.json`, read at user scope, with no projectFile or implicit user/project merge (A16). Clients write private-host exceptions; Web has no configuration-writing tool. The App Server registers the built-in Web row whenever a product home exists; Web requires no package installation. [PluginManager acceptance item 5](PluginManager.md#appendix-c-acceptance-m1) governs its on/off state: `plugin.disable {"name":"web"}` withdraws its tools from the next request of an open Session; `plugin.enable {"name":"web"}` restores them there and in new Sessions. The state survives a restart. Explicit `plugin.reload` returns `not_reloadable`. +None outside this document: the tool parameters, result formats, address policy, error codes and acceptance in Appendix A–E stay in force, and the previous version of this file's structure sections are replaced by the sections above. -## 7. Security +## Client-visible changes -- Admission: both tools declare `network`; every call passes Approval and Permission (read-only denies, workspace-write asks, FullAccess allows). -- SSRF: the policy is explicit. With `blockPrivateAddresses` off (default) Web connects to whatever the host can route to, including a local proxy, a TUN device or a Fake-IP answer; with it on, Web resolves once and checks every answer before the request, and pins the first permitted address when it connects directly. A proxy resolves the target in both `proxyDns` modes (A.4). Cross-host redirects need a new call and a new admission (A10). -- No ambient authority: `GET` only; no cookies, stored site credentials or client certificates; nothing from the Session except the URL the model wrote (A8). -- API key: read with the document per call; never in definitions, results, `structuredContent`, diagnostics or errors. -- Exfiltration through URLs is the inherent risk of the `network` category and is controlled by admission. -- With `proxy`, the target form follows A.4 (`CONNECT` for `https`, absolute-form for `http`); certificate verification, SNI and the `Host` header use the original URL host. +None. Both tools keep their names, schemas, descriptions, results and error codes; the search service still follows `settings.read` and the account's availability, and the declaration timing is the one [#1977](https://github.com/arcships/dim/pull/1977) merged. -## 8. Rule check +## Rule check -| Rule | How this document complies | +| Rule | Application | | --- | --- | -| Principles §4 rule 1 (commands for others' state) | Web changes no other module's state; tool results are written by ToolExecutor, their owner. | -| Principles §4 rule 2 (handover) | Not applicable: Web takes over no object; it only runs calls ToolExecutor hands it. | -| Principles §4 rule 3 (before callbacks only) | No intervention before a write; argument checks are inside the tool handler. | -| Principles §4 rule 4 (no business meaning in core) | No core change; the tools use the generic tool registration contract. | -| Principles §4 rule 5 (batch) | Not applicable: Web decides from call arguments and configuration, not from events. | -| Principles §4 rule 6 (context from handed-over events) | Results reach the model only as `step/tool-result` facts written by ToolExecutor. | -| Principles §4 rule 7 (public events and services only) | Web uses only `toolRegistry`, `managedSearch`, the Settings business source and its change events. | -| Principles §4 rule 8 (requirements to mechanism owners) | Reuse implemented C4, `managedSearch` and Settings bindings; adapter API keys live in Web's own user-only field and account OAuth tokens stay in the Rust managed provider. | -| Principles §4 rule 9 (only facts later decisions use) | Web writes no event; its fetch cache is memory only. | -| Principles §1 (Capability and App Server boundary) | Web is a built-in Session capability. Its code is the App Server process row `web` and the Session part `Web`. It adds no Web-specific host port. | -| ADR 002 D1 (scope follows state) | Session scope: Web holds no state shared across Sessions. | -| ADR 002 D2 (no wiring modules) | No wiring module; search adapters are built in (A1). | -| ADR 002 D3 (dependencies follow scope) | Settings is a process service; a missing required service fails the Web part's assembly and the Session continues without it. | -| ADR 002 D4 (structural vs business configuration) | PluginManager owns the built-in row's structural on/off state (§6); the `web` document is business configuration in Web's own Settings source, read at each call. | -| ADR 002 D5 (language-neutral contracts) | Contracts are neutral; the Rust form is Appendix G. | - -## 9. Requirements raised to mechanism owners - -None. Tool registration, source declarations, Settings read/write/events already have contracts and implementations; the API key is Web's own field. Web raises no additional core, rutis, loader, lifecycle, optional-dependency or diagnostics-service requirement. A missing required service fails assembly of this row. +| §1 parts and Capabilities | One Session part. It writes no Timeline event and folds no state, so it is not a Capability. | +| §2 scopes | Session: the cache and the registration live with the Session; nothing is shared across Sessions. | +| §3 orthogonality | Web reads the source, the account answer and the call's arguments; it returns only its own results. | +| §4 rule 1 (commands) | No command event: results are written by ToolExecutor as the call's fact. | +| §4 rule 2 (handover) | The call is ToolExecutor's; Web returns one result per call. | +| §4 rule 3 (before callbacks) | None registered. | +| §4 rule 4 (no business meaning in core) | Tool names, schemas and result text are Web's. | +| §4 rule 5 (batches) | No batches. | +| §4 rule 6 (context) | Results reach the model only as the call's `ToolResult`. | +| §4 rule 7 (public events and services) | Settings, the optional account face and the tool registry; no subscription of its own besides the account's availability. | +| §4 rule 8 (requirements) | None; the account's availability, subscription and search are defined by the account owner's contract. | +| §4 rule 9 (facts) | Web writes no event; the cache is memory only. | +| §7 values, ids and callbacks | Arguments and results are data; the tool handler is a callback by reference on the registration point; no object crosses. | +| §7 no proxy lookup | Web returns its own results; the account's state and search come from the account owner. | +| §7 one interface | One tool contribution per tool, one dynamic source; no service, no adapter. | +| §7 cross-language | Both tools are declared with data schemas and their results are data. | +| §7 one change | Replacing the search face with the account owner's operations happens in the same change that migrates the declaration and the call. | +| ADR 002 D1 | Session scope: no state is shared across Sessions. | +| ADR 027 D2 | Web resolves no service by id: Settings and the account owner are process dependencies declared at load, and no registration point is reached by id. | +| ADR 002 D2 | No wiring plugin: the tools are on the part; the source is the registry's registration point. | +| ADR 002 D3 | Dependencies point from Web to Settings, the account owner and the registry. | +| ADR 002 D4 | The `web` document is business configuration read at use; the plugin's on/off state is structural. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +None. The account owner's `availability`, `subscribe` and `search` and the tool registry's registration points cover the calls above. + +## Binding appendix + +The part registers one fixed contribution and one dynamic source on `ToolRegistry`; there is no service name of its own. Appendices A–E are the operation details and stay in force. + +```rust +/// `SettingsId` is the id `settings.register` answered for the `web` source. +#[derive(Clone)] +struct WebFetch { settings: String, cache: Arc<PageCache> } + +impl ToolHandler for WebFetch { + fn execute(&self, call: ToolCall, _context: ToolExecutionContext, cancelled: CancellationToken) + -> HostFuture<'_, ToolResult>; +} + +/// The dynamic source: `sets()` answers one set with `web_search` while a +/// search service is usable and no set otherwise. +impl ToolProvider for SearchSource { + fn sets(&self) -> Vec<ToolSet>; +} +``` + +--- ## Appendix A. Interface details @@ -351,13 +261,13 @@ Fake-IP DNS answers are ordinary addresses. With a proxy and `proxyDns: true` th | Field | Type | Default | | --- | --- | --- | -| `searchService` | `{ kind: "<built-in adapter id>", endpoint?: string, apiKey?: string }` or absent; user-only | absent (uses `dim-oauth` via `managedSearch` when signed in; otherwise `web_search` is not declared) | +| `searchService` | `{ kind: "<built-in adapter id>", endpoint?: string, apiKey?: string }` or absent; user-only | absent (uses `dim-oauth` through the account owner's `search` when signed in; otherwise `web_search` is not declared) | | `allowPrivateHosts` | string[]; user-only | `[]` | | `blockPrivateAddresses` | boolean; user-only | `false` | | `proxy` | string (URL); write-only; absent means the session's own proxy (A.4) | absent | | `proxyDns` | boolean; user-only | `true` | -Read at each call and used as delivered: Settings validates the document against the schema Web declares and applies its defaults on write and when reading a persisted file, and Web does not validate it again. Web has no tool that writes configuration, so the document is written only through the client methods (S8b). A change is a data update with notification, never a reload. The row's structural on/off state belongs to PluginManager (§6). Built-in adapter ids are an implementation choice (A13). The API key is `searchService.apiKey` (§1). +Read at each call and used as delivered: Settings validates the document against the schema Web declares and applies its defaults on write and when reading a persisted file, and Web does not validate it again. Web has no tool that writes configuration, so the document is written only through the client methods (S8b). A change is a data update with notification, never a reload. The row's structural on/off state belongs to PluginManager (PluginManager). Built-in adapter ids are an implementation choice (A13). The API key is `searchService.apiKey` (A.5). ### A.6 Timeline and capability mechanics @@ -451,25 +361,3 @@ Flow tests through public interfaces: tool calls in a test Session, a local HTTP | A14 | No framing text around fetched content | Judgment | Model-visible framing to define | | A15 | A configured proxy accepts both forms a target takes: `CONNECT <host>:<port>` for `https`, absolute-form requests for `http` | [ADR 024](../../adr/024-web-fetch-transport.md) | A proxy that accepts only one form cannot serve both schemes | | A16 | Initial source is user file `web.json`, read at user scope; no implicit project merge | Maintainer decision | Define project source/merge semantics before using existing projectFile | - -## Appendix F. Implementation boundaries - -| Question | Current boundary | -| --- | --- | -| Initial scope | Tool parameters, the default network policy, the content policy, A1–A14, A15's proxy forms and A16 are maintainer-confirmed. Web is the built-in process row `web` and its Session part. Product installation of optional packages remains PluginManager work. | -| Configuration diagnostics | Non-fatal configuration diagnostics for UI/persistence use ToolResult.structuredContent; model-actionable information still belongs in content, with no new channel | -| HTML to text | A scanner, not a browser. A `<` followed later by `>` starts a tag, including a bare `<` in prose. Script, style and navigation are removed by regular expressions before that scan. | -| Content encoding | `gzip`, `deflate` and `identity` are decoded. `br` and any other encoding fail as `connect_failed`. An incomplete gzip, zlib-wrapped deflate or raw deflate stream fails with `connect_failed`, unless the download limit was already reached, in which case the capped body is returned with `download_limited`. Raw deflate is the fallback for servers that omit the zlib wrapper. | -| User-Agent | `dim-web/` plus the `dim-app-server` package version | -| Transport | `reqwest`, HTTP/1 only, redirects off, a 10 s connect deadline, manual gzip/deflate decoding with the 5 MiB ceiling. The address policy runs before the request and pins the first permitted address when it is on ([ADR 024](../../adr/024-web-fetch-transport.md)) | - -## Appendix G. Rust binding - -The current Rust binding. Tool names and data shapes are unchanged. - -| Neutral | Rust | -| --- | --- | -| `toolRegistry.register` for `web_fetch` | The Session part injects `Keyed<ToolRegistry>` and calls `tools.register(ctx, ToolContribution {definition, handler})` in its `apply`; the registration is withdrawn when the part unloads | -| dynamic source for `web_search` | The part calls `tools.registerSource(ctx, "web", provider)`; the provider's `sets()` returns one `ToolSourceSet` (key `web`, a new UUID per set) while a service is usable and none otherwise; after a change it emits `ToolProviderChanged` under `tool_provider_changes(session)` from its own context | -| account availability | `ManagedSearch` answers the owner's current sign-in availability and its changes in-process; Web subscribes before its first read and, when managed search first becomes necessary for the Session, asks the owner for one provider-owned observation of its account store before deciding the declaration; afterwards the provider's watch is the source | -| declaration / `execute` | `ToolDefinition` / handler with `CancellationToken`; the disposer aborts in-flight requests ([tool contributions §4](../../architecture/rust-agent/tool-contributions.md)) | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 9fd3844b36..b007057266 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -609,7 +609,7 @@ The repository and Timeline operations use two names on the daemon that owns the and Session-scoped `timelineStore` provides the Timeline operations and completion notifications below. Both use the existing state owner; the split follows §9(6), without changing Session placement or the storage engine. -SessionTitle and FileAccess use the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md). +SessionTitle uses the Session store's `title` and `setTitle` operations, and FileAccess uses the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md) ([SessionTitle](plugins/SessionTitle.md#own-contract)). | Family | Operations | | --- | --- | diff --git a/docs/zh/design/plugins/Goal.md b/docs/zh/design/plugins/Goal.md index 99ad52201e..d133faa5bd 100644 --- a/docs/zh/design/plugins/Goal.md +++ b/docs/zh/design/plugins/Goal.md @@ -1,4 +1,5 @@ # Goal +> 目标契约以英文文档为准:[`docs/design/plugins/Goal.md`](../../../design/plugins/Goal.md)。本文件描述重构前的形状,其中的调用与接口在新契约落地时删除。 总体设计:[overview §4](../overview.md)。阶段:P2。语言:Rust([overview 附录 C](../overview.md))。作用域:Session + 分支([ADR 002](../../adr/002-plugin-scope.md))。依赖([路线图](../../../design/roadmap.md) P5):C1、C3、C4、C5、S1、S8b([#118](https://github.com/arcships/dim/issues/118))。 diff --git a/docs/zh/design/plugins/SessionTitle.md b/docs/zh/design/plugins/SessionTitle.md index 182fcc8832..7d3661571e 100644 --- a/docs/zh/design/plugins/SessionTitle.md +++ b/docs/zh/design/plugins/SessionTitle.md @@ -1,4 +1,5 @@ # SessionTitle +> 目标契约以英文文档为准:[`docs/design/plugins/SessionTitle.md`](../../../design/plugins/SessionTitle.md)。本文件描述重构前的形状,其中的调用与接口在新契约落地时删除。 总体设计:[overview](../overview.md)(SessionTitle)。作用域:[ADR 002](../../adr/002-plugin-scope.md)(Session)。 diff --git a/docs/zh/design/plugins/Web.md b/docs/zh/design/plugins/Web.md index 98a049eb16..7fbfa97579 100644 --- a/docs/zh/design/plugins/Web.md +++ b/docs/zh/design/plugins/Web.md @@ -1,4 +1,5 @@ # Web +> 目标契约以英文文档为准:[`docs/design/plugins/Web.md`](../../../design/plugins/Web.md)。本文件描述重构前的形状,其中的调用与接口在新契约落地时删除。 状态:已实现为 `dim-app-server` 内置 Rust 插件。总体设计:[overview](../overview.md)(Web)。阶段:P2。语言:Rust。作用域:[ADR 002](../../adr/002-plugin-scope.md)(Session)。 From 996079a83e826474b19a1104a1db03229df17757 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 11:24:44 +0800 Subject: [PATCH 2/6] docs(2033): round-4 review and self-check for the four owner contracts Goal keeps the trigger's sequence, names the state record's one writer, takes cancellation on the line read, carries a submission id, states the ended-line client change and the evaluator refusals, and uses GoalViewStatus. SessionTitle follows #2091's ChangeFn binding and drops the broadcast row. Web declares search for a configured adapter. Code Mode gates on the mount exclusion and its examples compile. Compatibility anchors and the standing documents' owner paragraphs point at the new contracts. Refs #2033 --- .../appserver/session-title-metadata.md | 22 +-- docs/design/overview.md | 6 +- docs/design/plugin-contract.md | 2 +- docs/design/plugins/CodeMode.md | 48 ++++--- docs/design/plugins/Goal-state-read.md | 2 + docs/design/plugins/Goal.md | 105 +++++++++++--- docs/design/plugins/Pursuit.md | 8 +- docs/design/plugins/SessionTitle.md | 130 ++++++++++++++---- docs/design/plugins/Web.md | 12 +- 9 files changed, 238 insertions(+), 97 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 035e960224..97d66ade62 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -18,8 +18,8 @@ channel ([C6](session-notices.md)), and Rpc shows the title in protocol v3 Sessi - **Data.** A revision counter (0 means never written) and either no title or a title `{text, source}` with source `auto` or `manual`. Clearing keeps the counter, so a revision never repeats. -- **Write.** `setTitle {sessionId, expectedRevision, title | null}` commits revision `expectedRevision + 1` or fails - `conflict`, `not_found` or `storage`. The call is the handover: SessionStore admits the write when called, unless it +- **Write.** `setTitle {sessionId, the change callback's current title and revision, title | null}` commits revision `the change callback's current title and revision + 1` or fails + `rejected`, `not_found` or `storage`. The call is the handover: SessionStore admits the write when called, unless it is closing, and settles it itself; dropping the call only loses the reply. - **Notice.** After each commit, `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}`, in commit order. @@ -66,7 +66,7 @@ protocol version. | Item | Meaning | | --- | --- | -| `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write sets it to `expectedRevision + 1`: a new title, the same text again, a source change or a clear | +| `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write sets it to `the change callback's current title and revision + 1`: a new title, the same text again, a source change or a clear | | `title` | `{text, source}` or none | | `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, enforced inside `setTitle`'s change callback ([SessionTitle](../plugins/SessionTitle.md#own-contract)) | @@ -88,7 +88,7 @@ protocol version. | Method | Mode | Request | Reply value | Errors | | --- | --- | --- | --- | --- | | `read` | async | `{sessionId}` | `{revision, title: {text, source} \| null}` | `not_found`, `storage` | -| `setTitle` | async | `{sessionId, expectedRevision, title: {text, source: "auto" \| "manual"} \| null}` | `{revision}`: the committed revision | `conflict`, `not_found`, `storage` | +| `setTitle` | async | `{id}` plus the caller's change: current `{revision, title}` in, next title or a refusal out | `{revision}`: the committed revision | `rejected`, `not_found`, `storage` | - Replies use one envelope, `{ok: true, value}` or `{ok: false, error: {code, message}}`, as `settings` does. - Neither method loads the Session. `read` reads committed state and does not wait for the title writer (§5). @@ -100,7 +100,7 @@ protocol version. | Code | When | State after | | --- | --- | --- | | `not_found` | The store holds no record of the Session: never created, deleted, or rolled back. A stored Session that is closed or not loaded is found | Unchanged | -| `conflict` | `expectedRevision` is not the current revision | Unchanged, no notice. Read again | +| `rejected` | the caller's change refused with its own code; nothing changed, no notice | Act on that code; an automatic title is discarded | | `storage` | The transaction failed, or the call arrived after SessionStore started closing (§6) | Unchanged, no notice | ### 4.2 Rust @@ -150,7 +150,7 @@ This settles the boundary that SessionTitle §0 left to S5b. | Before the call | The caller's own work. Cancelling it before the call writes nothing | | The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `storage` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | | After the call | SessionStore settles the write itself: it commits and announces, or fails and writes nothing. Dropping the call, unloading the calling row or losing the reply neither cancels nor undoes it. `setTitle` has no cancel action | -| Lost reply | The caller reads with `read`. It does not repeat the write blindly: a repeat at the old revision fails `conflict`, and one at the new revision would be a second change ([SessionTitle](../plugins/SessionTitle.md#errors)) | +| Lost reply | The caller reads with `title`. It does not repeat the write blindly: a repeat would be a second change, and an automatic title's change refuses once a title exists ([SessionTitle](../plugins/SessionTitle.md#errors)) | | SessionStore unload | Its disposer first stops admission: from then on a call fails `storage` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | Rejected: a cancel action that works until the transaction starts. It would only move the uncertainty, since a caller @@ -166,7 +166,7 @@ that drops the call still has to read to learn the outcome; and a JavaScript cal | `data` | `{title: string \| null, titleSource: "auto" \| "manual" \| null, titleRevision}` | - **Once per commit.** Emitted after each committed write with SessionStore's own context through - `session_broadcast::notify`. A conflict, a missing Session or a failed write emits nothing. + `session_broadcast::notify`. A refusal, a missing Session or a failed write emits nothing. - **No `sessionId` in `data`.** The channel names the Session, and Rpc adds `sessionId` to `session.notice` ([C6 D4](session-notices.md#10-decisions)). - **The list's fields.** `data` holds exactly the three title fields of a v3 Session list entry (§8). A client @@ -202,7 +202,7 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | --- | --- | --- | | `storage` | The catalog read fails as it does today | `storage_failed` | | `not_found` | The Session is not listed | `session_not_found` | -| `conflict` | — | SessionTitle reads again and retries ([SessionTitle](../plugins/SessionTitle.md#operations)) | +| `rejected` | — | the caller's change refused; an automatic title is discarded ([SessionTitle](../plugins/SessionTitle.md#operations)) | ## 9. Lifecycle @@ -219,7 +219,7 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | Scenario | Outcome | | --- | --- | -| Two writes with the same expected revision | The first to commit wins; the other fails `conflict` and announces nothing | +| Two writes | They commit in admission order and each announces its revision; a change that refuses leaves the title as it was | | Writes to different Sessions | Run one at a time by the one title writer; each commits in its own transaction | | `setTitle` and `session.delete` | The store's write transactions order them: a commit first is removed by the delete; a delete first makes the write `not_found` | | `setTitle` and `session.fork` | Independent: the fork copies no title | @@ -328,7 +328,7 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a 1. `setTitle` commits and returns the next revision; `read` returns it. Two v3 clients attached over IPC and WebSocket each receive exactly one `session.notice` per commit, in commit order, with `data` equal to the list's - title fields. A conflict and an unknown Session announce nothing. + title fields. A refusal and an unknown Session announce nothing. 2. Concurrent writers: every commit is announced once, in increasing `titleRevision` order. 3. A clear (`null`) commits a revision with no title and announces nulls. 4. `read` and `setTitle` of a Session that was never created, or was deleted: `not_found`. @@ -369,7 +369,7 @@ fixture](../../../runtime/fixtures/session-metadata.ts); items 6 and 12 hold the | D6 | `titleRevision` in v3 list entries | `title` and `titleSource` only | Without it a client cannot order a list reply against a notice (§8) | | D7 | List fields for protocol v3 only | All protocol versions | v1 and v2 are frozen and receive no title notices | | D8 | Service `sessionMetadata` with `read` and `setTitle`; the Rust binding uses `read` and `set_title` | A.2's method name `metadata` | `sessionMetadata.metadata` repeats itself; `read` matches `settings.read` | -| D9 | Errors `conflict`, `not_found`, `storage` as data; malformed calls are bridge errors | A `rejected` code as in `sessions` | The three codes are the write's outcomes; a malformed call is a programming error, as in `settings` | +| D9 | Errors `rejected`, `not_found`, `storage` as data; malformed calls are bridge errors | A `rejected` code as in `sessions` | The three codes are the write's outcomes; a malformed call is a programming error, as in `settings` | | D10 | `not_found` for a Session the store does not hold | `session_closed` | Maintainer decision; it is SessionStore's vocabulary, and SessionTitle maps it to `session_not_found` | | D11 | SessionStore stores text as given | Validating length and characters | SessionTitle owns the title rules and validates them; checking again would duplicate the contract | | D12 | SessionStore itself provides `sessionMetadata` | A part that never reloads | SessionStore reloads only with SqliteStorage (§12) | diff --git a/docs/design/overview.md b/docs/design/overview.md index 1ab2c8d9e4..07f0951692 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -68,7 +68,7 @@ Green parts are new and orange-bordered parts are changed. Each new plugin part | Plugin | Process | Session | Branch | Reason | | --- | --- | --- | --- | --- | | Questions | — | `ask_user` tool; `session.question.*` methods; in non-interactive Sessions `ask_user` answers that no one is available to answer | — (waiters of running `ask_user` calls live in the Session part; no events, the answer is the tool result) | The waiter is the Session-scoped tool handler's own call | -| Goal | — | `goal_update` tool and `session.goal.*` methods, which only write one `input/message` with `goal:objective` and/or `goal:status` keyed blocks | Goal state folded in sequence order from consumed goal change blocks; continuation decided by Goal when it consumes `turn/end`, `stop/interrupt` or `input/deleted` through the Dispatcher | A goal belongs to exactly one branch: the fold uses only that branch's own events, so child branches and forked Sessions start with no goal; continuation follows its events in order | +| Goal | — | `goal_update` tool and `session.goal.*` methods, which write one command `input/message`; the goal owner writes the state record (superseded by [Goal](plugins/Goal.md), target, pending [#2099](https://github.com/arcships/dim/pull/2099)) | Goal state folded in sequence order from consumed goal change blocks; continuation decided by Goal when it consumes `turn/end`, `stop/interrupt` or `input/deleted` through the Dispatcher | A goal belongs to exactly one branch: the fold uses only that branch's own events, so child branches and forked Sessions start with no goal; continuation follows its events in order | | ModelRecovery (proposal) | — | — | Proposed disposer registration (Loop port not implemented); the handover input it writes through the branch input entrance | The part decides only from committed branch facts and writes one input; the Loop keeps the turn and the batch | | Hooks | Configuration (`hooks`, `hooks-projects` and `hooks-plugins` Settings sources, `hooks.*` management methods and plugin `register`/`withdraw`/`plugins()`, `HookSources` port) in App Server | Hook documents (user, project and plugin); runner; a submit check registered with the Session's `submitChecks`, which the operator-input entries call (`UserPromptSubmit`) | advice registered with Permission (`PreToolUse`); `PermissionRequest` answered through Approval; `PostToolUse`, `PostToolUseFailure`, `Stop`, `SessionStart`, `Notification` from the Dispatcher | Rules apply to a Session; execution happens in a branch | | ShellInput | — | `shell.*` Session methods; runs in the Session's workspace and writes its input | — | Commands belong to the Session | @@ -163,7 +163,7 @@ Index of plugin design documents: [plugins/README.md](plugins/README.md). | ShellInput | Session | `!command` / `!!command` as `shell.run/stop/list` Session methods | P1 | Rust | [ShellInput](plugins/ShellInput.md) | | Attachments | Session | `attachment.put` for large text; Session files | P1 | Rust | [Attachments](plugins/Attachments.md) | | SessionTitle | Session | Title from the first adopted user input; `session.rename` | P1 | Rust | [SessionTitle](plugins/SessionTitle.md) | -| Goal | Session + branch | Goal state folded from `goal:objective` and `goal:status` input blocks; continuation; `goal_update`; `session.goal.*` | P2 | Rust | [Goal](plugins/Goal.md) | +| Goal | Session + branch | Goal state published by the line's owner; continuation; `goal_update`; `session.goal.*` (superseded shape: [Goal](plugins/Goal.md), target, pending [#2099](https://github.com/arcships/dim/pull/2099)) | P2 | Rust | [Goal](plugins/Goal.md) | | Web | Session | `web_search`, `web_fetch` | P2 | TypeScript first | [Web](plugins/Web.md) | | Hooks | Process + Session + branch | Command hooks in Dim's own configuration, with a Claude Code / Codex compatible document shape and script protocol, attached to business owners: Permission (pre-tool advice), Approval (permission requests), the operator-input entries (prompt check), branch inputs (post-tool, Stop, Session start) | M1 | Rust | [Hooks](plugins/Hooks.md) | | Scheduler | Process + Session | Scheduled jobs; `schedule` tool; run-outcome report | P2 | TypeScript first | [Scheduler](plugins/Scheduler.md) | @@ -226,7 +226,7 @@ sequenceDiagram IQ->>TL: input/message, then turn/start ``` -Every goal change (set, edit, pause, resume, clear, and the model's completed or blocked report through `goal_update`) is one `input/message` whose raw blocks carry the key `goal:objective` (set, edit), `goal:status` (set, pause, resume, completed, blocked, automatic pause) or retire both (clear); continuations carry no key and are only counted. Compaction ([ContextCompaction](https://github.com/arcships/dim/blob/roadmap/f1-production-compaction-host-compact-and-u/docs/design/plugins/ContextCompaction.md), F1; branch link until PR #108 merges) keeps the events from `retain_from` (the last turns) verbatim and replays the latest live block of each key placed before it, so the model keeps the current objective and status; it is a Loop step that writes no `turn/*`, so it never triggers a continuation decision. The tool and the `session.goal.*` methods only write that event; they never read Goal's state or decide. Goal's state is the fold of the consumed blocks in sequence order, with no exceptions: the latest live block of each key is the current objective and status, so what compaction replays always equals the fold, and a goal exists only while `goal:objective` is live. Goal decides continuation itself when it consumes `turn/end`, `stop/interrupt` or `input/deleted` through the Dispatcher, from consumed state only; it registers the write as owned work, returns, and rechecks consumed state before writing. Deleted inputs never change the state. A goal belongs to exactly one branch: the fold uses only the events written on that branch, never the inherited prefix, so a child branch and a forked Session's `main` start with no goal and a change there affects only that branch; when Goal consumes a new branch's `branch/start` and the inherited prefix still has a live goal key, it writes one `clear` there as owned work, so the model on the new branch does not take the parent's goal as its own. A `stop/interrupt` pauses the goal. If the interrupt lands after the continuation input, at most one extra turn runs, and the model sees the paused block. +Superseded by [Goal](plugins/Goal.md) (target, pending [#2099](https://github.com/arcships/dim/pull/2099)): the command is one input, the state record is written by the goal owner after its business fact, and a reader that needs the goal reads the owner's value. The paragraph below describes the pre-contract shape. Every goal change (set, edit, pause, resume, clear, and the model's completed or blocked report through `goal_update`) is one `input/message` whose raw blocks carry the key `goal:objective` (set, edit), `goal:status` (set, pause, resume, completed, blocked, automatic pause) or retire both (clear); continuations carry no key and are only counted. Compaction ([ContextCompaction](https://github.com/arcships/dim/blob/roadmap/f1-production-compaction-host-compact-and-u/docs/design/plugins/ContextCompaction.md), F1; branch link until PR #108 merges) keeps the events from `retain_from` (the last turns) verbatim and replays the latest live block of each key placed before it, so the model keeps the current objective and status; it is a Loop step that writes no `turn/*`, so it never triggers a continuation decision. The tool and the `session.goal.*` methods only write that event; they never read Goal's state or decide. Goal's state is the fold of the consumed blocks in sequence order, with no exceptions: the latest live block of each key is the current objective and status, so what compaction replays always equals the fold, and a goal exists only while `goal:objective` is live. Goal decides continuation itself when it consumes `turn/end`, `stop/interrupt` or `input/deleted` through the Dispatcher, from consumed state only; it registers the write as owned work, returns, and rechecks consumed state before writing. Deleted inputs never change the state. A goal belongs to exactly one branch: the fold uses only the events written on that branch, never the inherited prefix, so a child branch and a forked Session's `main` start with no goal and a change there affects only that branch; when Goal consumes a new branch's `branch/start` and the inherited prefix still has a live goal key, it writes one `clear` there as owned work, so the model on the new branch does not take the parent's goal as its own. A `stop/interrupt` pauses the goal. If the interrupt lands after the continuation input, at most one extra turn runs, and the model sees the paused block. ### 5.3 Observer through the Session broadcast (SessionTitle) diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 1d34d18338..61dc999c67 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -107,7 +107,7 @@ R4). This table says what each name Dim defines is for. | --- | --- | --- | --- | --- | | `sessions` | process | Agents | yes | Start or drive another Session | | `sessionPermissions` | process | Agents | yes | Marked `#[rutis::service]` | -| `sessionMetadata` | process | SessionStore | yes | SessionTitle is the title's one writer | +| the store's title operations ([SessionTitle](plugins/SessionTitle.md#own-contract), target, pending [#2091](https://github.com/arcships/dim/pull/2091)) | process | SessionStore | yes | SessionTitle is the title's one writer | | `settings` | process | Settings | yes | Business configuration | | `auxiliaryModel` | process | the profile's model-selection owner | yes | Auxiliary model requests | | `pluginFiles` | process | host | yes, when the host supplies a root | A process part's own files | diff --git a/docs/design/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index 677faace5d..cb24dad7da 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -8,10 +8,10 @@ Code Mode lets the model submit one bounded QuickJS program that invokes the req Code Mode owns: -- **The structural bounds.** `max_code_bytes`, `max_runtime_ms`, `max_calls`, `max_parallel_calls`, `max_memory_bytes`, `max_programs`, `max_output_bytes`, `max_single_result_bytes`. They are configuration, not tool parameters and not prompt text. +- **The structural bounds.** 256 KiB `max_code_bytes`, 600 s `max_runtime_ms`, 4096 `max_calls`, 16 `max_parallel_calls`, 1024 MiB `max_memory_bytes`, 2 `max_programs`, 16 MiB `max_output_bytes`, 4 MiB `max_single_result_bytes`. They are configuration, not tool parameters and not prompt text. - **The process program slots.** At most `max_programs` programs run in one process at a time; the slot is held from the program's start to its settlement and released by the quota owner, including when the caller unloads. - **The one-shot run.** One fresh QuickJS context per call with only `tools.list`, `tools.describe` and `tools.call`; the memory limit, the wall-clock interrupt and the program's cancellation; the outer result's text, effects and failure warning. -- **The tool declaration.** The `codemode` tool's name, description, schema, `session` risk and the v4 client gate. +- **The tool declaration.** The `codemode` tool's name, description, schema and `session` risk. The v4 gate is the Session's mount exclusion: the connection adds `codemode` to the excluded tools for a v1–v3 client, and the entry registers the contribution regardless. Callers keep as business: @@ -26,7 +26,7 @@ Callers keep as business: | At most `max_programs` programs per process | No: the cap is process state and must be settled when the run ends or the caller unloads | `codeMode.with_slot {work}` | | Each child call is admitted on its own | No: admission, the child batch and the terminal result are ToolExecutor's | ToolExecutor's nested operation ([#2028](https://github.com/arcships/dim/issues/2028)); the program only names a tool and its arguments | | A failed program returns a result the model reads | No: the failure text, the effects collected before it and the warning are the run's | the run's reply | -| Only v4 Sessions are offered the tool | No: the declaration is the entry's and the client's protocol version is SessionScope's record | the entry's declaration | +| Only v4 Sessions are offered the tool | No: the exclusion is the Session's creation record, set by the connection's protocol version | the mount exclusion `SessionConfig.excluded_tools`, as `exclude_codemode_below` sets it; the entry adds no version read | An operation or parameter exists only where its row says No. @@ -51,12 +51,14 @@ The line's run owner holds the slot around the program; the slot never leaves th ```rust // CodeModeLine: one program inside one process slot. The gate is the executor's; // the run closes it early to word the result, and the owner settles it again. -quota.with_slot(Arc::new(move |cancelled| Box::pin(async move { - let gate = executor.open(OpenRequest { parent_call_id: outer_call_id, context }, cancelled.clone()).await?; - let outcome = quick_js(code, gate.gate_id.clone(), cancelled.clone()).await; - let effects = executor.close(CloseRequest { gate_id: gate.gate_id }, cancelled).await?; - Ok(program_result(outcome, effects)) // the same effects appear once in the parent result -})), cancelled).await? +let slot: Result<ToolResult, ServiceError> = quota + .with_slot(caller, Arc::new(move |cancelled| Box::pin(async move { + let gate = executor.open(caller, OpenRequest { parent_call_id: outer_call_id, context }, &cancelled)?; + let outcome = quick_js(code, gate.gate_id.clone(), &cancelled).await; + let effects = executor.close(caller, CloseRequest { gate_id: gate.gate_id })?; + Ok(program_result(outcome, effects)) // the same effects appear once in the parent result + })), cancelled) + .await?; ``` ## Own contract @@ -65,11 +67,11 @@ quota.with_slot(Arc::new(move |cancelled| Box::pin(async move { | Owner | Operation | Use | | --- | --- | --- | -| Session access ([#2025](https://github.com/arcships/dim/issues/2025)) | the line's owner by line id | The entry reaches `CodeModeLine`; the run reaches the line's ToolExecutor | -| ToolExecutor ([#2028](https://github.com/arcships/dim/issues/2028)) | `open {parentCallId, context}` → `{gateId}`; `invoke {gateId, call}` → `{result}`; `close {gateId}` → `{effects}` | Child calls, admission, child facts; the run closes the gate to word its result, and the owner closes it again at parent settlement with the effects merged once | -| ToolBinding ([#2028](https://github.com/arcships/dim/issues/2028)) | `adopted {requestId}` → `{adopted}` | The request's pinned declarations for `tools.list`, `tools.describe`, `tools.call` | -| Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `toolRegistry.register` | The `codemode` contribution | -| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `config` | The Session's protocol version for the declaration | +| Session access ([#2025](https://github.com/arcships/dim/issues/2025), target, pending [#2093](https://github.com/arcships/dim/pull/2093)) | the line's owner by line id | The entry reaches `CodeModeLine`; the run reaches the line's ToolExecutor | +| ToolExecutor ([#2028](https://github.com/arcships/dim/issues/2028), target, pending [#2100](https://github.com/arcships/dim/pull/2100)) | `open {parentCallId, context}` → `{gateId}`; `invoke {gateId, call}` → `{result}`; `close {gateId}` → `{effects}` | Child calls, admission, child facts; the run closes the gate to word its result, and the owner closes it again at parent settlement with the effects merged once | +| ToolBinding ([#2028](https://github.com/arcships/dim/issues/2028), target, pending [#2100](https://github.com/arcships/dim/pull/2100)) | `adopted {requestId}` → `{adoption, tools}` | The request's pinned declarations for `tools.list`, `tools.describe`, `tools.call` | +| Session registries ([#2026](https://github.com/arcships/dim/issues/2026), target, pending [#2103](https://github.com/arcships/dim/pull/2103)) | `toolRegistry.register` | The `codemode` contribution | +| (none) | — | The v4 gate is the mount exclusion in the Session's creation record; no version read and no service call | ### Operations @@ -152,8 +154,8 @@ None. The `codemode` tool keeps its name, description, schema, risk and v4 gate; | §7 cross-language | The tool, the run and the quota are data and callbacks; the program's bridge is `tools.list/describe/call`. | | §7 one change | Deleting the process runner table, the runner trait and the executor wrapper happens in the same change that adds the quota operation and the line's run operation. | | ADR 002 D1 | Slots are process state; the run is line state; the declaration is Session state. | -| ADR 027 D1–D3 | The tool handler reaches `codeModeLine` and the line's ToolExecutor by the line id on its execution context; the resolution is not a dependency and is not kept across calls. | -| ADR 027 D2 | `codeModeLine` and ToolExecutor are branch data faces; no registration point or lifecycle service is resolved by id. | +| ADR 027 D1, D4 | The tool handler reaches `codeModeLine` and the line's ToolExecutor by the line id on its execution context; the resolution is not a dependency and is not kept across calls. | +| ADR 027 D3 | `codeModeLine` and ToolExecutor are branch data faces; no registration point or lifecycle service is resolved by id. | | ADR 002 D2 | No wiring plugin: both operations are on their owners' types; the mechanism resolves the line. | | ADR 002 D3 | Dependencies point from Code Mode to the registry, the mechanism and ToolExecutor. | | ADR 002 D4 | The bounds are structural configuration; no business setting is read. | @@ -161,13 +163,15 @@ None. The `codemode` tool keeps its name, description, schema, risk and v4 gate; ## Requirements raised to mechanism owners -- [TimelineTree #2024](https://github.com/arcships/dim/issues/2024): the cross-cutting decision names this owner's contract as the place that fixes who provides the line-id operations to Session parts. Code Mode needs two: a Session-registered tool handler resolving `codeModeLine` by the line id on its execution context, and the run resolving the line's ToolExecutor. SessionScope's contract has no such operation. +Both requirements below land in the id routing mechanism [#2127](https://github.com/arcships/dim/issues/2127), owned by the dim runtime; #2024's contract (#2092) states the line-id operations that mechanism serves. + +- [TimelineTree #2024](https://github.com/arcships/dim/issues/2024) (target, pending [#2092](https://github.com/arcships/dim/pull/2092)): the cross-cutting decision names this owner's contract as the place that fixes who provides the line-id operations to Session parts; the mechanism that serves them is [#2127](https://github.com/arcships/dim/issues/2127). Code Mode needs two: a Session-registered tool handler resolving `codeModeLine` by the line id on its execution context, and the run resolving the line's ToolExecutor. SessionScope's contract has no such operation. - [The branch tool chain #2028](https://github.com/arcships/dim/issues/2028): none open; `open`/`invoke` and `toolBinding.adopted` are what this contract calls ([#2100](https://github.com/arcships/dim/pull/2100)). - The line's timeline owner (runtime): child `step/tool-call` and `step/tool-result` batches carry `parent_call_id`; the v1–v3 projection omits them. ## Binding appendix -The process part provides `codeMode`; the branch part provides `codeModeLine`; the Session part registers the tool. Request, reply and error types are data; `cancelled` is the binding's cancellation argument. +The process part provides `codeMode`; the branch part provides `codeModeLine`; the Session part registers the tool. Both names are set with `#[rutis::service(name = ...)]` on the owner type. Request, reply and error types are data; `cancelled` is the binding's cancellation argument. ```rust use rutis::host::BoxFuture; @@ -176,12 +180,12 @@ use rutis::host::BoxFuture; impl ProgramSlots { /// Run `work` while holding one process program slot; `caller` binds the /// slot to the calling row, so the owner releases it at that row's unload. - pub async fn with_slot( + pub async fn with_slot<T>( &self, caller: &Ctx, - work: impl Fn(CancellationToken) -> BoxFuture<'static, Result<(), ServiceError>> + Send + Sync, - cancelled: CancellationToken, - ) -> Result<(), ServiceError>; + work: ChangeFn<T>, + cancelled: CancelledFn, + ) -> Result<T, ServiceError>; } /// The service error shape of every data face: `{code, message, data?}`. diff --git a/docs/design/plugins/Goal-state-read.md b/docs/design/plugins/Goal-state-read.md index 6a70955514..ea4588edb6 100644 --- a/docs/design/plugins/Goal-state-read.md +++ b/docs/design/plugins/Goal-state-read.md @@ -6,6 +6,8 @@ Issue: [#1320](https://github.com/arcships/dim/issues/1320)。 依据:[Goal](Goal.md)、[读取与输入删除](Goal-property-queries.md)、[设计规则](../../architecture/rust-agent/principles.md)、[ADR 002](../../adr/002-plugin-scope.md)、[插件合同](../plugin-contract.md)、[rutis](../rutis-usage.md)。本文件规定状态保存与读取合同。 +> 目标契约见 [Goal](Goal.md)。[Goal](Goal.md#client-visible-changes) 取代本文的命令与状态记录同批规则和「回复是 trigger 的 sequence」之外的排序描述;状态对象、加载映射与属性查询仍以本文为准。 + ## 1. 决定 1. 运行中的次数、轮次、输入和任务集合、评估关系、待处理报告、决定去重及写任务只存在于本次 Goal 实例的内存中。普通输入、input/consumed、turn/start、turn/end 和 exec 事件不因推进消费位置而写恢复记录。 diff --git a/docs/design/plugins/Goal.md b/docs/design/plugins/Goal.md index 1a43b81368..c6a5762c54 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -11,7 +11,7 @@ Goal owns: - **The goal of a line.** One objective, the judge that decides completion, the status (`active`, `paused` with a reason, `completed`, `blocked`, or none) and the moment it last changed. The state belongs to the line and ends with it. - **The decisions that follow a fact.** After a turn ends: continue, stop at the optional continuation limit, stop after three turns without progress, or ask for an evaluation. On an interrupt, a failed or cancelled turn, or an unload: pause with the reason. When a child line starts: retire the keys of an inherited goal. - **The texts the model reads.** The `dim-goal` marker's command block, state block and continuation, and the guide entry that explains them. -- **The commands' vocabulary.** `set`, `edit`, `pause`, `resume`, `clear` and the completion report, their parameter rules, and the two entry points that carry them (`session.goal.*` and the `goal_update` tool). +- **The commands' vocabulary.** `set`, `edit`, `pause`, `resume`, `clear` and the completion report, their parameter rules, and the two entry points that carry them (`session.goal.*` and the `goal_update` tool). The retained limits: an objective of 1..=4000 characters, a summary of 1..=2000, and `maxContinuations` in 1..=1000 with absence meaning no limit. - **The evaluator line's purpose.** Goal asks TimelineTree to open a child line cut at the turn end and closes it with the operation id it wrote. Callers keep as business: @@ -26,7 +26,7 @@ Callers keep as business: | The model reports completion or blockage | No: the report changes the goal, and its line is the call's line | the tool handler writes one command input to that line | | A client reads the goal of a line | No: the goal is the line owner's state and nothing else publishes it | `goalLine.read` at the line id | | The owner states the state to the model | No: the state block restates the whole goal and the live keys when it changes | the branch owner writes the state record input | -| A command is retried after a lost reply | No: accepting a command once is the input owner's rule | the submission id on `submit` | +| A command is retried after a lost reply | No: accepting a command once is the input owner's rule | `submissionId` on the request when the caller retries; Goal generates one when absent | | A client shows the goal of an ended line | Yes: the line's facts stay readable at its fixed head and the fold is the client's projection | business composes with TimelineTree's `read` | | A client reads the conversation line's goal without naming it | Yes: the line record carries the Session's current line | business composes with TimelineTree's `directory` | | The owner continues a goal after a turn | No: the decision uses the owner's fold, counters and tasks | branch-internal | @@ -35,7 +35,7 @@ An operation or parameter exists only where its row says No. ## Caller example -`session.goal.set` writes one command input to the named line; the branch owner decides and states the result. No object, no sequence, no wait. +`session.goal.set` writes one command input to the named line; the branch owner decides and states the result. The reply carries the committed command input's sequence, the same value the method returns today. ```rust // The entry checks its own parameters and resolves the line a client left unnamed. @@ -43,13 +43,13 @@ let line = match command.line { Some(line) => line, None => tree.directory()?.default, // TimelineTree's shape (#2092) }; -let _ = tree.line(LineRequest { line: line.clone() })?; // unknown_branch for a line that does not exist +let _ = tree.line(line.clone())?; // the tree's `unknown` kind; the method answers `unknown_branch` // Goal's own text: the command block carries the operation, the objective and the judge. let input = goal_command(&line, &command); line_owner::<InputQueue>(&line)? .submit(input, cancelled) .await?; -// The reply is the input's position; nothing else is returned and nothing is released. +// The reply is the committed command input's sequence; nothing else is returned and nothing is released. ``` `session.goal.get` reads the line owner's published value; the caller decides what "no owner" means for its screen. @@ -78,8 +78,8 @@ line_owner::<InputQueue>(&line)? | Owner | Operation | Use | | --- | --- | --- | | TimelineTree ([#2024](https://github.com/arcships/dim/issues/2024)) | `directory`, `line`, `read`, `create`, `end` | The conversation line; one line's record for the named line; an ended line's facts; opening and closing the evaluator line | -| The line's input owner ([#2027](https://github.com/arcships/dim/issues/2027)) | `submit` | The command input and the state record input | -| The line's timeline (branch runtime) | `append` | The business fact recovery reads | +| The line's input owner ([#2027](https://github.com/arcships/dim/issues/2027), target, pending [#2102](https://github.com/arcships/dim/pull/2102)) | `submit` | The command input only | +| The line's timeline (branch runtime) | `append` | The business fact recovery reads, then the state record input | | Dispatcher, BranchLifecycle, TimelineIdentity (branch runtime) | facts, activation, closing | Folding the line's facts and the branch part's lifetime | | SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `phase` | Not ending evaluator lines while the Session is closing | | Settings ([#2017](https://github.com/arcships/dim/issues/2017)) | `register`, `read` | The `goal` source's optional `maxContinuations` | @@ -93,14 +93,14 @@ The entry's operations are the five commands, the read, the tool and the guide e | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `session.goal.set` | Start a new execution of a goal on a line | `{sessionId, branchId?, objective, judge?}` | `{sequence}`: the accepted input's position | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | -| `session.goal.edit` | Replace the objective, keeping status and judge | `{sessionId, branchId?, objective}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | -| `session.goal.pause` / `resume` / `clear` | Pause, resume or clear the goal | `{sessionId, branchId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | -| `session.goal.get` | The goal of a line now | `{sessionId, branchId?}` | `{branchId, through, goal?}`; the goal carries `{objective, status, evaluator}` | The wait for the owner's fold stops | `invalid_params`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.set` | Start a new execution of a goal on a line | `{sessionId, branchId?, objective, judge?, submissionId?}` | `{sequence}`: the committed command input's sequence, as today | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.edit` | Replace the objective, keeping status and judge | `{sessionId, branchId?, objective, submissionId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.pause` / `resume` / `clear` | Pause, resume or clear the goal | `{sessionId, branchId?, submissionId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | +| `session.goal.get` | The goal of a line now | `{sessionId, branchId?}` | `{branchId, through, goal?}`; the goal carries `{objective, status, evaluator}` | The wait for the owner's fold stops | `invalid_params`, `service_reloading` (also for an ended line), `closed`, `operation_interrupted` | | `goal_update` | The model reports completion or blockage | `{status, summary}` | text in `ToolResult.content` | Before the input is submitted | the commands' codes, returned as an error result | -| `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | While the fold reaches the head | `closed` as the service error `{code, message}` | +| `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | The wait stops; the value is unaffected | `closed` | -`invalid_params` covers what Goal itself checks: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `unknown_branch` is TimelineTree's `line` refusal; `branch_ended` is the input owner's refusal; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. Every code above is one the client already receives today. +`invalid_params` covers what Goal itself checks: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `unknown_branch` is TimelineTree's `line` refusal (`unknown` in the tree's vocabulary, mapped to the published code); `branch_ended` is the input owner's refusal; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. Every code above is one the client already receives today. `goalLine.read` takes no request parameter: the line is the instance the mechanism resolved. Requests, replies and errors are data; `cancelled` is the binding's cancellation argument. @@ -112,6 +112,7 @@ The entry's operations are the five commands, the read, the tool and the guide e | `goalLine.read` | Wait for the branch part's fold to reach its head, answer the value | The wait stops; the value is unaffected | Nothing to release | `closed` when the part is closing | the branch part | | Branch decision | Consume a command input, decide from the fold, append the business fact, append the state record, then write the continuation or ask for an evaluation | The line's closers end the branch part's tasks; an admitted input is not withdrawn | — | Closing cancels the tasks, writes `paused` with its reason, then the services are withdrawn | the branch part: its own tasks, the fact and the record; the input owner: the continuation it accepted | | Evaluator line | Open a child line at the turn end with Goal's operation id; the evaluator reports a conclusion; Goal closes the line | The line's close stops the decision that would open it | — | On rebuild and on close Goal closes the evaluator lines it opened, before the Session closes | the branch part asks; TimelineTree creates, holds and closes the line | +| Evaluator line refused | `create` answers `branch_not_opener` or `branch_limit_reached`: Goal pauses the goal with reason `evaluation_failed` and writes no conclusion | — | — | — | the branch part; the parent line's fact carries the pause | The business fact precedes the state record: the fact is what recovery reads, the record is model-visible text. A crash between the two leaves the goal correct in recovery and one state block missing from history; the next change restates the whole state. This supersedes [Goal-state-read.md](Goal-state-read.md)'s one-batch command write; the state object, the load mapping and the property queries in that document stay. @@ -142,7 +143,7 @@ Flow tests through the entry's public interfaces and the branch owner: - `pause`, `resume` and `clear` change the status in the stated order; a paused goal does not continue; `clear` retires the model-visible keys. - `get` on an ended line answers `service_reloading`, and the line's facts still carry the last state for a client that folds them. - A turn end continues, stops at the configured limit, and stops after three turns without progress; an interrupt, a failed turn or an unload writes `paused` with its reason. -- An evaluator goal opens one child line per turn end and closes the line it opened on rebuild and on close; a conclusion sets `completed` or `blocked`. +- An evaluator goal opens one child line per turn end and closes the line it opened on rebuild and on close; a conclusion sets `completed` or `blocked`; a refused `create` (`branch_not_opener`, `branch_limit_reached`) pauses the goal with `evaluation_failed`. - A dropped read leaves nothing behind; a command submitted twice with one submission id is accepted once. ## Supersedes @@ -154,7 +155,9 @@ Flow tests through the entry's public interfaces and the branch owner: ## Client-visible changes -The `goal:state` record no longer shares one batch with the command. The model sees the command input first and the state record from the next request; the record's text format is unchanged. No client field, code or notification changes: `session.goal.*` keeps `{sequence}` and `{branchId, through, goal?}` with `{objective, status, evaluator}`, and every error code above is one the client already receives. Affected: the prompt-evaluation tests that assert the command and record order, and `Goal-state-read.md`'s ordering rule. +- `session.goal.*` replies keep their fields: `{sequence}` is the committed command input's sequence, the same value returned today; `session.goal.get` keeps `{branchId, through, goal?}` with `{objective, status, evaluator}`. Every error code above is one the client already receives. The write requests gain an optional `submissionId`; a client that sends none keeps today's behavior, and a retrying client sends the same id to be accepted once. +- An ended line no longer answers `session.goal.get` with its last goal: the entry has no live owner to read, and folding the line's facts in the entry is what this contract removes. `session.goal.get` answers `service_reloading` and a client shows no goal. Affected: `dim-cli`'s `/goal` and `sessions.status` projection (`crates/dim-cli/src/goal_command.rs`, `session_host.rs`) and the TUI's goal panel, which read the value. Migration: read the line's facts (`goal/state`) for an ended line, or show no goal; the CLI change ships with the implementation. +- The `goal:state` record no longer shares one batch with the command. The model sees the command input first and the state record from the next request; the record's text format is unchanged. Affected: the prompt-evaluation tests that assert the command and record order, and `Goal-state-read.md`'s ordering rule. ## Rule check @@ -170,15 +173,15 @@ The `goal:state` record no longer shares one batch with the command. The model s | §4 rule 5 (batches) | The fact and the record are separate appends in that order, so recovery never reads state that was not committed. | | §4 rule 6 (context) | The model reads goals only through adopted inputs; `goalLine.read` serves callers, not context preparation. | | §4 rule 7 (public events and services) | The branch part uses the Dispatcher, its timeline, TimelineTree and the input owner; the entry uses the registration points and the mechanism. | -| §4 rule 8 (requirements) | Two requirements are listed below; no core change. | +| §4 rule 8 (requirements) | Three requirements are listed below; no core change. | | §4 rule 9 (facts) | The goal is a line fact plus the model-visible record; execution counters stay in memory. | | §7 values, ids and callbacks | The entry writes an input (data) and reads a value at a line id; the mechanism resolves the line's owner; no object crosses. | | §7 no proxy lookup | The entry neither folds the line's state nor answers from Goal's facts; the branch owner answers its own value. | | §7 one interface | The commands are one method namespace and one tool contribution; the branch owner's face is one read; no adapter exists beside either. | | §7 cross-language | Commands, parameters, replies and errors are data; the tool result is text in `ToolResult.content`. | | §7 one change | The implementation task deletes the routing table, the re-fold path and the pre-commit callback in the same change that adds `goalLine.read` and migrates the entries. | -| ADR 027 D1–D3 | The entry reaches `GoalLine` and the line's `InputQueue` by line id; the resolution is not a dependency and is not kept across calls. The registration points it uses (`sessionMethods`, `toolRegistry`, `guideEntries`) are its own Session's, not resolved by id. | -| ADR 027 D2 | No registration point and no lifecycle service is resolved by line id: `GoalLine` and `InputQueue` are data faces of the branch group. | +| ADR 027 D1, D4 | The entry reaches `GoalLine` and the line's `InputQueue` by line id; the resolution is not a dependency and is not kept across calls. | +| ADR 027 D3 | No registration point and no lifecycle service is resolved by line id: `GoalLine` and `InputQueue` are data faces of the branch group; the registration points it uses (`sessionMethods`, `toolRegistry`, `guideEntries`) are its own Session's. | | ADR 002 D1 | The goal, its decisions and its tasks live in the branch; the Session entry registers the commands. | | ADR 002 D2 | No wiring plugin: the branch part provides `goalLine` on its own type; the mechanism resolves the line. | | ADR 002 D3 | Dependencies point from Goal to TimelineTree, the input owner, Settings and the runtime; nothing depends on Goal. | @@ -189,7 +192,65 @@ The `goal:state` record no longer shares one batch with the command. The model s - [TimelineTree #2024](https://github.com/arcships/dim/issues/2024): the cross-cutting decision names this owner's contract as the place that fixes who provides the line-id operations to Session parts. Goal needs two: a Session part resolving `GoalLine` for the read and the line's `InputQueue` for the command. SessionScope's contract has no such operation. - [The line's input owner #2027](https://github.com/arcships/dim/issues/2027): `submit` accepts one validated input with its submission id, commits it in order and answers its position; an ended line and a closing owner are data. -- The line's timeline owner (runtime, outside the #2015 scan): `append` accepts an input-message draft and an extension fact; Goal appends the fact and then the record. +- The line's timeline owner (runtime, outside the #2015 scan): `append` accepts an input-message draft and an extension fact; Goal appends the fact and then the record. The record is an input-message draft, never a second `submit`. +- The id routing mechanism is [#2127](https://github.com/arcships/dim/issues/2127); the `line_owner` requirement lands there, and #2024's contract states the line-id operations it serves ([target, pending #2092](https://github.com/arcships/dim/pull/2092)). + + +## 兼容锚点(Compatibility anchors) + +以下标题只为保留其他文档与代码注释里的旧锚点;每一节的正文都已并入上面的契约。 + +### 2. 数据与状态 + +目标属于一行;状态对象与加载映射见 [Goal-state-read.md](Goal-state-read.md),本契约的 [Own contract](#own-contract) 规定写入顺序。 + +### 3.4 新分支清除继承的目标 + +子行开始时不继承目标,见 [Own contract](#own-contract) 的 decisions 与 [Exceptions with reasons](#exceptions-with-reasons)。 + +### 5. 上下文映射 + +模型只经采用输入看到目标文本;见 [Own contract](#own-contract) 与 [Client-visible changes](#client-visible-changes)。 + +### 10. 实现 + +实现顺序与删除清单见 #2033 的交付评论。 + +### A.2 Session 方法 + +`session.goal.*` 的参数、回复与错误见 [Own contract](#own-contract)。 + +### A.3 读取目标 + +读目标见 [Own contract](#own-contract) 的 `session.goal.get` 与 `goalLine.read`;结束行不再回答。 + +### A.4 续跑决策 + +续跑、上限与无进展见 [Own contract](#own-contract) 的 decisions。 + +### A.5 模型可见文本 + +标记、状态块、命令块与续行仍是 Goal 的模型协议;文本格式不变,记录顺序见 [Client-visible changes](#client-visible-changes)。 + +### A.5.1 协议与策略 + +guide 条目见 [Own contract](#own-contract);策略句仍归 Goal。 + +### A.5.2 评估 + +评估分支与结论见 [Own contract](#own-contract) 的 flows 与 [Exceptions with reasons](#exceptions-with-reasons)。 + +### 附录 B 完整冲突表 + +冲突与终止见 [Own contract](#own-contract) 的 Flows。 + +### 附录 C 错误与恢复 + +错误码见 [Own contract](#own-contract) 的 Errors。 + +### 附录 E 假设 + +参数上限见 [Use and scope: responsibility split](#use-and-scope-responsibility-split)。 ## Binding appendix @@ -203,7 +264,7 @@ use rutis::host::BoxFuture; #[serde(rename_all = "camelCase")] pub struct GoalValue { pub objective: Option<String>, - pub status: GoalStatus, // dim_agent_types::GoalStatus: active | paused{reason} | completed | blocked | none + pub status: GoalViewStatus, // dim_agent_types::GoalViewStatus: active | paused{reason} | completed | blocked | none pub evaluator: bool, // the judge; `GoalView` uses this field name on the wire pub through: u64, } @@ -211,7 +272,7 @@ pub struct GoalValue { #[rutis::service] impl GoalLine { /// The goal of this line now; waits until the fold reaches the head. - pub async fn read(&self) -> Result<GoalValue, ServiceError>; + pub async fn read(&self, cancelled: CancelledFn) -> Result<GoalValue, ServiceError>; } /// The service error shape of every data face: `{code, message, data?}`. @@ -224,4 +285,4 @@ pub struct ServiceError { } ``` -`GoalStatus` and `GoalView` are the existing types in `dim_agent_types`; the command input's text and its `dim-goal` marker are the existing ones in `crates/dim-goal`, and their wire spelling is unchanged. +`GoalViewStatus` and `GoalView` are the existing types in `dim_agent_types`; the command input's text and its `dim-goal` marker are the existing ones in `crates/dim-goal`, and their wire spelling is unchanged. diff --git a/docs/design/plugins/Pursuit.md b/docs/design/plugins/Pursuit.md index 403d99d5c9..228c96a74c 100644 --- a/docs/design/plugins/Pursuit.md +++ b/docs/design/plugins/Pursuit.md @@ -14,7 +14,7 @@ Requirement ([feature list](../../feature-list.md), Agent behavior): keep workin | P2 | The judge is chosen per goal by `set`, recorded on the `set` block | It is the user's intent for that goal, a Timeline fact | | P3 | Evaluate when the worker's completion report stops Goal | That is the only point where the worker decides the goal is done. A worker's `blocked` stands (it needs the user); a limit, or the user's own interrupt or pause, is not a completion and starts nothing | | P4 | Under the evaluator judge the worker's `completed` is a request; the status stays `active` | Only the evaluator completes the goal. The current execution records a completion request without changing the business status; see [Goal A16](Goal.md#appendix-e-assumptions) | -| P5 | The evaluator is a child branch cut at that `turn/end` | It sees what was done and why, runs under the same policy, and is an ordinary branch created with `treeCommands.create` | +| P5 | The evaluator is a child branch cut at that `turn/end` | It sees what was done and why, runs under the same policy, and is an ordinary branch created with `timelineTree.create` | | P6 | The evaluator writes its conclusion to the working branch as input; Goal there decides | A branch folds only its own events; cross-branch communication is input by id ([plugin contract §5.2](../plugin-contract.md#52-consuming-facts)), and a line reads the line it was cut from through a tool result ([Timeline branches](../timeline-branches.md) §6). Callers write, owners decide | ## 2. User flow @@ -53,7 +53,7 @@ Every decision is taken as Goal takes its own: by the Dispatcher handler from co | Consumed event | Condition | Action | | --- | --- | --- | -| `turn/end` N | Goal's C1–C4 hold (active goal, not interrupted, turn `completed`, latest and undecided), the judge is `evaluator`, the execution holds a worker `completed` request that no later goal change superseded and for which no evaluation has been started, and no driving input is pending | Instead of Goal's continuation decision: `treeCommands.create(B, N, {prompt, source: {kind: "host", operation_id: "goal:evaluate:N"}}, cancelled)`. Goal's `decided` counts that `branch/create` as `N`'s decision (§3), within this execution; reload pauses the goal and never creates the old evaluator again | +| `turn/end` N | Goal's C1–C4 hold (active goal, not interrupted, turn `completed`, latest and undecided), the judge is `evaluator`, the execution holds a worker `completed` request that no later goal change superseded and for which no evaluation has been started, and no driving input is pending | Instead of Goal's continuation decision: `timelineTree.create(B, N, {prompt, source: {kind: "host", operation_id: "goal:evaluate:N"}}, cancelled)`. Goal's `decided` counts that `branch/create` as `N`'s decision (§3), within this execution; reload pauses the goal and never creates the old evaluator again | | `branch/create-failed` for `goal:evaluate:N`, or `create` throws before any `branch/create` for `N` committed | `N` is still current | Pause (`evaluation_failed`), marked `after="N"` as Goal's pauses are; the first of the two to write it supersedes `N` for the other. A creation that committed records its own outcome (a child or `branch/create-failed`), so that fact decides it, and a throw because the task was cancelled writes nothing | | Conclusion input for evaluation `N` | The first conclusion for `N`, from the branch named by the `branch/create` for `goal:evaluate:N`, and `N` is still current: no newer change follows `N` — a `set`, `edit`, `clear`, `pause` or `resume` trigger, a new worker `completed`, or an old keyed block. A model-facing `goal:state` input is not another completion request. The current business state and in-memory evaluation identity determine whether the conclusion is still eligible; paused stops it | `done`: `completed` by the evaluator. `blocked`: `blocked` by the evaluator. `continue`: Goal's continuation decision ([Goal A.4](Goal.md#a4-continuation-decision) C1, C5 and C6, C6 only when `maxContinuations` is set, and the background wait), then a continuation with the Pursuit text, or pause (`limit`); as at any turn end, a pending driving input means no continuation (C5), and a background task still open means no decision yet: the current execution keeps the conclusion in memory, and the cancelled end that closes the last open task may take it while that execution remains running. `failed`: pause (`evaluation_failed`) | @@ -65,7 +65,7 @@ The evaluator identity comes from the line source and parent ([§13](#13-ending- | Consumed event | Condition | Action | | --- | --- | --- | -| `turn/end` M, status `completed` | The reply has a conclusion | Write it to `B` with `treeCommands.input` (Append), marked `evaluation="N" evaluator="E"` | +| `turn/end` M, status `completed` | The reply has a conclusion | Write it to `B` with `timelineTree.input` (Append), marked `evaluation="N" evaluator="E"` | | `turn/end` M, status `completed` | No conclusion, and `M` is the evaluator's first turn end | Write a follow-up (Queue, `after="M"`) on the evaluator branch asking it to end with one of the three conclusions | | `turn/end` M, status `completed` | No conclusion, and `M` is not its first turn end (it was already asked once) | Write `continue` to `B` with the whole reply, truncated to 4000 characters, as the feedback | | `turn/end` M, status `failed` or `cancelled` | — | Write `failed` to `B` | @@ -175,7 +175,7 @@ Evaluator identity and branch ending use the existing [Timeline branches](../tim | # | Change | | --- | --- | | E1 | **Recognition from the line's source.** Goal on a line takes the evaluator role when `treeCommands.info(own id)` has `source = {kind: "host", operation_id: "goal:evaluate:N"}` and `parent = B`. It no longer reads the prompt's first line. The prompt keeps its `<dim-goal kind="evaluate" …>` first line, for the model only (§5) | -| E2 | **Goal ends its evaluator.** Evaluation `N` is settled on `B` once its conclusion or failure is decided (§4.1), or once a later goal change supersedes `N`. When it is settled, Goal on `B` ends `E` with `treeCommands.end(E, {kind: "host", operation_id: "goal:evaluate:N"})`, through an owned task that rechecks first. If the current execution has consumed the terminal fact for E, Goal does nothing. This is cleanup of work owned by the current execution, not a requirement to load historical evaluator relations or replay old decisions | +| E2 | **Goal ends its evaluator.** Evaluation `N` is settled on `B` once its conclusion or failure is decided (§4.1), or once a later goal change supersedes `N`. When it is settled, Goal on `B` ends `E` with `timelineTree.end(E, {kind: "host", operation_id: "goal:evaluate:N"})`, through an owned task that rechecks first. If the current execution has consumed the terminal fact for E, Goal does nothing. This is cleanup of work owned by the current execution, not a requirement to load historical evaluator relations or replay old decisions | | E3 | **An outside end before the conclusion is `failed`.** A `branch/ended` for `E` on `B` that comes before `E`'s conclusion, while `N` is current, is decided as `failed`: pause (`evaluation_failed`), as in §4.1 | Interfaces: diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 251462fd35..32efe6e15b 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -9,8 +9,8 @@ SessionTitle owns a Session's title policy: when a title is generated, what text SessionTitle owns: - **The moment of generation.** The first adopted input on the Session's conversation line — an operator input with user content, or Goal's applied objective — triggers one attempt; a Session that already has a title never generates one. -- **The text rules.** The instruction sent to the model, the 2000-code-point excerpt, the output normalization (one line, no quoting, collapsed whitespace) and the length bound from the `session-title` source. -- **The routing.** An explicit model from the source, otherwise the account owner's title operation when the adopted provider belongs to it, otherwise the adopted model, otherwise the excerpt fallback; one 30 s budget across the paths; three failed attempts end the attempts for this generation. +- **The text rules.** The instruction sent to the model, the 2000-code-point excerpt, the output normalization (one line, no quoting, collapsed whitespace) and the length bound from the `session-title` source (`maxLength` 10..=200, default 80). +- **The routing.** An explicit model from the source, otherwise the account owner's title operation when the adopted provider belongs to it, otherwise the adopted model, otherwise the excerpt fallback; one 30 s budget across the paths; three failed attempts end the attempts for this generation. The acceptance list is the previous version's Appendix D and is unchanged. - **The manual rename.** `session.rename`'s parameter rules and the text it accepts or clears. - **The requested initial title.** The title a launch carried is written once, as the first manual title, after the Session is published. @@ -37,15 +37,19 @@ An operation or parameter exists only where its row says No. ```rust let text = title_text(params.title.as_deref(), &document)?; // owner rules: trim, no control characters, length -let change = TitleChange::new(move |current: Option<StoredTitle>| { - // A manual rename always wins: the operator's text replaces whatever is stored. - Ok(text.clone().map(|text| Title { text, source: TitleSource::Manual })) +// The store's ChangeFn: the current title and revision in, the next title (none clears) or its own refusal out. +let change: ChangeFn = Arc::new(move |current: TitleState| { + let text = text.clone(); + Box::pin(async move { + // A manual rename always wins: the operator's text replaces whatever is stored. + Ok(text.map(|text| Title { text, source: TitleSource::Manual })) + }) }); let written = store - .setTitle(SetTitle { id: session }, change, cancelled) + .set_title(caller, SetTitle { id: session }, change) .await .map_err(|error| match error { - StoreError::Rejected { code, message } => wire_invalid(code, message), // the change refused the write + StoreError::Rejected { .. } => invalid_params("title refused"), // the change's refusal StoreError::NotFound => session_not_found(), other => storage_failed(other), })?; @@ -54,7 +58,15 @@ let written = store A generation attempt: the adopted input's text, the model, and one write whose `change` refuses once any title exists. ```rust -let input = tree.read(ReadLines { line: ROOT, scope: None, from: None, through: Some(adopted_at), fields: INPUT_FIELDS, limit: None }).await?; +let line = tree.directory()?.default; // the conversation line, as Goal resolves it +let input = tree.read(ReadLines { + line, + scope: None, + from: None, + through: Some(adopted_at), + fields: vec!["id".into(), "data.user".into(), "data.blocks".into()], + limit: None, +}).await?; let text: String = eligible_text(&input).chars().take(2000).collect(); let title = match route(&document, &adopted_model) { Route::Account(account) => match account.title(TitleRequest { provider, text }, cancel.clone()).await { @@ -65,11 +77,18 @@ let title = match route(&document, &adopted_model) { Route::Model(model) => generate_with_model(&model, &text).await?, Route::Excerpt => excerpt_title(&text, document.max_length), }; -let change = TitleChange::new(move |current: Option<StoredTitle>| match current { - Some(_) => Err(Rejected::new("titled", "the Session already has a title")), // the operator's title wins - None => Ok(Some(Title { text: title.clone(), source: TitleSource::Auto })), +let title = title.clone(); +let change: ChangeFn = Arc::new(move |current: TitleState| { + let title = title.clone(); + Box::pin(async move { + if current.title.is_some() { + // The operator's title wins; the attempt is discarded, not an error. + return Err(StoreRejected { code: "titled".into(), message: "the Session already has a title".into() }); + } + Ok(Some(Title { text: title, source: TitleSource::Auto })) + }) }); -store.setTitle(SetTitle { id }, change, cancel).await?; +store.set_title(caller, SetTitle { id }, change).await?; ``` ## Own contract @@ -78,12 +97,12 @@ store.setTitle(SetTitle { id }, change, cancel).await?; | Owner | Operation | Use | | --- | --- | --- | -| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025)) | `config`, `identity`, `activated`, `closing` | The creation record (`initialTitle`, `interactive`, `collaborationRole`), the Session id, publication and close | -| SessionStore ([#2018](https://github.com/arcships/dim/issues/2018)) | `title`, `setTitle` with a `change` callback | The current title (text, source, revision) inside the decision; the write, its announcement and the new revision | -| TimelineTree ([#2024](https://github.com/arcships/dim/issues/2024)) | `read` | The first adopted input's text and the adopted model at a fixed cutoff | -| Provider ([#2019](https://github.com/arcships/dim/issues/2019)) | `invoke` with `Once` | One title request on an adopted model | -| The Dim account owner ([#2019](https://github.com/arcships/dim/issues/2019), optional) | `title` | The relay's title endpoint when the adopted provider belongs to it | -| Settings ([#2017](https://github.com/arcships/dim/issues/2017)) | `register`, `read` | The `session-title` source: `enabled`, `maxLength`, `model` | +| SessionScope ([#2025](https://github.com/arcships/dim/issues/2025), target, pending [#2093](https://github.com/arcships/dim/pull/2093)) | `config`, `identity`, `activated`, `closing` | The creation record (`initialTitle`, `interactive`, `collaborationRole`), the Session id, publication and close | +| SessionStore ([#2018](https://github.com/arcships/dim/issues/2018), target, pending [#2091](https://github.com/arcships/dim/pull/2091)) | `title`, `setTitle` with a `change` | `title` answers `{revision, title?: {text, source}}`; `setTitle(caller, SetTitle, ChangeFn)` runs the change under the owner's serialization and answers `{revision}` | +| TimelineTree ([#2024](https://github.com/arcships/dim/issues/2024), target, pending [#2092](https://github.com/arcships/dim/pull/2092)) | `directory`, `read` | The conversation line; the first adopted input's text and the adopted model at a fixed cutoff | +| Provider ([#2019](https://github.com/arcships/dim/issues/2019), target, pending [#2096](https://github.com/arcships/dim/pull/2096)) | `invoke` with `Once` | One title request on an adopted model | +| The Dim account owner ([#2019](https://github.com/arcships/dim/issues/2019), target, pending [#2096](https://github.com/arcships/dim/pull/2096); optional) | `title` | The relay's title endpoint when the adopted provider belongs to it | +| Settings ([#2017](https://github.com/arcships/dim/issues/2017), target, pending [#2094](https://github.com/arcships/dim/pull/2094)) | `register`, `read` | The `session-title` source: `enabled`, `maxLength` (10..=200, default 80), `model` | | Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `sessionMethods.register` | Publishing `session.rename` | The account owner is read by its face name when generation needs it, so a profile without that owner generates through the model or the excerpt; this document does not require the account owner to exist. @@ -101,7 +120,7 @@ The account owner is read by its face name when generation needs it, so a profil | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `session.rename` | Check the text, call `setTitle` with a `change` that returns the manual text, answer the new revision | Before admission the call ends `cancelled`; an admitted write is not undone | Nothing to release | `closed` once the Session is closing; an admitted write settles in the store | SessionStore for the write and the exclusion; SessionTitle for nothing | +| `session.rename` | Check the text, call `set_title` with a `change` that returns the manual text, answer the new revision | Before admission the call ends without a write; an admitted write is not undone | Nothing to release | `service_reloading` once the part is unloading; an admitted write settles in the store | SessionStore for the write and the exclusion; SessionTitle for nothing | | Generation | Observe adoption, read the input and the model at a fixed cutoff, generate within the budget, fall back to the excerpt, write with a `change` that refuses when a title exists | Cancelled before admission: nothing is written; the in-flight model call is cancelled and joined | The task is cancelled; nothing is written | Cancelled before the store handover; an admitted write settles in the store | SessionTitle for the model call; SessionStore for the write and the exclusion | | Initial title | After publication, call `setTitle` with a `change` that returns the requested text only while the title is untitled | Before the write nothing is written | Cancelled with the part | A later rename or clear is never undone by a reload: the `change` sees the stored title and refuses | SessionStore | @@ -162,7 +181,7 @@ None. `session.rename` keeps its parameters, its `{title, titleSource, revision} | §4 rule 4 (no business meaning in core) | The instruction, the excerpt rule and the routing are SessionTitle's. | | §4 rule 5 (batches) | No batches. | | §4 rule 6 (context) | No model-visible text is added to the Session's context; the title request is a separate one-shot call. | -| §4 rule 7 (public events and services) | The Session broadcast, the line's read, the store's operations, Provider's `invoke`, the optional account face and Settings. | +| §4 rule 7 (public events and services) | The line's published adoption facts read at a fixed cutoff, the store's operations, Provider's `invoke`, the optional account face and Settings. | | §4 rule 8 (requirements) | One requirement on SessionStore, listed below. | | §4 rule 9 (facts) | The title never enters the Timeline; the store announces each commit. | | §7 values, ids and callbacks | The Session id, the title value and the revision cross; `setTitle` takes the caller's `change` by reference and the model request takes Provider's consumer; no object crosses. | @@ -171,6 +190,7 @@ None. `session.rename` keeps its parameters, its `{title, titleSource, revision} | §7 cross-language | The rename is data; the internal generation has no cross-owner caller. | | §7 one change | Deleting the optional generator name, the required auxiliary dependency and the model-text decode happens in the same change that adds the store precondition and the account call. | | ADR 002 D1 | The policy is Session state; the title value is the store's. | +| ADR 027 D4 | SessionTitle resolves nothing by id: its dependencies are process services and its own Session's line read, both declared at load. | | ADR 002 D2 | No wiring plugin: the part registers one namespace and calls owners' operations. | | ADR 002 D3 | Dependencies point from SessionTitle to SessionScope, SessionStore, TimelineTree, Provider, Settings and optionally the account owner. | | ADR 002 D4 | `enabled`, `maxLength` and `model` are business configuration read at use; enabling the plugin is structural. | @@ -178,7 +198,64 @@ None. `session.rename` keeps its parameters, its `{title, titleSource, revision} ## Requirements raised to mechanism owners -- None open. SessionStore's current contract ([#2091](https://github.com/arcships/dim/pull/2091)) has `setTitle {id} + change` running the change under the owner's serialization with `rejected` as a kind, and `title` answering `{text, source}`; this document depends on exactly that. +- [SessionStore #2091](https://github.com/arcships/dim/pull/2091) is open: `set_title(caller, SetTitle, ChangeFn)` running the change under the owner's serialization with `rejected` as a kind, and `title` answering `{revision, title?: {text, source}}`. SessionTitle's examples and appendix use that binding; landing order: #2091 before this contract's implementation. + + +## Compatibility anchors + +These headings exist only so the links in other documents and code comments resolve; their content is in the sections above. + +### 2. Data and state + +The title value and its revision are SessionStore's; the policy is in [Own contract](#own-contract). + +### 3.2 Manual rename + +See `session.rename` in [Own contract](#own-contract). + +### 3.3 Generation routing and optional service + +Routing is in [Own contract](#own-contract); the account owner is optional. + +### 4. Timing and conflicts + +A manual title always wins inside the store's change; see [Own contract](#own-contract) and [Client-visible changes](#client-visible-changes). + +### 5. Context mapping + +The title has no model-visible effect; see [Own contract](#own-contract). + +### 9. Requirements raised to mechanism owners + +See [Requirements raised to mechanism owners](#requirements-raised-to-mechanism-owners). + +### A.1 `session.rename` + +See `session.rename` in [Own contract](#own-contract). + +### A.2 Depended-on shapes (owners define them) + +The store's shapes are [#2091](https://github.com/arcships/dim/pull/2091)'s; see the dependency table in [Own contract](#own-contract). + +### A.3 Configuration + +`enabled`, `maxLength` (10..=200, default 80) and `model` are read from the `session-title` source; see [Own contract](#own-contract). + +### Appendix B. Full conflict table + +See [Own contract](#own-contract) and [Exceptions with reasons](#exceptions-with-reasons). + +### Appendix C. Errors and recovery + +See the error table in [Own contract](#own-contract). + +### Appendix D. Acceptance + +The previous version's acceptance list stays in force; see [Verification](#verification). + +### Appendix E. Assumptions + +See [Use and scope: responsibility split](#use-and-scope-responsibility-split). ## Binding appendix @@ -209,13 +286,10 @@ pub enum RenameError { OperationInterrupted, } -/// One title decision inside the store's exclusion. `StoredTitle` carries the -/// text, the source and the revision the store holds now; `Rejected` is the -/// store's kind for a change that refuses, and SessionTitle treats it as -/// "discarded" for an automatic title and as `invalid` for a rename. -pub type TitleChange = Arc< - dyn Fn(Option<StoredTitle>) -> Result<Option<Title>, Rejected> + Send + Sync, ->; +/// `ChangeFn`, `TitleState`, `Title`, `TitleSource`, `StoreRejected` and +/// `SetTitle` are SessionStore's types ([#2091](https://github.com/arcships/dim/pull/2091)); +/// this contract defines none of them. `set_title` takes `caller: &Ctx`, the +/// request and the change, and no cancellation argument. ``` The store's `title` and `setTitle` shapes are SessionStore's contract ([#2091](https://github.com/arcships/dim/pull/2091)); this appendix restates none of them. diff --git a/docs/design/plugins/Web.md b/docs/design/plugins/Web.md index 37a4ba9511..0ea611feda 100644 --- a/docs/design/plugins/Web.md +++ b/docs/design/plugins/Web.md @@ -65,11 +65,11 @@ Ok(numbered(&reply.results, &request)) | Owner | Operation | Use | | --- | --- | --- | -| Settings ([#2017](https://github.com/arcships/dim/issues/2017)) | `register`, `read` | The `web` source: search service, private-host exceptions, proxy, proxy DNS; read at each call | +| Settings ([#2017](https://github.com/arcships/dim/issues/2017), target, pending [#2094](https://github.com/arcships/dim/pull/2094)) | `register`, `read` | The `web` source: search service, private-host exceptions, proxy, proxy DNS; read at each call | | `dimAccount` (DimOAuth, [#2019](https://github.com/arcships/dim/issues/2019), optional) | `availability`, `subscribe`, `search` | The relay's sign-in state, its changes, and the relay search when the source names no adapter | -| Session registries ([#2026](https://github.com/arcships/dim/issues/2026)) | `toolRegistry.register`, `toolRegistry.register_source` | The fixed `web_fetch` contribution and the dynamic `web_search` source | +| Session registries ([#2026](https://github.com/arcships/dim/issues/2026), target, pending [#2103](https://github.com/arcships/dim/pull/2103)) | `toolRegistry.register`, `toolRegistry.register_source` | The fixed `web_fetch` contribution and the dynamic `web_search` source | -The account owner is read by its face name when the source names no search adapter. A profile without an account owner declares `web_fetch` only; a profile with one declares `web_search` while that owner reports a usable account. +A configured adapter with its key declares `web_search` without any account (Appendix A.5, A3). The account owner is read by its face name only when the source names no adapter or names `dim-oauth`; a profile without an account owner then declares `web_fetch` only, and a profile with one declares `web_search` while that owner reports a usable account. ### Operations @@ -162,7 +162,7 @@ impl ToolHandler for WebFetch { /// The dynamic source: `sets()` answers one set with `web_search` while a /// search service is usable and no set otherwise. impl ToolProvider for SearchSource { - fn sets(&self) -> Vec<ToolSet>; + fn sets(&self) -> Vec<Arc<ToolSourceSet>>; } ``` @@ -177,7 +177,7 @@ Web registers `web_fetch` once, from the part's apply, and offers `web_search` t | Method | Kind | Request | Reply | | --- | --- | --- | --- | | `toolRegistry.register` | async | `ToolDeclaration {name, description, inputSchema, risk: "network"}`, `execute` | Nothing once registered | -| `toolRegistry.registerSource` | — | source name `web`, `sets()` | one set while a search service is usable, none otherwise | +| `toolRegistry.register_source` | — | source name `web`, `sets()` | one set while a search service is usable, none otherwise | | `execute` (Web's function) | async | `ToolCall {sessionId, branchId, turnId, callId, arguments, config}, cancelled: Promise<void>` | `ToolResult {content: [{type: "text", text}], isError, structuredContent?}` | C4 supplies the existing by-reference `cancelled` Promise as the second argument. When it settles, Web aborts requests and releases sockets/timers before settling its call; row effects likewise release owned resources. ToolExecutor owns interruption terminal facts: Web writes no second cancellation fact and never retries an unknown outcome. Business errors are `ToolResult`s with `isError: true` (Appendix C); runtime/protocol binding failures retain C4 call-failure behavior rather than being masked as success or business data. Parameters are validated by the handler; a violation returns an error result without network access. @@ -267,7 +267,7 @@ Fake-IP DNS answers are ordinary addresses. With a proxy and `proxyDns: true` th | `proxy` | string (URL); write-only; absent means the session's own proxy (A.4) | absent | | `proxyDns` | boolean; user-only | `true` | -Read at each call and used as delivered: Settings validates the document against the schema Web declares and applies its defaults on write and when reading a persisted file, and Web does not validate it again. Web has no tool that writes configuration, so the document is written only through the client methods (S8b). A change is a data update with notification, never a reload. The row's structural on/off state belongs to PluginManager (PluginManager). Built-in adapter ids are an implementation choice (A13). The API key is `searchService.apiKey` (A.5). +Read at each call and used as delivered: Settings validates the document against the schema Web declares and applies its defaults on write and when reading a persisted file, and Web does not validate it again. Web has no tool that writes configuration, so the document is written only through the client methods (S8b). A change is a data update with notification, never a reload. The row's structural on/off state belongs to [PluginManager](PluginManager.md). Built-in adapter ids are an implementation choice (A13). The API key is `searchService.apiKey` (A.5). ### A.6 Timeline and capability mechanics From 30828fcaef0a7183e451fcbb7e2f8faa3a66f8d4 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 13:31:51 +0800 Subject: [PATCH 3/6] docs(2033): round-5 step-1 review fixes for the four owner contracts Goal keeps today's wire codes, gets English compatibility anchors, and maps the tree's unknown kind. SessionTitle adds the 0.1 field anchor and states the policy and acceptance it used to defer. Code Mode names the id routing mechanism, returns the work's reply, labels the executor's error kinds and names both faces in the appendix. The shared S5b title document is left to #2091. Refs #2033 --- .../appserver/session-title-metadata.md | 37 ++++----- docs/design/plugins/CodeMode.md | 35 +++++++-- docs/design/plugins/Goal.md | 76 +++++++++---------- docs/design/plugins/SessionTitle.md | 12 ++- 4 files changed, 92 insertions(+), 68 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 97d66ade62..540bd28dd9 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -5,7 +5,8 @@ The [target repository binding](../contracts/resource-owner-operations.md) moves Status: Implemented in roadmap item S5b ([#60](https://github.com/arcships/dim/issues/60), [#96](https://github.com/arcships/dim/pull/96)), after C6 ([#49](https://github.com/arcships/dim/issues/49), [#85](https://github.com/arcships/dim/pull/85)); the implementation follows this design. Review refined when a write -is admitted and how unload settles it (§6, D14). Requirement: [SessionTitle](../plugins/SessionTitle.md#own-contract). Overview: +is admitted and how unload settles it (§6, D14). Requirement: [SessionTitle](../plugins/SessionTitle.md) §2, §4 and +[A.2](../plugins/SessionTitle.md#a2-depended-on-shapes-owners-define-them). Overview: [Appendix B.2](../overview.md#b2-app-server-process-plugins), SessionStore and Rpc rows. Scope: [ADR 002](../../adr/002-plugin-scope.md) process scope, inside the existing SessionStore plugin, with three Rpc list fields. Consumer: SessionTitle. @@ -18,8 +19,8 @@ channel ([C6](session-notices.md)), and Rpc shows the title in protocol v3 Sessi - **Data.** A revision counter (0 means never written) and either no title or a title `{text, source}` with source `auto` or `manual`. Clearing keeps the counter, so a revision never repeats. -- **Write.** `setTitle {sessionId, the change callback's current title and revision, title | null}` commits revision `the change callback's current title and revision + 1` or fails - `rejected`, `not_found` or `storage`. The call is the handover: SessionStore admits the write when called, unless it +- **Write.** `setTitle {sessionId, expectedRevision, title | null}` commits revision `expectedRevision + 1` or fails + `conflict`, `not_found` or `storage`. The call is the handover: SessionStore admits the write when called, unless it is closing, and settles it itself; dropping the call only loses the reply. - **Notice.** After each commit, `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}`, in commit order. @@ -66,15 +67,15 @@ protocol version. | Item | Meaning | | --- | --- | -| `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write sets it to `the change callback's current title and revision + 1`: a new title, the same text again, a source change or a clear | +| `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write sets it to `expectedRevision + 1`: a new title, the same text again, a source change or a clear | | `title` | `{text, source}` or none | -| `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, enforced inside `setTitle`'s change callback ([SessionTitle](../plugins/SessionTitle.md#own-contract)) | +| `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, enforced through the revision check ([SessionTitle §4](../plugins/SessionTitle.md#4-timing-and-conflicts)) | - **A clear keeps the counter.** `title: null` leaves the Session's row with no title and the new revision. Were the row deleted, the counter would restart at 0, and a generation that read revision 0 before a rename and a clear would then commit an automatic title over the user's clear. - **Text as given.** SessionStore stores the text it receives. Title rules (trimming, length, a single line) are - SessionTitle's ([SessionTitle](../plugins/SessionTitle.md#own-contract)): its method validates rename input and + SessionTitle's ([A.3](../plugins/SessionTitle.md#a3-configuration)): its method validates rename input and normalizes generated text. The producer guarantees the contract, so SessionStore checks it again nowhere (AGENTS.md). - **Per Session.** Revisions of different Sessions are independent. A fork starts at 0. @@ -88,7 +89,7 @@ protocol version. | Method | Mode | Request | Reply value | Errors | | --- | --- | --- | --- | --- | | `read` | async | `{sessionId}` | `{revision, title: {text, source} \| null}` | `not_found`, `storage` | -| `setTitle` | async | `{id}` plus the caller's change: current `{revision, title}` in, next title or a refusal out | `{revision}`: the committed revision | `rejected`, `not_found`, `storage` | +| `setTitle` | async | `{sessionId, expectedRevision, title: {text, source: "auto" \| "manual"} \| null}` | `{revision}`: the committed revision | `conflict`, `not_found`, `storage` | - Replies use one envelope, `{ok: true, value}` or `{ok: false, error: {code, message}}`, as `settings` does. - Neither method loads the Session. `read` reads committed state and does not wait for the title writer (§5). @@ -100,7 +101,7 @@ protocol version. | Code | When | State after | | --- | --- | --- | | `not_found` | The store holds no record of the Session: never created, deleted, or rolled back. A stored Session that is closed or not loaded is found | Unchanged | -| `rejected` | the caller's change refused with its own code; nothing changed, no notice | Act on that code; an automatic title is discarded | +| `conflict` | `expectedRevision` is not the current revision | Unchanged, no notice. Read again | | `storage` | The transaction failed, or the call arrived after SessionStore started closing (§6) | Unchanged, no notice | ### 4.2 Rust @@ -150,7 +151,7 @@ This settles the boundary that SessionTitle §0 left to S5b. | Before the call | The caller's own work. Cancelling it before the call writes nothing | | The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `storage` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | | After the call | SessionStore settles the write itself: it commits and announces, or fails and writes nothing. Dropping the call, unloading the calling row or losing the reply neither cancels nor undoes it. `setTitle` has no cancel action | -| Lost reply | The caller reads with `title`. It does not repeat the write blindly: a repeat would be a second change, and an automatic title's change refuses once a title exists ([SessionTitle](../plugins/SessionTitle.md#errors)) | +| Lost reply | The caller reads with `read`. It does not repeat the write blindly: a repeat at the old revision fails `conflict`, and one at the new revision would be a second change ([SessionTitle Appendix C](../plugins/SessionTitle.md#appendix-c-errors-and-recovery)) | | SessionStore unload | Its disposer first stops admission: from then on a call fails `storage` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | Rejected: a cancel action that works until the transaction starts. It would only move the uncertainty, since a caller @@ -166,7 +167,7 @@ that drops the call still has to read to learn the outcome; and a JavaScript cal | `data` | `{title: string \| null, titleSource: "auto" \| "manual" \| null, titleRevision}` | - **Once per commit.** Emitted after each committed write with SessionStore's own context through - `session_broadcast::notify`. A refusal, a missing Session or a failed write emits nothing. + `session_broadcast::notify`. A conflict, a missing Session or a failed write emits nothing. - **No `sessionId` in `data`.** The channel names the Session, and Rpc adds `sessionId` to `session.notice` ([C6 D4](session-notices.md#10-decisions)). - **The list's fields.** `data` holds exactly the three title fields of a v3 Session list entry (§8). A client @@ -198,11 +199,11 @@ Protocol v3 `session.summaries` entries gain three fields: Rpc never calls `setTitle` and gains no method. How each error reaches clients: -| SessionStore | `session.summaries` | `session.rename` ([SessionTitle](../plugins/SessionTitle.md#operations)) | +| SessionStore | `session.summaries` | `session.rename` ([SessionTitle A.1](../plugins/SessionTitle.md#a1-sessionrename)) | | --- | --- | --- | | `storage` | The catalog read fails as it does today | `storage_failed` | | `not_found` | The Session is not listed | `session_not_found` | -| `rejected` | — | the caller's change refused; an automatic title is discarded ([SessionTitle](../plugins/SessionTitle.md#operations)) | +| `conflict` | — | SessionTitle reads again and retries ([§3.2](../plugins/SessionTitle.md#32-manual-rename)) | ## 9. Lifecycle @@ -212,21 +213,21 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | Load, unload, close, restart | Unchanged: the title is stored with the Session's rows, not with its instance. `read` and `setTitle` work on a Session that is not loaded; their notices are dropped, as nobody listens | | `session.delete` (S5c) | Removed in S5c's single delete transaction, before the Session record. Afterwards `read` and `setTitle` fail `not_found` | | Creation rollback | The same transaction as a delete; it removes a row that a racing write committed | -| `session.fork` (S5c) | Not copied ([SessionTitle](../plugins/SessionTitle.md#exceptions-with-reasons)): the fork starts untitled at revision 0 | +| `session.fork` (S5c) | Not copied ([SessionTitle A7](../plugins/SessionTitle.md#appendix-e-assumptions)): the fork starts untitled at revision 0 | | SessionStore or SqliteStorage reload | Settles as in §6. Consumers of `sessionMetadata` reload with SessionStore ([ADR 002](../../adr/002-plugin-scope.md) D3), which SessionTitle §1 accepts. SessionStore reloads only with SqliteStorage, which has no dependencies | ## 10. Timing and conflicts | Scenario | Outcome | | --- | --- | -| Two writes | They commit in admission order and each announces its revision; a change that refuses leaves the title as it was | +| Two writes with the same expected revision | The first to commit wins; the other fails `conflict` and announces nothing | | Writes to different Sessions | Run one at a time by the one title writer; each commits in its own transaction | | `setTitle` and `session.delete` | The store's write transactions order them: a commit first is removed by the delete; a delete first makes the write `not_found` | | `setTitle` and `session.fork` | Independent: the fork copies no title | | `setTitle` and Timeline appends | Independent rows; each uses its own transaction on the one store connection | | Notice and list read on one connection | §8: the higher `titleRevision` wins | | `setTitle` with no client attached | Committed; the notice is dropped; the next list shows the title | -| The same text written again | Commits a new revision and announces it ([SessionTitle](../plugins/SessionTitle.md#exceptions-with-reasons): a duplicate rename rewrites) | +| The same text written again | Commits a new revision and announces it ([SessionTitle Appendix B](../plugins/SessionTitle.md#appendix-b-full-conflict-table): a duplicate rename rewrites) | ## 11. Storage format @@ -280,7 +281,7 @@ after the upgrade commits (S5a's log line, with the version the store came from) | Identity | `dyn HostDispatch` at `host_key("sessionMetadata")`, provided by SessionStore; `register_shared("sessionMetadata")` in App Server's service catalog, beside `sessions` and `settings` | | Use | A C4 Session part declares `inject: ['sessionMetadata']` and calls `ctx.use('sessionMetadata')`, the path `settings` takes from a Session part ([settings-owner fixture](../../../runtime/fixtures/settings-owner.ts)). Types are in [npm/plugin.d.ts](../../../npm/plugin.d.ts) | | Modes | `read` and `setTitle` are both `async` | -| Writer | The service carries no caller identity, as for `settings` (AGENTS.md rule 11). SessionTitle is the title's one writer by design ([SessionTitle](../plugins/SessionTitle.md#own-contract)); other packages only read | +| Writer | The service carries no caller identity, as for `settings` (AGENTS.md rule 11). SessionTitle is the title's one writer by design ([SessionTitle §2](../plugins/SessionTitle.md#2-data-and-state)); other packages only read | | Reload | A consuming row reloads with SessionStore. SessionStore reloads only with SqliteStorage, so no directory part that never reloads is needed, unlike `sessions`, whose index reloads with Settings ([sessions D1](sessions-service.md#3-decisions)) | | Missing provider | A daemon without a native store has no SessionStore, so a row that injects `sessionMetadata` stays Pending under the existing rules; native Sessions continue | @@ -328,7 +329,7 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a 1. `setTitle` commits and returns the next revision; `read` returns it. Two v3 clients attached over IPC and WebSocket each receive exactly one `session.notice` per commit, in commit order, with `data` equal to the list's - title fields. A refusal and an unknown Session announce nothing. + title fields. A conflict and an unknown Session announce nothing. 2. Concurrent writers: every commit is announced once, in increasing `titleRevision` order. 3. A clear (`null`) commits a revision with no title and announces nulls. 4. `read` and `setTitle` of a Session that was never created, or was deleted: `not_found`. @@ -369,7 +370,7 @@ fixture](../../../runtime/fixtures/session-metadata.ts); items 6 and 12 hold the | D6 | `titleRevision` in v3 list entries | `title` and `titleSource` only | Without it a client cannot order a list reply against a notice (§8) | | D7 | List fields for protocol v3 only | All protocol versions | v1 and v2 are frozen and receive no title notices | | D8 | Service `sessionMetadata` with `read` and `setTitle`; the Rust binding uses `read` and `set_title` | A.2's method name `metadata` | `sessionMetadata.metadata` repeats itself; `read` matches `settings.read` | -| D9 | Errors `rejected`, `not_found`, `storage` as data; malformed calls are bridge errors | A `rejected` code as in `sessions` | The three codes are the write's outcomes; a malformed call is a programming error, as in `settings` | +| D9 | Errors `conflict`, `not_found`, `storage` as data; malformed calls are bridge errors | A `rejected` code as in `sessions` | The three codes are the write's outcomes; a malformed call is a programming error, as in `settings` | | D10 | `not_found` for a Session the store does not hold | `session_closed` | Maintainer decision; it is SessionStore's vocabulary, and SessionTitle maps it to `session_not_found` | | D11 | SessionStore stores text as given | Validating length and characters | SessionTitle owns the title rules and validates them; checking again would duplicate the contract | | D12 | SessionStore itself provides `sessionMetadata` | A part that never reloads | SessionStore reloads only with SqliteStorage (§12) | diff --git a/docs/design/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index cb24dad7da..be3cdbc4d1 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -67,7 +67,7 @@ let slot: Result<ToolResult, ServiceError> = quota | Owner | Operation | Use | | --- | --- | --- | -| Session access ([#2025](https://github.com/arcships/dim/issues/2025), target, pending [#2093](https://github.com/arcships/dim/pull/2093)) | the line's owner by line id | The entry reaches `CodeModeLine`; the run reaches the line's ToolExecutor | +| The id routing mechanism ([#2127](https://github.com/arcships/dim/issues/2127)) | `line_owner::<T>(line)` | The entry reaches `CodeModeLine`; the run reaches the line's ToolExecutor; #2024's contract states the line-id operations it serves ([target, pending #2092](https://github.com/arcships/dim/pull/2092)) | | ToolExecutor ([#2028](https://github.com/arcships/dim/issues/2028), target, pending [#2100](https://github.com/arcships/dim/pull/2100)) | `open {parentCallId, context}` → `{gateId}`; `invoke {gateId, call}` → `{result}`; `close {gateId}` → `{effects}` | Child calls, admission, child facts; the run closes the gate to word its result, and the owner closes it again at parent settlement with the effects merged once | | ToolBinding ([#2028](https://github.com/arcships/dim/issues/2028), target, pending [#2100](https://github.com/arcships/dim/pull/2100)) | `adopted {requestId}` → `{adoption, tools}` | The request's pinned declarations for `tools.list`, `tools.describe`, `tools.call` | | Session registries ([#2026](https://github.com/arcships/dim/issues/2026), target, pending [#2103](https://github.com/arcships/dim/pull/2103)) | `toolRegistry.register` | The `codemode` contribution | @@ -78,8 +78,8 @@ let slot: Result<ToolResult, ServiceError> = quota | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `codemode` | The model submits one program | `{code}` | the program's returned value as JSON text, or a terminal failure text, with the confirmed effects | The program is interrupted: a synchronous loop stops, a pending child is cancelled and new children are refused | `invalid_input` when the arguments or the code size are refused, returned as an error result | -| `codeModeLine.run` | Run one program on this line | `{outerCallId, code, context}` | `ToolResult` | Interrupts the program and closes the gate; committed children settle through ToolExecutor | `invalid`, `closed`, `cancelled` as the service error `{code, message}`; a failed program is the result's text | -| `codeMode.with_slot` | Run one program inside a process slot | `{work}` as a direct callback parameter, plus `caller: &Ctx` | `{}` | The work is cancelled and joined; the slot is released | `closed` as the service error `{code, message}`; a cancelled work is the callback's own result | +| `codeModeLine.run` | Run one program on this line | `{outerCallId, code, context}` | `ToolResult` | Interrupts the program and closes the gate; committed children settle through ToolExecutor | `invalid`, `closed`, `cancelled` as the service error `{code, message}`; a failed program is the result's text. The child gate's `interrupted`, `no_batch` and `gate_closed` are ToolExecutor's kinds, listed below for the program's handling, not this operation's errors | +| `codeMode.with_slot` | Run one program inside a process slot | `{work}` as a direct callback parameter, plus `caller: &Ctx` | the work's reply `T` | The work is cancelled and joined; the slot is released | `closed` as the service error `{code, message}`; a cancelled work is the callback's own result | The program's own failure is a result, not an operation error: the reply carries the failure text, the warning that child calls may have completed, and the confirmed effects. `invalid` is a code body over the limit; `closed` is the owner unloading; `cancelled` is the caller's cancellation before or during the run. All three are the service error `{code, message}`; the child invocation's `gate_closed`/`interrupted`/`no_batch` are ToolExecutor's errors, which the run turns into a program failure or a cancellation. @@ -99,8 +99,10 @@ The program's memory is bounded by QuickJS's own limit, its time by the wall-clo | --- | --- | | `invalid` | Fix the program: it exceeds the code byte limit | | `closed` | The line's run owner, the executor or the process quota is unloading; the next generation serves the next call | -| `interrupted` | The turn was interrupted before the gate existed; the run answers a cancellation result | -| `gate_closed` | The parent call settled or the batch was interrupted before the run closed the gate; the program's next child call fails and the run ends with the effects the parent already carries | +| `interrupted` (ToolExecutor's `open`) | The turn was interrupted before the gate existed; the run answers a cancellation result | +| `no_batch` (ToolExecutor's `open`) | The outer call is not in the current batch; a caller bug: the run answers a failure result naming it | +| `gate_closed` (ToolExecutor's `invoke`/`close`) | The parent call settled or the batch was interrupted before the run closed the gate; the program's next child call fails and the run ends with the effects the parent already carries | +| `closed` (ToolExecutor) | The executor is unloading; the run answers a cancellation result | | `cancelled` | The call stopped where the caller cancelled; committed children are reported in the effects | | a failed program (a result, not an error) | The model reads the failure text and the warning; it checks the effects before retrying | @@ -176,14 +178,14 @@ The process part provides `codeMode`; the branch part provides `codeModeLine`; t ```rust use rutis::host::BoxFuture; -#[rutis::service] +#[rutis::service(name = "codeMode")] impl ProgramSlots { /// Run `work` while holding one process program slot; `caller` binds the /// slot to the calling row, so the owner releases it at that row's unload. - pub async fn with_slot<T>( + pub async fn with_slot<T: Send>( &self, caller: &Ctx, - work: ChangeFn<T>, + work: WorkFn<T>, cancelled: CancelledFn, ) -> Result<T, ServiceError>; } @@ -205,6 +207,23 @@ pub struct RunProgram { pub context: ToolExecutionContext, } +/// The quota's work callback: it gets the caller's cancellation and answers the +/// work's own reply or a service error that keeps the caller's code. +pub type WorkFn<T> = Arc< + dyn Fn(CancelledFn) -> BoxFuture<'static, Result<T, ServiceError>> + Send + Sync, +>; + +#[rutis::service(name = "codeModeLine")] +impl CodeModeLine { + /// Run one program in this line's scope; the gate is ToolExecutor's. + pub async fn run( + &self, + caller: &Ctx, + request: RunProgram, + cancelled: CancelledFn, + ) -> Result<ToolResult, RunError>; +} + /// `RunError` is the same `{code, message}` shape: `invalid`, `closed`, `cancelled`. ``` diff --git a/docs/design/plugins/Goal.md b/docs/design/plugins/Goal.md index c6a5762c54..9226f7f608 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -43,7 +43,7 @@ let line = match command.line { Some(line) => line, None => tree.directory()?.default, // TimelineTree's shape (#2092) }; -let _ = tree.line(line.clone())?; // the tree's `unknown` kind; the method answers `unknown_branch` +let _ = tree.line(line.clone())?; // the tree's `unknown` kind; the method answers session_invalid_input // Goal's own text: the command block carries the operation, the objective and the judge. let input = goal_command(&line, &command); line_owner::<InputQueue>(&line)? @@ -93,14 +93,14 @@ The entry's operations are the five commands, the read, the tool and the guide e | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `session.goal.set` | Start a new execution of a goal on a line | `{sessionId, branchId?, objective, judge?, submissionId?}` | `{sequence}`: the committed command input's sequence, as today | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | -| `session.goal.edit` | Replace the objective, keeping status and judge | `{sessionId, branchId?, objective, submissionId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | -| `session.goal.pause` / `resume` / `clear` | Pause, resume or clear the goal | `{sessionId, branchId?, submissionId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `branch_ended`, `unknown_branch`, `service_reloading`, `closed`, `operation_interrupted` | -| `session.goal.get` | The goal of a line now | `{sessionId, branchId?}` | `{branchId, through, goal?}`; the goal carries `{objective, status, evaluator}` | The wait for the owner's fold stops | `invalid_params`, `service_reloading` (also for an ended line), `closed`, `operation_interrupted` | +| `session.goal.set` | Start a new execution of a goal on a line | `{sessionId, branchId?, objective, judge?, submissionId?}` | `{sequence}`: the committed command input's sequence, as today | Before the input is submitted | `invalid_params`, `session_invalid_input` (no such line), `branch_ended`, `service_reloading`, `session_closed`, `operation_interrupted` | +| `session.goal.edit` | Replace the objective, keeping status and judge | `{sessionId, branchId?, objective, submissionId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `session_invalid_input` (no such line), `branch_ended`, `service_reloading`, `session_closed`, `operation_interrupted` | +| `session.goal.pause` / `resume` / `clear` | Pause, resume or clear the goal | `{sessionId, branchId?, submissionId?}` | `{sequence}` | Before the input is submitted | `invalid_params`, `session_invalid_input` (no such line), `branch_ended`, `service_reloading`, `session_closed`, `operation_interrupted` | +| `session.goal.get` | The goal of a line now | `{sessionId, branchId?}` | `{branchId, through, goal?}`; the goal carries `{objective, status, evaluator}` | The wait for the owner's fold stops | `invalid_params`, `session_invalid_input` (no such line), `service_reloading` (also for an ended line), `session_closed`, `operation_interrupted` | | `goal_update` | The model reports completion or blockage | `{status, summary}` | text in `ToolResult.content` | Before the input is submitted | the commands' codes, returned as an error result | -| `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | The wait stops; the value is unaffected | `closed` | +| `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | The wait stops; the value is unaffected | `closed` (the service's `{code, message}`) | -`invalid_params` covers what Goal itself checks: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `unknown_branch` is TimelineTree's `line` refusal (`unknown` in the tree's vocabulary, mapped to the published code); `branch_ended` is the input owner's refusal; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. Every code above is one the client already receives today. +`invalid_params` is Goal's own parameter check: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `session_invalid_input` is the published code for TimelineTree's `unknown` kind and for `AgentError::InvalidInput`, and `session_closed` for `AgentError::Closed` (`crates/dim-agent-capabilities/src/methods.rs:137-154`); `branch_ended` is the ended-line refusal today, and the input owner's contract names it `line_ended` (target, pending [#2102](https://github.com/arcships/dim/pull/2102)), which lands as a client-visible code when that owner ships; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. Every code above is one a client receives today. `goalLine.read` takes no request parameter: the line is the instance the mechanism resolved. Requests, replies and errors are data; `cancelled` is the binding's cancellation argument. @@ -120,11 +120,11 @@ The business fact precedes the state record: the fact is what recovery reads, th | Kind | What the caller does next | | --- | --- | -| `invalid_params` | Fix the parameters: the objective, the judge, the summary, the line id | -| `unknown_branch` | The line does not exist; read the directory and choose a line | +| `invalid_params` | Fix the parameters: the objective, the judge, the summary, the line id; retry with the fix | +| `session_invalid_input` | The named line does not exist; read the directory and choose a line, then retry | | `branch_ended` | The line has ended; read its facts for history or choose an open line | | `service_reloading` | The line has no live goal owner or is reloading; show no goal, read history from the line's facts, retry later | -| `closed` | The Session or the input owner is unloading; the next generation serves the next Session | +| `session_closed` | The Session or the input owner is unloading; the next generation serves the next Session | | `operation_interrupted` | The mechanism interrupted the call on unload; the accepted input is settled, the read stops waiting | ## Exceptions with reasons @@ -196,61 +196,61 @@ Flow tests through the entry's public interfaces and the branch owner: - The id routing mechanism is [#2127](https://github.com/arcships/dim/issues/2127); the `line_owner` requirement lands there, and #2024's contract states the line-id operations it serves ([target, pending #2092](https://github.com/arcships/dim/pull/2092)). -## 兼容锚点(Compatibility anchors) +## Compatibility anchors -以下标题只为保留其他文档与代码注释里的旧锚点;每一节的正文都已并入上面的契约。 +These headings exist only so the links in other documents and code comments resolve; their content is in the sections above. -### 2. 数据与状态 +### 2. Data and state -目标属于一行;状态对象与加载映射见 [Goal-state-read.md](Goal-state-read.md),本契约的 [Own contract](#own-contract) 规定写入顺序。 +The goal belongs to a line; the state object and its load mapping are in [Goal-state-read.md](Goal-state-read.md), and [Own contract](#own-contract) states the write order. -### 3.4 新分支清除继承的目标 +### 3.4 A new branch clears the inherited goal -子行开始时不继承目标,见 [Own contract](#own-contract) 的 decisions 与 [Exceptions with reasons](#exceptions-with-reasons)。 +A child line starts with no goal; see the decisions in [Own contract](#own-contract) and [Exceptions with reasons](#exceptions-with-reasons). -### 5. 上下文映射 +### 5. Context mapping -模型只经采用输入看到目标文本;见 [Own contract](#own-contract) 与 [Client-visible changes](#client-visible-changes)。 +The model reads goals only through adopted inputs; see [Own contract](#own-contract) and [Client-visible changes](#client-visible-changes). -### 10. 实现 +### 10. Implementation -实现顺序与删除清单见 #2033 的交付评论。 +The implementation order and the deletion list are in #2033's delivery comment. -### A.2 Session 方法 +### A.2 Session methods -`session.goal.*` 的参数、回复与错误见 [Own contract](#own-contract)。 +The `session.goal.*` parameters, replies and errors are in [Own contract](#own-contract). -### A.3 读取目标 +### A.3 Reading the goal -读目标见 [Own contract](#own-contract) 的 `session.goal.get` 与 `goalLine.read`;结束行不再回答。 +See `session.goal.get` and `goalLine.read` in [Own contract](#own-contract); an ended line no longer answers. -### A.4 续跑决策 +### A.4 Continuation decision -续跑、上限与无进展见 [Own contract](#own-contract) 的 decisions。 +Continuation, the limit and no-progress are in [Own contract](#own-contract). -### A.5 模型可见文本 +### A.5 Model-visible texts -标记、状态块、命令块与续行仍是 Goal 的模型协议;文本格式不变,记录顺序见 [Client-visible changes](#client-visible-changes)。 +The marker, the state block, the command block and the continuation remain Goal's model protocol; the text format is unchanged, and the record's order is in [Client-visible changes](#client-visible-changes). -### A.5.1 协议与策略 +### A.5.1 Protocol and policy -guide 条目见 [Own contract](#own-contract);策略句仍归 Goal。 +The guide entry is in [Own contract](#own-contract); the policy sentences stay Goal's. -### A.5.2 评估 +### A.5.2 Evaluation -评估分支与结论见 [Own contract](#own-contract) 的 flows 与 [Exceptions with reasons](#exceptions-with-reasons)。 +The evaluator line and its conclusion are in [Own contract](#own-contract) and [Exceptions with reasons](#exceptions-with-reasons). -### 附录 B 完整冲突表 +### Appendix A. Interface details -冲突与终止见 [Own contract](#own-contract) 的 Flows。 +The command and read details are in [Own contract](#own-contract). -### 附录 C 错误与恢复 +### Appendix B. Full conflict table -错误码见 [Own contract](#own-contract) 的 Errors。 +Conflicts and termination are in [Own contract](#own-contract)'s Flows. -### 附录 E 假设 +### Appendix E. Assumptions -参数上限见 [Use and scope: responsibility split](#use-and-scope-responsibility-split)。 +The parameter limits are in [Use and scope: responsibility split](#use-and-scope-responsibility-split). ## Binding appendix diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 32efe6e15b..07bf217577 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -1,8 +1,8 @@ # SessionTitle -Scope: Session. Issue: #2033 (this contract). The generation policy, the operator's text rules and the acceptance list are the ones in the previous version of this document; this contract states the owner's shape and the calls it makes. +Scope: Session. Issue: #2033 (this contract). The generation policy, the operator's text rules and the acceptance list are restated below and in [Verification](#verification); this contract states the owner's shape and the calls it makes. -SessionTitle owns a Session's title policy: when a title is generated, what text is acceptable, when the operator's text replaces it, and the title a Session's creation requests. The title value itself belongs to SessionStore, which serializes the writes and announces each commit. The current shape is the one #2033's scan report describes. +SessionTitle owns a Session's title policy: when a title is generated, what text is acceptable, when the operator's text replaces it, and the title a Session's creation requests. The title value itself belongs to SessionStore, which serializes the writes and announces each commit. The current shape is the one #2033's scan report describes. The generation policy, the instruction text and the 2000-code-point excerpt are unchanged from the pre-contract document and are restated here: one instruction, one user message carrying the first adopted input's text, the first line normalized (quotes and trailing punctuation removed, whitespace collapsed), cut to `maxLength`, then the excerpt fallback. ## Use and scope: responsibility split @@ -10,7 +10,7 @@ SessionTitle owns: - **The moment of generation.** The first adopted input on the Session's conversation line — an operator input with user content, or Goal's applied objective — triggers one attempt; a Session that already has a title never generates one. - **The text rules.** The instruction sent to the model, the 2000-code-point excerpt, the output normalization (one line, no quoting, collapsed whitespace) and the length bound from the `session-title` source (`maxLength` 10..=200, default 80). -- **The routing.** An explicit model from the source, otherwise the account owner's title operation when the adopted provider belongs to it, otherwise the adopted model, otherwise the excerpt fallback; one 30 s budget across the paths; three failed attempts end the attempts for this generation. The acceptance list is the previous version's Appendix D and is unchanged. +- **The routing.** An explicit model from the source, otherwise the account owner's title operation when the adopted provider belongs to it, otherwise the adopted model, otherwise the excerpt fallback; one 30 s budget across the paths; three failed attempts end the attempts for this generation. Acceptance (unchanged from the pre-contract document): the first adopted input titles while its turn runs; an interrupt or failed turn still titles; member and non-interactive Sessions get none; a rename during generation wins; a titled Session is never regenerated; a cleared title regenerates from the first adopted input; reload before the store handover writes nothing; missing or invalid settings yield the defaults or fail without rewriting; a first input withdrawn before adoption never titles; a Goal-first Session titles from the objective alone; an absent or withdrawn account owner leaves generation and rename available. - **The manual rename.** `session.rename`'s parameter rules and the text it accepts or clears. - **The requested initial title.** The title a launch carried is written once, as the first manual title, after the Session is published. @@ -205,6 +205,10 @@ None. `session.rename` keeps its parameters, its `{title, titleSource, revision} These headings exist only so the links in other documents and code comments resolve; their content is in the sections above. +### 0.1 Fields read for one title attempt + +One attempt reads four fields at a fixed cutoff: the triggering input's id, its `data.user` text or Goal's `<objective>` in `data.blocks`, the first adopted input's id, and the adopted model from `context/configured`; the read shape is in [Own contract](#own-contract). + ### 2. Data and state The title value and its revision are SessionStore's; the policy is in [Own contract](#own-contract). @@ -251,7 +255,7 @@ See the error table in [Own contract](#own-contract). ### Appendix D. Acceptance -The previous version's acceptance list stays in force; see [Verification](#verification). +The acceptance items are in [Own contract](#own-contract)'s routing paragraph. ### Appendix E. Assumptions From d0e2db45b9eb7dfcba3db2a2aea53e5f33046225 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 14:10:28 +0800 Subject: [PATCH 4/6] docs(2033): align the route errors, the tool-binding row and the title links --- docs/design/contracts/runtime-owner-operations.md | 2 +- docs/design/plugins/Goal.md | 8 +++++--- docs/design/plugins/SessionTitle.md | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index f34abecf6a..76ff94e0c5 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -73,5 +73,5 @@ substitutes a newer head. | 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`, `bindCurrent`, `adopted({requestId}) → {adopted}`, `transfer`, `release`. ToolBinding retains the pinned handler generation; Code Mode reads `adopted` ([CodeMode](../plugins/CodeMode.md#own-contract)). | +| Loop, ToolExecutor and Code Mode readers → `toolBinding` | `bind({requestId, turnId, through, declared, sources}) → void`, `adopted({requestId}) → {adoption, tools}`, `claim({requestId, calls, context}) → void`, `transfer({from, to}) → void`, `release({requestId}) → void`, `retain_only({requestId}) → void`([ToolBinding](https://github.com/arcships/dim/pull/2100)). Settlement follows the line's `step/tool-result` and `turn/end`; `retain_only` is the Loop's own rebuild step. | | 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/plugins/Goal.md b/docs/design/plugins/Goal.md index 9226f7f608..d0874030f7 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -57,7 +57,9 @@ line_owner::<InputQueue>(&line)? ```rust let goal = match line_owner::<GoalLine>(&line) { Ok(owner) => owner.read().await?, - Err(NoInstance) => return Err(AgentError::Reloading("Goal".into())), // service_reloading + Err(NoLine) => return Err(AgentError::Reloading("Goal".into())), // service_reloading + Err(SessionClosing) => return Err(AgentError::Closed), // session_closed + // NoSession cannot arrive here: only a process caller receives it. }; // `goal.objective`, `goal.status`, `goal.evaluator`, `goal.through`; history is read from facts instead. ``` @@ -100,7 +102,7 @@ The entry's operations are the five commands, the read, the tool and the guide e | `goal_update` | The model reports completion or blockage | `{status, summary}` | text in `ToolResult.content` | Before the input is submitted | the commands' codes, returned as an error result | | `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | The wait stops; the value is unaffected | `closed` (the service's `{code, message}`) | -`invalid_params` is Goal's own parameter check: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `session_invalid_input` is the published code for TimelineTree's `unknown` kind and for `AgentError::InvalidInput`, and `session_closed` for `AgentError::Closed` (`crates/dim-agent-capabilities/src/methods.rs:137-154`); `branch_ended` is the ended-line refusal today, and the input owner's contract names it `line_ended` (target, pending [#2102](https://github.com/arcships/dim/pull/2102)), which lands as a client-visible code when that owner ships; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. Every code above is one a client receives today. +`invalid_params` is Goal's own parameter check: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `session_invalid_input` is the published code for TimelineTree's `unknown` kind and for `AgentError::InvalidInput`, and `session_closed` for `AgentError::Closed` (`crates/dim-agent-capabilities/src/methods.rs:137-154`); `branch_ended` is the ended-line refusal today, also for a route that answers `NoLine` after the record was read, and the input owner's contract names it `line_ended` (target, pending [#2102](https://github.com/arcships/dim/pull/2102)), which lands as a client-visible code when that owner ships; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. The entry keeps the mechanism's three answers apart: `NoLine` and a reloading owner are `service_reloading`, `SessionClosing` is `session_closed`, and `NoSession` never reaches a Session part. Every code above is one a client receives today. `goalLine.read` takes no request parameter: the line is the instance the mechanism resolved. Requests, replies and errors are data; `cancelled` is the binding's cancellation argument. @@ -123,7 +125,7 @@ The business fact precedes the state record: the fact is what recovery reads, th | `invalid_params` | Fix the parameters: the objective, the judge, the summary, the line id; retry with the fix | | `session_invalid_input` | The named line does not exist; read the directory and choose a line, then retry | | `branch_ended` | The line has ended; read its facts for history or choose an open line | -| `service_reloading` | The line has no live goal owner or is reloading; show no goal, read history from the line's facts, retry later | +| `service_reloading` | The id routing answered `NoLine` (the line is closing, ended or not this Session's) or the goal owner is reloading; show no goal, read history from the line's facts, retry later | | `session_closed` | The Session or the input owner is unloading; the next generation serves the next Session | | `operation_interrupted` | The mechanism interrupted the call on unload; the accepted input is settled, the read stops waiting | diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 07bf217577..c3236cea93 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -158,7 +158,7 @@ Flow tests through `session.create`, `session.submit`, `session.rename`, `sessio ## Supersedes -- [session-title-metadata.md](../appserver/session-title-metadata.md): the paragraph describing SessionTitle's calls on the old metadata service (`sessionMetadata.read`/`setTitle`, revision compare). The title value, the source and the notice stay that document's; this contract's dependency table replaces the calls. +- The store's `title` and `setTitle(caller, SetTitle, ChangeFn)` shapes are SessionStore's ([#2091](https://github.com/arcships/dim/pull/2091)); [session-title-metadata.md](../appserver/session-title-metadata.md) stays that owner's document for the title value, its source and the notice, and this contract adds no title operation of its own. - [resource-owner-operations.md](../contracts/resource-owner-operations.md): the SessionTitle row (`store.readMetadata`, `setTitle` with an existing title request). SessionTitle calls `store.title` and `store.setTitle` with a `change`. - [resource-faces.md](../resource-faces.md): the sentence that SessionTitle uses the process repository operations. - The Chinese mirror `docs/zh/design/plugins/SessionTitle.md` describes the pre-contract shape; its target is this document. From 02237876f010d698ef0aafcd3533ae184304b64c Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 14:28:11 +0800 Subject: [PATCH 5/6] docs(2033): cite the routing mechanism and the ADR decisions once --- docs/design/plugins/CodeMode.md | 2 +- docs/design/plugins/Goal.md | 4 ++-- docs/design/plugins/Web.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/design/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index be3cdbc4d1..b9f4ca1ccd 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -156,7 +156,7 @@ None. The `codemode` tool keeps its name, description, schema, risk and v4 gate; | §7 cross-language | The tool, the run and the quota are data and callbacks; the program's bridge is `tools.list/describe/call`. | | §7 one change | Deleting the process runner table, the runner trait and the executor wrapper happens in the same change that adds the quota operation and the line's run operation. | | ADR 002 D1 | Slots are process state; the run is line state; the declaration is Session state. | -| ADR 027 D1, D4 | The tool handler reaches `codeModeLine` and the line's ToolExecutor by the line id on its execution context; the resolution is not a dependency and is not kept across calls. | +| ADR 027 | Applies: D1 and D4. The mechanism is [#2127](https://github.com/arcships/dim/issues/2127). | | ADR 027 D3 | `codeModeLine` and ToolExecutor are branch data faces; no registration point or lifecycle service is resolved by id. | | ADR 002 D2 | No wiring plugin: both operations are on their owners' types; the mechanism resolves the line. | | ADR 002 D3 | Dependencies point from Code Mode to the registry, the mechanism and ToolExecutor. | diff --git a/docs/design/plugins/Goal.md b/docs/design/plugins/Goal.md index d0874030f7..688094b8c0 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -102,7 +102,7 @@ The entry's operations are the five commands, the read, the tool and the guide e | `goal_update` | The model reports completion or blockage | `{status, summary}` | text in `ToolResult.content` | Before the input is submitted | the commands' codes, returned as an error result | | `goalLine.read` | The line's published goal value | `{}` | `{objective?, status, evaluator, through}` | The wait stops; the value is unaffected | `closed` (the service's `{code, message}`) | -`invalid_params` is Goal's own parameter check: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `session_invalid_input` is the published code for TimelineTree's `unknown` kind and for `AgentError::InvalidInput`, and `session_closed` for `AgentError::Closed` (`crates/dim-agent-capabilities/src/methods.rs:137-154`); `branch_ended` is the ended-line refusal today, also for a route that answers `NoLine` after the record was read, and the input owner's contract names it `line_ended` (target, pending [#2102](https://github.com/arcships/dim/pull/2102)), which lands as a client-visible code when that owner ships; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. The entry keeps the mechanism's three answers apart: `NoLine` and a reloading owner are `service_reloading`, `SessionClosing` is `session_closed`, and `NoSession` never reaches a Session part. Every code above is one a client receives today. +`invalid_params` is Goal's own parameter check: an objective outside 1..=4000 characters, a summary outside 1..=2000, an unknown judge, an empty `branchId`. `session_invalid_input` is the published code for TimelineTree's `unknown` kind and for `AgentError::InvalidInput`, and `session_closed` for `AgentError::Closed` (`crates/dim-agent-capabilities/src/methods.rs:137-154`); `branch_ended` is the ended-line refusal today, also for a route that answers `NoLine` after the record was read, and the input owner's contract names it `line_ended` (target, pending [#2102](https://github.com/arcships/dim/pull/2102)), which lands as a client-visible code when that owner ships; `service_reloading` is the mechanism's answer that the line has no live goal owner, which the client shows as no goal and reads from history instead. The entry keeps the mechanism's three answers apart ([#2127](https://github.com/arcships/dim/issues/2127)): `NoLine` and a reloading owner are `service_reloading`, `SessionClosing` is `session_closed`, and `NoSession` never reaches a Session part. Every code above is one a client receives today. `goalLine.read` takes no request parameter: the line is the instance the mechanism resolved. Requests, replies and errors are data; `cancelled` is the binding's cancellation argument. @@ -182,7 +182,7 @@ Flow tests through the entry's public interfaces and the branch owner: | §7 one interface | The commands are one method namespace and one tool contribution; the branch owner's face is one read; no adapter exists beside either. | | §7 cross-language | Commands, parameters, replies and errors are data; the tool result is text in `ToolResult.content`. | | §7 one change | The implementation task deletes the routing table, the re-fold path and the pre-commit callback in the same change that adds `goalLine.read` and migrates the entries. | -| ADR 027 D1, D4 | The entry reaches `GoalLine` and the line's `InputQueue` by line id; the resolution is not a dependency and is not kept across calls. | +| ADR 027 | Applies: D1 and D4. The mechanism is [#2127](https://github.com/arcships/dim/issues/2127). | | ADR 027 D3 | No registration point and no lifecycle service is resolved by line id: `GoalLine` and `InputQueue` are data faces of the branch group; the registration points it uses (`sessionMethods`, `toolRegistry`, `guideEntries`) are its own Session's. | | ADR 002 D1 | The goal, its decisions and its tasks live in the branch; the Session entry registers the commands. | | ADR 002 D2 | No wiring plugin: the branch part provides `goalLine` on its own type; the mechanism resolves the line. | diff --git a/docs/design/plugins/Web.md b/docs/design/plugins/Web.md index 0ea611feda..37d65cb92b 100644 --- a/docs/design/plugins/Web.md +++ b/docs/design/plugins/Web.md @@ -135,7 +135,7 @@ None. Both tools keep their names, schemas, descriptions, results and error code | §7 cross-language | Both tools are declared with data schemas and their results are data. | | §7 one change | Replacing the search face with the account owner's operations happens in the same change that migrates the declaration and the call. | | ADR 002 D1 | Session scope: no state is shared across Sessions. | -| ADR 027 D2 | Web resolves no service by id: Settings and the account owner are process dependencies declared at load, and no registration point is reached by id. | +| ADR 027 | Not applicable: Web resolves no service by id; Settings and the account owner are process dependencies declared at load. | | ADR 002 D2 | No wiring plugin: the tools are on the part; the source is the registry's registration point. | | ADR 002 D3 | Dependencies point from Web to Settings, the account owner and the registry. | | ADR 002 D4 | The `web` document is business configuration read at use; the plugin's on/off state is structural. | From 8f440bde760430053141c96ca24f77ce1af764e6 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 14:34:34 +0800 Subject: [PATCH 6/6] docs(2033): list the three client-visible changes of the goal contract The ended-line read, the state record's order and the optional submission id are stated as separate client-visible changes with their affected callers. Refs #2033 --- docs/design/plugins/Goal.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/design/plugins/Goal.md b/docs/design/plugins/Goal.md index 688094b8c0..d2e6ecbc53 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -157,9 +157,13 @@ Flow tests through the entry's public interfaces and the branch owner: ## Client-visible changes -- `session.goal.*` replies keep their fields: `{sequence}` is the committed command input's sequence, the same value returned today; `session.goal.get` keeps `{branchId, through, goal?}` with `{objective, status, evaluator}`. Every error code above is one the client already receives. The write requests gain an optional `submissionId`; a client that sends none keeps today's behavior, and a retrying client sends the same id to be accepted once. -- An ended line no longer answers `session.goal.get` with its last goal: the entry has no live owner to read, and folding the line's facts in the entry is what this contract removes. `session.goal.get` answers `service_reloading` and a client shows no goal. Affected: `dim-cli`'s `/goal` and `sessions.status` projection (`crates/dim-cli/src/goal_command.rs`, `session_host.rs`) and the TUI's goal panel, which read the value. Migration: read the line's facts (`goal/state`) for an ended line, or show no goal; the CLI change ships with the implementation. -- The `goal:state` record no longer shares one batch with the command. The model sees the command input first and the state record from the next request; the record's text format is unchanged. Affected: the prompt-evaluation tests that assert the command and record order, and `Goal-state-read.md`'s ordering rule. +Three changes reach clients; everything else keeps its field names, codes and notifications. + +- **`session.goal.get` on an ended line answers `service_reloading`.** Today the entry folds the line's facts and answers its last `GoalRead`; after this contract the line has no live owner to read and the entry no longer folds. Affected: `dim-cli`'s `/goal` (`crates/dim-cli/src/goal_command.rs`), the `sessions.status` projection (`crates/dim-cli/src/session_host.rs`) and the TUI goal panel. Migration: read the line's facts (`goal/state`) for an ended line, or show no goal; the client change ships with the implementation. +- **The `goal:state` record follows the command.** The command input is written first and the state record after the business fact, so the model sees the command in that request and the record from the next one; the record's text format is unchanged. Affected: the prompt-evaluation tests that assert the command and record order, and `Goal-state-read.md`'s ordering rule; they are updated with the implementation. +- **The write requests gain an optional `submissionId`.** A client that sends none keeps today's behavior; a retrying client sends the same id to be accepted once. + +`session.goal.*` replies keep their fields: `{sequence}` is the committed command input's sequence, the same value returned today, and `session.goal.get` keeps `{branchId, through, goal?}` with `{objective, status, evaluator}`. ## Rule check