index.ts 52 KB

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