index.ts 57 KB

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