index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 { canOpenNativePath, openNativePath } from '@deepseek-ai/dsh-native-command'
  6. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  7. import type { SessionObservation } from '@deepseek-ai/dsh-session-query'
  8. import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
  9. import {
  10. ApiSessionAgentController,
  11. inspectApiSession,
  12. type ApiSessionAgentResult,
  13. } from './agent.ts'
  14. import { SessionCommandController } from './commands.ts'
  15. import { SessionControlController } from './control.ts'
  16. import { SessionHistoryController } from './history.ts'
  17. import { SessionFileReferences } from './file-references.ts'
  18. import { registerSessionFileUploadHttp } from './file-upload-http.ts'
  19. import { ApiSessionList, DEFAULT_COLD_BLANK_PROBE_MAX_BYTES } from './list.ts'
  20. import { buildModelCatalog } from './catalog.ts'
  21. import { installModelSelectionProjection } from './model-selection-projection.ts'
  22. import { SessionSkillCatalog } from './skill-catalog.ts'
  23. import type {
  24. ModelCatalog,
  25. SessionAttachmentRequest,
  26. SessionAttachmentValue,
  27. SessionCancelRequest,
  28. SessionCancelValue,
  29. SessionControlFrame,
  30. SessionCreateRequest,
  31. SessionCreateValue,
  32. SessionFollowFrame,
  33. SessionFollowRequest,
  34. SessionForkRequest,
  35. SessionForkValue,
  36. SessionListRequest,
  37. SessionListValue,
  38. SessionOpenWorkspacePathRequest,
  39. SessionOpenWorkspacePathValue,
  40. SessionPage,
  41. SessionPageRequest,
  42. SessionPromptRequest,
  43. SessionPromptValue,
  44. SessionRenameRequest,
  45. SessionRenameValue,
  46. SessionSearchRequest,
  47. SessionSearchValue,
  48. SessionSelectModelRequest,
  49. SessionSelectModelValue,
  50. SessionUpdateQueueRequest,
  51. SessionUpdateQueueValue,
  52. SessionUploadFileRequest,
  53. SessionUploadFileValue,
  54. } from './types.ts'
  55. export type * from './types.ts'
  56. export { ApiSessionNotFound } from './agent.ts'
  57. export { SessionFileReferences } from './file-references.ts'
  58. export { SessionSkillCatalog } from './skill-catalog.ts'
  59. declare module '@deepseek-ai/cordis' {
  60. interface Context {
  61. /** Host Session business API and Remote namespace owner. */
  62. sessionController: SessionController
  63. }
  64. }
  65. /** Session Controller deployment policy. */
  66. export interface Config {
  67. /** Maximum cold Session artifact size eligible for one full projection observation. */
  68. readonly coldBlankProbeMaxBytes?: number
  69. /** Override platform desktop-opener detection. */
  70. readonly nativeOpen?: boolean
  71. }
  72. /** Host integrations replaceable by direct unit tests. */
  73. export interface SessionControllerInternals {
  74. /** Native default-application handoff. */
  75. readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
  76. /** Native handoff availability probe. */
  77. readonly canOpenPath?: () => boolean
  78. }
  79. /** Host service backing the generated `ctx.remote.session` namespace. */
  80. export class SessionController extends TypertRemoteService {
  81. static inject = [
  82. 'agentDefaultModel',
  83. 'agents',
  84. 'attachments',
  85. 'llm',
  86. 'sessions',
  87. 'sessionProjections',
  88. 'sessionQuery',
  89. 'typert',
  90. 'workspaceRegistry',
  91. ]
  92. static Config: z<Config> = z.object({
  93. coldBlankProbeMaxBytes: z.natural().default(DEFAULT_COLD_BLANK_PROBE_MAX_BYTES),
  94. nativeOpen: z.boolean(),
  95. })
  96. private readonly agents: ApiSessionAgentController
  97. private readonly commands: SessionCommandController
  98. private readonly controlState: SessionControlController
  99. private readonly history: SessionHistoryController
  100. private readonly listState: ApiSessionList
  101. private readonly openPath: (path: string, signal: AbortSignal) => Promise<void>
  102. private readonly canOpenPath: () => boolean
  103. private readonly promotions = new Set<Promise<void>>()
  104. /**
  105. * @param ctx - Host context containing the Session capability assembly.
  106. * @param config - cold-list observation policy.
  107. */
  108. constructor(ctx: Context, config: Config, internals: SessionControllerInternals = {}) {
  109. super(ctx, 'sessionController', { namespace: 'session' })
  110. installModelSelectionProjection(ctx)
  111. this.agents = new ApiSessionAgentController(ctx)
  112. this.commands = new SessionCommandController(ctx, this.agents, process.cwd())
  113. registerSessionFileUploadHttp(ctx, this.commands)
  114. this.controlState = new SessionControlController(ctx)
  115. // Registered before history so reverse-order teardown closes every
  116. // follower before waiting for already-admitted promotions.
  117. ctx.effect(() => async () => {
  118. await Promise.allSettled([...this.promotions])
  119. }, 'session-controller.promotions')
  120. this.history = new SessionHistoryController(ctx, (observation) => { this.promote(observation) })
  121. this.listState = new ApiSessionList(
  122. ctx,
  123. config.coldBlankProbeMaxBytes ?? DEFAULT_COLD_BLANK_PROBE_MAX_BYTES,
  124. )
  125. this.openPath = internals.openPath ?? openNativePath
  126. this.canOpenPath = internals.canOpenPath
  127. ?? (() => config.nativeOpen ?? (internals.openPath !== undefined || canOpenNativePath()))
  128. ctx.plugin(SessionFileReferences)
  129. ctx.plugin(SessionSkillCatalog)
  130. ctx.on('session/created', (session) => {
  131. ctx.emit('api-session/added', this.listState.summaryFor(session))
  132. })
  133. ctx.on('session/disposed', (session) => {
  134. this.commands.releaseStagedFiles(session.id)
  135. ctx.emit('api-session/removed', session.id)
  136. })
  137. ctx.on('agent/status', ({ agent, status }) => {
  138. ctx.emit('api-session/status', agent.id, status === 'running')
  139. })
  140. ctx.on('agent/error', ({ agent, error }) => {
  141. ctx.emit('api-session/error', agent.id, errorChain(error))
  142. })
  143. ctx.on('session/event', (session, event) => {
  144. if (event.type === 'user/message' && event.data.source.kind === 'user'
  145. && 'rpcId' in event.data.source) {
  146. this.commands.retireObservedPrompt(session.id, event.data.source.rpcId)
  147. }
  148. if (event.type === 'request/header') {
  149. const agent = ctx.agents.get(session.id)
  150. if (agent?.session === session) this.agents.consumeSelection(
  151. agent,
  152. event.data.header.config.provider,
  153. event.data.header.config.model,
  154. event.data.header.config.reasoningEffort,
  155. )
  156. }
  157. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return
  158. ctx.emit('api-session/activity', session.id, event.time)
  159. })
  160. }
  161. private promote(observation: SessionObservation): void {
  162. const sessionId = observation.header.id
  163. const task = (async () => {
  164. using ownedObservation = observation
  165. const result = await this.agents.resolveObservedAgent(ownedObservation)
  166. if ('error' in result) this.ctx.emit('api-session/error', sessionId, result.error.message)
  167. })().catch((error: unknown) => {
  168. this.ctx.logger.error(`session-controller: background activation for "${sessionId}" failed: ${errorChain(error)}`)
  169. })
  170. this.promotions.add(task)
  171. void task.finally(() => { this.promotions.delete(task) })
  172. }
  173. /**
  174. * Resolve or resume one ordinary Session for another Host API domain.
  175. * @param sessionId - Session identity whose Agent owns the operation.
  176. * @returns the live Agent or the stable Session-domain failure.
  177. */
  178. resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult> {
  179. return this.agents.resolveAgent(sessionId)
  180. }
  181. /**
  182. * Inspect one attached or persisted Session without activating its Agent.
  183. * @param sessionId - durable Session identity.
  184. * @param signal - optional caller cancellation for persistence reads.
  185. * @returns the current attached state or persisted header and event prefix.
  186. */
  187. inspect(
  188. sessionId: SessionId,
  189. signal?: AbortSignal,
  190. ): Promise<{ meta: SessionHeader; events: readonly SessionEvent[] }> {
  191. const attached = this.ctx.sessions.get(sessionId)
  192. if (attached !== undefined) {
  193. return Promise.resolve({ meta: attached.header, events: attached.snapshotEvents() })
  194. }
  195. return inspectApiSession(this.ctx, sessionId, signal)
  196. }
  197. /**
  198. * Read all visible Session rows without resuming an Agent.
  199. * @param _request - reserved empty list request.
  200. * @param signal - cancellation for persistence reads.
  201. * @returns visible Session summaries ordered by activity.
  202. */
  203. @Remote('list')
  204. async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue> {
  205. return { items: await this.listState.list(signal) }
  206. }
  207. /**
  208. * Search visible Session content without resuming an Agent.
  209. * @param request - literal message-content query.
  210. * @param signal - cancellation for list and search reads.
  211. * @returns authorized bounded Session search results.
  212. */
  213. @Remote('search')
  214. search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue> {
  215. return this.listState.search(request.query, signal)
  216. }
  217. /**
  218. * Create or idempotently adopt one ordinary Session.
  219. * @param request - requested identity, location, and Agent preset.
  220. * @returns the Session identity and resolved preset when configured.
  221. */
  222. @Remote('create')
  223. create(request: SessionCreateRequest): Promise<SessionCreateValue> {
  224. return this.commands.create(request)
  225. }
  226. /**
  227. * Select one Session-local model after explicitly resuming the Session.
  228. * @param request - Session identity and requested model selection.
  229. * @returns the normalized selection installed for the Session.
  230. */
  231. @Remote('selectModel')
  232. selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
  233. return this.commands.selectModel(request)
  234. }
  235. /**
  236. * Describe every currently routable model for Host-generation selectors.
  237. * @returns provider-grouped models, the deployment default, and isolated provider failures.
  238. */
  239. @Remote('modelCatalog')
  240. modelCatalog(): Promise<ModelCatalog> {
  241. return buildModelCatalog(this.ctx)
  242. }
  243. /**
  244. * Report whether this deployment can hand a Session workspace path to a native desktop.
  245. * @returns true when the matching open operation is available.
  246. */
  247. @Remote
  248. canOpenWorkspacePath(): boolean {
  249. return this.canOpenPath()
  250. }
  251. /**
  252. * Open one path prepared by a Session-aware caller on the Host desktop.
  253. * @param request - path after best-effort Session workspace resolution.
  254. * @param signal - caller lifetime; abort terminates the native command.
  255. * @returns confirmation after the native opener accepts the path.
  256. * @throws RemoteError when the request is invalid, cancelled, or the opener fails.
  257. */
  258. @Remote('openWorkspacePath')
  259. async openWorkspacePath(
  260. request: SessionOpenWorkspacePathRequest,
  261. signal: AbortSignal,
  262. ): Promise<SessionOpenWorkspacePathValue> {
  263. if (request.path.length === 0) {
  264. throw new RemoteError(
  265. 'gateway/bad-request',
  266. 'session.openWorkspacePath requires a non-empty path',
  267. {},
  268. )
  269. }
  270. signal.throwIfAborted()
  271. try {
  272. await this.openPath(request.path, signal)
  273. return { opened: true }
  274. } catch (error: unknown) {
  275. if (signal.aborted) throw new RemoteError('gateway/cancelled', 'path open was aborted', {})
  276. throw new RemoteError(
  277. 'gateway/internal',
  278. `path open failed: ${error instanceof Error ? error.message : String(error)}`,
  279. {},
  280. )
  281. }
  282. }
  283. /**
  284. * Rename one Session after explicitly resuming it.
  285. * @param request - Session identity and proposed title.
  286. * @returns the accepted title and durable event sequence.
  287. */
  288. @Remote('rename')
  289. rename(request: SessionRenameRequest): Promise<SessionRenameValue> {
  290. return this.commands.rename(request)
  291. }
  292. /**
  293. * Fork one cold-readable completed-turn prefix into a new Session.
  294. * @param request - source Session and optional event anchor.
  295. * @returns the new Session identity.
  296. */
  297. @Remote('fork')
  298. fork(request: SessionForkRequest): Promise<SessionForkValue> {
  299. return this.commands.fork(request)
  300. }
  301. /**
  302. * Admit one prompt after explicitly resuming its Session.
  303. * @param request - Session identity, prompt content, source metadata, and delivery mode.
  304. * @param signal - caller cancellation before prompt admission begins.
  305. * @returns acknowledgement that the Agent accepted the prompt.
  306. */
  307. @Remote('prompt')
  308. prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue> {
  309. signal.throwIfAborted()
  310. return this.commands.prompt(request)
  311. }
  312. /**
  313. * Read one image proven reachable from the addressed Session log.
  314. * @param request - Session and attachment identities used for authorization.
  315. * @returns the durable attachment reference and base64-encoded bytes.
  316. */
  317. @Remote('attachment')
  318. attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue> {
  319. return this.commands.attachment(request)
  320. }
  321. /**
  322. * Persist one encoded file upload verbatim and stage it for a later prompt
  323. * on the same Session.
  324. * @param request - Session identity, base64 payload, and optional display name.
  325. * @param signal - caller cancellation before storage begins.
  326. * @returns an opaque per-upload receipt and the durable file reference.
  327. */
  328. @Remote('uploadFile')
  329. uploadFile(request: SessionUploadFileRequest, signal: AbortSignal): Promise<SessionUploadFileValue> {
  330. signal.throwIfAborted()
  331. return this.commands.uploadFile(request)
  332. }
  333. /**
  334. * Mutate one still-pending queue occurrence on a live Agent.
  335. * @param request - Session, queue item, and requested mutation.
  336. * @returns acknowledgement that the queue mutation was applied.
  337. */
  338. @Remote('updateQueue')
  339. updateQueue(request: SessionUpdateQueueRequest): SessionUpdateQueueValue {
  340. return this.commands.updateQueue(request)
  341. }
  342. /**
  343. * Cancel one active Agent turn without dropping its pending inbox.
  344. * @param request - Session whose active Agent turn is cancelled.
  345. * @returns acknowledgement that cancellation was requested.
  346. */
  347. @Remote('cancel')
  348. cancel(request: SessionCancelRequest): SessionCancelValue {
  349. return this.commands.cancel(request)
  350. }
  351. /**
  352. * Read one cold-safe, message-aligned Session history page.
  353. * @param request - durable address, backward cursor, and page budget.
  354. * @param signal - cancellation for persistence reads.
  355. * @returns one chronological page.
  356. */
  357. @Remote('page')
  358. page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage> {
  359. return this.history.page(request, signal)
  360. }
  361. /**
  362. * Follow one Session log from its opening or resume cursor.
  363. * @param request - durable address and last committed sequence already held by the caller.
  364. * @param signal - cancellation owned by the Remote stream carrier.
  365. * @returns a complete opening snapshot followed by gap-free event frames.
  366. */
  367. @Remote({ mode: 'stream' })
  368. follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame> {
  369. return this.history.follow(request, signal)
  370. }
  371. /**
  372. * Stream a complete live-control baseline followed by replacement frames.
  373. * @param signal - cancellation owned by the Remote stream carrier.
  374. * @returns one complete baseline followed by live replacement frames.
  375. */
  376. @Remote({ mode: 'stream' })
  377. control(signal: AbortSignal): AsyncIterable<SessionControlFrame> {
  378. return this.controlState.control(signal)
  379. }
  380. }
  381. export { buildModelCatalog }
  382. export default SessionController