server.ts 11 KB

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