@deepseek-ai/dsh-session-store 0.0.0-stage → 0.2.3-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,106 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/core/session-store/README.md
5
+ /:
6
+ en: 54dedea99ec5492c
7
+ zh: 23b29cb5d738dadb
8
+ /deepseek-ai-dsh-session-store:
9
+ en: 132cc3496f816988
10
+ zh: 4543500733af301b
11
+ /deepseek-ai-dsh-session-store/summary:
12
+ en: 5f6d384bd5498705
13
+ zh: 3dc9178ad7bf8770
14
+ /deepseek-ai-dsh-session-store/table-of-contents:
15
+ en: d152484eb41ac6b4
16
+ zh: 09388d293f9be9cb
17
+ /deepseek-ai-dsh-session-store/use-this-package:
18
+ en: 01da5c2585a5d238
19
+ zh: 3aca6dbb9c01ad62
20
+ /deepseek-ai-dsh-session-store/use-this-package/when-to-choose-it:
21
+ en: 1e15a47d11892a76
22
+ zh: a8032c57ec0a5758
23
+ /deepseek-ai-dsh-session-store/use-this-package/minimal-configuration:
24
+ en: cb34484323b15a8d
25
+ zh: 2c71471a656acebb
26
+ /deepseek-ai-dsh-session-store/use-this-package/exports:
27
+ en: 6be4244d9defd0f7
28
+ zh: b1c9eb963fded6dc
29
+ /deepseek-ai-dsh-session-store/use-this-package/create-and-inspect-sessions:
30
+ en: 3154d51706eea404
31
+ zh: f1f86c7f833cc021
32
+ /deepseek-ai-dsh-session-store/use-this-package/interface-and-class-names:
33
+ en: 0916807c7bb58de0
34
+ zh: c888bc5ddc5a5492
35
+ /deepseek-ai-dsh-session-store/use-this-package/validate-a-log:
36
+ en: 26016510ed0e75b4
37
+ zh: 76bd6be90a5f630f
38
+ /deepseek-ai-dsh-session-store/use-this-package/append-and-derive:
39
+ en: e843ca72b4510b1a
40
+ zh: f520d4375cca7d1a
41
+ /deepseek-ai-dsh-session-store/use-this-package/read-the-log:
42
+ en: c03fe1d97817a10f
43
+ zh: 5c4829fc1e625313
44
+ /deepseek-ai-dsh-session-store/use-this-package/write-experimental-plugin-records:
45
+ en: 2f61f52f0e50bdca
46
+ zh: 2e6de2a84edb0c46
47
+ /deepseek-ai-dsh-session-store/use-this-package/fork-a-session:
48
+ en: e430516d8c6e8d94
49
+ zh: 59ebddc22f8e0306
50
+ /deepseek-ai-dsh-session-store/use-this-package/flush-durable-state:
51
+ en: 70a7673145c851ad
52
+ zh: 0dd1667d9518993d
53
+ /deepseek-ai-dsh-session-store/understand-the-implementation:
54
+ en: ce7e776e9d516bdb
55
+ zh: 59d2751743db7795
56
+ /deepseek-ai-dsh-session-store/understand-the-implementation/design-concept:
57
+ en: 45399e9efb4c51a7
58
+ zh: 1a9b2dc3497c1e39
59
+ /deepseek-ai-dsh-session-store/understand-the-implementation/source-map:
60
+ en: e64abfa237027f1b
61
+ zh: 74dc367754faf0bc
62
+ /deepseek-ai-dsh-session-store/understand-the-implementation/append-validation:
63
+ en: 6a3c112126fb8db7
64
+ zh: 995e299f87426ceb
65
+ /deepseek-ai-dsh-session-store/understand-the-implementation/derived-history:
66
+ en: c455b76a468a00a2
67
+ zh: 2120fc3741924eec
68
+ /deepseek-ai-dsh-session-store/understand-the-implementation/the-request-header:
69
+ en: 62056d72ff5c78be
70
+ zh: 2024bc62bc381bc1
71
+ /deepseek-ai-dsh-session-store/further-exploration:
72
+ en: 86aadd261bc145d6
73
+ zh: 33547f0a45398038
74
+ /deepseek-ai-dsh-session-store/model-experience:
75
+ en: 215e7ba838619b7b
76
+ zh: a311da3843709f90
77
+ /deepseek-ai-dsh-session-store/model-experience/derived-message-history:
78
+ en: 3005f28ded3b28ea
79
+ zh: daaddc6df470b396
80
+ /deepseek-ai-dsh-session-store/model-experience/derived-message-history/what-the-model-sees:
81
+ en: 30ccd8296306b132
82
+ zh: 19efa5a43745585c
83
+ /deepseek-ai-dsh-session-store/model-experience/derived-message-history/token-effect:
84
+ en: 05e088199dac7f98
85
+ zh: 35868b5fb768e240
86
+ /deepseek-ai-dsh-session-store/model-experience/derived-message-history/kv-cache-effect:
87
+ en: 6c8079c7de029ed4
88
+ zh: 634d6f93ce6373c4
89
+ /deepseek-ai-dsh-session-store/model-experience/logged-request-header:
90
+ en: 5397f067293a55cd
91
+ zh: 1dcc30d0c214f175
92
+ /deepseek-ai-dsh-session-store/model-experience/logged-request-header/what-the-model-sees:
93
+ en: 590cf70b9d581616
94
+ zh: c4d46853114cb3d9
95
+ /deepseek-ai-dsh-session-store/model-experience/logged-request-header/token-effect:
96
+ en: 310b8f36a86443e5
97
+ zh: 906c4da8d03c5966
98
+ /deepseek-ai-dsh-session-store/model-experience/logged-request-header/kv-cache-effect:
99
+ en: 5eb30cfb410d52c0
100
+ zh: da56365b8ab896da
101
+ /deepseek-ai-dsh-session-store/known-limitations-and-deferred-work:
102
+ en: b67ed986feddd0e9
103
+ zh: a8acef2b2f18b603
104
+ /deepseek-ai-dsh-session-store/known-limitations-and-deferred-work/dev-note:
105
+ en: e67f633dc6fe7773
106
+ zh: 3bb0c20c93f16f98
package/README.md CHANGED
@@ -1,3 +1,275 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "The event-sourced session log and in-memory store for users and maintainers building, inspecting, or extending the durable record behind every agent interaction."
3
+ kind: "package-reference"
4
+ ---
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @deepseek-ai/dsh-session-store
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ `dsh-session-store` records every model-visible fact in an append-only session log and derives model history from that record. Consumers can inspect, replay, fork, and flush sessions while preserving historical events; compaction hides superseded entries from the active conversation without deleting them. Sessions remain in memory unless a persistence backend is added, and durability checkpoints wait for configured backends. Choose this package wherever an agent needs a reconstructable session record; it does not call models.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Understand the implementation](#understand-the-implementation)
18
+ - [Further Exploration](#further-exploration)
19
+ - [Model Experience](#model-experience)
20
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
21
+ - [Dev Note](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## Use this package
27
+
28
+ Mount `dsh-session-store` wherever a session must exist. It creates and holds event-sourced `Session` instances in memory; durable storage is layered on by a persistence plugin that subscribes to the `session/event` feed.
29
+
30
+ Session Store builds `Session` and `SessionStore` on the data layer in [`dsh-session-data`](../session-data/README.md). Writable data comes from `ctx.sessionData` (`create`, `open`, and `fork`). `Session.fromData(data, options)` constructs a detached Session and `SessionStore.prepare(data, options)` constructs a store-owned, unentered Session over caller-owned data with the shared `SessionConstructionOptions` (`{ mode: 'create' | 'restore' }`). Publication stays explicit: after `await data.flush()`, the owner enters and announces the Session under its fiber effect and closes the data after teardown. These members reach the definition interfaces through module augmentation, so a program that calls them declares `@deepseek-ai/dsh-session-data` as a dependency.
31
+
32
+ ### When to choose it
33
+
34
+ This plugin is the only provider of `ctx.sessions` on the Host: a plugin that injects `sessions` stays pending until this plugin loads. A package that only reads, names, or checks Session data imports [`@deepseek-ai/dsh-session`](../session/README.md) and needs no row. A package that imports this package in production code declares it in `peerDependencies`, so that it uses the `Session` class and the validation of the installed store; a bundle whose patch lists the row declares it in `dependencies`.
35
+
36
+ ### Minimal configuration
37
+
38
+ A composition loads the plugin with one row. The plugin has no configuration fields.
39
+
40
+ ```yaml
41
+ - id: session
42
+ name: '@deepseek-ai/dsh-session-store'
43
+ ```
44
+
45
+ Shipped profiles give this row the id `session`, and a patch addresses the row by that id. A row that names `@deepseek-ai/dsh-session` does not load, because that package exports no plugin: the Loader logs `invalid plugin, expect function or object with an "apply" method, received object` for the row, and every plugin that injects `sessions` stays pending.
46
+
47
+ Code that creates a `Context` without the Loader mounts the default export:
48
+
49
+ ```ts
50
+ import { Context } from '@deepseek-ai/cordis'
51
+ import { buildSessionHeader, type SessionId } from '@deepseek-ai/dsh-session'
52
+ import { brandString } from '@deepseek-ai/dsh-brand'
53
+ import PersistedSessionDataService from '@deepseek-ai/dsh-session-data-persisted'
54
+ import SessionStore from '@deepseek-ai/dsh-session-store'
55
+
56
+ const ctx = new Context()
57
+ await ctx.plugin(PersistedSessionDataService)
58
+ await ctx.plugin(SessionStore)
59
+ const id = brandString<SessionId>('example')
60
+ const data = await ctx.sessionData.create(buildSessionHeader(id))
61
+ const session = ctx.sessions.prepare(data, { mode: 'create' })
62
+ ```
63
+
64
+ ### Exports
65
+
66
+ The package has one entry, its root. Apart from `SessionPreparationOptions`, the types that these exports name, such as `SessionEvent` and `SessionId`, come from [`@deepseek-ai/dsh-session`](../session/README.md).
67
+
68
+ | Export | Use |
69
+ |---|---|
70
+ | `SessionStore` (default export) | The service that a composition row or `ctx.plugin()` loads; it provides `ctx.sessions` |
71
+ | `Session` | The class of every Session built over Session data; `Session.fromData(data, options)` is its detached constructor |
72
+ | `SessionPreparation`, `SessionPreparationOptions` | Wraps one unpublished Session; disposing it calls the `release` callback from its options once |
73
+ | `appendPluginRecord`, `pluginRecordOf` | [Write and read experimental plugin records](#write-experimental-plugin-records) |
74
+ | `foldSurface` | Replays `surfaceOp` markers and message projections over a complete event log |
75
+ | `canonicalHeader`, `headerEquals` | Normalize and compare request headers |
76
+ | `validateSessionLog` | [Validates a header and its events](#validate-a-log) without constructing a Session |
77
+
78
+ The package-internal `src/request-header.ts` also declares the request-header and route-metadata state definitions that `Session.requestHeader()` and `Session.requestContext()` evaluate, and `src/tool-history.ts` declares the tool-history state definition that `Session.toolHistory()` evaluates; they are not root exports.
79
+
80
+ ### Create and inspect sessions
81
+
82
+ Obtain writable data from `ctx.sessionData.create(id, meta?, options?)` or the complete-header `create(header, options?)`, from `ctx.sessionData.open(id, { mode: 'write' })` for a stored Session, or from a parent data's `fork`. `ctx.sessions.prepare(data, options)` performs only the synchronous Session construction with the store's registered projections, leaves data ownership with the caller, and does not enter or announce. The caller must `await data.flush()` before entering, then enter and announce under the owning fiber effect and close the data after teardown. `mode: 'create'` marks new data, including fork data, and `mode: 'restore'` marks an opened stored log.
83
+
84
+ `Session.fromData(data, options)` applies the same construction without a store. `get(id)` and `list()` find live sessions. Independent instances accept events without sending `session/event`; writes after store entry require a completed `session/created` announcement, and removal disables writes. Failed announcement or removal leaves writes disabled, and `session/disposed` is emitted only for an instance whose announcement began.
85
+
86
+ ```text
87
+ const data = await ctx.sessionData.create(buildSessionHeader(sessionId))
88
+ const session = ctx.sessions.prepare(data, { mode: 'create' })
89
+ ctx.sessions.get(sessionId) // the live session
90
+ ctx.sessions.list() // every live session, in creation order
91
+ ```
92
+
93
+ <a id="interface-and-class-names"></a>
94
+
95
+ ### Interface and class names
96
+
97
+ `ctx.sessions` and its methods return `interface Session`, which [`@deepseek-ai/dsh-session`](../session/README.md) declares, and the functions of this package that accept a Session take that interface. `Session.fromData(data, options)` returns the class this package exports under the same name. The class has private members, so TypeScript accepts it where the interface is required and rejects the interface where the class is required. A file that uses both names imports them under different local names:
98
+
99
+ ```ts
100
+ import { Session } from '@deepseek-ai/dsh-session-store'
101
+ import type { Session as SessionInterface } from '@deepseek-ai/dsh-session'
102
+ import type { SessionData } from '@deepseek-ai/dsh-session-data'
103
+
104
+ export function detached(data: SessionData): SessionInterface {
105
+ return Session.fromData(data, { mode: 'create' })
106
+ }
107
+ ```
108
+
109
+ <a id="validate-a-log"></a>
110
+
111
+ ### Validate a log
112
+
113
+ `validateSessionLog(header, events?, inheritedEventCount?, eventState?, projections?)` runs every check that constructing a Session performs, in the same two-phase order and with the same errors as that construction, without constructing one. Without `eventState` it checks borrowed seed values that were copied before validation; with `detached` or `shared-frozen` it validates and deeply freezes the adopted header in place and leaves events uncopied. The Session identity comes from `header.id`, and no in-memory inherited marker is appended. `checkSessionLog` in `dsh-session` runs the header, event-envelope, sequence, and inherited-cut checks; surface replay runs afterwards, when the Session is constructed or inside `validateSessionLog`, so a log that is invalid in several places can report a different first error than an interleaved per-event check.
114
+
115
+ <a id="append-and-derive"></a>
116
+
117
+ ### Append and derive
118
+
119
+ `session.append(type, data, opts?)` commits one typed event. It rejects read-only instances before reading payload fields, snapshots and freezes valid JSON, then rechecks write permission before committing and notifying observers. `session.deriveMessages()` projects the log into the `Message[]` the model sees, incrementally and cached:
120
+
121
+ ```text
122
+ session.append('user/message', { role: 'user', content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
123
+ { surfaceOp: 'append' })
124
+ session.deriveMessages() // the derived model history
125
+ ```
126
+
127
+ Plugins declare content-changing events with `@messageProjection` and register a pure definition through `ctx.sessions.registerMessageProjection()`. Session calls the definition before accepting an event and caches its immutable message updates. Missing definitions reject append and restore; unloading a used definition also blocks cached reads. `Session.fromData(data, { projections })` and `foldSurface(events, projections)` require explicit definitions; `ctx.sessions.prepare` uses the registered set. Reconstructors pass the fold's `projectedMessages` to `deriveEventMessage()`; live instance methods apply the same projections automatically. [Plugin-owned message projections](../../../.agents/notes/implemented/architecture/2026-09-11-plugin-owned-message-projections.md) defines ownership and offline assembly.
128
+
129
+ The [log format](../session/README.md#event-types-and-the-log-format) defines the `surfaceOp` and `sourceEventSeqs` that each event type requires, and an append that breaks it throws. Rejected appends do not change the log, derived state, or event feed.
130
+
131
+ ### Read the log
132
+
133
+ `session.seq` reads the current log length without materializing an array, and `session.eventAt(seq)` reads one accepted, deeply frozen event by sequence number. `session.snapshotEvents(fromSeq?, toSeqExclusive?)` materializes a frozen, stable snapshot of a half-open range; a complete current snapshot is cached until the next append. `eventAt()`, `snapshotEvents()`, and `ownEvents()` are deprecated: existing logic may remain unmigrated for now, but new production calls are prohibited. Repository test files may use these three readers under their scoped lint allowance ([policy](../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md)). Callers that only need a length use `seq`.
134
+
135
+ <a id="write-experimental-plugin-records"></a>
136
+
137
+ ### Write experimental plugin records
138
+
139
+ `appendPluginRecord(session, type, data)` appends one plugin record for a package under `packages/experimental/`; the `verify-plugin-record-callers` check rejects any other production caller in this repository. Plugins outside this repository must not call it either, although no repository check can inspect them.
140
+
141
+ Declare each record in `PluginRecordMap` through `@deepseek-ai/dsh-session/types`, with a description and an explicit payload type annotation in the owning experimental package's `src/`. Names use `plugin:<owner>/<record>`, where `owner` is the package name after removing the legacy `@deepseek-ai/dsh-experimental-` prefix when present, otherwise `@deepseek-ai/dsh-`; for example, `plugin:pi-extensions/entry`. TypeScript checks each name and payload against its declaration; the writer's runtime JSON snapshot rejects values that cannot be preserved losslessly. Put extension-defined or other dynamic names inside the payload of a declared record.
142
+
143
+ The [experimental persistence catalog](../../../docs/experimental-persistence-catalog.md) lists current plugin-record declarations with their owners, descriptions, payload type annotations, and source files. These declarations remain separate from `SessionEventMap`, expanded persistence schemas, released type history, and `KNOWN_SESSION_EVENT_TYPES`. Records carry `ignorable: true`: a build that does not recognize one retains and skips it on read. Records never enter the model-visible surface. Resume and fork carry them with the rest of the log; Session format migration keeps them on a best-effort basis.
144
+
145
+ `pluginRecordOf(event)` returns an event as a record, or `undefined` for any other event; a `ctx.sessionProjections` unit that passes each event to it rebuilds plugin state on resume. Its `data` remains `unknown` even when the current map declares the name. The owner validates it before use because earlier builds can write different payloads, and the V3-to-V4 format edge can rename an unknown ignorable V3 event into the same `plugin:` namespace. Removing or renaming a declaration does not discard stored records. The [ignorable events decision](../../../.agents/notes/implemented/architecture/2026-08-30-retain-ignorable-external-session-events.md) owns the compatibility policy.
146
+
147
+ <a id="fork-a-session"></a>
148
+
149
+ ### Fork a session
150
+
151
+ `data.fork(childId, { at, meta? })` on writable or read-only Session data creates writable child data through that data context's `sessionData` service. `at` is the required inclusive source event seq: the child inherits `[0..at]`, receives the tagged inherited marker, and closes an open tail with forked tool results and step/turn closers. Read-only data bounds the shared parent prefix by `persistedEventCount` when that is smaller.
152
+
153
+ Hand the child to `ctx.agents.createFromData(child, options)` or publish it through `ctx.sessions.prepare(child, { mode: 'create' })`, `await child.flush()`, `enter`, and `announce`; the caller owns the data and closes it after teardown. A rejected boundary throws `SessionForkError` with code `INVALID_BOUNDARY` from `@deepseek-ai/dsh-session`; array data without a service rejects with `SESSION_DATA_SERVICE_UNAVAILABLE`.
154
+
155
+ `SessionHeader.isSeeded` reports whether fork history exists without exposing a positional integer. `Session.inheritedEventCount` retains the exact checked `SessionLogOffset`; `ownEvents()` returns events at and after that cut, and `isOwnSeq(seq)` accepts only an existing child-owned position.
156
+
157
+ `session.append(type, data, ...opts)` appends one event and returns that event. `session.append(inputs)` accepts a readonly array of positional `[type, data, ...opts]` tuples (`SessionEventInput`) and returns the committed events in input order; an empty array appends nothing. Array admission validates every candidate and synchronous dispatch before changing the log or message surface, so observers read the complete committed group. Persistence listeners retain their own durability rules; array admission alone does not guarantee crash-atomic storage.
158
+
159
+ ### Flush durable state
160
+
161
+ `ctx.sessions.flush(session)` dispatches the awaited durability checkpoint: every persistence listener flushes and the call settles after all of them. A producer that needs an immediate durability barrier awaits it instead of assuming the write-behind drained.
162
+
163
+ -----
164
+
165
+ <a id="understand-the-implementation"></a>
166
+ ## Understand the implementation
167
+
168
+ <details>
169
+ <summary>Implementation internals — click to expand</summary>
170
+
171
+ This section explains how the package realizes the behavior above; the observable contract is covered in [Use this package](#use-this-package).
172
+
173
+ ### Design concept
174
+
175
+ The package is built on event sourcing: a `Session` is an append-only log of typed `SessionEvent`s, and everything else — model history, transcripts, telemetry, titles, persistence — derives from that stream. The surface is a derived projection: an incremental manager validates append candidates, advances the ordered view from committed events, and tracks `replaceGeneration` for positional replacements and `contentGeneration` for replacements and plugin-owned message changes. Model-visible means logged: anything that reaches a model request must be reconstructable from the log.
176
+
177
+ ### Source map
178
+
179
+ | File | Role |
180
+ |---|---|
181
+ | [`src/index.ts`](src/index.ts) | Plugin entry: `SessionStore` service, Session construction lifecycle, and `flush` |
182
+ | [`src/surface.ts`](src/surface.ts) | Ordered surface projection, replacement validation, `foldSurface` |
183
+ | [`src/validation.ts`](src/validation.ts) | `validateSessionLog`: the checks of Session construction without a Session |
184
+ | [`src/request-header.ts`](src/request-header.ts) | `request/header` folding and reconstruction |
185
+ | [`src/tool-history.ts`](src/tool-history.ts) | Tool definitions and updates reconstructed from request headers and developer messages |
186
+ | [`src/preparation.ts`](src/preparation.ts) | `SessionPreparation`: ownership of one unpublished Session |
187
+ | [`dsh-session`](../session/README.md) | Event types, the `Session` and `SessionStore` interfaces, validators, fork seed, and repair |
188
+ | [`dsh-util-values`](../../util/values/README.md) | Shared lossless JSON validation and detached snapshots |
189
+
190
+ ### Append validation
191
+
192
+ Every append uses the shared iterative `snapshotJsonValue()` pass, which reads, validates, and copies each nested value once, so a stateful getter cannot supply one value to validation and another to storage. Non-lossless-JSON payloads (BigInt, cycles, sparse arrays, `-0`, exotic prototypes) are rejected at the append site, before any backend flush. The append path constructs each `SessionSeq`; surface events additionally validate marker shape, cited source-event sequences, and complete shadowed-node coverage for replacements.
193
+
194
+ <a id="derived-history"></a>
195
+
196
+ ### Derived history
197
+
198
+ `deriveMessages()` caches deep-frozen projections and returns a fresh array per call. Plugin-owned projections change derived content without mutating recorded messages. Replacements and projection decisions invalidate the cache. [`deriveEventMessage`](../session/README.md#derived-history) in `@deepseek-ai/dsh-session` defines the message that each event derives to.
199
+
200
+ `surface.systemNodes` exposes current system sequences and whether their logged content arrays are empty, in surface order. Each read scans the current surface nodes, so the list reflects actual replaced positions; citations outside a replaced range do not remove nodes.
201
+
202
+ <a id="the-request-header"></a>
203
+
204
+ ### The request header
205
+
206
+ The loop logs a full canonical `request/header` snapshot (call config, adapter defaults, assembled tool schemas — the rendered system prompt is a `system/message` surface node, not header state) at each loop-instance boundary and on change; `requestHeaderStateDefinition.apply` reconstructs it by selecting the latest snapshot, `session.requestHeader()` returns that state incrementally, and every conversation request is a pure function of the log. Route metadata (`request/context`) is separate logged state appended only when the provider, model, capacity, or `systemPromptUpdate` mode differs; it records the actual prepared call's mode after prompt and user admission, rather than supplying that admission decision.
207
+
208
+ </details>
209
+
210
+ -----
211
+
212
+ <a id="further-exploration"></a>
213
+ ## Further Exploration
214
+
215
+ The package-level contract is enough for most consumers; read these when you need the surrounding domain.
216
+
217
+ - [Session definitions](../session/README.md) — the event types, log format rules, validators, and interfaces that this plugin implements.
218
+ - [Session subsystem](../../../docs/subsystems/session.md) — the full event vocabulary, surface types, and generated service API.
219
+ - [Persistence subsystem](../../../docs/subsystems/persistence.md) — how backends make this log durable.
220
+ - [Core subsystem](../../../docs/subsystems/core.md) — the loop that writes and derives from sessions.
221
+ - [Core group map](../README.md) — how the core packages compose.
222
+ - [Session definitions and the Session Store are separate packages](../../../.agents/notes/implemented/architecture/2026-12-01-session-definitions-and-session-store.md) — which export lives in which package, and why.
223
+
224
+ -----
225
+
226
+ <a id="model-experience"></a>
227
+ ## Model Experience
228
+
229
+ ### Derived message history
230
+
231
+ #### What the model sees
232
+
233
+ The model receives the complete messages from `system/message`, `developer/message`, `user/message`, `assistant/message`, and `tool/result` surface entries with logged projections applied, the system prompt first. Identities, roles, sources, and unmodified blocks retain their original values; projections never mint identities. Direct prompts and injected context remain separate `user/message` events whose sources preserve their attribution. Embedded streams, `assistant/attempt`, boundaries, and other log-only facts add no message.
234
+
235
+ #### Token effect
236
+
237
+ Appended surface entries are resent on later steps. A `replace` surface operation removes the shadowed entries from future inputs without deleting their raw log records.
238
+
239
+ #### KV Cache effect
240
+
241
+ Appended surface entries preserve reusable prefixes. A `replace` operation invalidates reuse from the first shadowed message even though the underlying event log stays append-only.
242
+
243
+ ### Logged request header
244
+
245
+ #### What the model sees
246
+
247
+ The session reconstructs active tool schemas and call config from request headers; provider-specific deferred and retained declarations are derived at dispatch. `toolHistory()` reads a pure state definition that the Session's data evaluates over committed headers and developer messages, applying only appended events after the first read. It resolves additions through their historical `headerSeq`, returns immutable snapshots, and restarts declarations on an explicit request series or a changed retained definition. Restoring a retained name with an unchanged definition continues the series; the recorded addition re-offers it. Both loop requests and compaction calls use this state. Headers lacking matching update records use complete active declarations. Same-name schema changes are allowed and invalidate prefix reuse even on `in-history` routes; registration-time rejection against historical tools is deferred ([rationale](../../../.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.md)). The system prompt remains part of `deriveMessages()`; header events add no message or prompt copy.
248
+
249
+ #### Token effect
250
+
251
+ Zero duplicate tokens from logging. The system nodes and schemas still incur their normal per-request cost.
252
+
253
+ #### KV Cache effect
254
+
255
+ Logging causes no invalidation, and exact reconstruction preserves request-prefix identity. A later header with changed config or schemas may invalidate reuse from its first difference; a prompt change that replaces surface node 0 invalidates reuse from the first token, while an in-history append keeps the prefix through the cached history reusable.
256
+
257
+ ## Known Limitations and Deferred Work
258
+
259
+ <a id="known-limitations-and-deferred-work"></a>
260
+
261
+ These limits define when the session store needs special care. They are current package constraints, not a task backlog.
262
+
263
+ - **Fork through Session data** — forks use `data.fork(childId, { at, meta? })` on a live Session's view or read-only data and therefore require a mounted `sessionData` service. Fork closes only the open tail; it does not repair missing results in previously closed steps.
264
+ - **No session tree beyond fork** — a pi-style entry tree over branched sessions is deferred unless a consumer needs more than boundary-based forking.
265
+ - **`appendPluginRecord` requires this package's class** — its parameter type is `interface Session`, but it commits through a private method of the class without a run-time type check, so an object that only implements the interface fails with a `TypeError`.
266
+
267
+ <a id="dev-note"></a>
268
+ ### Dev Note
269
+
270
+ <details>
271
+ <summary>Working context for maintainers — click to expand</summary>
272
+
273
+ None.
274
+
275
+ </details>