index.ts 46 KB

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