index.ts 51 KB

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