@deepseek-ai/dsh-session-data 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,52 @@
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-data/README.md
5
+ /:
6
+ en: f39f447d6683d739
7
+ zh: 7f6ae03d5d86eccb
8
+ /deepseek-ai-dsh-session-data:
9
+ en: 3344ef712511fd48
10
+ zh: 3abfdcb6b3823edc
11
+ /deepseek-ai-dsh-session-data/summary:
12
+ en: 4d2037ae23aebf2e
13
+ zh: da08aa25af96708f
14
+ /deepseek-ai-dsh-session-data/table-of-contents:
15
+ en: 80b31a934611cb4a
16
+ zh: 05f3f7f9cb2fd881
17
+ /deepseek-ai-dsh-session-data/use-this-package:
18
+ en: bbff250eba0f1b89
19
+ zh: 0a618f05cc88ee2b
20
+ /deepseek-ai-dsh-session-data/use-this-package/when-to-use-it:
21
+ en: f8c50618b885f3e3
22
+ zh: 24417e5e276ad9a6
23
+ /deepseek-ai-dsh-session-data/use-this-package/entry-point:
24
+ en: 53990f62bc1b94c5
25
+ zh: c936e127b4bea4d4
26
+ /deepseek-ai-dsh-session-data/use-this-package/read-only-and-writable-data:
27
+ en: fb62b8553daa8ce6
28
+ zh: 929c500bfdf78107
29
+ /deepseek-ai-dsh-session-data/use-this-package/evaluate-state-by-definition:
30
+ en: 515c4e7d443b2780
31
+ zh: f1f2f020613df8e1
32
+ /deepseek-ai-dsh-session-data/use-this-package/fork-child-data:
33
+ en: c1d56b09fcbab41c
34
+ zh: d9a7ecc283565979
35
+ /deepseek-ai-dsh-session-data/use-this-package/errors:
36
+ en: a8fd01358b3fcac0
37
+ zh: c065595ec831ca36
38
+ /deepseek-ai-dsh-session-data/use-this-package/module-augmentation:
39
+ en: 8b2f51c0ea9ccad3
40
+ zh: cc20f2982c0114a9
41
+ /deepseek-ai-dsh-session-data/understand-the-implementation:
42
+ en: 267f0619f21be6d7
43
+ zh: 3276d40ae8d2db4b
44
+ /deepseek-ai-dsh-session-data/further-exploration:
45
+ en: b7a017f607da99f5
46
+ zh: 4122202138816372
47
+ /deepseek-ai-dsh-session-data/known-limitations-and-deferred-work:
48
+ en: 08eff4636b849b5b
49
+ zh: 9bab93e1be86cb8a
50
+ /deepseek-ai-dsh-session-data/dev-note:
51
+ en: 5de1d6304e00c58f
52
+ zh: 3fee785f424f1018
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "Session data layer for package authors: the read-only and writable views of one Session's header, inherited cut, and event log, incremental state evaluation over that log, fork at an inclusive event, and the abstract ctx.sessionData service that creates and opens the data."
3
+ kind: "package-library"
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-data
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ `dsh-session-data` defines what a Session is built from: `ReadonlySessionData` and `SessionData` carry one Session's header, inherited cut, and event log, plus the write handle that stores appended events. Any data evaluates a state definition over its own log incrementally and forks child data at an inclusive event. `SessionDataService` is the abstract `ctx.sessionData` service whose provider creates and opens data. The package is a library with no plugin row; it also augments the `Session` and `SessionStore` interfaces with `readonlyView`, `prepare`, and `create`.
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
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
20
+ - [Dev Note](#dev-note)
21
+
22
+ -----
23
+
24
+ <a id="use-this-package"></a>
25
+ ## Use this package
26
+
27
+ ### When to use it
28
+
29
+ Reach for this package when code implements Session storage or reads Session data directly. The [Session Store](../session-store/README.md) builds its `Session` and `SessionStore` on it, AgentLoop creates and resumes Sessions through `ctx.sessionData`, Session Query observes cold sessions through read-only data, and the Session Controller forks through `SessionData.fork`. Applications mount a provider plugin such as [`dsh-session-data-persisted`](../../session/session-data-persisted/README.md); this package itself registers nothing.
30
+
31
+ ### Entry point
32
+
33
+ ```ts
34
+ import { ArraySessionData, SessionDataService, SESSION_DATA_READONLY } from '@deepseek-ai/dsh-session-data'
35
+ import type { ReadonlySessionData, SessionData, SessionStateDefinition } from '@deepseek-ai/dsh-session-data'
36
+ ```
37
+
38
+ `ctx.sessionData.create(id, meta?, options?)` builds and validates a new Session's header and seed; `create(header, options?)` accepts a complete header instead and returns writable `SessionData` that no Session has been built from yet. `ctx.sessionData.open(id, { mode: 'write' })` returns writable data for a stored Session resumed for writing; `open(id, { mode: 'read' })` returns a `ReadonlySessionData` snapshot whose `persistedEventCount` counts only stored events.
39
+
40
+ ### Read-only and writable data
41
+
42
+ `ReadonlySessionData` exposes `header`, `inheritedEventCount`, `seq`, `isEmpty`, the optional `persistedEventCount`, `readEvents(from?, to?)`, `eventAt(seq)`, `snapshotEvents(from?, to?)`, `evaluateState(definition)`, and `fork(childId, options)`. `eventAt` and `snapshotEvents` are synchronous transitional reads; new code uses `readEvents`. `SessionData` adds `append(events)`, `flush()`, `close()`, and `readonlyView()`, and owns its write handle until `close()`; a read-only instance rejects `append` with `HarnessError` code `SESSION_DATA_READONLY`. A writable instance returns one cached forwarding read-only view from `readonlyView()`, a read-only instance returns itself, and views stay readable after the data closes; `Session.readonlyView()`, added by module augmentation, returns that same view.
43
+
44
+ <a id="evaluate-state-by-definition"></a>
45
+
46
+ ### Evaluate state by definition
47
+
48
+ A `SessionStateDefinition` is a key, the state of the empty log, and a pure transition. `evaluateState(definition)` returns the state at the current log end: the first call for a definition object starts from `definition.init(header, inheritedEventCount)` and applies every committed event in order; later calls with the same object apply only the events appended since. Each data object keeps its own folds, keyed by the definition object, and a view shares its source's folds.
49
+
50
+ ```ts
51
+ import type { ReadonlySessionData, SessionStateDefinition } from '@deepseek-ai/dsh-session-data'
52
+
53
+ declare const session: { readonlyView(): ReadonlySessionData }
54
+
55
+ const countTurns: SessionStateDefinition<'turnCount', number> = {
56
+ key: 'turnCount',
57
+ init: () => 0,
58
+ apply: (count, event) => event.type === 'turn/start' ? count + 1 : count,
59
+ }
60
+
61
+ const turns: number = session.readonlyView().evaluateState(countTurns)
62
+ ```
63
+
64
+ The definer owns the definition and passes the same object on every read. `apply` should return `state` itself for events that do not change it. The returned state is shared by reference and is not frozen; do not mutate it. No registration is involved: the Session Store owns `requestHeaderStateDefinition` and `requestContextStateDefinition`, the first two definitions, and its `Session.requestHeader()` and `Session.requestContext()` evaluate them over the Session's data.
65
+
66
+ ### Fork child data
67
+
68
+ `fork(childId, { at, meta? })` creates writable child data through the `sessionData` service of the data's context. The child log inherits events `[0..at]`, marks the inherited cut, and closes a turn left open at `at` with forked results; the backend receives the complete child log at creation. The child header inherits the source `cwd` unless `meta.cwd` overrides it; other header fields come only from `meta`. For read-only data the shared parent prefix ends at `persistedEventCount` when that is smaller than `at + 1`. Hand the child to `ctx.agents.createFromData(child, { mode: 'create', ... })`.
69
+
70
+ ### Errors
71
+
72
+ | Code | Raised when |
73
+ |---|---|
74
+ | `SESSION_DATA_CORRUPT` | A read open finds a stored log that fails Session validation; `cause` carries the validation error |
75
+ | `SESSION_DATA_READONLY` | `append` is called on read-only data |
76
+ | `SESSION_DATA_SERVICE_UNAVAILABLE` | Array data rejects `fork`, or provider data cannot reach a `sessionData` service in its context |
77
+
78
+ A stored Session that is absent, or a missing persistence backend, surfaces `SessionPersistenceNotFoundError` from `dsh-session-persistence` through the provider. Forking at an event the data does not contain raises `SessionForkError` with code `INVALID_BOUNDARY` from `dsh-session`.
79
+
80
+ ### Module augmentation
81
+
82
+ Loading the package root augments the definitions that `dsh-session` declares: `Session.readonlyView(): ReadonlySessionData` and `SessionStore.prepare(data, options): Session`. `prepare` constructs synchronously without taking ownership, flushing, entering, or announcing; its caller flushes the data and runs the lifecycle. It takes the shared `SessionConstructionOptions` `{ mode: 'create' | 'restore' }`. `Session.fromData(data, options)` is the static class constructor over the same data and mode. A program that calls these members must import this package and declare the dependency; importing only types from `dsh-session` does not expose them.
83
+
84
+ <a id="understand-the-implementation"></a>
85
+ ## Understand the implementation
86
+
87
+ <details>
88
+ <summary>Implementation internals — click to expand</summary>
89
+
90
+ | File | Role |
91
+ |---|---|
92
+ | [`src/data.ts`](src/data.ts) | Data interfaces, `SessionStateDefinition`, `SessionDataService`, `Context.sessionData`, error codes, and `buildForkCreation` |
93
+ | [`src/data-array.ts`](src/data-array.ts) | `ReadonlyArraySessionData`, `ArraySessionData`, the forwarding read-only view, incremental state evaluation, and `appendInheritedSeedMarker` |
94
+ | [`src/augment.ts`](src/augment.ts) | The module augmentation of `Session` and `SessionStore` |
95
+
96
+ `ReadonlyArraySessionData` holds all array behavior; the `writable` flag alone separates it from `SessionData`'s array implementation `ArraySessionData`. `evaluateState` reads a `WeakMap` from definition object to the last state and the number of events it reflects, then applies the definition to each later event in order. The data of a `Session` keeps its own event array beside the surface log the class already holds; every append commits to both. `buildForkCreation` computes the seeded child header, `buildForkSeed` log, and parent source bounds that a provider's `fork` passes to `create`.
97
+
98
+ </details>
99
+
100
+ -----
101
+
102
+ <a id="further-exploration"></a>
103
+ ## Further Exploration
104
+
105
+ - [`dsh-session`](../session/README.md) — the event, header, and interface definitions the data carries.
106
+ - [`dsh-session-store`](../session-store/README.md) — `Session` and `ctx.sessions`, built on this data, and the two kernel state definitions.
107
+ - [`dsh-session-data-persisted`](../../session/session-data-persisted/README.md) — the provider that stores events through the mounted persistence backend.
108
+ - [Sessions subsystem](../../../docs/subsystems/session.md#session-data) — the data section of the Session reference.
109
+
110
+ -----
111
+
112
+ <a id="known-limitations-and-deferred-work"></a>
113
+ ## Known Limitations and Deferred Work
114
+
115
+ - **Evaluation is the interim main read.** Definitions are evaluated by the data that holds them; there is no registration, no read by key, and no snapshot of several states. Registered definitions read by key arrive with the projection-registry integration.
116
+ - **A fold belongs to one data object.** New data over the same log starts from `init` again; only the read-only view of the same data shares its folds.
117
+ - **Returned states are not frozen.** `evaluateState` returns the state by reference, and freezing is left to the reader that exposes it; `Session.requestHeader()` and `Session.requestContext()` deep-freeze each new state. Deep-freezing every intermediate state would cost more than most definitions need.
118
+ - **Array data cannot fork or open.** `fork` on array data rejects with `SESSION_DATA_SERVICE_UNAVAILABLE`; opening stored data is the provider's job.
119
+
120
+ <a id="dev-note"></a>
121
+ ## Dev Note
122
+
123
+ <details>
124
+ <summary>Working context for maintainers — click to expand</summary>
125
+
126
+ None.
127
+
128
+ </details>
package/README.zh.md ADDED
@@ -0,0 +1,128 @@
1
+ ---
2
+ description: "面向包作者的会话数据层:单个 Session 的头部、继承切点与事件日志的只读视图和可写视图,在该日志上的增量状态求值,在包含端点的事件处 fork,以及创建、打开这些数据的抽象 ctx.sessionData 服务。"
3
+ kind: "package-library"
4
+ ---
5
+
6
+ # @deepseek-ai/dsh-session-data
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ `dsh-session-data` 定义构建一个 Session 所需的材料:`ReadonlySessionData` 与 `SessionData` 承载单个 Session 的头部、继承切点与事件日志,以及存储已追加事件的写句柄。任何数据都能在自己的日志上增量求值一个状态定义,并在包含端点的事件处 fork 子数据。`SessionDataService` 是抽象的 `ctx.sessionData` 服务,由 provider 创建和打开数据。本包是库,没有插件行;它还通过模块增强为 `Session` 与 `SessionStore` 接口贡献 `readonlyView`、`prepare` 与 `create`。
13
+
14
+ ## 目录
15
+
16
+ - [使用本包](#use-this-package)
17
+ - [理解实现](#understand-the-implementation)
18
+ - [进一步探索](#further-exploration)
19
+ - [已知限制与延期工作](#known-limitations-and-deferred-work)
20
+ - [开发备注](#dev-note)
21
+
22
+ -----
23
+
24
+ <a id="use-this-package"></a>
25
+ ## 使用本包
26
+
27
+ ### 何时使用
28
+
29
+ 实现 Session 存储或直接读取 Session 数据的代码使用本包。[Session Store](../session-store/README.zh.md) 在它之上构建 `Session` 与 `SessionStore`,AgentLoop 经 `ctx.sessionData` 创建与恢复 Session,Session Query 经只读数据观察冷会话,Session Controller 经 `SessionData.fork` 执行 fork。应用挂载 [`dsh-session-data-persisted`](../../session/session-data-persisted/README.zh.md) 这类 provider 插件;本包自身不登记任何东西。
30
+
31
+ ### 入口
32
+
33
+ ```ts
34
+ import { ArraySessionData, SessionDataService, SESSION_DATA_READONLY } from '@deepseek-ai/dsh-session-data'
35
+ import type { ReadonlySessionData, SessionData, SessionStateDefinition } from '@deepseek-ai/dsh-session-data'
36
+ ```
37
+
38
+ `ctx.sessionData.create(id, meta?, options?)` 从 id 与 metadata 构建并校验新 Session 的头部与 seed;`create(header, options?)` 接受完整头部,返回尚未构建任何 Session 的可写 `SessionData`。`ctx.sessionData.open(id, { mode: 'write' })` 对以写入方式恢复的已存储 Session 返回可写数据;`open(id, { mode: 'read' })` 返回 `ReadonlySessionData` 快照,其 `persistedEventCount` 只统计已存储事件。
39
+
40
+ ### 只读数据与可写数据
41
+
42
+ `ReadonlySessionData` 暴露 `header`、`inheritedEventCount`、`seq`、`isEmpty`、可选的 `persistedEventCount`、`readEvents(from?, to?)`、`eventAt(seq)`、`snapshotEvents(from?, to?)`、`evaluateState(definition)` 与 `fork(childId, options)`。`eventAt` 与 `snapshotEvents` 是同步过渡读法,新代码使用 `readEvents`。`SessionData` 增加 `append(events)`、`flush()`、`close()` 与 `readonlyView()`,并持有写句柄直到 `close()`;只读实例以 `HarnessError` 错误码 `SESSION_DATA_READONLY` 拒绝 `append`。可写实例从 `readonlyView()` 返回一个缓存的转发只读视图,只读实例返回自身,数据关闭后视图仍可读取;经模块增强的 `Session.readonlyView()` 返回同一个视图。
43
+
44
+ <a id="evaluate-state-by-definition"></a>
45
+
46
+ ### 按定义求值状态
47
+
48
+ `SessionStateDefinition` 由一个 key、空日志的状态与一个纯转移函数组成。`evaluateState(definition)` 返回当前日志末尾的状态:首次对某个定义对象调用时从 `definition.init(header, inheritedEventCount)` 起步并按顺序应用每个已提交事件;之后用同一对象调用时只应用新追加的事件。每个数据对象按定义对象各保存自己的折叠结果,视图共享其来源数据的折叠结果。
49
+
50
+ ```ts
51
+ import type { ReadonlySessionData, SessionStateDefinition } from '@deepseek-ai/dsh-session-data'
52
+
53
+ declare const session: { readonlyView(): ReadonlySessionData }
54
+
55
+ const countTurns: SessionStateDefinition<'turnCount', number> = {
56
+ key: 'turnCount',
57
+ init: () => 0,
58
+ apply: (count, event) => event.type === 'turn/start' ? count + 1 : count,
59
+ }
60
+
61
+ const turns: number = session.readonlyView().evaluateState(countTurns)
62
+ ```
63
+
64
+ 定义归定义者所有,每次读取都传入同一个对象。对不改变状态的事件,`apply` 应返回 `state` 本身。返回的状态按引用共享,且未被冻结;不要修改它。此过程不涉及登记:Session Store 拥有最初的两个定义 `requestHeaderStateDefinition` 与 `requestContextStateDefinition`,它的 `Session.requestHeader()` 与 `Session.requestContext()` 在 Session 的数据上对它们求值。
65
+
66
+ ### fork 子数据
67
+
68
+ `fork(childId, { at, meta? })` 通过数据所在上下文的 `sessionData` 服务创建可写子数据。子日志继承事件 `[0..at]`,标记继承切点,并用 fork 结果关闭在 `at` 处仍未关闭的一轮;后端在创建时收到完整的子日志。子 header 默认继承源 `cwd`,由 `meta.cwd` 覆盖;其他 header 字段只来自 `meta`。对只读数据,当 `persistedEventCount` 小于 `at + 1` 时,共享的父前缀止于 `persistedEventCount`。把子数据交给 `ctx.agents.createFromData(child, { mode: 'create', ... })`。
69
+
70
+ ### 错误
71
+
72
+ | 错误码 | 触发条件 |
73
+ |---|---|
74
+ | `SESSION_DATA_CORRUPT` | 读取打开时发现已存储日志未通过 Session 校验;`cause` 携带校验错误 |
75
+ | `SESSION_DATA_READONLY` | 对只读数据调用 `append` |
76
+ | `SESSION_DATA_SERVICE_UNAVAILABLE` | 数组数据拒绝 `fork`,或 provider 数据在其上下文中无法取得 `sessionData` 服务 |
77
+
78
+ 已存储 Session 不存在或没有挂载持久化后端时,provider 原样传出 `dsh-session-persistence` 的 `SessionPersistenceNotFoundError`。在数据中不存在的事件处 fork 会从 `dsh-session` 抛出错误码为 `INVALID_BOUNDARY` 的 `SessionForkError`。
79
+
80
+ ### 模块增强
81
+
82
+ 加载包根入口会增强 `dsh-session` 声明的定义:`Session.readonlyView(): ReadonlySessionData` 与 `SessionStore.prepare(data, options): Session`。`prepare` 只做同步构造,不接管数据、不刷新、不进入也不公告;调用方负责刷新数据并运行生命周期。它接收共享的 `SessionConstructionOptions` `{ mode: 'create' | 'restore' }`。`Session.fromData(data, options)` 是作用于相同数据与 mode 的类静态构造入口。调用这些成员的程序必须导入本包并声明该依赖;只从 `dsh-session` 导入类型不会暴露它们。
83
+
84
+ <a id="understand-the-implementation"></a>
85
+ ## 理解实现
86
+
87
+ <details>
88
+ <summary>实现内部——点击展开</summary>
89
+
90
+ | 文件 | 职责 |
91
+ |---|---|
92
+ | [`src/data.ts`](src/data.ts) | 数据接口、`SessionStateDefinition`、`SessionDataService`、`Context.sessionData`、错误码,以及 `buildForkCreation` |
93
+ | [`src/data-array.ts`](src/data-array.ts) | `ReadonlyArraySessionData`、`ArraySessionData`、转发的只读视图、增量状态求值,以及 `appendInheritedSeedMarker` |
94
+ | [`src/augment.ts`](src/augment.ts) | 对 `Session` 与 `SessionStore` 的模块增强 |
95
+
96
+ `ReadonlyArraySessionData` 承载全部数组行为;仅凭 `writable` 标志就把它与 `SessionData` 的数组实现 `ArraySessionData` 区分开。`evaluateState` 从一个以定义对象为键的 `WeakMap` 读取上一次的状态及其已反映的事件数,再按顺序对该定义应用之后的每个事件。`Session` 的数据在类本身已持有的 surface 日志之外保留自己的事件数组;每次追加同时提交到两者。`buildForkCreation` 计算带种子的子会话头部、`buildForkSeed` 日志与父来源边界,provider 的 `fork` 把它们交给 `create`。
97
+
98
+ </details>
99
+
100
+ -----
101
+
102
+ <a id="further-exploration"></a>
103
+ ## 进一步探索
104
+
105
+ - [`dsh-session`](../session/README.zh.md) — 数据所承载的事件、头部与接口定义。
106
+ - [`dsh-session-store`](../session-store/README.zh.md) — 构建在这些数据之上的 `Session` 与 `ctx.sessions`,以及两个内核状态定义。
107
+ - [`dsh-session-data-persisted`](../../session/session-data-persisted/README.zh.md) — 通过已挂载的持久化后端存储事件的 provider。
108
+ - [Sessions 子系统](../../../docs/subsystems/session.zh.md#session-data) — Session 参考页中的数据一节。
109
+
110
+ -----
111
+
112
+ <a id="known-limitations-and-deferred-work"></a>
113
+ ## 已知限制与延期工作
114
+
115
+ - **求值是当前的主读法。** 定义由持有数据的数据对象求值;没有登记,没有按 key 读取,也没有多状态快照。按 key 读取已登记定义将随投影注册表接入提供。
116
+ - **一份折叠属于一个数据对象。** 基于同一日志的新数据对象会从 `init` 重新开始;只有同一数据的只读视图共享其折叠结果。
117
+ - **返回的状态未冻结。** `evaluateState` 按引用返回状态,冻结留给将状态暴露出去的读取方;`Session.requestHeader()` 与 `Session.requestContext()` 会深度冻结每个新状态。深度冻结每个中间状态的开销超过大多数定义所需。
118
+ - **数组数据不能 fork,也不能打开存储。** 对数组数据调用 `fork` 以 `SESSION_DATA_SERVICE_UNAVAILABLE` 拒绝;打开已存储数据是 provider 的职责。
119
+
120
+ <a id="dev-note"></a>
121
+ ## 开发备注
122
+
123
+ <details>
124
+ <summary>维护者工作上下文——点击展开</summary>
125
+
126
+ 无。
127
+
128
+ </details>
package/lib/index.js ADDED
@@ -0,0 +1,217 @@
1
+ import { Service } from "@deepseek-ai/cordis";
2
+ import { SessionForkError, SessionLogOffset, SessionSeq, buildForkSeed, buildSessionHeader, needsInheritedSeedMarker } from "@deepseek-ai/dsh-session";
3
+ import { HarnessError } from "@deepseek-ai/dsh-error";
4
+ import { deepFreeze } from "@deepseek-ai/dsh-util-values";
5
+ //#region lib/types/data.js
6
+ /**
7
+ * Session data: one Session's header, inherited cut, and event log, and the
8
+ * service that creates and opens it.
9
+ * @module @deepseek-ai/dsh-session-data
10
+ */
11
+ /** `HarnessError` code with which a read open rejects a stored log that fails Session validation; `cause` is the validation error. */
12
+ const SESSION_DATA_CORRUPT = "SESSION_DATA_CORRUPT";
13
+ /** `HarnessError` code with which read-only Session data rejects `append`. */
14
+ const SESSION_DATA_READONLY = "SESSION_DATA_READONLY";
15
+ /**
16
+ * `HarnessError` code session data rejects a fork with when no `sessionData`
17
+ * service backs it: the core array data, or service-backed data whose context
18
+ * lacks the service.
19
+ */
20
+ const SESSION_DATA_SERVICE_UNAVAILABLE = "SESSION_DATA_SERVICE_UNAVAILABLE";
21
+ /**
22
+ * Compute the child of {@link ReadonlySessionData.fork} from the source data:
23
+ * validate the fork point, build the seeded child header and the child log
24
+ * (`buildForkSeed`), and the parent source whose shared prefix ends at
25
+ * `at + 1`, or at `source.persistedEventCount` when that is smaller. The child
26
+ * inherits `source.header.cwd` unless `options.meta.cwd` overrides it.
27
+ * @param source - fork source data.
28
+ * @param childId - identity of the new child Session.
29
+ * @param options - fork point and child header fields.
30
+ * @returns what the `sessionData` service creates the child from.
31
+ * @throws {@link SessionForkError} with code `INVALID_BOUNDARY` when `at` is not an event of `source`.
32
+ */
33
+ function buildForkCreation(source, childId, options) {
34
+ const { at, meta } = options;
35
+ const events = source.snapshotEvents();
36
+ if (at >= events.length) throw new SessionForkError(`fork boundary ${at} does not exist in session "${source.header.id}" (last seq: ${events.at(-1)?.seq ?? "none"})`, "INVALID_BOUNDARY");
37
+ if (events[at]?.seq !== at) throw new SessionForkError(`fork boundary ${at} does not match a contiguous event seq in session "${source.header.id}"`, "INVALID_BOUNDARY");
38
+ const endSeq = SessionLogOffset(Math.min(at + 1, source.persistedEventCount ?? at + 1));
39
+ return {
40
+ header: buildSessionHeader(childId, {
41
+ ...source.header.cwd === void 0 ? {} : { cwd: source.header.cwd },
42
+ ...meta,
43
+ isSeeded: true
44
+ }),
45
+ options: {
46
+ seed: buildForkSeed(events, at),
47
+ inheritedEventCount: SessionLogOffset(at + 1),
48
+ parentSource: {
49
+ sessionId: source.header.id,
50
+ endSeq
51
+ }
52
+ }
53
+ };
54
+ }
55
+ /** Service (`ctx.sessionData`) that creates and opens {@link SessionData}. */
56
+ var SessionDataService = class extends Service {
57
+ constructor(ctx) {
58
+ super(ctx, "sessionData");
59
+ }
60
+ create(headerOrId, metaOrOptions, options) {
61
+ if (typeof headerOrId === "string") return this.createData(buildSessionHeader(headerOrId, metaOrOptions), options ?? {});
62
+ return this.createData(headerOrId, metaOrOptions ?? {});
63
+ }
64
+ };
65
+ //#endregion
66
+ //#region lib/types/data-array.js
67
+ /**
68
+ * Array-backed Session data and its read-only forwarding view.
69
+ * @module @deepseek-ai/dsh-session-data/data-array
70
+ */
71
+ /**
72
+ * Array-backed Session data holding all array behavior. The `writable` flag
73
+ * alone separates read-only instances (this class) from {@link ArraySessionData}.
74
+ * `flush` and `close` do nothing.
75
+ */
76
+ var ReadonlyArraySessionData = class {
77
+ header;
78
+ inheritedEventCount;
79
+ /** Accepted events; `append` grows them only on writable instances. */
80
+ events;
81
+ /** Cached immutable full snapshot, reused until the next append. */
82
+ eventsSnapshot;
83
+ view;
84
+ /** Incremental state evaluations by definition object: the state and how many events it reflects. */
85
+ folds = /* @__PURE__ */ new WeakMap();
86
+ /**
87
+ * @param log - log from `checkSessionLog`; the data takes ownership of `log.events`.
88
+ */
89
+ constructor(log) {
90
+ this.header = log.header;
91
+ this.inheritedEventCount = log.inheritedEventCount;
92
+ this.events = log.events;
93
+ }
94
+ get seq() {
95
+ return SessionLogOffset(this.events.length);
96
+ }
97
+ get isEmpty() {
98
+ return this.events.length === 0;
99
+ }
100
+ eventAt(seq) {
101
+ return this.events[seq];
102
+ }
103
+ snapshotEvents(fromSeq = SessionLogOffset(0), toSeqExclusive = this.seq) {
104
+ if (fromSeq === 0 && toSeqExclusive === this.events.length) {
105
+ this.eventsSnapshot ??= Object.freeze([...this.events]);
106
+ return this.eventsSnapshot;
107
+ }
108
+ return Object.freeze(this.events.slice(fromSeq, toSeqExclusive));
109
+ }
110
+ readEvents(fromSeq = SessionLogOffset(0), toSeqExclusive = this.seq) {
111
+ return Promise.resolve(this.snapshotEvents(fromSeq, toSeqExclusive));
112
+ }
113
+ /**
114
+ * Return this data's read-only view: a read-only instance itself, otherwise one cached forwarding view.
115
+ * @returns the same object on every call.
116
+ */
117
+ readonlyView() {
118
+ if (!this.writable) return this;
119
+ return this.view ??= new ReadonlySessionDataView(this);
120
+ }
121
+ evaluateState(definition) {
122
+ const fold = this.folds.get(definition) ?? {
123
+ state: definition.init(this.header, this.inheritedEventCount),
124
+ seq: 0
125
+ };
126
+ let state = fold.state;
127
+ for (let seq = fold.seq; seq < this.events.length; seq++) state = definition.apply(state, this.events[seq]);
128
+ this.folds.set(definition, {
129
+ state,
130
+ seq: this.events.length
131
+ });
132
+ return state;
133
+ }
134
+ fork(_childId, _options) {
135
+ return Promise.reject(new HarnessError(`session "${this.header.id}" data is not backed by a session data service; forking is unavailable`, SESSION_DATA_SERVICE_UNAVAILABLE));
136
+ }
137
+ /** Whether this instance accepts `append`; writable subclasses override it to return true. */
138
+ get writable() {
139
+ return false;
140
+ }
141
+ /**
142
+ * Add committed events to the in-memory log; see {@link SessionData.append}.
143
+ * @param events - validated, deeply frozen events at the next sequence numbers.
144
+ * @throws `HarnessError` with code {@link SESSION_DATA_READONLY} on a read-only instance.
145
+ */
146
+ append(events) {
147
+ if (!this.writable) throw new HarnessError(`session "${this.header.id}" data is read-only`, SESSION_DATA_READONLY);
148
+ for (const event of events) this.events.push(event);
149
+ this.eventsSnapshot = void 0;
150
+ }
151
+ /** Do nothing: array data owns no write handle; see {@link SessionData.flush}. */
152
+ flush() {
153
+ return Promise.resolve();
154
+ }
155
+ /** Do nothing: array data owns no write handle; see {@link SessionData.close}. */
156
+ close() {
157
+ return Promise.resolve();
158
+ }
159
+ };
160
+ /** View that forwards every read to its source data. */
161
+ var ReadonlySessionDataView = class {
162
+ source;
163
+ constructor(source) {
164
+ this.source = source;
165
+ }
166
+ get header() {
167
+ return this.source.header;
168
+ }
169
+ get inheritedEventCount() {
170
+ return this.source.inheritedEventCount;
171
+ }
172
+ get seq() {
173
+ return this.source.seq;
174
+ }
175
+ get isEmpty() {
176
+ return this.source.isEmpty;
177
+ }
178
+ readEvents(fromSeq, toSeqExclusive) {
179
+ return this.source.readEvents(fromSeq, toSeqExclusive);
180
+ }
181
+ eventAt(seq) {
182
+ return this.source.eventAt(seq);
183
+ }
184
+ snapshotEvents(fromSeq, toSeqExclusive) {
185
+ return this.source.snapshotEvents(fromSeq, toSeqExclusive);
186
+ }
187
+ evaluateState(definition) {
188
+ return this.source.evaluateState(definition);
189
+ }
190
+ fork(childId, options) {
191
+ return this.source.fork(childId, options);
192
+ }
193
+ };
194
+ /** Writable array-backed {@link SessionData} without a write handle: {@link ReadonlyArraySessionData} with its `writable` flag set. */
195
+ var ArraySessionData = class extends ReadonlyArraySessionData {
196
+ get writable() {
197
+ return true;
198
+ }
199
+ };
200
+ /**
201
+ * Append the tagged inherited marker that constructing a fresh fork child would
202
+ * append, so storage can receive the complete child log before the Session exists.
203
+ * Does nothing for an unseeded header or when the event at the inherited cut is already that marker.
204
+ * @param log - log from `checkSessionLog`; `log.events` grows in place.
205
+ */
206
+ function appendInheritedSeedMarker(log) {
207
+ if (!needsInheritedSeedMarker(log.header, log.events, log.inheritedEventCount)) return;
208
+ const marker = {
209
+ type: "session/end-seed",
210
+ seq: SessionSeq(log.events.length),
211
+ time: Date.now(),
212
+ data: { inherited: true }
213
+ };
214
+ log.events.push(deepFreeze(marker));
215
+ }
216
+ //#endregion
217
+ export { ArraySessionData, ReadonlyArraySessionData, SESSION_DATA_CORRUPT, SESSION_DATA_READONLY, SESSION_DATA_SERVICE_UNAVAILABLE, SessionDataService, appendInheritedSeedMarker, buildForkCreation };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Module augmentation of the Session definition with `readonlyView`, which
3
+ * reads this Session's data. A program that calls the member must load this
4
+ * package.
5
+ * @module @deepseek-ai/dsh-session-data/augment-session
6
+ */
7
+ import type { ReadonlySessionData } from './data.ts';
8
+ declare module '@deepseek-ai/dsh-session' {
9
+ interface Session {
10
+ /**
11
+ * Return the read-only view of this Session's data: the same object on every
12
+ * call, sharing the log and seeing later appends.
13
+ * @returns the data's view.
14
+ */
15
+ readonlyView(): ReadonlySessionData;
16
+ }
17
+ }
18
+ //# sourceMappingURL=augment-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"augment-session.d.ts","sourceRoot":"","sources":["../../src/augment-session.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAA;AAEpD,OAAO,QAAQ,0BAA0B,CAAC;IACxC,UAAU,OAAO;QACf;;;;WAIG;QACH,YAAY,IAAI,mBAAmB,CAAA;KACpC;CACF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"augment-session.js","sourceRoot":"","sources":["../../src/augment-session.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Module augmentation of the SessionStore definition with `prepare`, which
3
+ * constructs over Session data. A program that calls the member must load
4
+ * this package.
5
+ * @module @deepseek-ai/dsh-session-data/augment
6
+ */
7
+ import type { SessionData } from './data.ts';
8
+ import type { Session, SessionConstructionOptions } from '@deepseek-ai/dsh-session';
9
+ declare module '@deepseek-ai/dsh-session' {
10
+ interface SessionStore {
11
+ /**
12
+ * Construct a store-owned, unentered Session from data that no other Session
13
+ * was constructed from, with the store's message interpreters. Does not
14
+ * flush; the caller retains ownership and pairs this with data flush,
15
+ * `enter`, and `announce`.
16
+ * @param data - writable data; the caller still owns it when this throws.
17
+ * @param options.mode - `create` for new data, `restore` for opened stored data.
18
+ * @returns the store-owned session, not yet entered and read-only until announced.
19
+ * @throws if a session with the data's id already exists or surface replay fails.
20
+ */
21
+ prepare(data: SessionData, options: SessionConstructionOptions): Session;
22
+ }
23
+ }
24
+ /** The Session interface this package augments. */
25
+ export type { Session };
26
+ //# sourceMappingURL=augment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"augment.d.ts","sourceRoot":"","sources":["../../src/augment.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAC5C,OAAO,KAAK,EAAE,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAA;AAEnF,OAAO,QAAQ,0BAA0B,CAAC;IACxC,UAAU,YAAY;QACpB;;;;;;;;;WASG;QACH,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAA;KACzE;CACF;AAED,mDAAmD;AACnD,YAAY,EAAE,OAAO,EAAE,CAAA"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"augment.js","sourceRoot":"","sources":["../../src/augment.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}