index.ts 14 KB

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