@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 +21 -0
- package/README.i18n.yaml +106 -0
- package/README.md +274 -2
- package/README.zh.md +275 -0
- package/lib/index.js +1371 -0
- package/lib/types/index.d.ts +228 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/preparation.d.ts +33 -0
- package/lib/types/preparation.d.ts.map +1 -0
- package/lib/types/preparation.js.map +1 -0
- package/lib/types/request-header.d.ts +50 -0
- package/lib/types/request-header.d.ts.map +1 -0
- package/lib/types/request-header.js.map +1 -0
- package/lib/types/surface.d.ts +66 -0
- package/lib/types/surface.d.ts.map +1 -0
- package/lib/types/surface.js.map +1 -0
- package/lib/types/tool-history.d.ts +89 -0
- package/lib/types/tool-history.d.ts.map +1 -0
- package/lib/types/tool-history.js.map +1 -0
- package/lib/types/validation.d.ts +36 -0
- package/lib/types/validation.d.ts.map +1 -0
- package/lib/types/validation.js.map +1 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +50 -3
- package/src/index.ts +773 -0
- package/src/preparation.ts +49 -0
- package/src/request-header.ts +85 -0
- package/src/surface.ts +446 -0
- package/src/tool-history.ts +345 -0
- package/src/validation.ts +75 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ownership of one unpublished Session before registry publication.
|
|
3
|
+
* @module @deepseek-ai/dsh-session-store/preparation
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
7
|
+
|
|
8
|
+
/** Options for a preparation whose provider retains unpublished state. */
|
|
9
|
+
export interface SessionPreparationOptions {
|
|
10
|
+
/** Release provider-owned state when the Session was not published. */
|
|
11
|
+
readonly release?: () => void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* One exact unpublished Session and the provider state that keeps it usable.
|
|
16
|
+
* Disposal is synchronous and idempotent. Providers decide whether release
|
|
17
|
+
* returns the Session to a cache or discards it; publication may consume that
|
|
18
|
+
* state before disposal, making the callback a no-op.
|
|
19
|
+
*/
|
|
20
|
+
export class SessionPreparation implements Disposable {
|
|
21
|
+
private released = false
|
|
22
|
+
|
|
23
|
+
/** The exact Session to use for setup and publication. */
|
|
24
|
+
readonly session: Session
|
|
25
|
+
|
|
26
|
+
private constructor(
|
|
27
|
+
session: Session,
|
|
28
|
+
private readonly options: SessionPreparationOptions,
|
|
29
|
+
) {
|
|
30
|
+
this.session = session
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Wrap an unpublished Session in one preparation lifetime.
|
|
35
|
+
* @param session - exact unpublished Session.
|
|
36
|
+
* @param options - optional provider release behavior.
|
|
37
|
+
* @returns a preparation disposed after publication or rollback.
|
|
38
|
+
*/
|
|
39
|
+
static create(session: Session, options?: SessionPreparationOptions): SessionPreparation {
|
|
40
|
+
return new SessionPreparation(session, options ?? {})
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Release provider state once when this preparation leaves its caller. */
|
|
44
|
+
[Symbol.dispose](): void {
|
|
45
|
+
if (this.released) return
|
|
46
|
+
this.released = true
|
|
47
|
+
this.options.release?.()
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-header reconstruction utilities over full `request/header` session
|
|
3
|
+
* events. Anyone holding a session log reconstructs the {@link EpochHeader}
|
|
4
|
+
* any request was built under by taking the latest canonical snapshot; the
|
|
5
|
+
* loop uses the same equality helper to avoid logging unchanged headers. The
|
|
6
|
+
* route metadata of `request/context` events is reconstructed the same way.
|
|
7
|
+
*
|
|
8
|
+
* @module @deepseek-ai/dsh-session-store/request-header
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { callConfigEquals } from '@deepseek-ai/dsh-llm'
|
|
12
|
+
import type { ToolSchema } from '@deepseek-ai/dsh-llm'
|
|
13
|
+
import type { EpochHeader, RequestContext, SessionEvent } from '@deepseek-ai/dsh-session'
|
|
14
|
+
import type { SessionStateDefinition } from '@deepseek-ai/dsh-session-data'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Normalize a header to canonical form: an empty tool list becomes an absent
|
|
18
|
+
* field, matching how requests are built. Logging, folding, and comparison use
|
|
19
|
+
* this one representation.
|
|
20
|
+
* @param header - the header to normalize (not mutated).
|
|
21
|
+
* @returns the canonical header.
|
|
22
|
+
*/
|
|
23
|
+
export function canonicalHeader(header: EpochHeader): EpochHeader {
|
|
24
|
+
const adapterDefaults = header.adapterDefaults
|
|
25
|
+
return {
|
|
26
|
+
config: header.config,
|
|
27
|
+
...adapterDefaults?.reasoningEffort === true || adapterDefaults?.maxTokens === true
|
|
28
|
+
? { adapterDefaults }
|
|
29
|
+
: {},
|
|
30
|
+
...header.tools !== undefined && header.tools.length > 0 ? { tools: header.tools } : {},
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Canonical JSON equality for tool schemas assembled through the same path. */
|
|
35
|
+
function sameSchema(a: ToolSchema, b: ToolSchema): boolean {
|
|
36
|
+
return JSON.stringify(a) === JSON.stringify(b)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Field-wise equality over canonical headers. Tool schemas compare in order.
|
|
41
|
+
* @param a - one canonical header.
|
|
42
|
+
* @param b - the other.
|
|
43
|
+
* @returns whether config, adapter defaults, and tools all match.
|
|
44
|
+
*/
|
|
45
|
+
export function headerEquals(a: EpochHeader, b: EpochHeader): boolean {
|
|
46
|
+
if (
|
|
47
|
+
!callConfigEquals(a.config, b.config)
|
|
48
|
+
|| a.adapterDefaults?.reasoningEffort !== b.adapterDefaults?.reasoningEffort
|
|
49
|
+
|| a.adapterDefaults?.maxTokens !== b.adapterDefaults?.maxTokens
|
|
50
|
+
) return false
|
|
51
|
+
const at = a.tools ?? []
|
|
52
|
+
const bt = b.tools ?? []
|
|
53
|
+
return at.length === bt.length && at.every((tool, i) => sameSchema(tool, bt[i] as ToolSchema))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Request-header transition: a `request/header` event yields its canonical header; any other event returns `state` itself. */
|
|
57
|
+
function applyRequestHeader(state: EpochHeader | null, event: SessionEvent): EpochHeader | null {
|
|
58
|
+
return event.type === 'request/header' ? canonicalHeader(event.data.header) : state
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Request-context transition: a `request/context` event yields a copy of its route metadata; any other event returns `state` itself. */
|
|
62
|
+
function applyRequestContext(state: RequestContext | null, event: SessionEvent): RequestContext | null {
|
|
63
|
+
return event.type === 'request/context' ? { ...event.data } : state
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* State definition that `Session.requestHeader()` reads: the canonical
|
|
68
|
+
* {@link EpochHeader} of the latest `request/header` event, or `null` before
|
|
69
|
+
* the first one.
|
|
70
|
+
*/
|
|
71
|
+
export const requestHeaderStateDefinition = {
|
|
72
|
+
key: 'requestHeader',
|
|
73
|
+
init: () => null,
|
|
74
|
+
apply: applyRequestHeader,
|
|
75
|
+
} satisfies SessionStateDefinition<'requestHeader', EpochHeader | null>
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* State definition that `Session.requestContext()` reads: a copy of the latest
|
|
79
|
+
* `request/context` event's route metadata, or `null` before the first one.
|
|
80
|
+
*/
|
|
81
|
+
export const requestContextStateDefinition = {
|
|
82
|
+
key: 'requestContext',
|
|
83
|
+
init: () => null,
|
|
84
|
+
apply: applyRequestContext,
|
|
85
|
+
} satisfies SessionStateDefinition<'requestContext', RequestContext | null>
|
package/src/surface.ts
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The surface fold: replays `surfaceOp` markers and message projections over a
|
|
3
|
+
* session event log, as one complete pass ({@link foldSurface}) or
|
|
4
|
+
* incrementally behind `session.surface` ({@link SurfaceManager}).
|
|
5
|
+
*
|
|
6
|
+
* @module @deepseek-ai/dsh-session-store/surface
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Message, ToolSchema } from '@deepseek-ai/dsh-llm'
|
|
10
|
+
import {
|
|
11
|
+
assertSourceEventReferences,
|
|
12
|
+
deriveEventMessage,
|
|
13
|
+
MESSAGE_PROJECTION_EVENT_TYPES,
|
|
14
|
+
SessionLogOffset,
|
|
15
|
+
SessionSeq,
|
|
16
|
+
validateSessionEventData,
|
|
17
|
+
validateSurfaceMetadata,
|
|
18
|
+
} from '@deepseek-ai/dsh-session'
|
|
19
|
+
import type {
|
|
20
|
+
SessionEvent,
|
|
21
|
+
SessionMessageProjection,
|
|
22
|
+
SessionSeqCursor,
|
|
23
|
+
SessionSurface,
|
|
24
|
+
SurfaceFoldReplacement,
|
|
25
|
+
SurfaceFoldResult,
|
|
26
|
+
SurfaceOp,
|
|
27
|
+
SystemSurfaceNode,
|
|
28
|
+
} from '@deepseek-ai/dsh-session'
|
|
29
|
+
|
|
30
|
+
/** Whether a payload field is a JSON object rather than an array or scalar. */
|
|
31
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
32
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Mutable state shared by complete and incremental folds. */
|
|
36
|
+
interface SurfaceFoldState {
|
|
37
|
+
nodes: SessionSeq[]
|
|
38
|
+
replaceGeneration: number
|
|
39
|
+
contentGeneration: number
|
|
40
|
+
projectedMessages: Map<SessionSeq, Message>
|
|
41
|
+
projections: Set<SessionMessageProjection>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A validated replacement transition that has not mutated fold state yet. */
|
|
45
|
+
interface SurfaceReplacePlan extends SurfaceFoldReplacement {
|
|
46
|
+
kind: 'replace'
|
|
47
|
+
startIdx: number
|
|
48
|
+
endIdx: number
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** One validated surface transition that has not mutated fold state yet. */
|
|
52
|
+
type SurfacePlan =
|
|
53
|
+
| { kind: 'append'; seq: SessionSeq }
|
|
54
|
+
| SurfaceReplacePlan
|
|
55
|
+
| { kind: 'project'; projection: SessionMessageProjection; messages: ReadonlyMap<SessionSeq, Message> }
|
|
56
|
+
|
|
57
|
+
/** Create an empty surface fold state. */
|
|
58
|
+
function createFoldState(): SurfaceFoldState {
|
|
59
|
+
return { nodes: [], replaceGeneration: 0, contentGeneration: 0, projectedMessages: new Map(), projections: new Set() }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Resolve tool additions against their immutable historical request header. */
|
|
63
|
+
function assertDeveloperHeader(
|
|
64
|
+
event: SessionEvent,
|
|
65
|
+
read: (seq: number) => SessionEvent | undefined,
|
|
66
|
+
): void {
|
|
67
|
+
if (event.type !== 'developer/message') return
|
|
68
|
+
validateSessionEventData(event, `developer/message at seq ${event.seq}`)
|
|
69
|
+
if (event.data.headerSeq === undefined) return
|
|
70
|
+
const headerSeq = event.data.headerSeq
|
|
71
|
+
const headerEvent = read(headerSeq)
|
|
72
|
+
if (headerSeq >= event.seq || headerEvent?.type !== 'request/header') {
|
|
73
|
+
throw new Error('developer/message headerSeq must reference an earlier request/header')
|
|
74
|
+
}
|
|
75
|
+
for (const block of event.data.message.content) {
|
|
76
|
+
if (block.type !== 'tool-addition') continue
|
|
77
|
+
const definitions = headerEvent.data.header.tools?.filter(tool => tool.name === block.toolName) ?? []
|
|
78
|
+
if (definitions.length !== 1) {
|
|
79
|
+
throw new Error(`developer/message tool-addition "${block.toolName}" must name exactly one tool in headerSeq ${headerSeq}`)
|
|
80
|
+
}
|
|
81
|
+
const definition = definitions[0] as ToolSchema
|
|
82
|
+
if (typeof definition.description !== 'string' || !isRecord(definition.parameters)) {
|
|
83
|
+
throw new Error(`developer/message tool-addition "${block.toolName}" requires a complete tool definition in headerSeq ${headerSeq}`)
|
|
84
|
+
}
|
|
85
|
+
if (Object.hasOwn(definition, 'deferLoading') && definition.deferLoading !== true) {
|
|
86
|
+
throw new Error('developer/message referenced tool deferLoading must be true when present')
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Locate one replacement range without mutating the current fold state. */
|
|
92
|
+
function replacementRange(
|
|
93
|
+
state: SurfaceFoldState,
|
|
94
|
+
op: Extract<SurfaceOp, { op: 'replace' }>,
|
|
95
|
+
): Pick<SurfaceReplacePlan, 'startIdx' | 'endIdx' | 'shadowedSeqs'> {
|
|
96
|
+
const startIdx = state.nodes.indexOf(op.startSeq)
|
|
97
|
+
if (startIdx === -1) {
|
|
98
|
+
throw new Error(`surface replace: start seq ${op.startSeq} not found in surface`)
|
|
99
|
+
}
|
|
100
|
+
const endIdx = state.nodes.indexOf(op.endSeq)
|
|
101
|
+
if (endIdx === -1) {
|
|
102
|
+
throw new Error(`surface replace: end seq ${op.endSeq} not found in surface`)
|
|
103
|
+
}
|
|
104
|
+
if (startIdx > endIdx) {
|
|
105
|
+
throw new Error(`surface replace: start seq ${op.startSeq} (index ${startIdx}) is after end seq ${op.endSeq} (index ${endIdx})`)
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
startIdx,
|
|
109
|
+
endIdx,
|
|
110
|
+
shadowedSeqs: state.nodes.slice(startIdx, endIdx + 1),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Deep structural equality over the session-event JSON value domain
|
|
116
|
+
* (null/boolean/number/string, arrays, plain objects). Replaces
|
|
117
|
+
* `node:util`'s isDeepStrictEqual to keep this module browser-safe.
|
|
118
|
+
*/
|
|
119
|
+
function isDeepEqualJson(a: unknown, b: unknown): boolean {
|
|
120
|
+
if (a === b) return true
|
|
121
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
122
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
|
|
123
|
+
return a.every((item, i) => isDeepEqualJson(item, b[i]))
|
|
124
|
+
}
|
|
125
|
+
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
|
|
126
|
+
const aKeys = Object.keys(a)
|
|
127
|
+
const bRecord = b as Record<string, unknown>
|
|
128
|
+
if (aKeys.length !== Object.keys(b).length) return false
|
|
129
|
+
return aKeys.every(key => Object.hasOwn(b, key) && isDeepEqualJson((a as Record<string, unknown>)[key], bRecord[key]))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Restrict a tool-result replacement to one current result's content. */
|
|
133
|
+
function assertToolResultRewrite(
|
|
134
|
+
event: SessionEvent,
|
|
135
|
+
shadowedSeqs: readonly SessionSeq[],
|
|
136
|
+
read: (seq: number) => SessionEvent | undefined,
|
|
137
|
+
): void {
|
|
138
|
+
if (event.type !== 'tool/result') return
|
|
139
|
+
if (shadowedSeqs.length !== 1) {
|
|
140
|
+
throw new Error('tool/result surface replacement must rewrite exactly one current node')
|
|
141
|
+
}
|
|
142
|
+
for (const originalSeq of shadowedSeqs) {
|
|
143
|
+
const original = read(originalSeq)
|
|
144
|
+
if (original?.type !== 'tool/result') {
|
|
145
|
+
throw new Error('tool/result surface replacement must target a current tool/result')
|
|
146
|
+
}
|
|
147
|
+
const originalRest = { ...original.data } as Record<string, unknown>
|
|
148
|
+
const replacementRest = { ...event.data } as Record<string, unknown>
|
|
149
|
+
originalRest['message'] = {
|
|
150
|
+
...original.data.message,
|
|
151
|
+
content: null,
|
|
152
|
+
}
|
|
153
|
+
replacementRest['message'] = {
|
|
154
|
+
...event.data.message,
|
|
155
|
+
content: null,
|
|
156
|
+
}
|
|
157
|
+
if (!isDeepEqualJson(originalRest, replacementRest)) {
|
|
158
|
+
throw new Error('tool/result surface replacement may change only content')
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Protect the system prompt at surface node 0. A replacement covering node 0
|
|
165
|
+
* while that node is a `system/message` must itself be a `system/message` over
|
|
166
|
+
* exactly that node; later system nodes carry no protection and a compaction
|
|
167
|
+
* range may shadow them.
|
|
168
|
+
*/
|
|
169
|
+
function assertSystemHeadRewrite(
|
|
170
|
+
event: SessionEvent,
|
|
171
|
+
state: SurfaceFoldState,
|
|
172
|
+
startIdx: number,
|
|
173
|
+
shadowedSeqs: readonly SessionSeq[],
|
|
174
|
+
read: (seq: number) => SessionEvent | undefined,
|
|
175
|
+
): void {
|
|
176
|
+
if (startIdx !== 0) return
|
|
177
|
+
const head = read(state.nodes[0] as number)
|
|
178
|
+
if (head?.type !== 'system/message') return
|
|
179
|
+
if (event.type !== 'system/message' || shadowedSeqs.length !== 1) {
|
|
180
|
+
throw new Error('surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node')
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Validate one event at its replay boundary and prepare its atomic fold transition. */
|
|
185
|
+
function planSurfaceEvent(
|
|
186
|
+
state: SurfaceFoldState,
|
|
187
|
+
event: SessionEvent,
|
|
188
|
+
expectedSeq: SessionSeq,
|
|
189
|
+
events: readonly SessionEvent[],
|
|
190
|
+
baseSeq: SessionLogOffset,
|
|
191
|
+
projections: readonly SessionMessageProjection[],
|
|
192
|
+
candidates?: readonly SessionEvent[],
|
|
193
|
+
): SurfacePlan | undefined {
|
|
194
|
+
if (event.seq !== expectedSeq) {
|
|
195
|
+
throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`)
|
|
196
|
+
}
|
|
197
|
+
const surfaceOp = validateSurfaceMetadata(event)
|
|
198
|
+
const read = (seq: number): SessionEvent | undefined => {
|
|
199
|
+
const index = seq - baseSeq
|
|
200
|
+
return index < events.length ? events[index] : candidates?.[index - events.length]
|
|
201
|
+
}
|
|
202
|
+
assertDeveloperHeader(event, read)
|
|
203
|
+
const projection = projections.find(item => item.type === event.type)
|
|
204
|
+
if (projection !== undefined) {
|
|
205
|
+
let projectionEvents: readonly SessionEvent[] | undefined
|
|
206
|
+
return { kind: 'project', projection, messages: projection.project(event, {
|
|
207
|
+
nodes: state.nodes,
|
|
208
|
+
get events() { return candidates === undefined ? events : (projectionEvents ??= [...events, ...candidates]) },
|
|
209
|
+
baseSeq,
|
|
210
|
+
messages: state.projectedMessages,
|
|
211
|
+
}) }
|
|
212
|
+
}
|
|
213
|
+
if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) {
|
|
214
|
+
throw new Error(`session event "${event.type}" requires a message projection; load its owning plugin or supply its projection definition`)
|
|
215
|
+
}
|
|
216
|
+
if (surfaceOp === undefined) return
|
|
217
|
+
if (surfaceOp === 'append') {
|
|
218
|
+
return { kind: 'append', seq: event.seq }
|
|
219
|
+
}
|
|
220
|
+
const range = replacementRange(state, surfaceOp)
|
|
221
|
+
assertSourceEventReferences(event, range.shadowedSeqs)
|
|
222
|
+
assertToolResultRewrite(event, range.shadowedSeqs, read)
|
|
223
|
+
assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, read)
|
|
224
|
+
return {
|
|
225
|
+
kind: 'replace',
|
|
226
|
+
seq: event.seq,
|
|
227
|
+
start: surfaceOp.startSeq,
|
|
228
|
+
end: surfaceOp.endSeq,
|
|
229
|
+
...range,
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Apply one event and return replacement metadata only when one occurred. */
|
|
234
|
+
function applySurfaceEvent(
|
|
235
|
+
state: SurfaceFoldState,
|
|
236
|
+
event: SessionEvent,
|
|
237
|
+
expectedSeq: SessionSeq,
|
|
238
|
+
events: readonly SessionEvent[],
|
|
239
|
+
baseSeq: SessionLogOffset,
|
|
240
|
+
projections: readonly SessionMessageProjection[],
|
|
241
|
+
): SurfaceFoldReplacement | undefined {
|
|
242
|
+
const plan = planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections)
|
|
243
|
+
return applySurfacePlan(state, plan)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Commit one previously validated surface transition. */
|
|
247
|
+
function applySurfacePlan(
|
|
248
|
+
state: SurfaceFoldState,
|
|
249
|
+
plan: SurfacePlan | undefined,
|
|
250
|
+
): SurfaceFoldReplacement | undefined {
|
|
251
|
+
if (plan?.kind === 'append') {
|
|
252
|
+
state.nodes.push(plan.seq)
|
|
253
|
+
} else if (plan?.kind === 'replace') {
|
|
254
|
+
state.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq)
|
|
255
|
+
state.replaceGeneration += 1
|
|
256
|
+
state.contentGeneration += 1
|
|
257
|
+
} else if (plan?.kind === 'project') {
|
|
258
|
+
for (const [seq, message] of plan.messages) state.projectedMessages.set(seq, message)
|
|
259
|
+
state.projections.add(plan.projection)
|
|
260
|
+
state.contentGeneration += 1
|
|
261
|
+
}
|
|
262
|
+
if (plan?.kind !== 'replace') return
|
|
263
|
+
return {
|
|
264
|
+
seq: plan.seq,
|
|
265
|
+
start: plan.start,
|
|
266
|
+
end: plan.end,
|
|
267
|
+
shadowedSeqs: plan.shadowedSeqs,
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Replay a complete session log through the canonical surface fold.
|
|
273
|
+
* @param events - session events in contiguous seq order.
|
|
274
|
+
* @param projections - pure interpreters for plugin-owned message changes; required definitions must be supplied.
|
|
275
|
+
* @returns detached current sequences and replacement history.
|
|
276
|
+
* @throws when an interpreter is missing or an event violates its projection, surface metadata, source attribution, or replacement rules.
|
|
277
|
+
*/
|
|
278
|
+
export function foldSurface(events: readonly SessionEvent[], projections: readonly SessionMessageProjection[] = []): SurfaceFoldResult {
|
|
279
|
+
const state = createFoldState()
|
|
280
|
+
const replacements: SurfaceFoldReplacement[] = []
|
|
281
|
+
for (const [index, event] of events.entries()) {
|
|
282
|
+
const replacement = applySurfaceEvent(
|
|
283
|
+
state,
|
|
284
|
+
event,
|
|
285
|
+
SessionSeq(index),
|
|
286
|
+
events,
|
|
287
|
+
SessionLogOffset(0),
|
|
288
|
+
projections,
|
|
289
|
+
)
|
|
290
|
+
if (replacement !== undefined) replacements.push(replacement)
|
|
291
|
+
}
|
|
292
|
+
return { nodes: [...state.nodes], replacements, projectedMessages: new Map(state.projectedMessages) }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Incremental ordered surface view and append-boundary validator. */
|
|
296
|
+
export class SurfaceManager implements SessionSurface {
|
|
297
|
+
/** Shared transition state; replacement history is not retained. */
|
|
298
|
+
private _state = createFoldState()
|
|
299
|
+
/** Last processed absolute seq. */
|
|
300
|
+
private _lastProcessedSeq: SessionSeqCursor
|
|
301
|
+
/** Candidate already validated by `validateNext`, pending exact log admission. */
|
|
302
|
+
private _pendingPlan: { event: SessionEvent; expectedSeq: SessionSeq; plan: SurfacePlan | undefined } | undefined
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* @param log - Contiguous complete log or loaded event window.
|
|
306
|
+
* @param baseSeq - Absolute sequence of the window's first event.
|
|
307
|
+
* @param projections - live borrowed definitions; removing a used definition invalidates further reads.
|
|
308
|
+
*/
|
|
309
|
+
constructor(
|
|
310
|
+
private log: readonly SessionEvent[],
|
|
311
|
+
private readonly baseSeq: SessionLogOffset = SessionLogOffset(0),
|
|
312
|
+
private readonly projections: readonly SessionMessageProjection[] = [],
|
|
313
|
+
) {
|
|
314
|
+
this._lastProcessedSeq = baseSeq === 0 ? -1 : SessionSeq(baseSeq - 1)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Validate the next candidate without mutating the committed surface.
|
|
319
|
+
* @param event - candidate event that has not entered the log yet.
|
|
320
|
+
*/
|
|
321
|
+
validateNext(event: SessionEvent): void {
|
|
322
|
+
this._assertProjections()
|
|
323
|
+
if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
|
|
324
|
+
const expectedSeq = SessionSeq(this.baseSeq + this.log.length)
|
|
325
|
+
this._pendingPlan = {
|
|
326
|
+
event,
|
|
327
|
+
expectedSeq,
|
|
328
|
+
plan: planSurfaceEvent(this._state, event, expectedSeq, this.log, this.baseSeq, this.projections),
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Validate consecutive candidates against an isolated surface fold.
|
|
334
|
+
* @param events - candidates immediately following the committed log.
|
|
335
|
+
* @returns a callback adopting the validated fold after all candidates enter the log.
|
|
336
|
+
*/
|
|
337
|
+
prepareBatch(events: readonly SessionEvent[]): () => void {
|
|
338
|
+
this._assertProjections()
|
|
339
|
+
if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
|
|
340
|
+
const lastProcessedSeq = SessionSeq(this.baseSeq + this.log.length + events.length - 1)
|
|
341
|
+
if (events.every(event => (event.surfaceOp === undefined || event.surfaceOp === 'append')
|
|
342
|
+
&& !this.projections.some(projection => projection.type === event.type))) {
|
|
343
|
+
const plans = events.map((event, index) => planSurfaceEvent(
|
|
344
|
+
this._state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events,
|
|
345
|
+
))
|
|
346
|
+
return () => {
|
|
347
|
+
for (const plan of plans) applySurfacePlan(this._state, plan)
|
|
348
|
+
this._lastProcessedSeq = lastProcessedSeq
|
|
349
|
+
this._pendingPlan = undefined
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
const state: SurfaceFoldState = {
|
|
353
|
+
...this._state,
|
|
354
|
+
nodes: [...this._state.nodes],
|
|
355
|
+
projectedMessages: new Map(this._state.projectedMessages),
|
|
356
|
+
projections: new Set(this._state.projections),
|
|
357
|
+
}
|
|
358
|
+
const plans = events.map((event, index) => {
|
|
359
|
+
const plan = planSurfaceEvent(
|
|
360
|
+
state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events,
|
|
361
|
+
)
|
|
362
|
+
applySurfacePlan(state, plan)
|
|
363
|
+
return plan
|
|
364
|
+
})
|
|
365
|
+
return () => {
|
|
366
|
+
for (const plan of plans) applySurfacePlan(this._state, plan)
|
|
367
|
+
this._lastProcessedSeq = lastProcessedSeq
|
|
368
|
+
this._pendingPlan = undefined
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Monotonic count of folded positional replacements. */
|
|
373
|
+
get replaceGeneration(): number {
|
|
374
|
+
this._assertProjections()
|
|
375
|
+
if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
|
|
376
|
+
return this._state.replaceGeneration
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Monotonic count of committed changes to existing model-visible content. */
|
|
380
|
+
get contentGeneration(): number {
|
|
381
|
+
this._assertProjections()
|
|
382
|
+
if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
|
|
383
|
+
return this._state.contentGeneration
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Project one message with every committed message projection applied.
|
|
388
|
+
* @param event - message-producing or log-only event.
|
|
389
|
+
* @returns its immutable projected message, or null when it produces none.
|
|
390
|
+
*/
|
|
391
|
+
deriveEventMessage(event: SessionEvent): Message | null {
|
|
392
|
+
this._assertProjections()
|
|
393
|
+
if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
|
|
394
|
+
return deriveEventMessage(event, this._state.projectedMessages)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Surface event sequences in model-visible order. */
|
|
398
|
+
get nodes(): readonly SessionSeq[] {
|
|
399
|
+
this._assertProjections()
|
|
400
|
+
if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
|
|
401
|
+
return this._state.nodes
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** System nodes in surface order, including nodes whose content array is empty; scans current nodes on each read. */
|
|
405
|
+
get systemNodes(): readonly SystemSurfaceNode[] {
|
|
406
|
+
const systems: SystemSurfaceNode[] = []
|
|
407
|
+
for (const seq of this.nodes) {
|
|
408
|
+
const event = this.log[seq - this.baseSeq]
|
|
409
|
+
if (event?.type === 'system/message') systems.push({ seq, isEmpty: event.data.message.content.length === 0 })
|
|
410
|
+
}
|
|
411
|
+
return systems
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Fold events appended since the previous access. */
|
|
415
|
+
private _processDelta(): void {
|
|
416
|
+
const tailSeq = this.baseSeq + this.log.length - 1
|
|
417
|
+
for (let seq = this._lastProcessedSeq + 1; seq <= tailSeq; seq++) {
|
|
418
|
+
const index = seq - this.baseSeq
|
|
419
|
+
// oxlint-disable-next-line typescript/no-non-null-assertion -- bounded by the loop condition
|
|
420
|
+
const event = this.log[index]!
|
|
421
|
+
const pending = this._pendingPlan
|
|
422
|
+
if (pending?.event === event && pending.expectedSeq === seq) {
|
|
423
|
+
applySurfacePlan(this._state, pending.plan)
|
|
424
|
+
} else {
|
|
425
|
+
applySurfaceEvent(this._state, event, SessionSeq(seq), this.log, this.baseSeq, this.projections)
|
|
426
|
+
}
|
|
427
|
+
if (pending !== undefined && pending.expectedSeq <= seq) this._pendingPlan = undefined
|
|
428
|
+
this._lastProcessedSeq = SessionSeq(seq)
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Cached messages cannot outlive the definitions that interpreted their log. */
|
|
433
|
+
private _assertProjections(): void {
|
|
434
|
+
const candidate = this._pendingPlan
|
|
435
|
+
const pending = candidate !== undefined && this.log[candidate.expectedSeq - this.baseSeq] === candidate.event
|
|
436
|
+
? candidate.plan : undefined
|
|
437
|
+
const required = pending?.kind === 'project'
|
|
438
|
+
? [...this._state.projections, pending.projection]
|
|
439
|
+
: this._state.projections
|
|
440
|
+
for (const projection of required) {
|
|
441
|
+
if (!this.projections.includes(projection)) {
|
|
442
|
+
throw new Error(`session message projection "${projection.type}" was removed or replaced; restore the session with its owning plugin`)
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|