list.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /** Cold-safe Session list and search projection. */
  2. import { stat } from 'node:fs/promises'
  3. import type { Context } from '@deepseek-ai/cordis'
  4. import type {} from '@deepseek-ai/dsh-agent-presets'
  5. import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment'
  6. import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  7. import type {} from '@deepseek-ai/dsh-session-projection'
  8. import type {} from '@deepseek-ai/dsh-session-projection-cache'
  9. import { SessionQueryError, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query'
  10. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  11. import { z } from 'zod'
  12. import {
  13. SESSION_SEARCH_RESULT_LIMIT,
  14. SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS,
  15. } from './types.ts'
  16. import type {
  17. SessionListMetadata, SessionProjectionHints, SessionProjectionValues, SessionSearchItem,
  18. SessionSearchValue, SessionSummary,
  19. } from './types.ts'
  20. /** Default maximum artifact size eligible for one cold projection observation. */
  21. export const DEFAULT_COLD_BLANK_PROBE_MAX_BYTES = 1024
  22. const COLD_SUMMARY_BATCH_SIZE = 16
  23. const SEARCH_PROVIDER_CALL_LIMIT = 100
  24. const SESSION_SEARCH_QUERY_MAX_CHARS = 500
  25. const MESSAGE_TYPES = new Set(['user/message', 'assistant/message'])
  26. const sessionListMetadataSchema: z.ZodType<SessionListMetadata> = z.object({
  27. blank: z.boolean(),
  28. lastPromptAt: z.number().nullable(),
  29. })
  30. const imageLimitsSchema = z.object({
  31. maxImageBytes: z.number().int().positive(),
  32. maxImagesPerMessage: z.number().int().positive(),
  33. maxMessageImageBytes: z.number().int().positive(),
  34. maxImagePixels: z.number().int().positive(),
  35. maxImageDimension: z.number().int().positive(),
  36. mediaTypes: z.array(z.string()),
  37. }) as unknown as z.ZodType<ImageAttachmentLimits>
  38. /**
  39. * Advance the Session-list metadata projection by one committed event.
  40. * @param state - metadata before the event.
  41. * @param event - next committed Session event.
  42. * @returns the original or advanced metadata value.
  43. */
  44. export function applySessionListMetadata(
  45. state: SessionListMetadata,
  46. event: SessionEvent,
  47. ): SessionListMetadata {
  48. const blank = state.blank && event.type !== 'turn/start'
  49. const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user'
  50. ? event.time
  51. : state.lastPromptAt
  52. return blank === state.blank && lastPromptAt === state.lastPromptAt
  53. ? state
  54. : { blank, lastPromptAt }
  55. }
  56. /**
  57. * Return the longest prefix containing at most `maximum` Unicode code points.
  58. * @param value - source text.
  59. * @param maximum - maximum number of Unicode code points.
  60. * @returns the source text or its longest allowed prefix.
  61. */
  62. export function truncateUnicodeCodePoints(value: string, maximum: number): string {
  63. let count = 0
  64. let end = 0
  65. for (const codePoint of value) {
  66. if (count === maximum) return value.slice(0, end)
  67. count++
  68. end += codePoint.length
  69. }
  70. return value
  71. }
  72. /** Owns list projection registration, bounded cold summaries, and authorized search. */
  73. export class ApiSessionList {
  74. /**
  75. * @param ctx - Host context carrying Session, query, persistence, and projection services.
  76. * @param coldBlankProbeMaxBytes - maximum physical artifact size eligible for a full observation.
  77. */
  78. constructor(
  79. private readonly ctx: Context,
  80. private readonly coldBlankProbeMaxBytes: number,
  81. ) {
  82. ctx.sessionProjections.register<'sessionListMetadata', SessionListMetadata>({
  83. key: 'sessionListMetadata',
  84. stateSchema: sessionListMetadataSchema,
  85. init: () => ({ blank: true, lastPromptAt: null }),
  86. apply: applySessionListMetadata,
  87. wire: { viewSchema: sessionListMetadataSchema, view: state => state },
  88. stateVersion: 1,
  89. })
  90. ctx.inject(['attachments'], (attachmentCtx) => {
  91. ctx.sessionProjections.register<'imageLimits', null>({
  92. key: 'imageLimits',
  93. stateSchema: z.null(),
  94. init: () => null,
  95. apply: state => state,
  96. wire: {
  97. viewSchema: imageLimitsSchema,
  98. view: () => attachmentCtx.attachments.imageLimits,
  99. },
  100. stateVersion: 1,
  101. })
  102. })
  103. }
  104. /**
  105. * Build one current attached-Session summary.
  106. * @param session - attached Session to summarize.
  107. * @returns current list metadata and available projections.
  108. */
  109. summaryFor(session: Session): SessionSummary {
  110. const projections = this.projectionsFor(session.header, session)
  111. const metadata = projections?.values.sessionListMetadata
  112. return {
  113. sessionId: session.id,
  114. updatedAt: updatedAt(session.header, metadata),
  115. running: this.ctx.agents.get(session.id)?.status === 'running',
  116. blank: metadata?.blank ?? session.seq === 0,
  117. ...listFields(session.header),
  118. ...(projections === undefined ? {} : { projections }),
  119. }
  120. }
  121. /**
  122. * Read every visible attached and persisted Session without activating an Agent.
  123. * @param signal - optional cancellation for persistence reads.
  124. * @returns visible Session summaries ordered by activity.
  125. */
  126. async list(signal?: AbortSignal): Promise<SessionSummary[]> {
  127. signal?.throwIfAborted()
  128. const records = await this.ctx.sessionQuery.listSessions(signal)
  129. signal?.throwIfAborted()
  130. const items: SessionSummary[] = []
  131. const cold: SessionHeader[] = []
  132. for (const record of records) {
  133. const live = this.ctx.sessions.get(record.header.id)
  134. if (live !== undefined) {
  135. items.push(this.summaryFor(live))
  136. continue
  137. }
  138. if (record.header.cwd === undefined) continue
  139. cold.push(record.header)
  140. }
  141. for (let offset = 0; offset < cold.length; offset += COLD_SUMMARY_BATCH_SIZE) {
  142. const settled = await Promise.allSettled(cold.slice(offset, offset + COLD_SUMMARY_BATCH_SIZE)
  143. .map(header => this.summarizeCold(header, signal)))
  144. for (const result of settled) {
  145. if (result.status === 'rejected') throw result.reason
  146. items.push(result.value)
  147. }
  148. }
  149. items.sort((left, right) => right.updatedAt - left.updatedAt)
  150. return items
  151. }
  152. private async summarizeCold(
  153. header: SessionHeader,
  154. signal: AbortSignal | undefined,
  155. ): Promise<SessionSummary> {
  156. const cached = this.projectionsFor(header, undefined)
  157. const projections = cached?.values.sessionListMetadata?.blank === false
  158. ? cached
  159. : await this.probeSmallCold(header, signal) ?? cached
  160. const raced = this.ctx.sessions.get(header.id)
  161. if (raced !== undefined) return this.summaryFor(raced)
  162. const metadata = projections?.values.sessionListMetadata
  163. return {
  164. sessionId: header.id,
  165. updatedAt: updatedAt(header, metadata),
  166. running: false,
  167. // A large or inaccessible cache miss remains unknown and visible.
  168. blank: metadata?.blank ?? false,
  169. ...listFields(header),
  170. ...(projections === undefined ? {} : { projections }),
  171. }
  172. }
  173. private async probeSmallCold(
  174. header: SessionHeader,
  175. signal: AbortSignal | undefined,
  176. ): Promise<SessionProjectionHints | undefined> {
  177. if (this.coldBlankProbeMaxBytes === 0) return undefined
  178. const persistence = this.ctx.get('sessionPersistence')
  179. const location = persistence?.locate(header)
  180. if (location === undefined) return undefined
  181. signal?.throwIfAborted()
  182. try {
  183. if ((await stat(location.path)).size > this.coldBlankProbeMaxBytes) return undefined
  184. } catch {
  185. signal?.throwIfAborted()
  186. return undefined
  187. }
  188. try {
  189. using observation = await this.ctx.sessionQuery.observeSession(header.id, {
  190. ...(signal === undefined ? {} : { signal }),
  191. projectionMode: 'all',
  192. })
  193. const block = observation.projections
  194. return block === undefined
  195. ? undefined
  196. : { asOfSeq: block.asOfSeq, values: block.values as SessionProjectionValues }
  197. } catch (error: unknown) {
  198. signal?.throwIfAborted()
  199. this.ctx.logger.warn(
  200. `api-session.list: small cold observation for "${header.id}" failed; serving it as visible: ${String(error)}`,
  201. )
  202. return undefined
  203. }
  204. }
  205. /**
  206. * Search current visible message content without activating any matching Session.
  207. * @param query - literal message-content query.
  208. * @param signal - cancellation for list and search reads.
  209. * @returns authorized bounded Session search results.
  210. */
  211. async search(query: string, signal: AbortSignal): Promise<SessionSearchValue> {
  212. const normalizedQuery = normalizeSearchQuery(query)
  213. signal.throwIfAborted()
  214. const provider = this.ctx.get('sessionQuery')
  215. if (provider === undefined) {
  216. throw new RemoteError(
  217. 'gateway/internal',
  218. 'session search is unavailable: this deployment does not mount @deepseek-ai/dsh-session-query',
  219. {},
  220. )
  221. }
  222. try {
  223. const visible = await provider.listSessions(signal)
  224. signal.throwIfAborted()
  225. const visibleIds = new Set(visible
  226. .filter(record => record.header.cwd !== undefined)
  227. .map(record => record.header.id))
  228. if (visibleIds.size === 0) return { items: [], hasMore: false }
  229. const authorized: SessionSearchItem[] = []
  230. const acceptedIds = new Set<SessionId>()
  231. const seenCursors = new Set<SessionSearchCursor>()
  232. let cursor: SessionSearchCursor | undefined
  233. let providerCalls = 0
  234. let pageLimit = SESSION_SEARCH_RESULT_LIMIT
  235. while (authorized.length <= SESSION_SEARCH_RESULT_LIMIT) {
  236. signal.throwIfAborted()
  237. if (providerCalls >= SEARCH_PROVIDER_CALL_LIMIT) {
  238. throw new Error(`session search provider exceeded the ${SEARCH_PROVIDER_CALL_LIMIT}-call work budget`)
  239. }
  240. providerCalls++
  241. const requestedCursor = cursor
  242. const requestedLimit = pageLimit
  243. let page
  244. try {
  245. page = await provider.searchSessions({
  246. query: normalizedQuery,
  247. eventFilters: [
  248. { kind: 'type', values: ['user/message', 'assistant/message'] },
  249. { kind: 'surface', values: ['current'] },
  250. ],
  251. limit: requestedLimit,
  252. ...(requestedCursor === undefined ? {} : { cursor: requestedCursor }),
  253. }, { signal })
  254. signal.throwIfAborted()
  255. } catch (error: unknown) {
  256. signal.throwIfAborted()
  257. if (requestedCursor === undefined
  258. && error instanceof SessionQueryError
  259. && error.code === 'SESSION_QUERY_INVALID_LIMIT'
  260. && requestedLimit > 1) {
  261. pageLimit = Math.max(1, Math.floor(requestedLimit / 2))
  262. continue
  263. }
  264. if (requestedCursor !== undefined
  265. && error instanceof SessionQueryError
  266. && error.code === 'SESSION_QUERY_STALE_CURSOR') {
  267. authorized.length = 0
  268. acceptedIds.clear()
  269. seenCursors.clear()
  270. cursor = undefined
  271. continue
  272. }
  273. throw error
  274. }
  275. if (page.items.length > requestedLimit) {
  276. throw new Error(`session search provider returned ${String(page.items.length)} items; maximum is ${String(requestedLimit)}`)
  277. }
  278. for (const hit of page.items) {
  279. if (authorized.length > SESSION_SEARCH_RESULT_LIMIT) continue
  280. if (!visibleIds.has(hit.header.id)
  281. || hit.bestMatch.sessionId !== hit.header.id
  282. || hit.bestMatch.surface !== 'current'
  283. || !MESSAGE_TYPES.has(hit.bestMatch.type)
  284. || acceptedIds.has(hit.header.id)) continue
  285. acceptedIds.add(hit.header.id)
  286. authorized.push({
  287. sessionId: hit.header.id,
  288. snippet: truncateUnicodeCodePoints(hit.bestMatch.snippet, SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS),
  289. })
  290. }
  291. if (page.nextCursor !== undefined) {
  292. if (seenCursors.has(page.nextCursor)) {
  293. throw new Error('session search provider repeated a continuation cursor')
  294. }
  295. seenCursors.add(page.nextCursor)
  296. }
  297. if (authorized.length > SESSION_SEARCH_RESULT_LIMIT || page.nextCursor === undefined) break
  298. cursor = page.nextCursor
  299. }
  300. return {
  301. items: authorized.slice(0, SESSION_SEARCH_RESULT_LIMIT),
  302. hasMore: authorized.length > SESSION_SEARCH_RESULT_LIMIT,
  303. }
  304. } catch (error: unknown) {
  305. signal.throwIfAborted()
  306. if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED') {
  307. throw new RemoteError('gateway/cancelled', 'session search was aborted', {})
  308. }
  309. throw new RemoteError('gateway/internal', `session search failed: ${String(error)}`, {})
  310. }
  311. }
  312. private projectionsFor(
  313. header: SessionHeader,
  314. session: Session | undefined,
  315. ): SessionProjectionHints | undefined {
  316. try {
  317. const block = session === undefined
  318. ? this.ctx.get('sessionProjectionCache')?.cachedSnapshot(header)
  319. : this.ctx.sessionProjections.cachedSnapshot(session)
  320. return block !== undefined && Object.keys(block.values).length > 0
  321. ? {
  322. asOfSeq: block.asOfSeq,
  323. // Listing hints contain every currently cached wire value but remain
  324. // partial: missing cells and cache rows are never materialized here.
  325. values: block.values as SessionProjectionValues,
  326. }
  327. : undefined
  328. } catch (error) {
  329. this.ctx.logger.warn(
  330. `api-session.list: projection column for "${header.id}" failed; serving the row without it: ${String(error)}`,
  331. )
  332. return undefined
  333. }
  334. }
  335. }
  336. function normalizeSearchQuery(query: string): string {
  337. const normalized = query.trim()
  338. if (normalized.length === 0) {
  339. throw new RemoteError('gateway/bad-request', 'session search query must not be empty', {})
  340. }
  341. if (normalized.length > SESSION_SEARCH_QUERY_MAX_CHARS) {
  342. throw new RemoteError(
  343. 'gateway/bad-request',
  344. `session search query must contain at most ${SESSION_SEARCH_QUERY_MAX_CHARS} UTF-16 code units`,
  345. {},
  346. )
  347. }
  348. if (normalized.includes('\0')) {
  349. throw new RemoteError('gateway/bad-request', 'session search query must not contain NUL', {})
  350. }
  351. return normalized
  352. }
  353. function updatedAt(header: SessionHeader, metadata: SessionListMetadata | undefined): number {
  354. return Math.max(header.createdAt, metadata?.lastPromptAt ?? 0)
  355. }
  356. function listFields(header: SessionHeader): {
  357. readonly parentSessionId?: SessionId
  358. readonly origin?: 'subagent'
  359. readonly cwd?: string
  360. } {
  361. return {
  362. ...(header.parentSession === undefined ? {} : { parentSessionId: header.parentSession }),
  363. ...(header.origin === undefined ? {} : { origin: header.origin }),
  364. ...(header.cwd === undefined ? {} : { cwd: header.cwd }),
  365. }
  366. }