index.ts 14 KB

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