session.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. // Sessions remain resident after creation so their open Remote sources keep running off-screen.
  2. import type { Context } from '@deepseek-ai/cordis'
  3. import { bytesToBase64, randomUUID } from '@deepseek-ai/dsh-util-crypto'
  4. import type { FileUploadProgress } from '@deepseek-ai/dsh-client-file-upload/client'
  5. import type { AttachmentIdType, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
  6. import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
  7. import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
  8. import { SessionLogOffset, SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types'
  9. import { SessionEventStream } from '../transport.ts'
  10. import type { SessionJournalChange } from '../transport.ts'
  11. import type {
  12. PromptContentPart,
  13. QueueAction,
  14. SessionAddress,
  15. SessionControlFrame,
  16. SessionProjectionBaseline,
  17. SessionQueuedItem,
  18. SessionRequestId,
  19. SessionUploadFileValue,
  20. } from '../../types.ts'
  21. import { SESSION_FILE_UPLOAD_PATH } from '../../file-upload-path.ts'
  22. import type {
  23. BeginSubmissionInput, PendingSubmissionRetirement, SessionFace, SubmissionHandle,
  24. } from '../contract/session.ts'
  25. import type {
  26. OpenState, PendingSubmission, PromptError, SessionSnapshot,
  27. } from '../contract/snapshot.ts'
  28. import { MutableSessionEventSource } from '../contract/events.ts'
  29. import type {
  30. SessionEventLikeEntry, SessionLiveEventEntry,
  31. } from '../contract/events.ts'
  32. import { Notifier } from './notifier.ts'
  33. import { isRemoteFailure } from '@deepseek-ai/dsh-api-gateway/client'
  34. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  35. import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
  36. import type { SessionRemotes } from './remotes.ts'
  37. import { ProjectionValueStore } from './projection-store.ts'
  38. import type { ProjectionsBaseline } from './projection-store.ts'
  39. import { resolvedClientTimeZone } from '../time-zone.ts'
  40. import { SessionQueueMirror } from './queue-mirror.ts'
  41. function projectionsBaseline(value: SessionProjectionBaseline): ProjectionsBaseline {
  42. return {
  43. ...value,
  44. asOfSeq: value.asOfSeq === -1 ? -1 : SessionSeq(value.asOfSeq),
  45. }
  46. }
  47. /** Messages requested per history page. */
  48. export const PAGE_MESSAGES = 50
  49. /** Messages requested per page while a turn jump loops backwards (fewer, larger round trips). */
  50. export const JUMP_PAGE_MESSAGES = 200
  51. /** Manager-owned observers of a Session object's local state edges. */
  52. export interface SessionOptions {
  53. /** Catalog-discovered address selecting non-activating subagent transport. */
  54. address?: SubagentAddress
  55. /** Whether the exact direct parent Agent was live at the latest catalog read; absent before that read. */
  56. parentAvailable?: boolean
  57. /**
  58. * First ACCEPTED prompt on a blank session (fires at most once, on the
  59. * prompt RPC's success response): the manager mirrors the blank→false flip
  60. * into its list row so the session surfaces without waiting for a host
  61. * frame. Acceptance is the flip point because it proves the user message
  62. * is in the host log; a rejected first prompt keeps the session blank
  63. * (hidden, still reusable by connectWorkspace).
  64. */
  65. onEngaged?(session: Session): void
  66. /**
  67. * Manager-owned projection value store to adopt (frames route through the
  68. * manager and values outlive instantiation); omitted, the Session owns a
  69. * private store (bare object-layer construction).
  70. */
  71. projections?: ProjectionValueStore
  72. }
  73. /**
  74. * Owns a session's event window, lifecycle state, and observable
  75. * snapshot. React bindings remain outside this data layer. Features see only
  76. * the {@link SessionFace} slice (ISession verbs + the snapshot source); the
  77. * remaining public members are Session Controller internals.
  78. */
  79. export class Session implements SessionFace {
  80. // ---- Window and derived state (all private; the snapshot is the only read API) ----
  81. private baseSeq = SessionLogOffset(0)
  82. private hasMore = false
  83. private openState: OpenState = 'cold'
  84. private openError: RemoteFailure | null = null
  85. private openPromise: Promise<void> | null = null
  86. /** Bumped by stream replacement to invalidate an in-flight doOpen. Stale
  87. * passes drop all writes once the generation moves on. */
  88. private openGeneration = 0
  89. private loadingOlder = false
  90. /** Shared low-water target of the running jump loop; null when no jump is paging. */
  91. private jumpTargetSeq: SessionSeq | null = null
  92. /** The running jump loop's completion, shared by retargeting callers. */
  93. private jumpPromise: Promise<void> | null = null
  94. /** Authoritative stream-only inbox snapshot; pending work never hits history. */
  95. private readonly queueMirror = new SessionQueueMirror()
  96. private running = false
  97. private address: SubagentAddress | undefined
  98. private parentAvailable: boolean | undefined
  99. /**
  100. * Sticky send marker, private input of the composerPhase derivation: set
  101. * synchronously before prompt()'s first await, never reset — the blank →
  102. * engaging edge of the phase machine (see ComposerPhase).
  103. */
  104. private promptAttempted = false
  105. /** A first accepted prompt stays in the engaging phase until its turn is observable. */
  106. private firstPromptPendingTurn = false
  107. /** Empty-log mirror (see ConversationSnapshot.blank); unknown bare sessions begin conservatively blank. */
  108. private blankBit = true
  109. private removed = false
  110. private promptError: PromptError | null = null
  111. private lastAgentError: string | null = null
  112. /** Local submission echoes, insertion-ordered (see SessionSnapshot.pendingSubmissions). */
  113. private pendingSubmissions: readonly PendingSubmission[] = []
  114. /** Per-echo settlement state; `retiring` latches the first observation so a
  115. * queue frame and its durable event cannot both retire one echo. */
  116. private readonly submissionSettlements = new Map<SessionRequestId, {
  117. readonly onRetire?: ((retirement: PendingSubmissionRetirement) => void) | undefined
  118. retiring: boolean
  119. }>()
  120. /** Owns the addressed page/follow lifecycle while this Session is open. */
  121. private events: SessionEventStream | undefined
  122. /**
  123. * Per-session projection value store (push model; see the session-projection
  124. * subsystem page, docs/subsystems/session-projection.md): finished whole
  125. * values computed on the Host, seeded by the tail page's
  126. * projections block and updated by Session Controller control frames under the
  127. * one higher-seq-wins rule. Keys are read via `projections.faceOf(key)`
  128. * (the useProjection resolution face); the conversation snapshot never
  129. * carries projection values, and no client-side domain folding exists.
  130. * Manager-owned when constructed through SessionManager (frames route and
  131. * the store outlives instantiation, the title-snapshot precedent); a bare
  132. * construction gets a private store.
  133. */
  134. readonly projections: ProjectionValueStore
  135. /** Contiguous history and live tail consumed by Conversation assembly. */
  136. readonly eventSource = new MutableSessionEventSource()
  137. private snapshotCache: SessionSnapshot
  138. private readonly notifier: Notifier
  139. /**
  140. * Agent-scoped cordis context, bound once by ClientSessions when it
  141. * mints the scope (the client mirror of the host Agent's loopCtx). The
  142. * Session dispatches its own scoped events through it; undefined means
  143. * unbound (bare object-layer construction) or already pruned — both skip
  144. * dispatch-dependent behavior rather than fail.
  145. */
  146. private actx: Context | undefined
  147. /**
  148. * @param sessionId - Host session identity (client sessions are always Host-born).
  149. * @param remote - generated Remote namespaces this session calls.
  150. * @param options - optional manager-owned state observers.
  151. */
  152. constructor(
  153. readonly sessionId: SessionId,
  154. private readonly remote: SessionRemotes,
  155. private readonly options: SessionOptions = {},
  156. ) {
  157. this.projections = options.projections ?? new ProjectionValueStore()
  158. this.address = options.address
  159. this.parentAvailable = options.parentAvailable
  160. this.notifier = new Notifier(() => {
  161. this.snapshotCache = this.buildSnapshot()
  162. })
  163. this.snapshotCache = this.buildSnapshot()
  164. }
  165. /**
  166. * Bind the Agent-scoped context minted by ClientSessions (single write;
  167. * a second bind is a wiring error and throws). Direction stays one-way at
  168. * this binding boundary: consumers still reach the Session via `sessions.sessionOf`,
  169. * while the Session holds its own dispatch point (host Agent.loopCtx
  170. * mirror).
  171. * @param actx - the agent's scoped context.
  172. */
  173. bindScope(actx: Context): void {
  174. if (this.actx !== undefined) throw new Error(`session ${this.sessionId} already has a bound scope`)
  175. this.actx = actx
  176. }
  177. /** Release the bound scope at prune time (a later rebind accompanies a freshly minted scope). */
  178. unbindScope(): void {
  179. this.actx = undefined
  180. }
  181. // ---- Operations ----
  182. /**
  183. * Register one local submission echo (see the ISession declaration).
  184. * Synchronous through markDirty: the echo is in the very next snapshot, so
  185. * the conversation can paint it before the caller starts serializing.
  186. * @param input - echo content and the optional settlement callback.
  187. * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
  188. */
  189. beginSubmission(input: BeginSubmissionInput): SubmissionHandle {
  190. const requestId = randomUUID() as SessionRequestId
  191. this.pendingSubmissions = [...this.pendingSubmissions, {
  192. requestId,
  193. placement: this.running
  194. ? input.mode === 'steer' ? 'steering' : 'queued'
  195. : 'transcript',
  196. time: Date.now(),
  197. text: input.text,
  198. attachments: input.attachments,
  199. }]
  200. this.submissionSettlements.set(requestId, { onRetire: input.onRetire, retiring: false })
  201. // The blank → engaging edge flips here, ahead of prompt(): the composer
  202. // docks and the echo renders on the click's own frame.
  203. this.promptAttempted = true
  204. this.notifier.markDirty()
  205. return { requestId, abandon: () => { this.retireFailedSubmission(requestId) } }
  206. }
  207. /**
  208. * Send (queue/steer passed through 1:1); failures land in the snapshot's promptError.
  209. * @param content - text, browser-owned temporary image uploads, and staged-file receipts.
  210. * @param mode - queue appends after the current turn; steer interrupts it.
  211. * @param signal - optional caller cancellation for the complete admission round-trip.
  212. * @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
  213. * @returns the prompt result (also mirrored into promptError on failure).
  214. */
  215. async prompt(
  216. content: PromptContentPart[],
  217. mode: 'queue' | 'steer',
  218. signal?: AbortSignal,
  219. requestId?: SessionRequestId,
  220. ): Promise<RemoteResult<{ accepted: true }>> {
  221. this.promptError = null
  222. this.lastAgentError = null
  223. // Synchronous, before the first await: the blank → engaging edge must be
  224. // visible on the session area's very first frame when a caller sends
  225. // ahead of navigation (first-send flow).
  226. this.promptAttempted = true
  227. if (this.blankBit) this.firstPromptPendingTurn = true
  228. this.notifier.markDirty()
  229. let result: RemoteResult<{ accepted: true }>
  230. if (this.address === undefined) {
  231. const clientTimeZone = resolvedClientTimeZone()
  232. result = await this.remote.session.prompt({
  233. requestId: requestId ?? randomUUID() as SessionRequestId,
  234. sessionId: this.sessionId,
  235. mode,
  236. content,
  237. clientTimeZone,
  238. }, signal)
  239. } else if (content.some(part => part.type === 'file')) {
  240. result = {
  241. ok: false,
  242. error: new RemoteError(
  243. 'subagent/attachment-invalid',
  244. 'subagent continuation does not accept files',
  245. { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
  246. ),
  247. }
  248. } else {
  249. // The preceding branch rejects file parts before the narrower subagent
  250. // wire type is used; this array is not filtered or reordered.
  251. const routedContent = content as Exclude<PromptContentPart, { readonly type: 'file' }>[]
  252. const routed = await this.remote.subagents.prompt({
  253. requestId: randomUUID() as SessionRequestId,
  254. parentSessionId: this.address.parentSessionId,
  255. childSessionId: this.address.childSessionId,
  256. mode: 'continuable',
  257. content: routedContent,
  258. clientTimeZone: resolvedClientTimeZone(),
  259. }, signal)
  260. result = routed.ok ? { ok: true, value: { accepted: true } } : routed
  261. }
  262. if (!result.ok) {
  263. if (requestId !== undefined) this.retireFailedSubmission(requestId)
  264. this.promptError = { op: 'send', error: result.error }
  265. this.notifier.markDirty()
  266. return result
  267. }
  268. // Blank flips on ACCEPTANCE, not attempt: an accepted prompt starts the
  269. // conversation's first turn on the host (the host criterion — a logged
  270. // turn/start — is fact, not optimism; standalone command and projection
  271. // events never flip it), while a rejected first prompt must keep the
  272. // session blank — the client-side blank mirror only ever lowers, so
  273. // flipping early on a failure would surface the session forever and
  274. // strip its connectWorkspace reuse eligibility against the host's
  275. // authority.
  276. if (this.blankBit) {
  277. this.blankBit = false
  278. this.options.onEngaged?.(this)
  279. this.notifier.markDirty()
  280. }
  281. return result
  282. }
  283. /**
  284. * Persist one browser file verbatim and stage it for a later prompt on this
  285. * session (ordinary sessions only; subagent conversations refuse).
  286. * @param data - exact bytes, a browser Blob, or a one-shot byte stream.
  287. * @param name - optional display name; the host sanitizes the stored leaf name.
  288. * @param signal - optional cancellation for the active upload.
  289. * @param onProgress - optional byte-progress observer for background bodies.
  290. * @returns the staged-upload receipt and durable file reference, or the business error.
  291. */
  292. async uploadFile(
  293. data: Blob | Uint8Array | ReadableStream<Uint8Array>,
  294. name?: string,
  295. signal?: AbortSignal,
  296. onProgress?: (progress: FileUploadProgress) => void,
  297. ): Promise<RemoteResult<SessionUploadFileValue>> {
  298. if (this.address !== undefined) {
  299. return {
  300. ok: false,
  301. error: new RemoteError(
  302. 'subagent/attachment-invalid',
  303. 'subagent conversations do not accept file uploads',
  304. { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
  305. ),
  306. }
  307. }
  308. if (!(data instanceof Uint8Array) && this.actx?.fileUpload.available === true) {
  309. const query = new URLSearchParams({ sessionId: this.sessionId })
  310. if (name !== undefined) query.set('name', name)
  311. const response = await this.actx.fileUpload.post({
  312. path: `${SESSION_FILE_UPLOAD_PATH}?${query.toString()}`,
  313. body: data,
  314. headers: { 'content-type': 'application/octet-stream' },
  315. ...(signal === undefined ? {} : { signal }),
  316. ...(onProgress === undefined ? {} : { onProgress }),
  317. })
  318. if (response.status !== 200) {
  319. throw new Error(`file upload transport failed with HTTP ${String(response.status)}`)
  320. }
  321. return parseFileUploadResult(response.body)
  322. }
  323. if (!(data instanceof Uint8Array) && !(data instanceof Blob)) {
  324. throw new Error('stream file upload requires a bound Client file-upload service')
  325. }
  326. const bytes = data instanceof Uint8Array ? data : new Uint8Array(await data.arrayBuffer())
  327. return this.remote.session.uploadFile({
  328. sessionId: this.sessionId,
  329. data: bytesToBase64(bytes),
  330. ...(name === undefined ? {} : { name }),
  331. }, signal)
  332. }
  333. /**
  334. * Resolve one image referenced by this session into browser-consumable bytes.
  335. * @param attachmentId - opaque id found in the folded session log.
  336. * @returns the authenticated reference and decoded bytes.
  337. */
  338. async readAttachment(
  339. attachmentId: AttachmentIdType,
  340. ): Promise<RemoteResult<{ attachment: ImageAttachmentRef; data: Uint8Array }>> {
  341. const result = await this.remote.session.attachment({
  342. sessionId: this.sessionId,
  343. attachmentId,
  344. })
  345. if (!result.ok) return result
  346. const binary = atob(result.value.data)
  347. const data = Uint8Array.from(binary, char => char.charCodeAt(0))
  348. return { ok: true, value: { attachment: result.value.attachment, data } }
  349. }
  350. /** Apply one operation to a still-pending queue occurrence. */
  351. async updateQueue(itemId: MessageId, action: QueueAction): Promise<RemoteResult<{ accepted: true }>> {
  352. return this.remote.session.updateQueue({ sessionId: this.sessionId, itemId, action })
  353. }
  354. /**
  355. * Stop the active turn while the Host preserves pending inbox work; failures
  356. * land in promptError (same error-strip display slot). A subagent address
  357. * routes through `subagents.interruptByParent`, whose durable parent-address
  358. * authority works without a live parent Agent.
  359. * @returns the cancel result.
  360. */
  361. async cancel(): Promise<RemoteResult<{ accepted: true }>> {
  362. const address = this.address
  363. const result = address !== undefined
  364. ? await this.remote.subagents.interruptByParent(
  365. address.childSessionId,
  366. address.parentSessionId,
  367. 'continuable',
  368. )
  369. : await this.remote.session.cancel({ sessionId: this.sessionId })
  370. if (!result.ok) {
  371. this.promptError = { op: 'stop', error: result.error }
  372. this.notifier.markDirty()
  373. }
  374. return result
  375. }
  376. /**
  377. * Rename: contract session.rename 1:1. On success settle the 'title'
  378. * projection cell from the response's `{title, seq}` under the store's
  379. * higher-seq-wins rule (the push frame arriving later is a no-op replay),
  380. * so the list row and any useProjection('title') reader update without
  381. * waiting for the control-stream projection update.
  382. * @param title - raw title text (the host normalizes acceptance).
  383. * @returns the rename result (normalized accepted title + title event seq).
  384. */
  385. async rename(title: string): Promise<RemoteResult<{ title: string; seq: SessionSeq }>> {
  386. const result = await this.remote.session.rename({ sessionId: this.sessionId, title })
  387. if (!result.ok) return result
  388. const seq = SessionSeq(result.value.seq)
  389. this.projections.apply('title', result.value.title, seq)
  390. return { ok: true, value: { title: result.value.title, seq } }
  391. }
  392. /**
  393. * Execute one slash-command line against this session's agent — pure
  394. * admission semantics (the host executor durably logs the lifecycle;
  395. * outcomes render as flow nodes, never as a response echo).
  396. * @param line - the full command line, leading slash included.
  397. * @returns the admission result.
  398. */
  399. async command(line: string): Promise<RemoteResult<{ matched: boolean }>> {
  400. const result = await this.remote.commands.execute(this.sessionId, line, [])
  401. if (!result.ok) return result
  402. return { ok: true, value: { matched: result.value !== undefined } }
  403. }
  404. /** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */
  405. open(): Promise<void> {
  406. if (this.openState === 'open') return Promise.resolve()
  407. if (this.openPromise !== null) return this.openPromise
  408. const promise = this.doOpen(this.openGeneration).finally(() => {
  409. // Identity-guarded: a superseded open must not null out the promise resync just started.
  410. if (this.openPromise === promise) this.openPromise = null
  411. })
  412. this.openPromise = promise
  413. return promise
  414. }
  415. /** Page up: pull one earlier page with the window's first seq as beforeSeq and prepend. */
  416. async loadOlder(): Promise<void> {
  417. if (this.openState !== 'open' || !this.hasMore || this.loadingOlder) return
  418. const events = this.events
  419. if (events === undefined) return
  420. this.loadingOlder = true
  421. this.notifier.markDirty()
  422. try {
  423. await events.prepend({ beforeSeq: this.baseSeq, maxMessages: PAGE_MESSAGES })
  424. } catch (error) {
  425. if (!isRemoteFailure(error)) {
  426. console.error('[session-controller] loadOlder failed:', error)
  427. }
  428. } finally {
  429. this.loadingOlder = false
  430. this.notifier.markDirty()
  431. }
  432. }
  433. /** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */
  434. loadThrough(seq: SessionSeq): Promise<void> {
  435. if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq) return Promise.resolve()
  436. if (this.jumpPromise !== null) {
  437. // Retarget the running loop to the lowest requested seq.
  438. this.jumpTargetSeq = SessionSeq(Math.min(this.jumpTargetSeq ?? seq, seq))
  439. return this.jumpPromise
  440. }
  441. // A plain single-page pull owns the busy flag; the jump does not queue
  442. // behind it (the caller retries once it settles) and must leave no
  443. // target behind — only the loop's finally clears that field, and no
  444. // loop starts here.
  445. if (this.loadingOlder) return Promise.resolve()
  446. this.jumpTargetSeq = seq
  447. this.loadingOlder = true
  448. this.notifier.markDirty()
  449. // Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the
  450. // stream generation; this pass then stops instead of paging the new
  451. // generation toward its old target.
  452. const generation = this.openGeneration
  453. this.jumpPromise = (async () => {
  454. try {
  455. while (this.hasMore && this.jumpTargetSeq !== null && this.baseSeq > this.jumpTargetSeq) {
  456. if (generation !== this.openGeneration) return
  457. const events = this.events
  458. if (events === undefined) return
  459. const before = this.baseSeq
  460. await events.prepend({ beforeSeq: this.baseSeq, maxMessages: JUMP_PAGE_MESSAGES })
  461. // No-progress guard: an empty or dropped page that still claims more
  462. // history must end the loop, not spin it.
  463. if (this.baseSeq >= before) return
  464. }
  465. } catch (error) {
  466. if (!isRemoteFailure(error)) {
  467. console.error('[session-controller] loadThrough failed:', error)
  468. }
  469. } finally {
  470. this.jumpTargetSeq = null
  471. this.jumpPromise = null
  472. this.loadingOlder = false
  473. this.notifier.markDirty()
  474. }
  475. })()
  476. return this.jumpPromise
  477. }
  478. /** Rebuild an opened history source after address replacement.
  479. * Invalidates any in-flight open first; queue state belongs to the independently
  480. * reconnecting control stream and remains untouched. */
  481. async resync(): Promise<void> {
  482. if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open)
  483. this.openGeneration++
  484. const events = this.events
  485. this.events = undefined
  486. await events?.dispose()
  487. this.openPromise = null
  488. this.openState = 'cold'
  489. this.openError = null
  490. this.baseSeq = SessionLogOffset(0)
  491. this.notifier.markDirty()
  492. await this.open()
  493. }
  494. // ---- Subscription API (useSyncExternalStore direct wiring) ----
  495. /**
  496. * uSES subscription entry.
  497. * @param listener - change callback.
  498. * @returns the unsubscribe function.
  499. */
  500. subscribe(listener: () => void): () => void {
  501. return this.notifier.subscribe(listener)
  502. }
  503. /**
  504. * Cached Session snapshot (rebuilt lazily when dirty with no listeners).
  505. * @returns the cached reference (stable until the next flush).
  506. */
  507. getSnapshot(): SessionSnapshot {
  508. this.notifier.ensureFresh()
  509. return this.snapshotCache
  510. }
  511. // ---- Manager-only entry points (@internal; never called by the UI) ----
  512. /**
  513. * Replace every transient control value for this Session from one stream baseline.
  514. * @param queue - complete pending queue for this Session.
  515. */
  516. replaceControl(queue: readonly SessionQueuedItem[]): void {
  517. this.queueMirror.replace(queue)
  518. this.observeSubmissionQueue(queue)
  519. this.notifier.markDirty()
  520. }
  521. /**
  522. * Apply one Session-addressed live control update.
  523. * @param frame - queue replacement addressed to this Session.
  524. */
  525. handleControlFrame(frame: Extract<SessionControlFrame, { type: 'queue' }>): void {
  526. this.queueMirror.replace(frame.items)
  527. this.observeSubmissionQueue(frame.items)
  528. this.notifier.markDirty()
  529. }
  530. /**
  531. * Running-bit relay from the host stream (list entry and snapshot stay consistent).
  532. * @param running - the new running state.
  533. */
  534. handleRunning(running: boolean): void {
  535. // Turn-start conversion: a blank session never runs, so the first
  536. // running:true proves another side's first message landed.
  537. if (running && this.blankBit) {
  538. this.blankBit = false
  539. this.notifier.markDirty()
  540. }
  541. if (running) this.firstPromptPendingTurn = false
  542. if (this.running === running) return
  543. this.running = running
  544. this.notifier.markDirty()
  545. }
  546. /**
  547. * Install or clear the catalog-discovered transport address. A changed
  548. * address rebuilds an already-open window through its new history route.
  549. * @param address - direct parent/child address, or undefined for ordinary transport.
  550. * @param parentAvailable - latest exact-parent availability hint, or undefined before a catalog read.
  551. */
  552. configureSubagent(address: SubagentAddress | undefined, parentAvailable?: boolean): void {
  553. const same = this.address?.parentSessionId === address?.parentSessionId
  554. && this.address?.childSessionId === address?.childSessionId
  555. && this.address?.mode === address?.mode
  556. this.address = address
  557. this.parentAvailable = parentAvailable
  558. if (!same && this.openState !== 'cold') void this.resync()
  559. else this.notifier.markDirty()
  560. }
  561. /**
  562. * Update only the parent availability hint from a catalog refresh.
  563. * @param available - whether the exact direct parent is live.
  564. */
  565. handleSubagentParentAvailable(available: boolean): void {
  566. if (this.parentAvailable === available) return
  567. this.parentAvailable = available
  568. this.notifier.markDirty()
  569. }
  570. /**
  571. * Blank-bit relay from the authoritative summary source (`session.list` and
  572. * `api-session/added`). Monotone: once any signal (local first send,
  573. * running flip, an earlier summary) cleared it, a stale true never
  574. * re-blanks.
  575. * @param blank - the summary's derived empty-log bit.
  576. */
  577. handleBlank(blank: boolean): void {
  578. if (blank === this.blankBit) return
  579. if (blank && (this.promptAttempted || this.running)) return
  580. this.blankBit = blank
  581. this.notifier.markDirty()
  582. }
  583. /** `api-session/removed` relay: flag the snapshot while retaining the resident instance. */
  584. handleRemoved(): void {
  585. this.removed = true
  586. this.notifier.markDirty()
  587. }
  588. /**
  589. * `api-session/error` relay: the outlet for live failures with no turn position.
  590. * @param message - the stringified error.
  591. */
  592. handleAgentError(message: string): void {
  593. this.lastAgentError = message
  594. this.notifier.markDirty()
  595. }
  596. /**
  597. * Stop the Session's live Remote source.
  598. * @returns when the Remote iterator has completed teardown.
  599. */
  600. async dispose(): Promise<void> {
  601. // Unsettled echoes retire as failed so their owners can restore or
  602. // release browser resources; echoes already scheduled as observed keep
  603. // that settlement.
  604. for (const requestId of [...this.submissionSettlements.keys()]) {
  605. this.retireFailedSubmission(requestId)
  606. }
  607. this.openGeneration++
  608. const events = this.events
  609. this.events = undefined
  610. await events?.dispose()
  611. }
  612. // ---- Private ----
  613. /** @param generation - openGeneration at launch; stale passes cannot publish after replacement. */
  614. private async doOpen(generation: number): Promise<void> {
  615. this.openState = 'loading'
  616. this.openError = null
  617. this.notifier.markDirty()
  618. const events = new SessionEventStream(this.remote, this.sessionAddress(), {
  619. publish: (change) => {
  620. if (generation !== this.openGeneration || this.events !== events) return
  621. this.acceptEventChange(change)
  622. },
  623. failed: (error) => {
  624. this.failEventStream(events, generation, error)
  625. },
  626. })
  627. this.events = events
  628. try {
  629. await events.open({ maxMessages: PAGE_MESSAGES })
  630. if (generation !== this.openGeneration || this.events !== events) return
  631. this.openState = 'open'
  632. } catch (error) {
  633. if (generation !== this.openGeneration || this.events !== events) return
  634. if (!isRemoteFailure(error)) throw error
  635. this.events = undefined
  636. this.openState = 'error'
  637. this.openError = error
  638. } finally {
  639. if (generation === this.openGeneration) this.notifier.markDirty()
  640. }
  641. }
  642. /** Apply one contiguous journal update already reconciled by the Remote stream. */
  643. private acceptEventChange(change: SessionJournalChange): void {
  644. switch (change.type) {
  645. case 'replace':
  646. this.installWindow(
  647. change.entries,
  648. change.hasMore,
  649. change.page.projections === undefined ? undefined : projectionsBaseline(change.page.projections),
  650. )
  651. return
  652. case 'prepend':
  653. this.prependWindow(change.entries, change.hasMore)
  654. return
  655. case 'append':
  656. if (this.appendLive(change.entry)) this.notifier.markDirty()
  657. }
  658. }
  659. /** Replace the complete contiguous window and apply page-owned projection metadata. */
  660. private installWindow(entries: readonly SessionEventLikeEntry[], hasMore: boolean, projections?: ProjectionsBaseline): void {
  661. this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0)
  662. this.hasMore = hasMore
  663. if (entries.some(entry => entry.event.type === 'turn/start')) this.firstPromptPendingTurn = false
  664. if (projections !== undefined) this.projections.seed(projections)
  665. this.eventSource.replace(entries, hasMore)
  666. for (const entry of entries) this.observeSubmissionEvent(entry.event)
  667. this.notifier.markDirty()
  668. }
  669. /** Prepend one stream-validated history page. */
  670. private prependWindow(entries: readonly SessionEventLikeEntry[], hasMore: boolean): void {
  671. this.baseSeq = entries[0] === undefined ? this.baseSeq : SessionLogOffset(entries[0].event.seq)
  672. this.hasMore = hasMore
  673. this.eventSource.prepend(entries, hasMore)
  674. }
  675. /** Append one stream-validated live event. */
  676. private appendLive(entry: SessionLiveEventEntry): boolean {
  677. const event = entry.event
  678. const awaitingFirstTurn = this.firstPromptPendingTurn
  679. if (event.type === 'turn/start') this.firstPromptPendingTurn = false
  680. const queueChanged = this.queueMirror.acceptDurable(event)
  681. this.eventSource.append(entry)
  682. // After the feed append: the conversation assembly's animation frame is
  683. // registered by the feed subscribers above, so the echo-retirement frame
  684. // scheduled here always runs after the durable node became renderable.
  685. this.observeSubmissionEvent(event)
  686. return queueChanged || awaitingFirstTurn !== this.firstPromptPendingTurn
  687. }
  688. /** Retire the matching echo when a durable browser-prompt `user/message` becomes visible. */
  689. private observeSubmissionEvent(event: { readonly type: string; readonly data?: unknown }): void {
  690. if (this.submissionSettlements.size === 0 || event.type !== 'user/message') return
  691. // Structural read: window entries may be compact history records, so the
  692. // fields are narrowed rather than trusted (same posture as Conversation
  693. // assembly matchers).
  694. const data = event.data as { readonly source?: unknown; readonly content?: unknown } | undefined
  695. const source = data?.source as { readonly kind?: unknown; readonly rpcId?: unknown } | undefined
  696. if (source?.kind !== 'user' || typeof source.rpcId !== 'string') return
  697. this.scheduleObservedRetirement(source.rpcId as SessionRequestId, attachmentRefsIn(data?.content))
  698. }
  699. /** Retire echoes whose prompts landed in the host inbox instead of the log (running-turn submissions). */
  700. private observeSubmissionQueue(items: readonly SessionQueuedItem[]): void {
  701. if (this.submissionSettlements.size === 0) return
  702. for (const item of items) {
  703. if (item.rpcId !== undefined) {
  704. this.scheduleObservedRetirement(item.rpcId, attachmentRefsIn(item.message.content))
  705. }
  706. }
  707. }
  708. /**
  709. * Latch one observed settlement and remove the echo an animation frame
  710. * later. The delay keeps the echo in the snapshot until the frame in which
  711. * the durable node (whose assembly frame was registered first) is
  712. * renderable; the render-time rpcId dedupe hides the one-frame overlap.
  713. */
  714. private scheduleObservedRetirement(
  715. requestId: SessionRequestId,
  716. attachments: readonly (ImageAttachmentRef | FileAttachmentRef)[],
  717. ): void {
  718. const settlement = this.submissionSettlements.get(requestId)
  719. if (settlement === undefined || settlement.retiring) return
  720. settlement.retiring = true
  721. scheduleFrame(() => { this.finishSubmission(requestId, { reason: 'observed', attachments }) })
  722. }
  723. /** Remove one unsettled echo immediately (prompt rejection, abort, or disposal). */
  724. private retireFailedSubmission(requestId: SessionRequestId): void {
  725. const settlement = this.submissionSettlements.get(requestId)
  726. if (settlement === undefined || settlement.retiring) return
  727. settlement.retiring = true
  728. this.finishSubmission(requestId, { reason: 'failed' })
  729. }
  730. /** Single removal point: drop the echo, publish, then notify the owner. */
  731. private finishSubmission(requestId: SessionRequestId, retirement: PendingSubmissionRetirement): void {
  732. const settlement = this.submissionSettlements.get(requestId)
  733. /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
  734. if (settlement === undefined) return
  735. this.submissionSettlements.delete(requestId)
  736. this.pendingSubmissions = this.pendingSubmissions.filter(echo => echo.requestId !== requestId)
  737. this.notifier.markDirty()
  738. settlement.onRetire?.(retirement)
  739. }
  740. /** Publish a terminal background failure only while this stream still owns the Session. */
  741. private failEventStream(events: SessionEventStream, generation: number, error: unknown): void {
  742. if (generation !== this.openGeneration || this.events !== events) return
  743. if (!isRemoteFailure(error)) throw error
  744. this.openGeneration++
  745. this.events = undefined
  746. this.openPromise = null
  747. this.openState = 'error'
  748. this.openError = error
  749. void events.dispose()
  750. this.notifier.markDirty()
  751. }
  752. private buildSnapshot(): SessionSnapshot {
  753. return {
  754. sessionId: this.sessionId,
  755. queue: this.queueMirror.snapshot(),
  756. pendingSubmissions: this.pendingSubmissions,
  757. running: this.running,
  758. subagent: this.address === undefined
  759. ? null
  760. : {
  761. address: this.address,
  762. ...(this.parentAvailable === undefined ? {} : { parentAvailable: this.parentAvailable }),
  763. },
  764. removed: this.removed,
  765. openState: this.openState,
  766. openError: this.openError,
  767. hasMore: this.hasMore,
  768. loadingOlder: this.loadingOlder,
  769. promptError: this.promptError,
  770. blank: this.blankBit,
  771. lastAgentError: this.lastAgentError,
  772. promptAttempted: this.promptAttempted,
  773. awaitingFirstTurn: this.firstPromptPendingTurn,
  774. }
  775. }
  776. private sessionAddress(): SessionAddress {
  777. return this.address === undefined
  778. ? { kind: 'session', sessionId: this.sessionId }
  779. : { kind: 'subagent', ...this.address }
  780. }
  781. }
  782. function parseFileUploadResult(body: string): RemoteResult<SessionUploadFileValue> {
  783. const value = JSON.parse(body) as unknown
  784. if (!isRecord(value) || typeof value.ok !== 'boolean') {
  785. throw new TypeError('file upload transport returned an invalid result')
  786. }
  787. if (!value.ok) {
  788. const error = value.error
  789. if (!isRecord(error) || typeof error.code !== 'string'
  790. || typeof error.message !== 'string' || !isRecord(error.details)) {
  791. throw new TypeError('file upload transport returned an invalid failure')
  792. }
  793. return {
  794. ok: false,
  795. error: new RemoteError(error.code as never, error.message, error.details as never),
  796. }
  797. }
  798. const result = value.value
  799. const file = isRecord(result) ? result.file : undefined
  800. if (!isRecord(result) || typeof result.receiptId !== 'string' || !isRecord(file)
  801. || typeof file.attachmentId !== 'string' || typeof file.name !== 'string'
  802. || typeof file.bytes !== 'number' || !Number.isSafeInteger(file.bytes) || file.bytes < 0) {
  803. throw new TypeError('file upload transport returned an invalid receipt')
  804. }
  805. return {
  806. ok: true,
  807. value: {
  808. receiptId: result.receiptId as SessionUploadFileValue['receiptId'],
  809. file: {
  810. attachmentId: file.attachmentId as SessionUploadFileValue['file']['attachmentId'],
  811. name: file.name,
  812. bytes: file.bytes,
  813. },
  814. },
  815. }
  816. }
  817. function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
  818. return typeof value === 'object' && value !== null && !Array.isArray(value)
  819. }
  820. /** Run one callback on the next animation frame, or a macrotask where no frame clock exists. */
  821. function scheduleFrame(fn: () => void): void {
  822. if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => { fn() })
  823. else setTimeout(fn, 0)
  824. }
  825. /** Attachment references in one structurally-read content block list, in block order. */
  826. function attachmentRefsIn(content: unknown): readonly (ImageAttachmentRef | FileAttachmentRef)[] {
  827. if (!Array.isArray(content)) return []
  828. const refs: Array<ImageAttachmentRef | FileAttachmentRef> = []
  829. for (const block of content) {
  830. if (typeof block !== 'object' || block === null) continue
  831. const candidate = block as { readonly type?: unknown; readonly attachment?: unknown }
  832. if ((candidate.type === 'image' || candidate.type === 'file')
  833. && typeof candidate.attachment === 'object' && candidate.attachment !== null) {
  834. refs.push(candidate.attachment as ImageAttachmentRef | FileAttachmentRef)
  835. }
  836. }
  837. return refs
  838. }