index.ts 51 KB

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