index.ts 50 KB

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