index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 {} from '@deepseek-ai/dsh-client-file-upload'
  6. import { canOpenNativePath, openNativePath } from '@deepseek-ai/dsh-native-command'
  7. import type { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence'
  9. import type { SessionObservation } from '@deepseek-ai/dsh-session-query'
  10. import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
  11. import {
  12. ApiSessionAgentController,
  13. inspectApiSession,
  14. type ApiSessionAgentResult,
  15. } from './agent.ts'
  16. import { SessionCommandController } from './commands.ts'
  17. import { SessionControlController } from './control.ts'
  18. import { SessionHistoryController } from './history.ts'
  19. import { SessionFileReferences } from './file-references.ts'
  20. import { ApiSessionList } from './list.ts'
  21. import { buildModelCatalog } from './catalog.ts'
  22. import { installModelSelectionProjection } from './model-selection-projection.ts'
  23. import { SessionSkillCatalog } from './skill-catalog.ts'
  24. import { SessionMediaReferences } from './media-references.ts'
  25. import type {
  26. ModelCatalog,
  27. SessionAttachmentRequest,
  28. SessionAttachmentValue,
  29. SessionCancelRequest,
  30. SessionCancelValue,
  31. SessionControlFrame,
  32. SessionCreateRequest,
  33. SessionCreateValue,
  34. SessionFollowFrame,
  35. SessionFollowRequest,
  36. SessionForkRequest,
  37. SessionForkValue,
  38. SessionListRequest,
  39. SessionListValue,
  40. SessionOpenWorkspacePathRequest,
  41. SessionOpenWorkspacePathValue,
  42. SessionPage,
  43. SessionPageRequest,
  44. SessionPromptRequest,
  45. SessionPromptValue,
  46. SessionRenameRequest,
  47. SessionRenameValue,
  48. SessionSearchRequest,
  49. SessionSearchValue,
  50. SessionSelectModelRequest,
  51. SessionSelectModelValue,
  52. SessionUpdateQueueRequest,
  53. SessionUpdateQueueValue,
  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. /** Override platform desktop-opener detection. */
  68. readonly nativeOpen?: boolean
  69. }
  70. /** Host integrations replaceable by direct unit tests. */
  71. export interface SessionControllerInternals {
  72. /** Native default-application handoff. */
  73. readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
  74. /** Native handoff availability probe. */
  75. readonly canOpenPath?: () => boolean
  76. }
  77. /** Host service backing the generated `ctx.remote.session` namespace. */
  78. export class SessionController extends TypertRemoteService {
  79. static inject = [
  80. 'agentDefaultModel',
  81. 'agents',
  82. 'attachments',
  83. 'fileUploads',
  84. 'llm',
  85. 'sessions',
  86. 'sessionProjections',
  87. 'sessionQuery',
  88. 'typert',
  89. 'workspaceRegistry',
  90. ]
  91. static Config: z<Config> = z.object({
  92. nativeOpen: z.boolean(),
  93. })
  94. private readonly agents: ApiSessionAgentController
  95. private readonly commands: SessionCommandController
  96. private readonly controlState: SessionControlController
  97. private readonly history: SessionHistoryController
  98. private readonly listState: ApiSessionList
  99. private readonly openPath: (path: string, signal: AbortSignal) => Promise<void>
  100. private readonly canOpenPath: () => boolean
  101. private readonly promotions = new Set<Promise<void>>()
  102. /**
  103. * @param ctx - Host context containing the Session capability assembly.
  104. * @param config - native-opener deployment policy.
  105. * @param internals - host integrations replaceable by direct unit tests.
  106. */
  107. constructor(ctx: Context, config: Config, internals: SessionControllerInternals = {}) {
  108. super(ctx, 'sessionController', { namespace: 'session' })
  109. installModelSelectionProjection(ctx)
  110. this.agents = new ApiSessionAgentController(ctx)
  111. this.commands = new SessionCommandController(ctx, this.agents, process.cwd())
  112. ctx.effect(() => ctx.fileUploads.registerAgentResolver(async (sessionId) => {
  113. const result = await this.agents.resolveAgent(sessionId)
  114. if ('error' in result) throw result.error
  115. return result.agent
  116. }), 'session-controller: file-upload Agent resolver')
  117. this.controlState = new SessionControlController(ctx)
  118. // Registered before history so reverse-order teardown closes every
  119. // follower before waiting for already-admitted promotions.
  120. ctx.effect(() => async () => {
  121. await Promise.allSettled([...this.promotions])
  122. }, 'session-controller.promotions')
  123. this.history = new SessionHistoryController(ctx, (observation) => { this.promote(observation) })
  124. this.listState = new ApiSessionList(ctx)
  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(SessionMediaReferences)
  130. ctx.plugin(SessionSkillCatalog)
  131. ctx.on('session/created', (session) => {
  132. ctx.emit('api-session/added', this.listState.summaryFor(session))
  133. })
  134. ctx.on('session/disposed', (session) => {
  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 === 'request/header') {
  145. const agent = ctx.agents.get(session.id)
  146. if (agent?.session === session) this.agents.consumeSelection(
  147. agent,
  148. event.data.header.config.provider,
  149. event.data.header.config.model,
  150. event.data.header.config.reasoningEffort,
  151. )
  152. }
  153. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return
  154. ctx.emit('api-session/activity', session.id, event.time)
  155. })
  156. }
  157. private promote(observation: SessionObservation): void {
  158. const sessionId = observation.header.id
  159. const task = (async () => {
  160. using ownedObservation = observation
  161. const result = await this.agents.resolveObservedAgent(ownedObservation)
  162. if ('error' in result) this.ctx.emit('api-session/error', sessionId, result.error.message)
  163. })().catch((error: unknown) => {
  164. this.ctx.logger.error(`session-controller: background activation for "${sessionId}" failed: ${errorChain(error)}`)
  165. })
  166. this.promotions.add(task)
  167. void task.finally(() => { this.promotions.delete(task) })
  168. }
  169. /**
  170. * Resolve or resume one ordinary Session for another Host API domain.
  171. * @param sessionId - Session identity whose Agent owns the operation.
  172. * @returns the live Agent or the stable Session-domain failure.
  173. */
  174. resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult> {
  175. return this.agents.resolveAgent(sessionId)
  176. }
  177. /**
  178. * Inspect one attached or persisted Session without activating its Agent.
  179. * @param sessionId - durable Session identity.
  180. * @param signal - optional caller cancellation for persistence reads.
  181. * @returns the current attached state or persisted header and event prefix.
  182. */
  183. inspect(
  184. sessionId: SessionId,
  185. signal?: AbortSignal,
  186. ): Promise<SessionInspection> {
  187. const attached = this.ctx.sessions.get(sessionId)
  188. if (attached !== undefined) {
  189. return Promise.resolve({
  190. meta: attached.header,
  191. inheritedEventCount: attached.inheritedEventCount,
  192. events: attached.snapshotEvents(),
  193. })
  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. * Mutate one still-pending queue occurrence on a live Agent.
  323. * @param request - Session, queue item, and requested mutation.
  324. * @returns acknowledgement that the queue mutation was applied.
  325. */
  326. @Remote('updateQueue')
  327. updateQueue(request: SessionUpdateQueueRequest): SessionUpdateQueueValue {
  328. return this.commands.updateQueue(request)
  329. }
  330. /**
  331. * Cancel one active Agent turn without dropping its pending inbox.
  332. * @param request - Session whose active Agent turn is cancelled.
  333. * @returns acknowledgement that cancellation was requested.
  334. */
  335. @Remote('cancel')
  336. cancel(request: SessionCancelRequest): SessionCancelValue {
  337. return this.commands.cancel(request)
  338. }
  339. /**
  340. * Read one cold-safe, message-aligned Session history page.
  341. * @param request - durable address, backward cursor, and page budget.
  342. * @param signal - cancellation for persistence reads.
  343. * @returns one chronological page.
  344. */
  345. @Remote('page')
  346. page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage> {
  347. return this.history.page(request, signal)
  348. }
  349. /**
  350. * Follow one Session log from its opening or resume cursor.
  351. * @param request - durable address and last committed sequence already held by the caller.
  352. * @param signal - cancellation owned by the Remote stream carrier.
  353. * @returns a complete opening snapshot followed by gap-free durable event
  354. * frames and optional cursorless assistant-stream frames.
  355. */
  356. @Remote({ mode: 'stream' })
  357. follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame> {
  358. return this.history.follow(request, signal)
  359. }
  360. /**
  361. * Stream a complete live-control baseline followed by replacement frames.
  362. * @param signal - cancellation owned by the Remote stream carrier.
  363. * @returns one complete baseline followed by live replacement frames.
  364. */
  365. @Remote({ mode: 'stream' })
  366. control(signal: AbortSignal): AsyncIterable<SessionControlFrame> {
  367. return this.controlState.control(signal)
  368. }
  369. }
  370. export { buildModelCatalog }
  371. export default SessionController