index.ts 14 KB

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