index.ts 54 KB

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