index.ts 51 KB

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