index.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /**
  2. * Event-sourced session service: append-only session log, in-memory store, and
  3. * the derived LLM message history. Persistence is a plugin concern (subscribe
  4. * to `session/event`, drain on `session/flush`).
  5. *
  6. * @module @deepseek-ai/dsh-session
  7. */
  8. import { Context, Service } from 'cordis'
  9. import { isAbsolute } from 'node:path'
  10. import { deepFreeze } from '@deepseek-ai/dsh-llm'
  11. import type { ContentBlock, Message, MessageSource } from '@deepseek-ai/dsh-llm'
  12. import { SESSION_FORMAT_VERSION, SessionId } from './types.ts'
  13. import type { CreateSessionOptions, EpochHeader, SessionEvent, SessionEventMap, SessionEventType, SessionHeader, SurfaceIntent, SurfaceEventType } from './types.ts'
  14. import { isJsonValue } from './json.ts'
  15. import { SurfaceManager, isSurfaceEligibleType } from './surface.ts'
  16. import { foldRequestHeader } from './request-header.ts'
  17. export * from './types.ts'
  18. export { isJsonValue } from './json.ts'
  19. export type { JsonValue } from './json.ts'
  20. export { interruptedTurnClosers } from './repair.ts'
  21. export type { SurfaceNode } from './surface.ts'
  22. export { isSurfaceEvent, isSurfaceEligibleType } from './surface.ts'
  23. export { isToolPairingBalanced } from './tool-pairing.ts'
  24. export { applyHeaderDelta, canonicalHeader, diffHeader, foldRequestHeader, headerEquals } from './request-header.ts'
  25. declare module 'cordis' {
  26. interface Context {
  27. sessions: SessionStore
  28. }
  29. interface Events {
  30. /**
  31. * A session was created in the store.
  32. * @param session - the session just entered and announced.
  33. * @mode emit
  34. */
  35. 'session/created'(session: Session): void
  36. /**
  37. * An event was appended to a session log (sync, fire-and-forget). This is
  38. * the per-append feed a UI or invariant plugin tails.
  39. * @param session - the session whose log grew.
  40. * @param event - the appended event, exactly as recorded.
  41. * @mode emit
  42. */
  43. 'session/event'(session: Session, event: SessionEvent): void
  44. /**
  45. * Awaited durability checkpoint. The agent loop awaits
  46. * `ctx.parallel('session/flush', session)` at every turn end; persistence
  47. * plugins (JSONL, SQLite) drain their write-behind buffers here and on
  48. * fiber dispose. Awaited (parallel), not a waterfall: every listener runs
  49. * and the loop waits for all of them, but none can veto.
  50. * @param session - the session whose buffered events must reach durable storage.
  51. * @mode parallel
  52. */
  53. 'session/flush'(session: Session): Promise<void> | void
  54. }
  55. }
  56. /**
  57. * Renders a `context/message` or `steering/message` event as a tagged
  58. * synthetic user-role message (the system-reminder pattern: zero adapter
  59. * burden, models distinguish it from real user prompts by the envelope).
  60. *
  61. * Live-adapter review has validated the tagged-envelope rendering against
  62. * current DeepSeek behavior; provider-specific mismatches belong in that
  63. * adapter, not in the canonical session vocabulary.
  64. */
  65. function renderTagged(tag: string, content: ContentBlock[], source: MessageSource): ContentBlock[] {
  66. const open = `<${tag} source=${JSON.stringify(source.kind)}>`
  67. const close = `</${tag}>`
  68. return [
  69. { type: 'text', text: open },
  70. ...content,
  71. { type: 'text', text: close },
  72. ]
  73. }
  74. /**
  75. * An event-sourced session: an append-only log of {@link SessionEvent}s.
  76. *
  77. * Plain class (not a Service) — create instances via `ctx.sessions.create()`.
  78. * Seeding with an existing event log replays/forks a session.
  79. */
  80. export class Session {
  81. private log: SessionEvent[] = []
  82. /** Set by the store so appends are observable; undefined when detached. */
  83. onAppend: ((event: SessionEvent) => void) | undefined
  84. /**
  85. * Derived surface — a cached linked list of message-producing events.
  86. * Lazily rebuilt from `surfaceOp` markers in the log; processes only new
  87. * events (delta) on each access — the log is append-only, so prior events
  88. * never change.
  89. * `append`. Undefined until first accessed (including after fork/seed).
  90. */
  91. private _surface: SurfaceManager | undefined
  92. /** The surface linked list over this session's event log. */
  93. get surface(): SurfaceManager {
  94. if (!this._surface) this._surface = new SurfaceManager(this.log)
  95. return this._surface
  96. }
  97. /**
  98. * Immutable creation metadata (format version, cwd, lineage, seed boundary).
  99. * Supplied by the store via `ctx.sessions.create()`. When a `Session` is
  100. * constructed bare (tests, ad-hoc replay), a minimal header is synthesized
  101. * (stamped with the current {@link SESSION_FORMAT_VERSION}) so
  102. * `session.header` is always present. Kept out of the event log — it is a
  103. * storage concern, not replayable conversation state.
  104. */
  105. readonly header: SessionHeader
  106. constructor(public readonly id: SessionId, seed?: SessionEvent[], header?: SessionHeader) {
  107. if (seed) {
  108. // Validate the seed to the SAME invariants `append` enforces, so a
  109. // replay/fork (`ctx.sessions.create(id, { seed })`) cannot construct a
  110. // live log that no persistence backend could store: each event's `data`
  111. // must be JSON-serializable, and `seq` must be contiguous from 0 (the
  112. // `seq = log.length` contract the whole system relies on). Without this,
  113. // a bad seed would surface only later as a backend rejection or a silent
  114. // divergence between the live log and disk.
  115. seed.forEach((event, index) => {
  116. if (event.seq !== index) {
  117. throw new Error(`seed event at index ${index} has seq ${event.seq} (expected ${index}); seed must be contiguous from 0`)
  118. }
  119. if (!isJsonValue(event.data)) {
  120. throw new Error(`seed event "${event.type}" (seq ${event.seq}) carries non-JSON-serializable data`)
  121. }
  122. // Surface-eligible events MUST carry a surfaceOp marker — the surface is
  123. // the sole source of derived history, so a marker-less message event
  124. // would load fine yet vanish from deriveMessages(). `append` enforces
  125. // this at compile time via its typed overload; a seed arrives as raw
  126. // SessionEvent[] (replay/fork/load), bypassing that, so re-check at
  127. // runtime here rather than silently resuming with empty history.
  128. if (isSurfaceEligibleType(event.type)
  129. && (event as SessionEvent<SurfaceEventType>).surfaceOp === undefined) {
  130. throw new Error(`seed event "${event.type}" (seq ${event.seq}) is surface-eligible but carries no surfaceOp marker`)
  131. }
  132. })
  133. // Deep-clone each seed event, NOT just the array: the seed events and
  134. // their `data` are still owned by the caller (or the source session of a
  135. // fork), so keeping the references would let a post-create mutation of the
  136. // original rewrite this session's durable log — or reintroduce a
  137. // non-JSON-serializable value AFTER the validation above. Snapshotting at
  138. // the boundary makes `session.events` independent and keeps it equal to
  139. // what was validated. Serializability is guaranteed by the check above, so
  140. // structuredClone can never hit a non-cloneable value here.
  141. this.log = seed.map(event => structuredClone(event))
  142. }
  143. this.header = header ?? { version: SESSION_FORMAT_VERSION, id, createdAt: Date.now() }
  144. }
  145. /**
  146. * The append-only event log, exposed live by reference (readonly-typed, not
  147. * a snapshot): later appends are visible through the same array.
  148. */
  149. get events(): readonly SessionEvent[] {
  150. return this.log
  151. }
  152. /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
  153. get seq(): number {
  154. return this.log.length
  155. }
  156. /**
  157. * Append one typed event to the log and synchronously notify observers via
  158. * `onAppend`. The hot path never blocks on I/O — persistence plugins buffer
  159. * asynchronously.
  160. *
  161. * @param type - The event type (key of {@link SessionEventMap}).
  162. * @param data - The event payload; must be JSON-serializable.
  163. * @param opts - Surface metadata: `surfaceOp` controls how the event enters
  164. * the surface linked list; `sourceEventSeqs` records provenance (the seq
  165. * numbers of events this one derives from). REQUIRED for
  166. * {@link SurfaceEventType} events (every message-producing event must
  167. * declare how it joins the surface, the sole source of derived history) and
  168. * rejected by the compiler for non-surface types like `turn/start` or
  169. * `assistant/chunk`.
  170. * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
  171. * `data` that entered the log, so reading `event.data` back sees the logged
  172. * value, never the caller's still-mutable input.
  173. * @throws if `data` is not losslessly JSON-serializable (BigInt, function,
  174. * symbol, undefined, non-finite number, circular ref, or an exotic object
  175. * like Map/Set/Date). The event log is the durable source of truth, so this
  176. * invariant is enforced at the source — a bad event never enters the log,
  177. * keeping `session.events` always equal to what a backend can persist. The
  178. * throw surfaces at the buggy caller's append site, not asynchronously in a
  179. * backend flush.
  180. */
  181. append<T extends SessionEventType>(
  182. type: T,
  183. data: SessionEventMap[T],
  184. ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : []
  185. ): SessionEvent<T> {
  186. if (!isJsonValue(data)) {
  187. throw new Error(`session event "${type}" carries non-JSON-serializable data`)
  188. }
  189. const surfaceOpts: SurfaceIntent | undefined = opts[0]
  190. // Surface-eligible events MUST carry a surfaceOp marker — the surface is the
  191. // sole source of derived history, so a marker-less message event would be
  192. // logged yet vanish from deriveMessages(). The typed `opts` overload makes
  193. // the marker mandatory only when `T` is a SPECIFIC SurfaceEventType literal;
  194. // when `T` widens to the SessionEventType union (a caller iterating raw
  195. // events: `for (const e of log) append(e.type, e.data)`), the conditional
  196. // rest collapses to optional and the compiler stops enforcing it. Re-check
  197. // at runtime so that loophole can't silently drop history.
  198. if (isSurfaceEligibleType(type) && surfaceOpts?.surfaceOp === undefined) {
  199. throw new Error(`session event "${type}" is surface-eligible and requires a surfaceOp marker`)
  200. }
  201. // Snapshot `data` into the log, NOT the caller's reference: the validation
  202. // above proves it is JSON-serializable AT THIS MOMENT, but the caller still
  203. // owns the object and could mutate it afterwards (before a persistence
  204. // flush, or permanently in the in-memory history) — making `session.events`
  205. // diverge from the value that passed validation, or reintroducing a
  206. // non-serializable value. Cloning here keeps the log equal to what was
  207. // validated. structuredClone is safe because serializability was just
  208. // checked. The returned event carries the SAME snapshot, so a caller reading
  209. // back `event.data` sees the logged value, not its own mutable input.
  210. //
  211. // Surface metadata is snapshot separately: sourceEventSeqs (number[] —
  212. // primitives, so array spread is a complete copy) and surfaceOp (a string
  213. // primitive, or cloned if it's a replace object).
  214. // Build the event shape with conditional surface fields via spreading.
  215. // The result is cast through `unknown` because the conditional spreads
  216. // produce an intersection type that the assignability checker can't
  217. // narrow to a specific discriminated-union member when T is generic.
  218. // This is a safe internal boundary: data was validated above, and
  219. // surface metadata was snapshot from primitive/clone-safe values.
  220. const event = {
  221. type,
  222. seq: this.log.length,
  223. time: Date.now(),
  224. data: structuredClone(data),
  225. ...surfaceOpts?.sourceEventSeqs !== undefined ? { sourceEventSeqs: [...surfaceOpts.sourceEventSeqs] } : {},
  226. ...surfaceOpts?.surfaceOp !== undefined ? {
  227. surfaceOp: typeof surfaceOpts.surfaceOp === 'string' ? surfaceOpts.surfaceOp : structuredClone(surfaceOpts.surfaceOp),
  228. } : {},
  229. } as unknown as SessionEvent<T>
  230. this.log.push(event as unknown as SessionEvent)
  231. this.onAppend?.(event as unknown as SessionEvent)
  232. return event
  233. }
  234. /** Cached fold of the request-header events — see {@link requestHeader}. */
  235. private headerFold: EpochHeader | undefined
  236. /** Log position (events consumed) the header fold has reached. */
  237. private headerFoldSeq = 0
  238. /**
  239. * The {@link EpochHeader} in force after the log's last header event — the
  240. * header the NEXT request will be compared against — or undefined before
  241. * the first `request/header` snapshot. The live, incrementally-maintained
  242. * form of `foldRequestHeader(session.events)`: each header event is folded
  243. * once, when first seen, so a per-step read costs O(new events).
  244. * @returns the folded header, or undefined when no header event exists yet.
  245. */
  246. requestHeader(): EpochHeader | undefined {
  247. if (this.headerFoldSeq < this.log.length) {
  248. // Frozen on update: the fold is session state exposed by reference — a
  249. // consumer mutating it in place (instead of building a replacement)
  250. // would desync every later comparison against the log, so mutation
  251. // throws instead.
  252. this.headerFold = deepFreeze(foldRequestHeader(this.log.slice(this.headerFoldSeq), this.headerFold))
  253. this.headerFoldSeq = this.log.length
  254. }
  255. return this.headerFold
  256. }
  257. /** The derived-message cache: frozen projections, extended per unseen node. */
  258. private derived: Message[] = []
  259. /** Surface position (nodes projected) the cache has reached. */
  260. private derivedNodes = 0
  261. /** {@link SurfaceManager.replaceGeneration} the cache was built under. */
  262. private derivedGeneration = 0
  263. /**
  264. * Derive the LLM message history by walking the session surface — the linked
  265. * list of message-producing events maintained by `surfaceOp` markers. The
  266. * surface is the single source of derived history: every message-producing
  267. * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
  268. * turn boundary) is correctly absent, and a compaction `replace` deletes the
  269. * shadowed nodes from the derivation. The projection rules are
  270. * {@link deriveEventMessage}, folded per node.
  271. *
  272. * CACHED: each surface node is projected exactly once, when first seen — a
  273. * call costs O(new nodes), and a surface rewrite (a `replace`;
  274. * {@link SurfaceManager.replaceGeneration}) rebuilds. The returned array is
  275. * a fresh snapshot per call (later appends never grow an array a caller
  276. * already holds); the `Message` objects in it are SHARED and **deep-frozen**
  277. * — cloned once off the log at projection time, so consumers can never
  278. * mutate logged data, and mutation attempts throw instead of silently
  279. * diverging replay from history.
  280. * @returns a fresh array of the shared, frozen derived history.
  281. */
  282. deriveMessages(): Message[] {
  283. const nodes = this.surface.nodes
  284. const generation = this.surface.replaceGeneration
  285. if (generation !== this.derivedGeneration) {
  286. this.derived = []
  287. this.derivedNodes = 0
  288. this.derivedGeneration = generation
  289. }
  290. for (const node of nodes.slice(this.derivedNodes)) {
  291. // Surface nodes are built from this.log — node.seq is always a valid
  292. // index by construction. The non-null assertion expresses that invariant.
  293. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  294. const msg = this.deriveEventMessage(this.log[node.seq]!)
  295. // A surface node is one of the five message-producing types, but an
  296. // empty-content assistant/message (a max-tokens step that hosts only
  297. // usage) derives to null and must not enter the transcript.
  298. if (msg) this.derived.push(deepFreeze(msg))
  299. }
  300. this.derivedNodes = nodes.length
  301. return [...this.derived]
  302. }
  303. /**
  304. * Project a single event into the LLM message it derives to, or null when
  305. * it produces none — a non-surface event (chunk, boundary, log-only record)
  306. * or an empty-content assistant/message (which exists only to host usage).
  307. * The per-node pure function {@link deriveMessages} folds over the surface;
  308. * an external reconstructor (or the dev invariant) folds the same function
  309. * over a log prefix's surface to rebuild the exact messages any request was
  310. * built from (the reconstructability RFC). The returned `content` is
  311. * deep-cloned off the logged event: the log is append-only by contract, so
  312. * no live reference to logged data leaves this boundary.
  313. * @param event - the event to project.
  314. * @returns the derived message, or null when the event produces none.
  315. */
  316. deriveEventMessage(event: SessionEvent): Message | null {
  317. // Intentionally non-exhaustive: only message-producing events derive
  318. // history; turn/step boundaries, chunks, usage, and errors are
  319. // trace/replay data.
  320. switch (event.type) {
  321. case 'user/message': {
  322. return { role: 'user', content: structuredClone(event.data.content) }
  323. }
  324. case 'assistant/message': {
  325. // Skip an empty-content assistant/message: it exists only to host a
  326. // max-tokens step's usage and must not inject a content-less assistant
  327. // turn into the provider transcript.
  328. if (event.data.content.length === 0) return null
  329. return { role: 'assistant', content: structuredClone(event.data.content) }
  330. }
  331. case 'tool/result': {
  332. const { callId, content, isError } = event.data
  333. return {
  334. role: 'user',
  335. content: [{ type: 'tool-result', toolCallId: callId, content: structuredClone(content), isError }],
  336. }
  337. }
  338. case 'context/message': {
  339. const { content, source } = event.data
  340. return { role: 'user', content: renderTagged('context', structuredClone(content), source) }
  341. }
  342. case 'steering/message': {
  343. const { content, source } = event.data
  344. return { role: 'user', content: renderTagged('steering', structuredClone(content), source) }
  345. }
  346. default:
  347. // A non-surface event (boundary, chunk, log-only record) projects to
  348. // no message. Merge-extensible union: no assertNever here.
  349. return null
  350. }
  351. }
  352. }
  353. /** A fork source: either the live session object or its live store id. */
  354. export type SessionForkSource = Session | SessionId
  355. /**
  356. * Rejection codes for session forking: the fork source id is unknown to the
  357. * live store (`SESSION_NOT_FOUND`) or names a session object that is not the
  358. * store's live instance (`SESSION_NOT_LIVE`); the requested child id is
  359. * already taken (`SESSION_ALREADY_EXISTS`); the boundary is not a contiguous
  360. * existing seq (`INVALID_BOUNDARY`); or the boundary event is not a
  361. * `turn/end` — a fork must cut on a closed turn (`OPEN_TURN`).
  362. */
  363. export type SessionForkErrorCode =
  364. | 'SESSION_NOT_FOUND'
  365. | 'SESSION_NOT_LIVE'
  366. | 'SESSION_ALREADY_EXISTS'
  367. | 'INVALID_BOUNDARY'
  368. | 'OPEN_TURN'
  369. /** Typed error for session fork rejections. */
  370. export class SessionForkError extends Error {
  371. constructor(message: string, public readonly code: SessionForkErrorCode) {
  372. super(message)
  373. this.name = 'SessionForkError'
  374. }
  375. }
  376. /**
  377. * In-memory session store (`ctx.sessions`).
  378. *
  379. * Persistence is intentionally not implemented here — persistence plugins
  380. * subscribe to `session/event` and flush on `session/flush` / dispose.
  381. */
  382. export class SessionStore extends Service {
  383. private store = new Map<SessionId, Session>()
  384. private counter = 0
  385. constructor(ctx: Context) {
  386. super(ctx, 'sessions')
  387. }
  388. /**
  389. * Create a session owned by the calling fiber: disposing that fiber stops
  390. * event notification and removes the session from the store. `options.seed`
  391. * populates the session with a copy of those events (replay/fork);
  392. * `options.meta` attaches creation metadata (validated absolute `cwd`,
  393. * `parentSession` lineage) as the immutable {@link SessionHeader} (the store
  394. * fills `version`/`id`/`createdAt`).
  395. *
  396. * For an agent whose session must be torn down IN ORDER with its loop (so the
  397. * loop's final flush is captured before `onAppend` detaches), do NOT use this
  398. * — fold the session lifecycle into the agent's own effect via
  399. * {@link prepare} + {@link enter} + {@link announce} (see `dsh-agent-loop`'s
  400. * `startOwned`).
  401. *
  402. * @param id - the session id; omitted, the store mints `session-<n>`.
  403. * @param options - seed events and/or creation metadata for the header.
  404. * @returns the live session, already entered and announced.
  405. * @throws if a session with `id` already exists, or if `meta.cwd` is a
  406. * non-absolute path (storage backends key directories off it).
  407. */
  408. create(id?: SessionId, options?: CreateSessionOptions): Session {
  409. const session = this.prepare(id, options)
  410. // Single effect owned by the calling fiber. Yield the detach BEFORE
  411. // announcing so a throwing `session/created` listener rolls the attach back
  412. // (the generator effect disposes already-yielded disposers on a throw)
  413. // instead of leaking the store entry + onAppend.
  414. this.ctx.effect(function* (this: SessionStore) {
  415. yield this.enter(session)
  416. this.announce(session)
  417. }.bind(this), 'sessions.create()')
  418. return session
  419. }
  420. /**
  421. * Build a session WITHOUT entering it into the store — validate the id/cwd and
  422. * construct the {@link Session} (with its immutable {@link SessionHeader}).
  423. * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
  424. * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
  425. * effect so a fiber unload tears the session + agent down as a single ORDERED
  426. * chain rather than as racing sibling effects — which would detach `onAppend`
  427. * before the loop's closing `session/flush`, dropping the closing events.
  428. *
  429. * @param id - the session id; omitted, the store mints `session-<n>`.
  430. * @param options - seed events and/or creation metadata for the header.
  431. * @returns the constructed session, NOT yet in the store.
  432. * @throws if a session with `id` already exists, or if `meta.cwd` is a
  433. * non-absolute path.
  434. */
  435. prepare(id?: SessionId, options?: CreateSessionOptions): Session {
  436. const sessionId = SessionId(id ?? `session-${++this.counter}`)
  437. if (this.store.has(sessionId)) throw new Error(`session "${sessionId}" already exists`)
  438. const cwd = options?.meta?.cwd
  439. if (cwd !== undefined && !isAbsolute(cwd)) {
  440. throw new Error(`session cwd must be an absolute path, got "${cwd}"`)
  441. }
  442. const header: SessionHeader = {
  443. version: SESSION_FORMAT_VERSION,
  444. id: sessionId,
  445. createdAt: options?.meta?.createdAt ?? Date.now(),
  446. ...cwd !== undefined ? { cwd } : {},
  447. ...options?.meta?.parentSession !== undefined ? { parentSession: options.meta.parentSession } : {},
  448. ...options?.meta?.seedLength !== undefined ? { seedLength: options.meta.seedLength } : {},
  449. }
  450. return new Session(sessionId, options?.seed, header)
  451. }
  452. /**
  453. * Enter a {@link prepare}d session into the store: wire `onAppend` →
  454. * `session/event` and add it to the store. Returns the DETACH disposer
  455. * (`onAppend = undefined` + store removal). Does NOT emit `session/created` —
  456. * the caller yields this disposer inside its effect and THEN calls
  457. * {@link announce}, so a throwing `session/created` listener rolls the attach
  458. * back instead of leaking it.
  459. *
  460. * Re-checks the id for a duplicate: `prepare` and `enter` are public
  461. * cross-package primitives and a caller may interleave arbitrary work (or
  462. * another create) between them, so a stale prepared session must NOT overwrite
  463. * a live store entry of the same id — its detach disposer would later delete
  464. * the REAL session. The {@link create} convenience and the agent factory call
  465. * the two back-to-back so they never trip this, but the public seam cannot
  466. * assume that.
  467. *
  468. * @param session - a {@link prepare}d session not yet in the store.
  469. * @returns the detach disposer (`onAppend = undefined` + store removal).
  470. * @throws if a session with this id is already in the store.
  471. */
  472. enter(session: Session): () => void {
  473. if (this.store.has(session.id)) throw new Error(`session "${session.id}" already exists`)
  474. session.onAppend = (event) => { this.ctx.emit('session/event', session, event) }
  475. this.store.set(session.id, session)
  476. return () => {
  477. session.onAppend = undefined
  478. this.store.delete(session.id)
  479. }
  480. }
  481. /** Emit `session/created` for an {@link enter}ed session. Separate from
  482. * {@link enter} so the caller can yield the detach disposer first (rollback
  483. * safety — see {@link enter}).
  484. * @param session - the entered session to announce to listeners. */
  485. announce(session: Session): void {
  486. this.ctx.emit('session/created', session)
  487. }
  488. /**
  489. * Look up a live session.
  490. * @param id - the session id to look up.
  491. * @returns the session, or undefined when no live session has that id.
  492. */
  493. get(id: SessionId): Session | undefined {
  494. return this.store.get(id)
  495. }
  496. /**
  497. * All live sessions, in creation order.
  498. * @returns a fresh array; mutating it does not affect the store.
  499. */
  500. list(): Session[] {
  501. return [...this.store.values()]
  502. }
  503. /**
  504. * Create a live child session from a turn-enclosed prefix of a live source.
  505. * `boundary` is an inclusive source event seq; omitted means the source's
  506. * current last event. A non-empty selected slice must end at `turn/end`.
  507. *
  508. * @param source - Live source session object or id.
  509. * @param boundary - Inclusive source event seq to fork through; omitted means
  510. * the source's current last event, and omitted on an empty source forks an
  511. * empty child.
  512. * @param childSessionId - Optional child session id; omitted delegates to
  513. * `SessionStore`'s id policy.
  514. * @returns The created live child session.
  515. */
  516. fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Session {
  517. if (childSessionId !== undefined && this.get(childSessionId) !== undefined) {
  518. throw new SessionForkError(`session "${childSessionId}" already exists`, 'SESSION_ALREADY_EXISTS')
  519. }
  520. const liveSource = this._resolveForkSource(source)
  521. const seed = this._forkSeed(liveSource, boundary)
  522. return this.create(childSessionId, {
  523. seed,
  524. meta: {
  525. ...liveSource.header.cwd !== undefined ? { cwd: liveSource.header.cwd } : {},
  526. parentSession: liveSource.id,
  527. seedLength: seed.length,
  528. },
  529. })
  530. }
  531. private _forkSeed(session: Session, requestedBoundary: number | undefined): SessionEvent[] {
  532. const events = session.events
  533. const lastEvent = events.at(-1)
  534. let boundary: number
  535. if (requestedBoundary !== undefined) {
  536. boundary = requestedBoundary
  537. } else {
  538. if (lastEvent === undefined) return []
  539. boundary = lastEvent.seq
  540. }
  541. if (!Number.isSafeInteger(boundary) || boundary < 0) {
  542. throw new SessionForkError(
  543. `fork boundary for session "${session.id}" must be a non-negative safe integer, got ${String(boundary)}`,
  544. 'INVALID_BOUNDARY',
  545. )
  546. }
  547. if (boundary >= events.length) {
  548. const lastSeq = events.at(-1)?.seq
  549. throw new SessionForkError(
  550. `fork boundary ${boundary} does not exist in session "${session.id}" (last seq: ${lastSeq ?? 'none'})`,
  551. 'INVALID_BOUNDARY',
  552. )
  553. }
  554. const boundaryEvent = events[boundary]
  555. if (boundaryEvent === undefined || boundaryEvent.seq !== boundary) {
  556. throw new SessionForkError(
  557. `fork boundary ${boundary} does not match a contiguous event seq in session "${session.id}"`,
  558. 'INVALID_BOUNDARY',
  559. )
  560. }
  561. if (boundaryEvent.type !== 'turn/end') {
  562. throw new SessionForkError(
  563. `fork boundary ${boundary} in session "${session.id}" must be turn/end, got ${boundaryEvent.type}`,
  564. 'OPEN_TURN',
  565. )
  566. }
  567. return events.slice(0, boundary + 1).map(event => structuredClone(event))
  568. }
  569. private _resolveForkSource(source: SessionForkSource): Session {
  570. if (typeof source === 'string') {
  571. const session = this.get(source)
  572. if (session === undefined) throw new SessionForkError(`session "${source}" not found`, 'SESSION_NOT_FOUND')
  573. return session
  574. }
  575. const live = this.get(source.id)
  576. if (live === undefined) {
  577. throw new SessionForkError(`session "${source.id}" not found`, 'SESSION_NOT_FOUND')
  578. }
  579. if (live !== source) throw new SessionForkError(`session "${source.id}" is not the live store instance`, 'SESSION_NOT_LIVE')
  580. return source
  581. }
  582. }
  583. export default SessionStore