index.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. /**
  2. * Event-sourced session service: append-only session log, in-memory store, and
  3. * the derived LLM message history. Persistence is a plugin concern (subscribe
  4. * to `session/event`, drain on `session/flush`).
  5. *
  6. * @module @deepseek-ai/dsh-session
  7. */
  8. import { Context, Service } from 'cordis'
  9. import { isAbsolute } from 'node:path'
  10. import { deepFreeze } from '@deepseek-ai/dsh-llm'
  11. import { scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope'
  12. import type { Scoped } from '@deepseek-ai/dsh-scope'
  13. import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm'
  14. import { SESSION_FORMAT_VERSION, SessionId } from './types.ts'
  15. import type { CreateSessionOptions, EpochHeader, OutOfBandSessionEventType, PromptMessageData, SessionEvent, SessionEventMap, SessionEventType, SessionHeader, SurfaceIntent, SurfaceEventType, TurnTrigger } from './types.ts'
  16. import { snapshotJsonValue } from './json.ts'
  17. import { SurfaceManager } from './surface.ts'
  18. import type { SessionSurface } from './surface.ts'
  19. import { foldRequestHeader } from './request-header.ts'
  20. export * from './types.ts'
  21. export { isJsonValue, snapshotJsonValue } from './json.ts'
  22. export type { JsonValue } from './json.ts'
  23. export { interruptedTurnClosers, TOOL_NOT_STARTED, TOOL_OUTCOME_UNKNOWN } from './repair.ts'
  24. export { decodeStorageRecord, packChunkRuns } from './chunk-rows.ts'
  25. export type { ChunkRow, StorageRecord } from './chunk-rows.ts'
  26. export type { SessionSurface, SurfaceFoldReplacement, SurfaceFoldResult } from './surface.ts'
  27. export { foldSurface, isSurfaceEvent, isSurfaceEligibleType } from './surface.ts'
  28. export { canonicalHeader, foldRequestHeader, headerEquals } from './request-header.ts'
  29. /**
  30. * Return the human-facing prompt blocks from a durable prompt message.
  31. * @param data - ordinary or steering prompt event data.
  32. * @returns the effective direct prompt, excluding baked prefix context.
  33. */
  34. export function displayPromptContent(data: PromptMessageData): ContentBlock[] {
  35. return data.envelope?.displayContent ?? data.content
  36. }
  37. /**
  38. * Find the latest closed message-triggered turn, excluding injection and
  39. * plugin-owned zero-step turns.
  40. * @param events - session events, or an owned suffix, to inspect.
  41. * @returns the latest matching turn end, or `undefined`.
  42. */
  43. export function findLastMessageTurnEnd(
  44. events: readonly SessionEvent[],
  45. ): SessionEvent<'turn/end'> | undefined {
  46. const messageTurns = new Set<number>()
  47. let latest: SessionEvent<'turn/end'> | undefined
  48. for (const event of events) {
  49. if (event.type === 'turn/start') {
  50. if (event.data.trigger.kind === 'message') messageTurns.add(event.data.turn)
  51. continue
  52. }
  53. if (event.type === 'turn/end' && messageTurns.delete(event.data.turn)) latest = event
  54. }
  55. return latest
  56. }
  57. declare module 'cordis' {
  58. interface Context {
  59. sessions: SessionStore
  60. }
  61. interface Events {
  62. /**
  63. * Creation announcement during session publication. A synchronous throw vetoes and rolls
  64. * back with a paired disposal; detach requested during dispatch is deferred.
  65. * A returned-promise rejection is logged but cannot retroactively veto this
  66. * synchronous boundary.
  67. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
  68. * receive only sessions entered through that agent's context.
  69. * @param session - the session just entered and announced.
  70. * @dshScopeScan unsupported
  71. * @mode emit
  72. */
  73. 'session/created'(this: Scoped<Session>, session: Session): void
  74. /**
  75. * Emitted once when an announced session leaves the store, including
  76. * publication rollback, but never for an entry whose creation announcement
  77. * did not begin. Listener failures are logged and contained.
  78. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
  79. * @param session - the session that is no longer live in the store.
  80. * @dshScopeScan unsupported
  81. * @mode emit
  82. */
  83. 'session/disposed'(this: Scoped<Session>, session: Session): void
  84. /**
  85. * Post-commit, fire-and-forget append feed. The listener snapshot resolves
  86. * before the log push, but callbacks run after it; observer failures are
  87. * logged and contained without making the committed append fail.
  88. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
  89. * receive only events from sessions entered through that agent's context.
  90. * @param session - the session whose log grew.
  91. * @param event - the appended event, exactly as recorded.
  92. * @dshScopeScan unsupported
  93. * @mode emit
  94. */
  95. 'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
  96. /**
  97. * Awaited parallel durability checkpoint: every listener runs and the
  98. * caller awaits all of them, with no waterfall veto. Dispatch through
  99. * {@link SessionStore.flush}. Scope-filtered dispatch
  100. * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
  101. * @param session - the session whose buffered events must reach durable storage.
  102. * @dshScopeScan unsupported
  103. * @mode parallel
  104. */
  105. 'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
  106. }
  107. }
  108. /** Detach, validate, and freeze the creation metadata published by a session. */
  109. function snapshotSessionHeader(id: SessionId, source?: SessionHeader): SessionHeader {
  110. const input: unknown = source === undefined
  111. ? { version: SESSION_FORMAT_VERSION, id, createdAt: Date.now() }
  112. : source
  113. const snapshot = snapshotJsonValue(input)
  114. if (snapshot === undefined) throw new Error('session header is not losslessly JSON-serializable')
  115. if (snapshot === null || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
  116. throw new Error('session header is not a plain JSON record')
  117. }
  118. const record = snapshot as Record<string, unknown>
  119. if (record.version !== SESSION_FORMAT_VERSION) {
  120. throw new Error(`session header version must be ${SESSION_FORMAT_VERSION}, got ${String(record.version)}`)
  121. }
  122. if (record.id !== id) {
  123. throw new Error(`session header id "${String(record.id)}" does not match session id "${id}"`)
  124. }
  125. if (typeof record.createdAt !== 'number'
  126. || !Number.isSafeInteger(record.createdAt)
  127. || record.createdAt < 0) {
  128. throw new Error('session header createdAt must be a non-negative safe integer')
  129. }
  130. if (record.cwd !== undefined) {
  131. if (typeof record.cwd !== 'string') throw new Error('session header cwd must be a string')
  132. if (!isAbsolute(record.cwd)) {
  133. throw new Error(`session header cwd must be an absolute path, got "${record.cwd}"`)
  134. }
  135. }
  136. if (record.parentSession !== undefined && typeof record.parentSession !== 'string') {
  137. throw new Error('session header parentSession must be a string')
  138. }
  139. if (record.seedLength !== undefined
  140. && (typeof record.seedLength !== 'number' || !Number.isSafeInteger(record.seedLength) || record.seedLength < 0)) {
  141. throw new Error('session header seedLength must be a non-negative safe integer')
  142. }
  143. if (record.delegationDepth !== undefined
  144. && (typeof record.delegationDepth !== 'number' || !Number.isSafeInteger(record.delegationDepth) || record.delegationDepth < 0)) {
  145. throw new Error('session header delegationDepth must be a non-negative safe integer')
  146. }
  147. return deepFreeze(record as unknown as SessionHeader)
  148. }
  149. /** Validate the fixed event envelope after one-pass JSON materialization. */
  150. function assertSessionEventEnvelope(value: Record<string, unknown>, index: number): asserts value is SessionEvent {
  151. const event = value
  152. if (event['type'] === 'request/header-delta') {
  153. throw new Error(`seed event at index ${index} uses unsupported legacy request/header-delta format`)
  154. }
  155. const allowed = new Set(['type', 'seq', 'time', 'data', 'surfaceOp', 'sourceEventSeqs'])
  156. if (Object.keys(event).some(key => !allowed.has(key))
  157. || !Object.hasOwn(event, 'type') || typeof event['type'] !== 'string'
  158. || !Object.hasOwn(event, 'seq') || typeof event['seq'] !== 'number'
  159. || !Number.isSafeInteger(event['seq']) || event['seq'] < 0
  160. || !Object.hasOwn(event, 'time') || typeof event['time'] !== 'number'
  161. || !Number.isSafeInteger(event['time']) || event['time'] < 0
  162. || !Object.hasOwn(event, 'data')) {
  163. throw new Error(`seed event at index ${index} has an invalid event envelope`)
  164. }
  165. assertCurrentLlmShape(event, index)
  166. assertCurrentTurnEndShape(event, index)
  167. }
  168. /** Reject pre-provider request headers and assistant messages at the seed/load boundary. */
  169. function assertCurrentLlmShape(event: Record<string, unknown>, index: number): void {
  170. const data = event['data']
  171. if (typeof data !== 'object' || data === null) return
  172. const record = data as Record<string, unknown>
  173. if (event['type'] === 'request/header') {
  174. const header = record['header']
  175. const config = typeof header === 'object' && header !== null ? (header as Record<string, unknown>)['config'] : undefined
  176. if (!hasProviderModel(config)) throw new Error(`seed request/header at index ${index} lacks provider/model`)
  177. const reasoningEffort = (config as Record<string, unknown>)['reasoningEffort']
  178. if (reasoningEffort !== undefined
  179. && (typeof reasoningEffort !== 'string' || reasoningEffort.length === 0)) {
  180. throw new Error(`seed request/header at index ${index} has an invalid reasoningEffort`)
  181. }
  182. }
  183. if (event['type'] === 'assistant/message' && !hasProviderModel(record['provenance'])) {
  184. throw new Error(`seed assistant/message at index ${index} lacks provider/model provenance`)
  185. }
  186. }
  187. /** Reject legacy aborted outcomes that persisted caller-owned reason detail. */
  188. function assertCurrentTurnEndShape(event: Record<string, unknown>, index: number): void {
  189. if (event['type'] !== 'turn/end') return
  190. const data = event['data']
  191. /* v8 ignore next -- this migration recognizes only the legacy object shape; format-wide payload validation is separate. */
  192. if (typeof data !== 'object' || data === null) return
  193. const reason = (data as Record<string, unknown>)['reason']
  194. /* v8 ignore next -- non-object reasons cannot carry the legacy aborted detail this migration removes. */
  195. if (typeof reason !== 'object' || reason === null || Array.isArray(reason)) return
  196. const record = reason as Record<string, unknown>
  197. if (record['kind'] === 'aborted'
  198. && (Object.keys(record).length !== 1 || !Object.hasOwn(record, 'kind'))) {
  199. throw new Error(`seed turn/end at index ${index} uses unsupported reason-bearing aborted format`)
  200. }
  201. }
  202. /** Whether an unknown value carries the current provider/model pair. */
  203. function hasProviderModel(value: unknown): boolean {
  204. if (typeof value !== 'object' || value === null) return false
  205. const pair = value as Record<string, unknown>
  206. return typeof pair['provider'] === 'string' && pair['provider'].length > 0
  207. && typeof pair['model'] === 'string' && pair['model'].length > 0
  208. }
  209. /** Reject request-header vocabulary removed with the legacy delta codec. */
  210. function assertSupportedRequestHeader(type: string, data: unknown, location: string): void {
  211. if (type === 'request/header-delta') {
  212. throw new Error(`${location} uses unsupported legacy request/header-delta format`)
  213. }
  214. if (type === 'request/header'
  215. && data !== null && typeof data === 'object' && !Array.isArray(data)
  216. && (data as Record<string, unknown>)['reason'] === 'fallback') {
  217. throw new Error(`${location} uses unsupported legacy request/header reason "fallback"`)
  218. }
  219. }
  220. type SessionCallback = (...args: unknown[]) => unknown
  221. /** Resolve one listener snapshot, including Cordis's internal dispatch checks. */
  222. function collectSessionCallbacks(ctx: Context, args: unknown[]): SessionCallback[] {
  223. return [...ctx.events.dispatch('emit', args)] as SessionCallback[]
  224. }
  225. /** Invoke one resolved observe-only listener snapshot with per-listener containment. */
  226. function invokeContainedSessionObservers(
  227. ctx: Context,
  228. name: 'session/event' | 'session/disposed',
  229. id: SessionId,
  230. args: unknown[],
  231. callbacks: SessionCallback[],
  232. ): void {
  233. for (const callback of callbacks) {
  234. try {
  235. const returned: unknown = callback(...args)
  236. void Promise.resolve(returned).catch((error: unknown) => {
  237. ctx.logger.warn(`session "${id}": ${name} listener rejected: ${String(error)}`)
  238. })
  239. } catch (error: unknown) {
  240. ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`)
  241. }
  242. }
  243. }
  244. /** All mutable lifecycle state for one exact store entry. */
  245. interface SessionEntry {
  246. readonly id: SessionId
  247. readonly session: Session
  248. readonly carrier: Scoped<Session>
  249. readonly emitCtx: Context
  250. announced: boolean
  251. announcing: boolean
  252. appending: boolean
  253. outOfBand: boolean
  254. detachRequested: boolean
  255. detach(): void
  256. }
  257. /** Store attachment for the append path; module-private to keep Session store-agnostic publicly. */
  258. const attachments = new WeakMap<Session, SessionEntry>()
  259. /**
  260. * An event-sourced session: an append-only log of {@link SessionEvent}s.
  261. *
  262. * Plain class (not a Service) — create instances via `ctx.sessions.create()`.
  263. * Seeding with an existing event log replays/forks a session.
  264. */
  265. export class Session {
  266. private log: SessionEvent[] = []
  267. /** Single incremental owner of surface acceptance and projection state. */
  268. private readonly surfaceManager = new SurfaceManager(this.log)
  269. /** The ordered surface over this session's event log. */
  270. get surface(): SessionSurface {
  271. return this.surfaceManager
  272. }
  273. /**
  274. * Detached, deep-frozen creation metadata (format version, cwd, lineage,
  275. * seed boundary). Supplied by the store via `ctx.sessions.create()`. When a
  276. * `Session` is constructed bare (tests, ad-hoc replay), a minimal header is
  277. * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
  278. * `session.header` is always present. Kept out of the event log — it is a
  279. * storage concern, not replayable conversation state.
  280. */
  281. readonly header: SessionHeader
  282. /** The session identity, derived from its durable header's single copy. */
  283. get id(): SessionId {
  284. return this.header.id
  285. }
  286. constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader) {
  287. if (seed) {
  288. // Validate the seed to the SAME invariants `append` enforces, so a
  289. // replay/fork (`ctx.sessions.create(id, { seed })`) cannot construct a
  290. // live log that no persistence backend could store: each event's `data`
  291. // must be JSON-serializable, and `seq` must be contiguous from 0 (the
  292. // `seq = log.length` contract the whole system relies on). Without this,
  293. // a bad seed would surface only later as a backend rejection or a silent
  294. // divergence between the live log and disk.
  295. for (const [index, source] of seed.entries()) {
  296. // The seed is a persistence/replay boundary: validate and detach the
  297. // complete event in one lossless-JSON pass.
  298. const snapshot = snapshotJsonValue(source)
  299. if (snapshot === undefined) {
  300. throw new Error(`seed event at index ${index} is not losslessly JSON-serializable`)
  301. }
  302. assertSessionEventEnvelope(snapshot, index)
  303. assertSupportedRequestHeader(snapshot.type, snapshot.data, `seed event at index ${index}`)
  304. if (snapshot.seq !== index) {
  305. throw new Error(`seed event at index ${index} has seq ${snapshot.seq} (expected ${index}); seed must be contiguous from 0`)
  306. }
  307. // A seed is accepted incrementally through the same transition as a
  308. // live append and a full-log fold. The candidate is planned before it
  309. // enters `log`, so a failure cannot partially mutate the surface.
  310. try {
  311. this.surfaceManager.validateNext(snapshot)
  312. } catch (error: unknown) {
  313. throw new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : 'invalid surface metadata'}`)
  314. }
  315. this.log.push(deepFreeze(snapshot))
  316. }
  317. }
  318. this.header = snapshotSessionHeader(id, header)
  319. }
  320. /** Cached immutable public snapshot of the private append-only log. */
  321. private eventsSnapshot: readonly SessionEvent[] | undefined
  322. /**
  323. * An immutable snapshot of the append-only event log. The snapshot is reused
  324. * until the next append; a previously returned array does not grow later.
  325. * Events and their nested data are deep-frozen at acceptance, so neither a
  326. * cast nor ordinary JavaScript can rewrite durable history.
  327. */
  328. get events(): readonly SessionEvent[] {
  329. this.eventsSnapshot ??= Object.freeze([...this.log])
  330. return this.eventsSnapshot
  331. }
  332. /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
  333. get seq(): number {
  334. return this.log.length
  335. }
  336. /**
  337. * Append one typed event to the log and synchronously notify observers via
  338. * the store-owned, module-private publication hooks. The hot path never blocks
  339. * on I/O — persistence plugins buffer asynchronously. Once the event enters
  340. * the log, the append is committed: observer failures are logged and
  341. * contained per listener, so they do not change the return value or prevent
  342. * later listeners from observing the same accepted event.
  343. *
  344. * @param type - The event type (key of {@link SessionEventMap}).
  345. * @param data - The event payload; must be JSON-serializable.
  346. * @param opts - Surface metadata: `surfaceOp` controls how the event enters
  347. * the ordered surface; `sourceEventSeqs` records provenance (the seq
  348. * numbers of events this one derives from). REQUIRED for
  349. * {@link SurfaceEventType} events (every message-producing event must
  350. * declare how it joins the surface, the sole source of derived history) and
  351. * rejected by the compiler for non-surface types like `turn/start` or
  352. * `assistant/chunk`.
  353. * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
  354. * `data` that entered the log, so reading `event.data` back sees the logged
  355. * value, never the caller's still-mutable input.
  356. * @throws if `data` or surface metadata is not losslessly JSON-serializable
  357. * (BigInt, function, symbol, undefined, negative zero, non-finite number,
  358. * circular reference, sparse array, or an exotic object such as
  359. * Map/Set/Date/class instance), or when the candidate violates the
  360. * canonical surface contract (marker shape and eligibility, unique
  361. * earlier provenance, positional replacement validity, and complete
  362. * shadowed-node coverage). One recursive pass reads, validates, and
  363. * copies each nested value once, so a stateful getter cannot supply one value
  364. * to validation and another to storage. The event log is the durable source
  365. * of truth, so a bad event fails at the append site rather than later during
  366. * a backend flush. A synchronous internal dispatch validation failure or an
  367. * append reentered while this acceptance/publication boundary is open also
  368. * rejects before the log changes.
  369. */
  370. append<T extends SessionEventType>(
  371. type: T,
  372. data: SessionEventMap[T],
  373. ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : []
  374. ): SessionEvent<T> {
  375. const surfaceOpts: SurfaceIntent | undefined = opts[0]
  376. const surfaceMetadata = {
  377. ...surfaceOpts?.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: surfaceOpts.sourceEventSeqs },
  378. ...surfaceOpts?.surfaceOp === undefined ? {} : { surfaceOp: surfaceOpts.surfaceOp },
  379. }
  380. const dataSnapshot = snapshotJsonValue(data)
  381. if (dataSnapshot === undefined) {
  382. throw new Error(`session event "${type}" carries non-JSON-serializable data`)
  383. }
  384. assertSupportedRequestHeader(type, dataSnapshot, `session event "${type}"`)
  385. const surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata)
  386. if (surfaceMetadataSnapshot === undefined) {
  387. throw new Error(`session event "${type}" carries non-JSON-serializable surface metadata`)
  388. }
  389. const entry = attachments.get(this)
  390. if (entry?.appending) {
  391. throw new Error('session append cannot reenter while another append is being published')
  392. }
  393. const event = deepFreeze({
  394. type,
  395. seq: this.log.length,
  396. time: Date.now(),
  397. data: dataSnapshot,
  398. ...(surfaceMetadataSnapshot as { surfaceOp?: unknown; sourceEventSeqs?: unknown }),
  399. } as unknown as SessionEvent<T>)
  400. this.surfaceManager.validateNext(event as SessionEvent)
  401. if (entry !== undefined) entry.appending = true
  402. try {
  403. let callbacks: SessionCallback[] | undefined
  404. const callbackArgs: unknown[] = [this, event]
  405. if (entry !== undefined) {
  406. callbacks = collectSessionCallbacks(entry.emitCtx, [entry.carrier, 'session/event', ...callbackArgs])
  407. }
  408. this.log.push(event as SessionEvent)
  409. this.eventsSnapshot = undefined
  410. if (callbacks !== undefined && entry !== undefined) {
  411. invokeContainedSessionObservers(entry.emitCtx, 'session/event', entry.id, callbackArgs, callbacks)
  412. }
  413. return event
  414. } finally {
  415. if (entry !== undefined) {
  416. entry.appending = false
  417. if (entry.detachRequested && !entry.announcing && !entry.outOfBand) entry.detach()
  418. }
  419. }
  420. }
  421. /** Cached fold of the request-header events — see {@link requestHeader}. */
  422. private headerFold: EpochHeader | undefined
  423. /** Log position (events consumed) the header fold has reached. */
  424. private headerFoldSeq = 0
  425. /**
  426. * The {@link EpochHeader} in force after the log's last header event — the
  427. * header the NEXT request will be compared against — or undefined before
  428. * the first `request/header` snapshot. The live, incrementally-maintained
  429. * form of `foldRequestHeader(session.events)`: each header event is folded
  430. * once, when first seen, so a per-step read costs O(new events).
  431. * @returns the folded header, or undefined when no header event exists yet.
  432. */
  433. requestHeader(): EpochHeader | undefined {
  434. if (this.headerFoldSeq < this.log.length) {
  435. // Frozen on update: the fold is session state exposed by reference — a
  436. // consumer mutating it in place (instead of building a replacement)
  437. // would desync every later comparison against the log, so mutation
  438. // throws instead.
  439. this.headerFold = deepFreeze(foldRequestHeader(this.log.slice(this.headerFoldSeq), this.headerFold))
  440. this.headerFoldSeq = this.log.length
  441. }
  442. return this.headerFold
  443. }
  444. /** The derived-message cache: frozen projections, extended per unseen node. */
  445. private derived: Message[] = []
  446. /** Surface position (nodes projected) the cache has reached. */
  447. private derivedNodes = 0
  448. /** {@link SurfaceManager.replaceGeneration} the cache was built under. */
  449. private derivedGeneration = 0
  450. /**
  451. * Derive the LLM message history by walking the ordered sequences of
  452. * message-producing events maintained by `surfaceOp` markers. The
  453. * surface is the single source of derived history: every message-producing
  454. * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
  455. * turn boundary) is correctly absent, and a compaction `replace` deletes the
  456. * shadowed nodes from the derivation. The projection rules are
  457. * {@link deriveEventMessage}, folded per node.
  458. *
  459. * CACHED: each surface node is projected exactly once, when first seen — a
  460. * call costs O(new nodes), and a surface rewrite (a `replace`;
  461. * {@link SessionSurface.replaceGeneration}) rebuilds. The returned array is
  462. * a fresh snapshot per call (later appends never grow an array a caller
  463. * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
  464. * Their content reuses the already frozen durable event data, so the cache
  465. * needs no second deep clone and consumers still cannot mutate the log.
  466. * @returns a fresh array of the shared, frozen derived history.
  467. */
  468. deriveMessages(): Message[] {
  469. const surface = this.surface
  470. const nodes = surface.nodes
  471. const generation = surface.replaceGeneration
  472. if (generation !== this.derivedGeneration) {
  473. this.derived = []
  474. this.derivedNodes = 0
  475. this.derivedGeneration = generation
  476. }
  477. for (const seq of nodes.slice(this.derivedNodes)) {
  478. // Surface sequences are built from this.log — seq is always a valid
  479. // index by construction. The non-null assertion expresses that invariant.
  480. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  481. const msg = this.deriveEventMessage(this.log[seq]!)
  482. // A surface node is one of the five message-producing types, but an
  483. // empty-content assistant/message (a max-tokens step that hosts only
  484. // usage) derives to null and must not enter the transcript.
  485. if (msg) this.derived.push(deepFreeze(msg))
  486. }
  487. this.derivedNodes = nodes.length
  488. return [...this.derived]
  489. }
  490. /**
  491. * Project a single event into the LLM message it derives to, or null when
  492. * it produces none — a non-surface event (chunk, boundary, log-only record)
  493. * or an empty-content assistant/message (which exists only to host usage).
  494. * The per-node pure function {@link deriveMessages} folds over the surface;
  495. * an external reconstructor (or the dev invariant) folds the same function
  496. * over a log prefix's surface to rebuild the exact messages any request was
  497. * built from (the reconstructability Agent Note). The returned message wrapper is
  498. * fresh; its content reuses the logged event's already deep-frozen durable
  499. * data, so changing the wrapper cannot rewrite the log and changing content
  500. * throws.
  501. * @param event - the event to project.
  502. * @returns the derived message, or null when the event produces none.
  503. */
  504. deriveEventMessage(event: SessionEvent): Message | null {
  505. // Intentionally non-exhaustive: only message-producing events derive
  506. // history; turn/step boundaries, chunks, usage, and errors are
  507. // trace/replay data.
  508. switch (event.type) {
  509. // Ordinary prompts, injected context, and mid-turn steering project
  510. // identically in user role: the event's model-facing content stays
  511. // verbatim. A prompt envelope is model-hidden display metadata; its
  512. // prefix bytes are already present in content. The message's `source`/`meta`
  513. // and steering's `turn` are also log-only. Do NOT
  514. // re-add per-type framing (e.g. `<context>`/`<steering>`) here: framing is
  515. // caller-owned — a producer bakes it into `content`, as workspace-context
  516. // does with `<system-reminder>` — or, if reintroduced, must be driven by
  517. // the event `meta` map and a dedicated renderer, keeping this projection a
  518. // verbatim pass-through. See the deferred design note in
  519. // ../../../../.agents/notes/implemented/simplification/2026-07-20-unwrap-injected-content-envelopes.md
  520. case 'user/message':
  521. case 'steering/message': {
  522. return { role: 'user', content: event.data.content }
  523. }
  524. case 'assistant/message': {
  525. // Skip an empty-content assistant/message: it exists only to host a
  526. // max-tokens step's usage and must not inject a content-less assistant
  527. // turn into the provider transcript.
  528. if (event.data.content.length === 0) return null
  529. return { role: 'assistant', content: event.data.content, provenance: event.data.provenance }
  530. }
  531. case 'tool/result': {
  532. const { callId, content, isError } = event.data
  533. return {
  534. role: 'user',
  535. content: [{ type: 'tool-result', toolCallId: callId, content, isError }],
  536. }
  537. }
  538. default:
  539. // A non-surface event (boundary, chunk, log-only record) projects to
  540. // no message. Merge-extensible union: no assertNever here.
  541. return null
  542. }
  543. }
  544. }
  545. /** A fork source: either the live session object or its live store id. */
  546. export type SessionForkSource = Session | SessionId
  547. /**
  548. * Rejection codes for session forking: the fork source id is unknown to the
  549. * live store (`SESSION_NOT_FOUND`) or names a session object that is not the
  550. * store's live instance (`SESSION_NOT_LIVE`); the requested child id is
  551. * already taken (`SESSION_ALREADY_EXISTS`); the boundary is not a contiguous
  552. * existing seq (`INVALID_BOUNDARY`); or the boundary event is not a
  553. * `turn/end` — a fork must cut on a closed turn (`OPEN_TURN`).
  554. */
  555. export type SessionForkErrorCode =
  556. | 'SESSION_NOT_FOUND'
  557. | 'SESSION_NOT_LIVE'
  558. | 'SESSION_ALREADY_EXISTS'
  559. | 'INVALID_BOUNDARY'
  560. | 'OPEN_TURN'
  561. /** Typed error for session fork rejections. */
  562. export class SessionForkError extends Error {
  563. constructor(message: string, public readonly code: SessionForkErrorCode) {
  564. super(message)
  565. this.name = 'SessionForkError'
  566. }
  567. }
  568. /**
  569. * In-memory session store (`ctx.sessions`).
  570. *
  571. * Persistence is intentionally not implemented here — persistence plugins
  572. * subscribe to `session/event` and flush on `session/flush` / dispose.
  573. */
  574. export class SessionStore extends Service {
  575. private store = new Map<SessionId, SessionEntry>()
  576. private counter = 0
  577. constructor(ctx: Context) {
  578. super(ctx, 'sessions')
  579. }
  580. /**
  581. * Create a session owned by the calling fiber: disposing that fiber stops
  582. * event notification and removes the session from the store. `options.seed`
  583. * populates the session with a copy of those events (replay/fork);
  584. * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
  585. * and parent lineage, and delegation depth) as the immutable
  586. * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
  587. *
  588. * For an agent whose session must be torn down IN ORDER with its loop (so the
  589. * loop's final flush is captured before the store attachment ends), do NOT use this
  590. * — fold the session lifecycle into the agent's own effect via
  591. * {@link prepare} + {@link enter} + {@link announce} (see
  592. * `dsh-agent-loop`'s creation transaction).
  593. *
  594. * @param id - the session id; omitted, the store mints `session-<n>`.
  595. * @param options - seed events and/or creation metadata for the header.
  596. * @returns the live session, already entered and announced.
  597. * @throws if a session with `id` already exists, metadata is not a plain
  598. * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
  599. * non-absolute path (storage backends key directories off it).
  600. */
  601. create(id?: SessionId, options?: CreateSessionOptions): Session {
  602. const session = this.prepare(id, options)
  603. // Single effect owned by the calling fiber. Yield the detach BEFORE
  604. // announcing so a throwing `session/created` listener rolls the attach back
  605. // (the generator effect disposes already-yielded disposers on a throw)
  606. // instead of leaking the store entry and its publication hooks.
  607. this.ctx.effect(function* (this: SessionStore) {
  608. yield this.enter(session)
  609. this.announce(session)
  610. }.bind(this), 'sessions.create()')
  611. return session
  612. }
  613. /**
  614. * Build a session WITHOUT entering it into the store — validate the id/cwd and
  615. * construct the {@link Session} (with its immutable {@link SessionHeader}).
  616. * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
  617. * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
  618. * effect so a fiber unload tears the session + agent down as a single ORDERED
  619. * chain rather than as racing sibling effects — which would remove the publication hooks
  620. * before the loop's closing `session/flush`, dropping the closing events.
  621. *
  622. * @param id - the session id; omitted, the store mints `session-<n>`.
  623. * @param options - seed events and/or creation metadata for the header.
  624. * @returns the constructed session, NOT yet in the store.
  625. * @throws if a session with `id` already exists, metadata is not a plain
  626. * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
  627. * non-absolute path.
  628. */
  629. prepare(id?: SessionId, options?: CreateSessionOptions): Session {
  630. let sessionId: SessionId
  631. if (id === undefined) {
  632. do sessionId = SessionId(`session-${++this.counter}`)
  633. while (this.store.has(sessionId))
  634. } else {
  635. sessionId = SessionId(id)
  636. }
  637. if (this.store.has(sessionId)) throw new Error(`session "${sessionId}" already exists`)
  638. const seed = options?.seed
  639. const meta = options?.meta
  640. const header: SessionHeader = {
  641. version: SESSION_FORMAT_VERSION,
  642. id: sessionId,
  643. createdAt: meta?.createdAt ?? Date.now(),
  644. ...meta?.cwd === undefined ? {} : { cwd: meta.cwd },
  645. ...meta?.parentSession === undefined ? {} : { parentSession: meta.parentSession },
  646. ...meta?.seedLength === undefined ? {} : { seedLength: meta.seedLength },
  647. ...meta?.delegationDepth === undefined ? {} : { delegationDepth: meta.delegationDepth },
  648. }
  649. return new Session(sessionId, seed, header)
  650. }
  651. /**
  652. * Enter a {@link prepare}d session into the store: install the module-private
  653. * append publication hooks and add it to the store. Returns the DETACH
  654. * disposer (hooks + store removal). Does NOT emit `session/created` —
  655. * the caller yields this disposer inside its effect and THEN calls
  656. * {@link announce}, so a throwing `session/created` listener rolls the attach
  657. * back instead of leaking it.
  658. *
  659. * Re-checks the id for a duplicate: `prepare` and `enter` are public
  660. * cross-package primitives and a caller may interleave arbitrary work (or
  661. * another create) between them, so a stale prepared session must NOT overwrite
  662. * a live store entry of the same id — its detach disposer would later delete
  663. * the REAL session. The {@link create} convenience and the agent factory call
  664. * the two back-to-back so they never trip this, but the public seam cannot
  665. * assume that.
  666. *
  667. * @param session - a {@link prepare}d session not yet in the store.
  668. * @returns the detach disposer (publication hooks + store removal). When called from
  669. * a synchronous `session/created` listener, removal and disposal wait until
  670. * that creation dispatch unwinds.
  671. * @throws if a session with this id is already in the store.
  672. */
  673. enter(session: Session): () => void {
  674. const id = session.id
  675. const carrier = scopeTarget(session, scopeOf(this.ctx))
  676. // This is the authoritative collision boundary after arbitrary unpublished
  677. // preparation. Only one exact same-id transaction can publish.
  678. if (this.store.has(id)) throw new Error(`session "${id}" already exists`)
  679. if (attachments.has(session)) throw new Error(`session "${id}" is already attached to a store`)
  680. const entry: SessionEntry = {
  681. id,
  682. session,
  683. carrier,
  684. emitCtx: this.ctx,
  685. announced: false,
  686. announcing: false,
  687. appending: false,
  688. outOfBand: false,
  689. detachRequested: false,
  690. detach: () => { this.detachEntered(entry) },
  691. }
  692. this.store.set(id, entry)
  693. attachments.set(session, entry)
  694. let entered = true
  695. const detach = (): void => {
  696. if (!entered) return
  697. entered = false
  698. // A lifecycle listener may own the advanced detach capability. Keep the
  699. // entry and its publication hooks live until synchronous creation or append
  700. // publication unwinds, then publish the paired disposal edge.
  701. if (entry.announcing || entry.appending || entry.outOfBand) {
  702. entry.detachRequested = true
  703. return
  704. }
  705. entry.detach()
  706. }
  707. return detach
  708. }
  709. /** Remove one exact entered session and emit its paired disposal when announced. */
  710. private detachEntered(entry: SessionEntry): void {
  711. entry.detachRequested = false
  712. // A stale capability cannot remove observers or storage belonging to a
  713. // later same-id lifecycle.
  714. /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
  715. if (this.store.get(entry.id) !== entry) return
  716. this.store.delete(entry.id)
  717. attachments.delete(entry.session)
  718. if (entry.announced) this.emitDisposed(entry)
  719. }
  720. /** Emit `session/created` exactly once for an {@link enter}ed session (with
  721. * the carrier {@link enter} captured). Separate from {@link enter} so the
  722. * caller can yield the detach disposer first (rollback safety — see
  723. * {@link enter}).
  724. * @param session - the entered session to announce to listeners.
  725. * @throws if the session is not live or its announcement already began,
  726. * including a reentrant call from a creation listener. */
  727. announce(session: Session): void {
  728. const entry = this.liveEntryFor(session)
  729. if (entry.announced || entry.announcing) {
  730. throw new Error(`session "${entry.id}" was already announced`)
  731. }
  732. // Mark before emit: Cordis emit may deliver to earlier listeners and then
  733. // throw. Rollback must still pair that partial creation with disposal, and
  734. // a listener cannot recursively create a second lifecycle edge.
  735. entry.announced = true
  736. const callbackArgs: unknown[] = [session]
  737. entry.announcing = true
  738. try {
  739. const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/created', session])
  740. for (const callback of callbacks) {
  741. // Synchronous throws intentionally propagate and veto publication; the
  742. // yielded detach then emits the paired disposal edge. An async function
  743. // is nevertheless assignable to a void listener, so observe its returned
  744. // promise: rejection is too late to roll back and must be logged instead
  745. // of becoming unhandled.
  746. const returned: unknown = callback(...callbackArgs)
  747. void Promise.resolve(returned).catch((error: unknown) => {
  748. this.ctx.logger.warn(`session "${entry.id}": session/created listener rejected: ${String(error)}`)
  749. })
  750. }
  751. } finally {
  752. entry.announcing = false
  753. if (entry.detachRequested && !entry.appending && !entry.outOfBand) entry.detach()
  754. }
  755. }
  756. /** Emit the paired teardown notification with per-listener containment. */
  757. private emitDisposed(entry: SessionEntry): void {
  758. const callbackArgs: unknown[] = [entry.session]
  759. try {
  760. const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/disposed', entry.session])
  761. invokeContainedSessionObservers(this.ctx, 'session/disposed', entry.id, callbackArgs, callbacks)
  762. } catch (error: unknown) {
  763. this.ctx.logger.warn(`session "${entry.id}": session/disposed dispatch threw: ${String(error)}`)
  764. }
  765. }
  766. /**
  767. * Dispatch the awaited `session/flush` durability checkpoint for `session`,
  768. * with the carrier captured at {@link enter}. THE flush entry point: the
  769. * store owns the carrier, so callers (the loop's turn-end checkpoint, idle
  770. * injection, teardown drains) must come through here rather than dispatch a
  771. * raw `ctx.parallel('session/flush', …)` — one owner, one spelling, and the
  772. * scoped-dispatch invariant can pin it.
  773. * @param session - the session whose buffered events must reach durable storage.
  774. * @returns resolves when every flush listener has settled; after all settle,
  775. * rejects with the first registered listener failure if any listener failed.
  776. */
  777. async flush(session: Session): Promise<void> {
  778. const { carrier } = this.liveEntryFor(session)
  779. const callbackArgs: unknown[] = [session]
  780. const callbacks = collectSessionCallbacks(this.ctx, [carrier, 'session/flush', session])
  781. const results = await Promise.allSettled(callbacks.map((callback) => {
  782. try {
  783. return callback(...callbackArgs)
  784. } catch (error: unknown) {
  785. // Preserve the listener's exact rejection value; flush is a caller-owned
  786. // failure boundary, and Cordis listeners may throw arbitrary values.
  787. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
  788. return Promise.reject(error)
  789. }
  790. }))
  791. const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected')
  792. if (failure !== undefined) throw failure.reason
  793. }
  794. /**
  795. * Append one plugin-declared log-only event without borrowing the agent
  796. * loop's lifecycle. An open turn receives the event directly and remains
  797. * responsible for its ordinary checkpoint. A closed log receives one
  798. * zero-step turn around the event, followed by an awaited flush.
  799. *
  800. * Once the synthetic `turn/start` commits, this method always attempts its
  801. * matching `turn/end` and flush, including when the target append fails.
  802. * Detachment requested by an event or flush listener is deferred until that
  803. * sequence settles, so publication cannot switch from a live scoped session
  804. * to an unobserved bare `Session` halfway through the update.
  805. *
  806. * @param session - exact live session that owns the target log.
  807. * @param type - event type opted into {@link OutOfBandSessionEventMap} by its owner.
  808. * @param data - typed JSON payload for the target event.
  809. * @param trigger - plugin-owned turn trigger used only when the log is closed.
  810. * @returns the accepted target event with its assigned sequence and timestamp.
  811. * @throws when the session is detached, another out-of-band append is active,
  812. * event acceptance fails, the synthetic turn cannot close, or flushing fails.
  813. */
  814. async appendOutOfBand<T extends OutOfBandSessionEventType>(
  815. session: Session,
  816. type: T,
  817. data: SessionEventMap[T],
  818. trigger: TurnTrigger,
  819. ): Promise<SessionEvent<T>> {
  820. const entry = this.liveEntryFor(session)
  821. if (entry.outOfBand) {
  822. throw new Error(`session "${session.id}" already has an out-of-band append in progress`)
  823. }
  824. entry.outOfBand = true
  825. // `T` is excluded from SurfaceEventType by OutOfBandSessionEventType, but
  826. // TypeScript does not reduce Session.append's conditional rest parameter
  827. // through a generic intersection. Preserve that proven two-argument call
  828. // shape without widening the public Session.append overload.
  829. const appendLogOnly = session.append.bind(session) as unknown as <K extends OutOfBandSessionEventType>(
  830. eventType: K,
  831. eventData: SessionEventMap[K],
  832. ) => SessionEvent<K>
  833. try {
  834. const lastBoundary = session.events.findLast(event => event.type === 'turn/start' || event.type === 'turn/end')
  835. if (lastBoundary?.type === 'turn/start') {
  836. return appendLogOnly(type, data)
  837. }
  838. const lastStart = session.events.findLast(event => event.type === 'turn/start')
  839. const turn = (lastStart?.data.turn ?? 0) + 1
  840. let accepted: SessionEvent<T> | undefined
  841. let failure: unknown
  842. let opened = false
  843. try {
  844. session.append('turn/start', { turn, trigger })
  845. opened = true
  846. accepted = appendLogOnly(type, data)
  847. } catch (error: unknown) {
  848. failure = error
  849. } finally {
  850. if (opened) {
  851. // The only target types admitted by OutOfBandSessionEventMap are
  852. // log-only plugin events, so the synthetic turn remains open here.
  853. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  854. try {
  855. await this.flush(session)
  856. } catch (error: unknown) {
  857. if (failure === undefined) failure = error
  858. }
  859. }
  860. }
  861. if (failure !== undefined) {
  862. // eslint-disable-next-line @typescript-eslint/only-throw-error -- preserve an arbitrary flush-listener rejection exactly
  863. throw failure
  864. }
  865. /* v8 ignore next -- accepted is assigned unless an append failure was captured above. */
  866. if (accepted === undefined) throw new Error('out-of-band append completed without an accepted event')
  867. return accepted
  868. } finally {
  869. entry.outOfBand = false
  870. if (entry.detachRequested && !entry.announcing && !entry.appending) entry.detach()
  871. }
  872. }
  873. /** Return the exact live entry; detached/prepared objects reject. */
  874. private liveEntryFor(session: Session): SessionEntry {
  875. const entry = attachments.get(session)
  876. if (entry === undefined || this.store.get(entry.id) !== entry) {
  877. throw new Error(`session "${session.id}" is not live in this store`)
  878. }
  879. return entry
  880. }
  881. /**
  882. * Look up a live session.
  883. * @param id - the session id to look up.
  884. * @returns the session, or undefined when no live session has that id.
  885. */
  886. get(id: SessionId): Session | undefined {
  887. return this.store.get(id)?.session
  888. }
  889. /**
  890. * All live sessions, in creation order.
  891. * @returns a fresh array; mutating it does not affect the store.
  892. */
  893. list(): Session[] {
  894. return [...this.store.values()].map(entry => entry.session)
  895. }
  896. /**
  897. * Create a live child session from a turn-enclosed prefix of a live source.
  898. * `boundary` is an inclusive source event seq; omitted means the source's
  899. * current last event. A non-empty selected slice must end at `turn/end`.
  900. *
  901. * @param source - Live source session object or id.
  902. * @param boundary - Inclusive source event seq to fork through; omitted means
  903. * the source's current last event, and omitted on an empty source forks an
  904. * empty child.
  905. * @param childSessionId - Optional child session id; omitted delegates to
  906. * `SessionStore`'s id policy.
  907. * @returns The created live child session.
  908. */
  909. fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Session {
  910. if (childSessionId !== undefined && this.get(childSessionId) !== undefined) {
  911. throw new SessionForkError(`session "${childSessionId}" already exists`, 'SESSION_ALREADY_EXISTS')
  912. }
  913. const liveSource = this._resolveForkSource(source)
  914. const seed = this._forkSeed(liveSource, boundary)
  915. return this.create(childSessionId, {
  916. seed,
  917. meta: {
  918. ...liveSource.header.cwd !== undefined ? { cwd: liveSource.header.cwd } : {},
  919. parentSession: liveSource.id,
  920. seedLength: seed.length,
  921. },
  922. })
  923. }
  924. private _forkSeed(session: Session, requestedBoundary: number | undefined): SessionEvent[] {
  925. const events = session.events
  926. const lastEvent = events.at(-1)
  927. let boundary: number
  928. if (requestedBoundary !== undefined) {
  929. boundary = requestedBoundary
  930. } else {
  931. if (lastEvent === undefined) return []
  932. boundary = lastEvent.seq
  933. }
  934. if (!Number.isSafeInteger(boundary) || boundary < 0) {
  935. throw new SessionForkError(
  936. `fork boundary for session "${session.id}" must be a non-negative safe integer, got ${String(boundary)}`,
  937. 'INVALID_BOUNDARY',
  938. )
  939. }
  940. if (boundary >= events.length) {
  941. const lastSeq = events.at(-1)?.seq
  942. throw new SessionForkError(
  943. `fork boundary ${boundary} does not exist in session "${session.id}" (last seq: ${lastSeq ?? 'none'})`,
  944. 'INVALID_BOUNDARY',
  945. )
  946. }
  947. const boundaryEvent = events[boundary]
  948. if (boundaryEvent === undefined || boundaryEvent.seq !== boundary) {
  949. throw new SessionForkError(
  950. `fork boundary ${boundary} does not match a contiguous event seq in session "${session.id}"`,
  951. 'INVALID_BOUNDARY',
  952. )
  953. }
  954. if (boundaryEvent.type !== 'turn/end') {
  955. throw new SessionForkError(
  956. `fork boundary ${boundary} in session "${session.id}" must be turn/end, got ${boundaryEvent.type}`,
  957. 'OPEN_TURN',
  958. )
  959. }
  960. return events.slice(0, boundary + 1)
  961. }
  962. private _resolveForkSource(source: SessionForkSource): Session {
  963. if (typeof source === 'string') {
  964. const session = this.get(source)
  965. if (session === undefined) throw new SessionForkError(`session "${source}" not found`, 'SESSION_NOT_FOUND')
  966. return session
  967. }
  968. const live = this.get(source.id)
  969. if (live === undefined) {
  970. throw new SessionForkError(`session "${source.id}" not found`, 'SESSION_NOT_FOUND')
  971. }
  972. if (live !== source) throw new SessionForkError(`session "${source.id}" is not the live store instance`, 'SESSION_NOT_LIVE')
  973. return source
  974. }
  975. }
  976. export default SessionStore