server.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /**
  2. * JSON-RPC method and notification surface for out-of-process harness SDKs.
  3. * The surrounding context owns plugins, persistence, and configured adapters.
  4. *
  5. * @module @deepseek-ai/dsh-jsonrpc/server
  6. */
  7. import type { Context } from 'cordis'
  8. import { resolve } from 'node:path'
  9. import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
  10. import { carrierKeyOf, type Scoped } from '@deepseek-ai/dsh-scope'
  11. import { findLastMessageTurnEnd, SessionId, type TurnEndReason } from '@deepseek-ai/dsh-session'
  12. import type SubagentService from '@deepseek-ai/dsh-subagent'
  13. import type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent'
  14. import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
  15. import type {
  16. InitializeParams,
  17. InitializeResult,
  18. JsonRpcTransportPeer,
  19. SessionEventNotification,
  20. SessionFinishedNotification,
  21. SessionPromptParams,
  22. SessionPromptResult,
  23. SubagentFinishedNotification,
  24. SubagentStartedNotification,
  25. } from '@deepseek-ai/dsh-sdk-protocol'
  26. interface SessionRecord {
  27. handle: AgentHandle
  28. lastTurnEnd: TurnEndReason | undefined
  29. activePrompt: boolean
  30. }
  31. /** Recover the delegating parent from the service-owned scoped carrier. */
  32. function subagentParentOf(carrier: Scoped<SubagentService>): Agent {
  33. return carrierKeyOf(carrier) as Agent
  34. }
  35. /** Deployment-specific status mapping for SDK turn and subagent outcomes. */
  36. export interface HarnessSdkServerOptions {
  37. /** Report max-token termination as an accepted result instead of an infrastructure error. */
  38. maxTokensAsSuccess?: boolean
  39. }
  40. function successStatus(reason: string, options: HarnessSdkServerOptions): 'ok' | 'error' {
  41. if (reason === 'completed') return 'ok'
  42. return reason === 'max-tokens' && options.maxTokensAsSuccess === true ? 'ok' : 'error'
  43. }
  44. /**
  45. * SDK server over one booted harness context and transport peer. Construction
  46. * subscribes to session, agent, and subagent lifecycle events until shutdown;
  47. * reinitialization is unsupported.
  48. */
  49. export class HarnessSdkServer {
  50. private cwd = process.cwd()
  51. private provider = 'deepseek'
  52. private model = 'deepseek'
  53. private llmFiber: { dispose(): Promise<void> } | undefined
  54. private readonly sessions = new Map<string, SessionRecord>()
  55. private readonly sessionCreations = new Map<string, Promise<SessionRecord>>()
  56. private readonly disposers: (() => void)[] = []
  57. private shutdownTask: Promise<Record<string, never>> | undefined
  58. private shuttingDown = false
  59. constructor(
  60. private readonly ctx: Context,
  61. private readonly transport: JsonRpcTransportPeer,
  62. private readonly options: HarnessSdkServerOptions = {},
  63. ) {
  64. const serverOptions = this.options
  65. this.disposers.push(ctx.on('session/event', (session, event) => {
  66. if (event.type === 'turn/end') {
  67. const rec = this.sessions.get(String(session.id))
  68. if (rec && findLastMessageTurnEnd(session.events)?.seq === event.seq) {
  69. rec.lastTurnEnd = event.data.reason
  70. }
  71. }
  72. const payload: SessionEventNotification = { sessionId: String(session.id), event }
  73. this.transport.notify('session.event', payload)
  74. }))
  75. this.disposers.push(ctx.on('session/created', (session) => {
  76. const parentSession = session.header.parentSession
  77. if (parentSession === undefined) return
  78. const payload: SubagentStartedNotification = {
  79. parentSessionId: String(parentSession),
  80. childSessionId: String(session.id),
  81. }
  82. this.transport.notify('subagent.started', payload)
  83. }))
  84. this.disposers.push(ctx.on('subagent/end', function (this: Scoped<SubagentService>, info: SubagentRunEndInfo) {
  85. const parent = subagentParentOf(this)
  86. // This protocol reports only in-process child sessions. The service
  87. // snapshots the provider's exact run provenance through child disposal;
  88. // matching ids or parent lineage alone never establishes locality.
  89. if (!info.local) return
  90. const payload: SubagentFinishedNotification = {
  91. provider: info.provider,
  92. agentId: String(info.id),
  93. parentSessionId: String(parent.session.id),
  94. childSessionId: String(info.id),
  95. status: successStatus(info.stopReason, serverOptions),
  96. stopReason: info.stopReason,
  97. ...(info.lastAssistantMessage === undefined ? {} : { lastAssistantMessage: info.lastAssistantMessage }),
  98. }
  99. transport.notify('subagent.finished', payload)
  100. }))
  101. }
  102. /**
  103. * Configure the SDK route, mounting the DeepSeek fallback only when unowned.
  104. * @param params - SDK handshake parameters.
  105. * @returns server identity for the handshake.
  106. */
  107. async initialize(params: InitializeParams): Promise<InitializeResult> {
  108. this.cwd = resolve(params.cwd)
  109. this.provider = params.provider
  110. this.model = params.model
  111. if (!this.hasAdapterFor(this.provider)) {
  112. if (this.provider !== 'deepseek') throw new Error(`no adapter registered for provider "${this.provider}"`)
  113. this.llmFiber = await this.ctx.plugin(LlmDeepSeek, {})
  114. }
  115. return { serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' } }
  116. }
  117. /**
  118. * Run one prompt to settlement; overlap on the same session fails.
  119. * @param params - target session and user content.
  120. * @returns acceptance after the turn settled.
  121. */
  122. async prompt(params: SessionPromptParams): Promise<SessionPromptResult> {
  123. const rec = await this.getOrCreateSession(params.sessionId)
  124. if (rec.activePrompt) throw new Error(`session already has an active prompt: ${params.sessionId}`)
  125. // An agent-loop-only reload disposes the loop's agents while this record
  126. // survives; a retained agent accepts followup() silently, so validate the
  127. // record against the live registry before delivery (as the ACP bridge does).
  128. if (this.ctx.agents.get(rec.handle.agent.id) !== rec.handle.agent) {
  129. throw new Error(`session agent was disposed outside the server: ${params.sessionId}`)
  130. }
  131. rec.activePrompt = true
  132. try {
  133. rec.lastTurnEnd = undefined
  134. rec.handle.agent.followup({ content: params.contentBlocks, source: { kind: 'user' } })
  135. await rec.handle.agent.whenIdle()
  136. const payload: SessionFinishedNotification = {
  137. sessionId: params.sessionId,
  138. status: this.finishedStatus(rec.lastTurnEnd),
  139. reason: rec.lastTurnEnd,
  140. }
  141. this.transport.notify('session.finished', payload)
  142. return { accepted: true }
  143. } finally {
  144. rec.activePrompt = false
  145. }
  146. }
  147. /**
  148. * Dispose server-owned agents, adapter, and subscriptions to quiescence.
  149. * The surrounding context remains running.
  150. * @returns empty JSON-RPC result.
  151. */
  152. shutdown(): Promise<Record<string, never>> {
  153. this.shutdownTask ??= this.performShutdown()
  154. return this.shutdownTask
  155. }
  156. private async performShutdown(): Promise<Record<string, never>> {
  157. this.shuttingDown = true
  158. const pendingCreations = [...this.sessionCreations.values()]
  159. await Promise.allSettled(pendingCreations)
  160. this.sessionCreations.clear()
  161. const records = [...this.sessions.values()]
  162. this.sessions.clear()
  163. const failures: unknown[] = []
  164. while (this.disposers.length > 0) {
  165. try {
  166. this.disposers.pop()?.()
  167. } catch (error) {
  168. failures.push(error)
  169. }
  170. }
  171. const teardownResults = await Promise.allSettled([
  172. ...records.map(rec => Promise.resolve().then(() => rec.handle.dispose())),
  173. ...(this.llmFiber === undefined ? [] : [Promise.resolve().then(() => this.llmFiber?.dispose())]),
  174. ])
  175. this.llmFiber = undefined
  176. failures.push(...teardownResults
  177. .filter((result): result is PromiseRejectedResult => result.status === 'rejected')
  178. .map(result => result.reason as unknown))
  179. if (failures.length === 1) throw failures[0]
  180. if (failures.length > 1) throw new AggregateError(failures, 'SDK server teardown failed')
  181. return {}
  182. }
  183. /**
  184. * Dispatch one incoming JSON-RPC request to its typed handler. Throws (→ a
  185. * JSON-RPC error response) on an unknown method.
  186. * @param method - the JSON-RPC method name.
  187. * @param params - the raw params object from the wire.
  188. * @returns the handler's result, to be serialized as the response.
  189. */
  190. async handleRequest(method: string, params: Record<string, unknown> | undefined): Promise<unknown> {
  191. switch (method) {
  192. case 'initialize':
  193. return this.initialize(params as unknown as InitializeParams)
  194. case 'session/prompt':
  195. return this.prompt(params as unknown as SessionPromptParams)
  196. case 'shutdown':
  197. return this.shutdown()
  198. default:
  199. throw new Error(`unknown DeepSeek Harness SDK runtime method: ${method}`)
  200. }
  201. }
  202. private async getOrCreateSession(sessionId: string): Promise<SessionRecord> {
  203. if (this.shuttingDown) throw new Error('SDK server is shutting down')
  204. const existing = this.sessions.get(sessionId)
  205. if (existing) return existing
  206. const pending = this.sessionCreations.get(sessionId)
  207. if (pending) return pending
  208. const creation = this.createSession(sessionId)
  209. this.sessionCreations.set(sessionId, creation)
  210. void creation.then(
  211. () => { this.sessionCreations.delete(sessionId) },
  212. () => { this.sessionCreations.delete(sessionId) },
  213. )
  214. return creation
  215. }
  216. private async createSession(sessionId: string): Promise<SessionRecord> {
  217. const handle = await this.ctx.agents.create({
  218. sessionId: SessionId(sessionId),
  219. meta: { cwd: this.cwd },
  220. agentOptions: { provider: this.provider, model: this.model },
  221. })
  222. const rec: SessionRecord = { handle, lastTurnEnd: undefined, activePrompt: false }
  223. this.sessions.set(sessionId, rec)
  224. return rec
  225. }
  226. private finishedStatus(reason: TurnEndReason | undefined): 'ok' | 'error' {
  227. if (!reason) return 'error'
  228. return successStatus(reason.kind, this.options)
  229. }
  230. private hasAdapterFor(provider: string): boolean {
  231. return this.ctx.get('llm')?.listProviders().some(entry => entry.id === provider) ?? false
  232. }
  233. }