index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /** Session Remote owner: cold reads, explicit Agent commands, and live control state. */
  2. import { Context } from '@deepseek-ai/cordis'
  3. import z from '@deepseek-ai/schemastery'
  4. import { errorChain } from '@deepseek-ai/dsh-llm'
  5. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  6. import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
  7. import {
  8. ApiSessionAgentController,
  9. inspectApiSession,
  10. type ApiSessionAgentResult,
  11. } from './agent.ts'
  12. import { SessionCommandController } from './commands.ts'
  13. import { SessionControlController } from './control.ts'
  14. import { SessionHistoryController } from './history.ts'
  15. import { ApiSessionList, DEFAULT_COLD_BLANK_PROBE_MAX_BYTES } from './list.ts'
  16. import type {
  17. SessionAttachmentRequest,
  18. SessionAttachmentValue,
  19. SessionCancelRequest,
  20. SessionCancelValue,
  21. SessionControlFrame,
  22. SessionCreateRequest,
  23. SessionCreateValue,
  24. SessionFollowFrame,
  25. SessionFollowRequest,
  26. SessionForkRequest,
  27. SessionForkValue,
  28. SessionListRequest,
  29. SessionListValue,
  30. SessionModels,
  31. SessionModelsRequest,
  32. SessionPage,
  33. SessionPageRequest,
  34. SessionPromptRequest,
  35. SessionPromptValue,
  36. SessionRenameRequest,
  37. SessionRenameValue,
  38. SessionSearchRequest,
  39. SessionSearchValue,
  40. SessionSelectModelRequest,
  41. SessionSelectModelValue,
  42. SessionUpdateQueueRequest,
  43. SessionUpdateQueueValue,
  44. } from './types.ts'
  45. export type * from './types.ts'
  46. export { ApiSessionNotFound } from './agent.ts'
  47. declare module '@deepseek-ai/cordis' {
  48. interface Context {
  49. /** Host Session business API and Remote namespace owner. */
  50. sessionController: SessionController
  51. }
  52. }
  53. /** Session Controller deployment policy. */
  54. export interface Config {
  55. /** Maximum cold Session artifact size read to determine blankness. */
  56. readonly coldBlankProbeMaxBytes?: number
  57. }
  58. /** Host service backing the generated `ctx.remote.session` namespace. */
  59. export class SessionController extends TypertRemoteService {
  60. static inject = [
  61. 'agentDefaultModel',
  62. 'agents',
  63. 'attachments',
  64. 'llm',
  65. 'sessions',
  66. 'sessionQuery',
  67. 'typert',
  68. 'workspaceRegistry',
  69. ]
  70. static Config: z<Config> = z.object({
  71. coldBlankProbeMaxBytes: z.natural().default(DEFAULT_COLD_BLANK_PROBE_MAX_BYTES),
  72. })
  73. private readonly agents: ApiSessionAgentController
  74. private readonly commands: SessionCommandController
  75. private readonly controlState: SessionControlController
  76. private readonly history: SessionHistoryController
  77. private readonly listState: ApiSessionList
  78. /**
  79. * @param ctx - Host context containing the Session capability assembly.
  80. * @param config - cold-list read policy.
  81. */
  82. constructor(ctx: Context, config: Config) {
  83. super(ctx, 'sessionController', { namespace: 'session' })
  84. this.agents = new ApiSessionAgentController(ctx)
  85. this.commands = new SessionCommandController(ctx, this.agents, process.cwd())
  86. this.controlState = new SessionControlController(ctx)
  87. this.history = new SessionHistoryController(ctx)
  88. this.listState = new ApiSessionList(
  89. ctx,
  90. config.coldBlankProbeMaxBytes ?? DEFAULT_COLD_BLANK_PROBE_MAX_BYTES,
  91. )
  92. ctx.on('session/created', (session) => {
  93. ctx.emit('api-session/added', this.listState.summaryFor(session))
  94. })
  95. ctx.on('session/disposed', (session) => {
  96. ctx.emit('api-session/removed', session.id)
  97. })
  98. ctx.on('agent/status', ({ agent, status }) => {
  99. ctx.emit('api-session/status', agent.id, status === 'running')
  100. })
  101. ctx.on('agent/error', ({ agent, error }) => {
  102. ctx.emit('api-session/error', agent.id, errorChain(error))
  103. })
  104. ctx.on('session/event', (session, event) => {
  105. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return
  106. ctx.emit('api-session/activity', session.id, event.time)
  107. })
  108. }
  109. /**
  110. * Resolve or resume one ordinary Session for another Host API domain.
  111. * @param sessionId - Session identity whose Agent owns the operation.
  112. * @returns the live Agent or the stable Session-domain failure.
  113. */
  114. resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult> {
  115. return this.agents.resolveAgent(sessionId)
  116. }
  117. /**
  118. * Inspect one attached or persisted Session without activating its Agent.
  119. * @param sessionId - durable Session identity.
  120. * @param signal - optional caller cancellation for persistence reads.
  121. * @returns the current attached state or persisted header and event prefix.
  122. */
  123. inspect(
  124. sessionId: SessionId,
  125. signal?: AbortSignal,
  126. ): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  127. const attached = this.ctx.sessions.get(sessionId)
  128. if (attached !== undefined) {
  129. return Promise.resolve({ meta: attached.header, events: [...attached.events] })
  130. }
  131. return inspectApiSession(this.ctx, sessionId, signal)
  132. }
  133. /**
  134. * Read all visible Session rows without resuming an Agent.
  135. * @param _request - reserved empty list request.
  136. * @param signal - cancellation for persistence reads.
  137. * @returns visible Session summaries ordered by activity.
  138. */
  139. @Remote('list')
  140. async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue> {
  141. return { items: await this.listState.list(signal) }
  142. }
  143. /**
  144. * Search visible Session content without resuming an Agent.
  145. * @param request - literal message-content query.
  146. * @param signal - cancellation for list and search reads.
  147. * @returns authorized bounded Session search results.
  148. */
  149. @Remote('search')
  150. search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue> {
  151. return this.listState.search(request.query, signal)
  152. }
  153. /**
  154. * Create or idempotently adopt one ordinary Session.
  155. * @param request - requested identity, location, and Agent preset.
  156. * @returns the Session identity and resolved preset when configured.
  157. */
  158. @Remote('create')
  159. create(request: SessionCreateRequest): Promise<SessionCreateValue> {
  160. return this.commands.create(request)
  161. }
  162. /**
  163. * Read model choices after explicitly resuming the addressed Session.
  164. * @param request - Session whose model state is requested.
  165. * @returns the current selection and available model groups.
  166. */
  167. @Remote('models')
  168. models(request: SessionModelsRequest): Promise<SessionModels> {
  169. return this.commands.models(request)
  170. }
  171. /**
  172. * Select one Session-local model after explicitly resuming the Session.
  173. * @param request - Session identity and requested model selection.
  174. * @returns the normalized selection installed for the Session.
  175. */
  176. @Remote('selectModel')
  177. selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
  178. return this.commands.selectModel(request)
  179. }
  180. /**
  181. * Rename one Session after explicitly resuming it.
  182. * @param request - Session identity and proposed title.
  183. * @returns the accepted title and durable event sequence.
  184. */
  185. @Remote('rename')
  186. rename(request: SessionRenameRequest): Promise<SessionRenameValue> {
  187. return this.commands.rename(request)
  188. }
  189. /**
  190. * Fork one cold-readable completed-turn prefix into a new Session.
  191. * @param request - source Session and optional event anchor.
  192. * @returns the new Session identity.
  193. */
  194. @Remote('fork')
  195. fork(request: SessionForkRequest): Promise<SessionForkValue> {
  196. return this.commands.fork(request)
  197. }
  198. /**
  199. * Admit one prompt after explicitly resuming its Session.
  200. * @param request - Session identity, prompt content, source metadata, and delivery mode.
  201. * @param signal - caller cancellation before prompt admission begins.
  202. * @returns acknowledgement that the Agent accepted the prompt.
  203. */
  204. @Remote('prompt')
  205. prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue> {
  206. signal.throwIfAborted()
  207. return this.commands.prompt(request)
  208. }
  209. /**
  210. * Read one image proven reachable from the addressed Session log.
  211. * @param request - Session and attachment identities used for authorization.
  212. * @returns the durable attachment reference and base64-encoded bytes.
  213. */
  214. @Remote('attachment')
  215. attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue> {
  216. return this.commands.attachment(request)
  217. }
  218. /**
  219. * Mutate one still-pending queue occurrence on a live Agent.
  220. * @param request - Session, queue item, and requested mutation.
  221. * @returns acknowledgement that the queue mutation was applied.
  222. */
  223. @Remote('updateQueue')
  224. updateQueue(request: SessionUpdateQueueRequest): SessionUpdateQueueValue {
  225. return this.commands.updateQueue(request)
  226. }
  227. /**
  228. * Cancel one active Agent turn without dropping its pending inbox.
  229. * @param request - Session whose active Agent turn is cancelled.
  230. * @returns acknowledgement that cancellation was requested.
  231. */
  232. @Remote('cancel')
  233. cancel(request: SessionCancelRequest): SessionCancelValue {
  234. return this.commands.cancel(request)
  235. }
  236. /**
  237. * Read one cold-safe, message-aligned Session history page.
  238. * @param request - durable address, backward cursor, and page budget.
  239. * @param signal - cancellation for persistence reads.
  240. * @returns one chronological page and optional latest projections.
  241. */
  242. @Remote('page')
  243. page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage> {
  244. return this.history.page(request, signal)
  245. }
  246. /**
  247. * Follow one Session log from its opening or resume cursor.
  248. * @param request - durable address and last committed sequence already held by the caller.
  249. * @param signal - cancellation owned by the Remote stream carrier.
  250. * @returns an opened cursor followed by gap-free event frames.
  251. */
  252. @Remote({ mode: 'stream' })
  253. follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame> {
  254. return this.history.follow(request, signal)
  255. }
  256. /**
  257. * Stream a complete live-control baseline followed by replacement frames.
  258. * @param signal - cancellation owned by the Remote stream carrier.
  259. * @returns one complete baseline followed by live replacement frames.
  260. */
  261. @Remote({ mode: 'stream' })
  262. control(signal: AbortSignal): AsyncIterable<SessionControlFrame> {
  263. return this.controlState.control(signal)
  264. }
  265. }
  266. export { buildModelCatalog } from './catalog.ts'
  267. export default SessionController