* feat(sdk): report why a session agent was disposed A request for a session whose agent left the registry now states whether the whole runtime is shutting down, the SDK server is shutting down, or only the agent loop was unloaded. During runtime shutdown it names the last process event observed before teardown; for an agent-loop unload it gives the time and the plugin whose unload began first. The liveness check reads the registry as optional, so both stages of root disposal report the same failure. Refs #8737 * fix(sdk): keep the runtime observation out of the plugin entry exports The static gates reject a new read of the Cordis root context, a value export from a function plugin entry, and new assertions to unknown. The plugin entry now passes the server an observation built from the root fiber it already holds, the helper lives in the internal process-events module, and the new tests complete the handshake instead of casting the server. Refs #8737 * fix(sdk): keep the process-event record from throwing and state the unload origin as an observation A rejection value without a string form made the failure text throw inside a prepended listener, which would end the dispatch before the listener that owns the event. The text now falls back to a fixed marker. The plugin named for an agent-loop unload is the first one unloading at that time, which overlapping unloads can make unrelated, so the message and README say that. Refs #8737 * feat(python-sdk): log the runtime's stderr lines as they arrive The runtime writes its fatal report, including the stack of an unhandled rejection that ends the process, to its own stderr. The SDK kept those lines in memory and attached them only to initialization, timeout, and transport failures, so a host saw none of it for an ordinary JSON-RPC error. Each line now also goes to the Python logger deepseek_harness.runtime at INFO. Refs #8737
741 lines
35 KiB
TypeScript
741 lines
35 KiB
TypeScript
/**
|
|
* JSON-RPC methods and notifications for out-of-process harness SDKs.
|
|
* The surrounding context owns plugins, persistence, and configured adapters.
|
|
*
|
|
* @module @deepseek-ai/dsh-sdk-jsonrpc-server/server
|
|
*/
|
|
|
|
import type {} from '@deepseek-ai/dsh-fs'
|
|
import { FiberState, type Context, type Fiber } from '@deepseek-ai/cordis'
|
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
import { resolve } from 'node:path'
|
|
import { QueryActivity } from './query-activity.ts'
|
|
import { SdkUserQuestionBridge } from './user-questions.ts'
|
|
import { queryCommand } from './query-input.ts'
|
|
import { queryCommandImages, queryContent } from './query-content.ts'
|
|
import { brandString } from '@deepseek-ai/dsh-brand'
|
|
import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
|
|
import { admitEncodedImages, type EncodedImageAttachment, type ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
|
|
import { createUserMessage, type ReasoningEffortId, type ContentBlock, type LlmRuntime } from '@deepseek-ai/dsh-llm'
|
|
import type { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
|
import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time'
|
|
import type {} from '@deepseek-ai/dsh-working-directory'
|
|
import type {} from '@deepseek-ai/dsh-user-approval'
|
|
import type {} from '@deepseek-ai/dsh-permission-presets'
|
|
|
|
import type {} from '@deepseek-ai/dsh-schedule'
|
|
import type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent'
|
|
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
|
|
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
|
|
import type {
|
|
ApprovalRequestParams,
|
|
CommandExecution,
|
|
InitializeParams,
|
|
InitializeResult,
|
|
JsonRpcTransportPeer,
|
|
SessionEventNotification,
|
|
SessionQueryParams,
|
|
SessionQueryResult,
|
|
SessionPromptParams,
|
|
SessionPromptResult,
|
|
SessionResumeParams,
|
|
SessionWaitParams,
|
|
SessionWorkingDirectoryParams,
|
|
SessionWorkingDirectorySetParams,
|
|
SessionWorkingDirectoryResult,
|
|
SdkEncodedImageBlock,
|
|
SubagentFinishedNotification,
|
|
SubagentStartedNotification,
|
|
} from '@deepseek-ai/dsh-sdk-protocol'
|
|
|
|
declare module '@deepseek-ai/dsh-llm' {
|
|
interface MessageSourceMap {
|
|
/** SDK prompt with its canonical user time zone, when one was reported or sampled. */
|
|
'sdk-user': { kind: 'user'; clientTimeZone?: string }
|
|
}
|
|
}
|
|
|
|
interface SessionRecord {
|
|
handle: AgentHandle
|
|
/** Latest live failure not superseded by a subsequently committed terminal. */
|
|
failure: { readonly error: unknown; readonly atOffset: SessionLogOffset } | undefined
|
|
/** When the registry dropped this Agent while the server still held its handle, and the first plugin unloading at that time. */
|
|
disposal: { readonly at: Date; readonly origin: string | undefined } | undefined
|
|
}
|
|
|
|
/** A process event observed by the hosting plugin entry. */
|
|
export interface RuntimeProcessEvent {
|
|
/** Event name and, for a failure, the first line of its message. */
|
|
readonly description: string
|
|
readonly at: Date
|
|
}
|
|
|
|
/** What the hosting plugin entry observes about the runtime that surrounds the server. */
|
|
export interface RuntimeObservation {
|
|
/** Whether disposal of the whole runtime is in progress, which ends every plugin in the process. */
|
|
unloading(): boolean
|
|
/** The last process event recorded before that disposal began; an observation, not an established cause. */
|
|
lastProcessEvent(): RuntimeProcessEvent | undefined
|
|
}
|
|
|
|
function encodedImage(block: SessionPromptParams['contentBlocks'][number]): block is SdkEncodedImageBlock {
|
|
return block.type === 'image' && 'data' in block
|
|
}
|
|
|
|
async function durablePromptContent(ctx: Context, blocks: SessionPromptParams['contentBlocks']): Promise<ContentBlock[]> {
|
|
const images = blocks.filter(encodedImage)
|
|
if (images.length === 0) return blocks as ContentBlock[]
|
|
const attachments = ctx.get('attachments')
|
|
if (attachments === undefined) throw new Error('SDK image prompt requires an attachment store')
|
|
const refs = await admitEncodedImages(attachments, images.map((image): EncodedImageAttachment => ({
|
|
data: image.data,
|
|
mediaType: image.mimeType,
|
|
...image.name === undefined ? {} : { name: image.name },
|
|
})))
|
|
let next = 0
|
|
return blocks.map(block => encodedImage(block)
|
|
? { type: 'image', attachment: refs[next++] as ImageAttachmentRef }
|
|
: block)
|
|
}
|
|
|
|
/**
|
|
* Resolve the canonical zone recorded on one SDK prompt.
|
|
* An explicit zone must canonicalize; an omitted zone samples this process at call time.
|
|
* @param requested - caller-reported zone, or undefined to sample the process zone.
|
|
* @returns the canonical zone, or undefined when the sampled process zone is absent or unusable.
|
|
* @throws TypeError naming the rejected explicit value and the accepted formats.
|
|
*/
|
|
function promptTimeZone(requested: string | undefined): string | undefined {
|
|
if (requested !== undefined) {
|
|
const canonical = canonicalClientTimeZone(requested)
|
|
if (canonical === undefined) {
|
|
throw new TypeError(`timeZone must be UTC or a valid IANA Area/Location name: ${JSON.stringify(requested)}`)
|
|
}
|
|
return canonical
|
|
}
|
|
// ICU reports an unknown TZ as undefined, Etc/Unknown, or an offset such as +00:00 for TZ=GMT.
|
|
const sampled = new Intl.DateTimeFormat().resolvedOptions().timeZone as string | undefined
|
|
return sampled === undefined ? undefined : canonicalClientTimeZone(sampled)
|
|
}
|
|
|
|
/** Deployment-specific status mapping for SDK turn and subagent outcomes. */
|
|
export interface HarnessSdkJsonRpcServerOptions {
|
|
/** Report max-token termination as an accepted result instead of an infrastructure error. */
|
|
maxTokensAsSuccess?: boolean
|
|
/** Runtime state that a liveness failure reports; without it the failure makes no statement about the runtime. */
|
|
runtime?: RuntimeObservation
|
|
}
|
|
|
|
function successStatus(reason: string, options: HarnessSdkJsonRpcServerOptions): 'ok' | 'error' {
|
|
if (reason === 'completed') return 'ok'
|
|
return reason === 'max-tokens' && options.maxTokensAsSuccess === true ? 'ok' : 'error'
|
|
}
|
|
|
|
/**
|
|
* SDK server over one booted harness context and transport peer. Construction
|
|
* subscribes to session, agent, and subagent lifecycle events until shutdown;
|
|
* reinitialization is unsupported.
|
|
*/
|
|
export class HarnessSdkJsonRpcServer {
|
|
private cwd = process.cwd()
|
|
private provider = 'deepseek-official'
|
|
private model = 'deepseek-official'
|
|
private reasoningEffort: ReasoningEffortId | undefined
|
|
private maxTokens: number | undefined
|
|
private llmFiber: { dispose(): Promise<void> } | undefined
|
|
private authFiber: { dispose(): Promise<void> } | undefined
|
|
private readonly sessions = new Map<string, SessionRecord>()
|
|
private readonly sessionCreations = new Map<string, Promise<SessionRecord>>()
|
|
private readonly commandTasks = new Set<Promise<CommandExecution | undefined>>()
|
|
private readonly queryInvocation = new AsyncLocalStorage<QueryActivity>()
|
|
private readonly queryActivities = new Set<QueryActivity>()
|
|
private readonly goalLifetime: { dispose(): Promise<void> }
|
|
private readonly disposers: (() => void)[] = []
|
|
private shutdownTask: Promise<Record<string, never>> | undefined
|
|
private shuttingDown = false
|
|
private readonly unloading = new Set<Fiber>()
|
|
/** Name of the plugin whose unload began while no other was in progress; overlapping unloads can make it an unrelated plugin. */
|
|
private unloadOrigin: string | undefined
|
|
private initialized = false
|
|
private approvalRequests = false
|
|
private readonly lifetime = new AbortController()
|
|
private readonly userQuestions: SdkUserQuestionBridge
|
|
private readonly initialization = Promise.withResolvers<void>()
|
|
/** Restored by a reminder and available for the client's first resume. */
|
|
private readonly scheduledSessions = new Map<string, Promise<SessionRecord>>()
|
|
|
|
constructor(
|
|
private readonly ctx: Context,
|
|
private readonly transport: JsonRpcTransportPeer,
|
|
private readonly options: HarnessSdkJsonRpcServerOptions = {},
|
|
) {
|
|
this.goalLifetime = ctx.inject(['goals'], (goalCtx) => {
|
|
goalCtx.effect(() => () => {
|
|
for (const activity of this.queryActivities) activity.goalUnavailable()
|
|
})
|
|
})
|
|
this.disposers.push(ctx.on('approval/request', async (request, next) => {
|
|
if (!this.approvalRequests || !this.ownsAgent(request.agent)) return next()
|
|
const params: ApprovalRequestParams = {
|
|
sessionId: request.agent.session.id,
|
|
toolName: request.toolName,
|
|
...(request.callId === undefined ? {} : { callId: request.callId }),
|
|
...(request.reason === undefined ? {} : { reason: request.reason }),
|
|
}
|
|
const signal = request.signal === undefined
|
|
? this.lifetime.signal
|
|
: AbortSignal.any([request.signal, this.lifetime.signal])
|
|
const result = await this.transport.request('approval/request', params, signal)
|
|
if (result === null || typeof result !== 'object' || !('outcome' in result)
|
|
|| (result.outcome !== 'allowed-once' && result.outcome !== 'rejected' && result.outcome !== 'cancelled')) {
|
|
throw new TypeError('approval/request response requires an allowed-once, rejected, or cancelled outcome')
|
|
}
|
|
return result.outcome
|
|
}))
|
|
const serverOptions = this.options
|
|
this.userQuestions = new SdkUserQuestionBridge(ctx, transport, agent =>
|
|
this.sessions.get(agent.session.id)?.handle.agent === agent)
|
|
this.disposers.push(ctx.on('schedule/resolve-agent', async (sessionId) => {
|
|
// Startup delivery must wait for the SDK model route and output limit.
|
|
await this.initialization.promise
|
|
if (this.shuttingDown) throw new Error('SDK server is shutting down')
|
|
const existing = this.sessions.get(sessionId)
|
|
const pending = this.sessionCreations.get(sessionId)
|
|
if (existing !== undefined) {
|
|
this.assertLiveAgent(existing, sessionId)
|
|
return existing.handle.agent
|
|
}
|
|
if (pending !== undefined) return (await pending).handle.agent
|
|
const restoration = this.openSession(sessionId, true)
|
|
this.scheduledSessions.set(sessionId, restoration)
|
|
try {
|
|
return (await restoration).handle.agent
|
|
} catch (error) {
|
|
this.scheduledSessions.delete(sessionId)
|
|
throw error
|
|
}
|
|
}))
|
|
this.disposers.push(ctx.on('session/event', (session, event) => {
|
|
const record = this.sessions.get(session.id)
|
|
if (event.type === 'turn/end' && record?.handle.agent.session === session
|
|
&& record.failure !== undefined && event.seq >= record.failure.atOffset) {
|
|
record.failure = undefined
|
|
}
|
|
const payload: SessionEventNotification = { sessionId: String(session.id), event }
|
|
this.transport.notify('session.event', payload)
|
|
}))
|
|
this.disposers.push(ctx.on('agent/error', ({ agent, error }) => {
|
|
const record = this.sessions.get(agent.session.id)
|
|
if (record?.handle.agent !== agent) return
|
|
record.failure = { error, atOffset: agent.session.seq }
|
|
}))
|
|
this.disposers.push(ctx.on('agent/disposed', ({ agent }) => {
|
|
const record = this.sessions.get(agent.session.id)
|
|
if (record?.handle.agent === agent) record.disposal = { at: new Date(), origin: this.unloadOrigin }
|
|
}))
|
|
this.disposers.push(ctx.on('internal/status', (fiber, previous) => {
|
|
if (fiber.state === FiberState.UNLOADING) {
|
|
if (this.unloading.size === 0) this.unloadOrigin = fiber.name
|
|
this.unloading.add(fiber)
|
|
} else if (previous === FiberState.UNLOADING) {
|
|
this.unloading.delete(fiber)
|
|
if (this.unloading.size === 0) this.unloadOrigin = undefined
|
|
}
|
|
}))
|
|
this.disposers.push(ctx.on('agent/status', ({ agent, status }) => {
|
|
this.transport.notify('session.status', { sessionId: String(agent.session.id), status })
|
|
}))
|
|
this.disposers.push(ctx.on('session/created', (session) => {
|
|
const parentSession = session.header.parentSession
|
|
if (session.header.origin !== 'subagent' || parentSession === undefined) return
|
|
const payload: SubagentStartedNotification = {
|
|
parentSessionId: String(parentSession),
|
|
childSessionId: String(session.id),
|
|
}
|
|
this.transport.notify('subagent.started', payload)
|
|
}))
|
|
this.disposers.push(ctx.on('subagent/end', (info: SubagentRunEndInfo) => {
|
|
// This protocol reports only in-process child sessions. The service
|
|
// snapshots the provider name and local flag through child disposal;
|
|
// matching ids or parent lineage alone never establishes locality.
|
|
if (!info.local) return
|
|
const payload: SubagentFinishedNotification = {
|
|
provider: info.provider,
|
|
agentId: String(info.id),
|
|
parentSessionId: String(info.parentSessionId),
|
|
childSessionId: String(info.id),
|
|
status: successStatus(info.stopReason, serverOptions),
|
|
stopReason: info.stopReason,
|
|
...(info.lastAssistantMessage === undefined
|
|
? {}
|
|
: { lastAssistantMessage: [...info.lastAssistantMessage] }),
|
|
}
|
|
transport.notify('subagent.finished', payload)
|
|
}))
|
|
}
|
|
|
|
/**
|
|
* Validate and configure the SDK route, mounting the DeepSeek fallback only when unowned.
|
|
* @param params - SDK handshake parameters.
|
|
* @returns server identity for the handshake.
|
|
*/
|
|
async initialize(params: InitializeParams): Promise<InitializeResult> {
|
|
if (params.approvalRequests !== undefined && typeof params.approvalRequests !== 'boolean') {
|
|
throw new TypeError('initialize approvalRequests must be a boolean')
|
|
}
|
|
if (params.reasoningEffort !== undefined
|
|
&& (typeof params.reasoningEffort !== 'string' || params.reasoningEffort.length === 0)) {
|
|
throw new TypeError('initialize reasoningEffort must be a non-empty string')
|
|
}
|
|
if (params.maxTokens !== undefined
|
|
&& (!Number.isSafeInteger(params.maxTokens) || params.maxTokens <= 0)) {
|
|
throw new TypeError('initialize maxTokens must be a positive safe integer')
|
|
}
|
|
const cwd = resolve(params.cwd)
|
|
const provider = params.provider
|
|
const model = params.model
|
|
const reasoningEffort = params.reasoningEffort === undefined
|
|
? undefined
|
|
: brandString<ReasoningEffortId>(params.reasoningEffort)
|
|
if (!this.hasAdapterFor(provider)) {
|
|
if (provider !== 'deepseek-official') throw new Error(`no adapter registered for provider "${provider}"`)
|
|
// The route requires the DeepSeek authentication service; a composition without one gets it with the fallback route.
|
|
if (this.ctx.get('deepseekAuth') === undefined) this.authFiber = await this.ctx.plugin(DeepSeekAuth)
|
|
try {
|
|
this.llmFiber = await this.ctx.plugin(LlmDeepSeek)
|
|
} catch (error: unknown) {
|
|
// Without the route nothing here uses the authentication service this call mounted.
|
|
const mounted = this.authFiber
|
|
this.authFiber = undefined
|
|
await mounted?.dispose()
|
|
throw error
|
|
}
|
|
}
|
|
// Adapter presence was read from this service above; a successful fallback mount also requires it.
|
|
const llm = this.ctx.get('llm') as LlmRuntime
|
|
await llm.resolveCallConfig({
|
|
provider,
|
|
model,
|
|
...reasoningEffort === undefined ? {} : { reasoningEffort },
|
|
...params.maxTokens === undefined ? {} : { maxTokens: params.maxTokens },
|
|
})
|
|
this.cwd = cwd
|
|
this.provider = provider
|
|
this.model = model
|
|
this.reasoningEffort = reasoningEffort
|
|
this.maxTokens = params.maxTokens
|
|
this.approvalRequests = params.approvalRequests === true
|
|
this.userQuestions.enabled = params.capabilities?.userQuestions === true
|
|
this.initialized = true
|
|
this.initialization.resolve()
|
|
return { serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' } }
|
|
}
|
|
|
|
/**
|
|
* Queue one identified prompt without assigning later activity to it.
|
|
* The message records the explicit or sampled canonical zone; an unusable sampled zone records none.
|
|
* @param params - target session, user content, and optional user time zone.
|
|
* @returns the durable message identity.
|
|
* @throws TypeError before Session creation when an explicit time zone is not UTC or IANA Area/Location.
|
|
*/
|
|
async prompt(params: SessionPromptParams): Promise<SessionPromptResult> {
|
|
if (!this.initialized) throw new Error('SDK server is not initialized')
|
|
const clientTimeZone = promptTimeZone(params.timeZone)
|
|
const rec = await this.getOrCreateSession(params.sessionId)
|
|
this.lifetime.signal.throwIfAborted()
|
|
// An agent-loop-only reload disposes the loop's agents while this record
|
|
// survives; a retained agent accepts followup() silently, so validate the
|
|
// record against the live registry before delivery.
|
|
this.assertLiveAgent(rec, params.sessionId)
|
|
const content = await durablePromptContent(this.ctx, params.contentBlocks)
|
|
this.lifetime.signal.throwIfAborted()
|
|
// Attachment admission crosses an async boundary where shutdown or an
|
|
// agent-loop reload may detach the retained handle.
|
|
this.assertLiveAgent(rec, params.sessionId)
|
|
const message = createUserMessage({
|
|
content,
|
|
source: clientTimeZone === undefined ? { kind: 'user' } : { kind: 'user', clientTimeZone },
|
|
})
|
|
rec.handle.agent.followup(message)
|
|
return { messageId: message.id }
|
|
}
|
|
|
|
/**
|
|
* Dispatch text as a Desktop-style input; native commands own Session state changes.
|
|
* Only the prompt branch records the time zone; native commands do not, matching Desktop command input.
|
|
* @param params - ordered content blocks, receiving Session, and optional prompt time zone.
|
|
* @returns a prompt receipt or native command acknowledgment; command activity completes by notification.
|
|
* @throws TypeError before routing when an explicit time zone is not UTC or IANA Area/Location.
|
|
* @throws on runtime failure; a recognized command failure never falls back to a prompt.
|
|
*/
|
|
async query(params: SessionQueryParams): Promise<SessionQueryResult> {
|
|
if (!this.initialized) throw new Error('SDK server is not initialized')
|
|
if (this.shuttingDown) throw new Error('SDK server is shutting down')
|
|
if (params.timeZone !== undefined) promptTimeZone(params.timeZone)
|
|
const text = params.contentBlocks.find(block => block.type === 'text')
|
|
if (text?.text.trim().startsWith('/')) {
|
|
const commands = this.ctx.get('commands')
|
|
if (commands !== undefined) {
|
|
const rec = await this.getOrCreateSession(params.sessionId)
|
|
this.lifetime.signal.throwIfAborted()
|
|
this.assertLiveAgent(rec, params.sessionId)
|
|
const line = queryCommand(text.text, commands.list(rec.handle.agent))
|
|
if (line !== undefined) {
|
|
const images = queryCommandImages(params.contentBlocks, text)
|
|
const activity: QueryActivity = new QueryActivity(this.ctx, rec.handle.agent, this.transport,
|
|
() => this.queryInvocation.getStore() === activity, this.lifetime.signal,
|
|
(current) => { this.queryActivities.delete(current) })
|
|
this.queryActivities.add(activity)
|
|
try {
|
|
const task = this.queryInvocation.run(activity, () => commands.execute(rec.handle.agent, line, images.map(image => ({
|
|
type: 'image', data: image.data, mediaType: image.mimeType,
|
|
...image.name === undefined ? {} : { name: image.name },
|
|
})), this.lifetime.signal))
|
|
this.commandTasks.add(task)
|
|
try {
|
|
const execution = await task
|
|
if (execution === undefined) throw new Error('The selected command is unavailable in this SDK profile')
|
|
activity.accept(execution)
|
|
return { kind: 'command', execution }
|
|
} finally {
|
|
this.commandTasks.delete(task)
|
|
}
|
|
} catch (error) {
|
|
activity.close()
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const receipt = await this.prompt({
|
|
sessionId: params.sessionId,
|
|
contentBlocks: params.contentBlocks,
|
|
...params.timeZone === undefined ? {} : { timeZone: params.timeZone },
|
|
})
|
|
return { kind: 'prompt', ...receipt }
|
|
}
|
|
|
|
/**
|
|
* Restore a persisted session and repair its interrupted final turn without sending input.
|
|
* Uses the initialized model route while preserving the stored session identity and directory.
|
|
* An explicit permission preset is persisted during setup before execution; omission preserves saved permissions.
|
|
* Already scheduled restorations reject permission overrides because execution may have started.
|
|
* Rejects subagent, missing, unreadable, or already owned sessions; never creates a replacement.
|
|
* @param params - persisted session identity in the configured persistence store.
|
|
* @returns an empty result after the Agent is ready for prompts.
|
|
*/
|
|
async resume(params: SessionResumeParams): Promise<Record<string, never>> {
|
|
if (!this.initialized) throw new Error('SDK server is not initialized')
|
|
if (this.shuttingDown) throw new Error('SDK server is shutting down')
|
|
const sessionId = params.sessionId
|
|
const restoration = this.scheduledSessions.get(sessionId)
|
|
if (restoration !== undefined) {
|
|
if (params.permissionMode !== undefined) {
|
|
throw new Error('cannot override permissions of a session already restored by a reminder; use /permission')
|
|
}
|
|
this.scheduledSessions.delete(sessionId)
|
|
const record = await restoration
|
|
this.assertLiveAgent(record, sessionId)
|
|
return {}
|
|
}
|
|
if (this.sessions.has(sessionId) || this.sessionCreations.has(sessionId)) {
|
|
throw new Error(`SDK session is already open or opening: ${sessionId}`)
|
|
}
|
|
await this.openSession(sessionId, true, params.permissionMode)
|
|
return {}
|
|
}
|
|
|
|
/**
|
|
* Wait for an existing owned Agent and its managed descendants to finish.
|
|
* The response follows all Session notifications emitted during the wait.
|
|
* Rejects a live Agent failure that has no subsequent durable terminal.
|
|
* @param params - the SDK-owned session to observe without creating one.
|
|
* @returns an empty result after the root stays idle across the descendant check.
|
|
*/
|
|
async wait(params: SessionWaitParams): Promise<Record<string, never>> {
|
|
if (!this.initialized) throw new Error('SDK server is not initialized')
|
|
const rec = this.sessions.get(params.sessionId)
|
|
if (rec === undefined) throw new Error(`unknown SDK session: ${params.sessionId}`)
|
|
const agent = rec.handle.agent
|
|
const subagents = this.ctx.get('subagents')
|
|
while (true) {
|
|
this.assertLiveAgent(rec, params.sessionId)
|
|
await agent.whenIdle()
|
|
const idleSeq = agent.session.seq
|
|
const children = await subagents?.waitForTreeWork(agent)
|
|
this.assertLiveAgent(rec, params.sessionId)
|
|
if (!children && agent.status === 'idle' && agent.session.seq === idleSeq) {
|
|
if (rec.failure !== undefined) throw rec.failure.error
|
|
return {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolves live SDK ownership; root lookup failures other than SubagentError/UNAUTHORIZED propagate.
|
|
* @param agent - Agent whose requests need routing.
|
|
* @returns Whether this server owns the Agent or its live subagent tree root.
|
|
*/
|
|
private ownsAgent(agent: Agent): boolean {
|
|
const agents = this.ctx.agents
|
|
if (agents.get(agent.id) !== agent) return false
|
|
if (this.sessions.get(agent.session.id)?.handle.agent === agent) return true
|
|
const subagents = this.ctx.get('subagents')
|
|
if (subagents === undefined) return false
|
|
let root: Agent
|
|
try {
|
|
root = subagents.rootOf(agent)
|
|
} catch (error: unknown) {
|
|
if (typeof error === 'object' && error !== null
|
|
&& 'name' in error && error.name === 'SubagentError'
|
|
&& 'code' in error && error.code === 'UNAUTHORIZED') return false
|
|
throw error
|
|
}
|
|
return this.sessions.get(root.session.id)?.handle.agent === root
|
|
}
|
|
|
|
/** Reject a retained record whose Agent left the registry, naming what the server observed. */
|
|
private assertLiveAgent(rec: SessionRecord, sessionId: string): void {
|
|
// Root disposal also unloads the registry; reading it as optional keeps one failure for both stages.
|
|
if (this.ctx.get('agents')?.get(rec.handle.agent.id) === rec.handle.agent) return
|
|
throw new Error(`session agent was disposed outside the server: ${sessionId}; ${this.disposalContext(rec)}`)
|
|
}
|
|
|
|
private disposalContext(rec: SessionRecord): string {
|
|
const runtime = this.options.runtime
|
|
if (runtime?.unloading()) {
|
|
const event = runtime.lastProcessEvent()
|
|
return event === undefined
|
|
? 'the runtime is shutting down; no process event was observed before teardown'
|
|
: `the runtime is shutting down; last process event before teardown: ${event.description} at ${event.at.toISOString()}`
|
|
}
|
|
if (this.shuttingDown) return 'the SDK server is shutting down'
|
|
// Runtime disposal removes this server's listeners before the Agent leaves, so a record exists only here.
|
|
const at = rec.disposal === undefined ? '' : ` at ${rec.disposal.at.toISOString()}`
|
|
const running = runtime === undefined ? '' : ' while the runtime keeps running'
|
|
const origin = rec.disposal?.origin ? `; first plugin unloading at that time: "${rec.disposal.origin}"` : ''
|
|
return `the agent loop was unloaded${at}${running}${origin}`
|
|
}
|
|
|
|
/**
|
|
* Read a Session's effective directory, recovering a missing directory to its origin.
|
|
* @param params - target Session; an unknown id creates it.
|
|
* @returns the absolute effective directory.
|
|
*/
|
|
async getWorkingDirectory(params: SessionWorkingDirectoryParams): Promise<SessionWorkingDirectoryResult> {
|
|
const agent = await this.workingDirectoryAgent(params.sessionId)
|
|
return { cwd: await this.ctx.workingDirectory.ensure(agent) }
|
|
}
|
|
|
|
/**
|
|
* Change a Session's directory and queue its model-visible transition.
|
|
* @param params - target Session and absolute or current-directory-relative path.
|
|
* @returns the validated absolute directory; the origin is unchanged and the workspace-write boundary follows the directory.
|
|
*/
|
|
async setWorkingDirectory(params: SessionWorkingDirectorySetParams): Promise<SessionWorkingDirectoryResult> {
|
|
const agent = await this.workingDirectoryAgent(params.sessionId)
|
|
return { cwd: await this.ctx.workingDirectory.set(agent, params.path) }
|
|
}
|
|
|
|
private async workingDirectoryAgent(sessionId: string): Promise<Agent> {
|
|
if (!this.initialized) throw new Error('SDK server is not initialized')
|
|
const rec = await this.getOrCreateSession(sessionId)
|
|
this.assertLiveAgent(rec, sessionId)
|
|
return rec.handle.agent
|
|
}
|
|
|
|
/**
|
|
* Dispose server-owned agents, adapter, and subscriptions to quiescence.
|
|
* Managed descendants drain before the root Agent handles and adapter are released.
|
|
* The surrounding context remains running.
|
|
* @returns empty JSON-RPC result.
|
|
*/
|
|
shutdown(): Promise<Record<string, never>> {
|
|
this.shutdownTask ??= this.performShutdown()
|
|
return this.shutdownTask
|
|
}
|
|
|
|
private async performShutdown(): Promise<Record<string, never>> {
|
|
this.shuttingDown = true
|
|
this.lifetime.abort(new Error('SDK server is shutting down'))
|
|
this.userQuestions.close()
|
|
this.initialization.resolve()
|
|
const pendingCreations = [...this.sessionCreations.values()]
|
|
await Promise.allSettled(pendingCreations)
|
|
await Promise.allSettled([...this.commandTasks])
|
|
this.queryInvocation.disable()
|
|
this.sessionCreations.clear()
|
|
this.scheduledSessions.clear()
|
|
const records = [...this.sessions.values()]
|
|
this.sessions.clear()
|
|
const failures: unknown[] = []
|
|
while (this.disposers.length > 0) {
|
|
try {
|
|
this.disposers.pop()?.()
|
|
} catch (error) {
|
|
failures.push(error)
|
|
}
|
|
}
|
|
try {
|
|
await this.ctx.get('subagents')?.drainDescendants(records.map(rec => rec.handle.agent))
|
|
} catch (error: unknown) {
|
|
failures.push(error)
|
|
}
|
|
const teardownResults = await Promise.allSettled([
|
|
this.goalLifetime.dispose(),
|
|
...records.map(rec => Promise.resolve().then(() => rec.handle.dispose())),
|
|
...(this.llmFiber === undefined ? [] : [Promise.resolve().then(async () => {
|
|
// The route requires the authentication service, so the route goes first; its failure does not keep the service.
|
|
try { await this.llmFiber?.dispose() } finally { await this.authFiber?.dispose() }
|
|
})]),
|
|
])
|
|
this.llmFiber = undefined
|
|
this.authFiber = undefined
|
|
failures.push(...teardownResults
|
|
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
|
.map(result => result.reason as unknown))
|
|
if (failures.length === 1) throw failures[0]
|
|
if (failures.length > 1) throw new AggregateError(failures, 'SDK server teardown failed')
|
|
return {}
|
|
}
|
|
|
|
/**
|
|
* Dispatch one incoming JSON-RPC request to its typed handler. Throws (→ a
|
|
* JSON-RPC error response) on an unknown method.
|
|
* @param method - the JSON-RPC method name.
|
|
* @param params - the raw params object from the wire.
|
|
* @returns the handler's result, to be serialized as the response.
|
|
*/
|
|
async handleRequest(method: string, params: Record<string, unknown> | undefined): Promise<unknown> {
|
|
switch (method) {
|
|
case 'initialize':
|
|
return this.initialize(params as unknown as InitializeParams)
|
|
case 'session/prompt':
|
|
if (params?.timeZone !== undefined && typeof params.timeZone !== 'string') {
|
|
throw new TypeError('session/prompt timeZone must be a string')
|
|
}
|
|
return this.prompt(params as unknown as SessionPromptParams)
|
|
case 'session/query': {
|
|
if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0
|
|
|| Object.keys(params).some(key => key !== 'sessionId' && key !== 'contentBlocks' && key !== 'timeZone')) {
|
|
throw new TypeError('session/query requires a non-empty sessionId and contentBlocks, with an optional timeZone')
|
|
}
|
|
if (params.timeZone !== undefined && typeof params.timeZone !== 'string') {
|
|
throw new TypeError('session/query timeZone must be a string')
|
|
}
|
|
return this.query({
|
|
sessionId: brandString<SessionId>(params.sessionId), contentBlocks: queryContent(params.contentBlocks),
|
|
...params.timeZone === undefined ? {} : { timeZone: params.timeZone },
|
|
})
|
|
}
|
|
case 'session/resume': {
|
|
if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) {
|
|
throw new TypeError('session/resume requires a non-empty sessionId string')
|
|
}
|
|
const unknownKey = Object.keys(params).find(key => key !== 'sessionId' && key !== 'permissionMode')
|
|
if (unknownKey !== undefined) {
|
|
throw new TypeError(`unknown session/resume parameter ${JSON.stringify(unknownKey)}; expected sessionId and optional permissionMode`)
|
|
}
|
|
const { sessionId, permissionMode } = params
|
|
if (permissionMode !== undefined && (typeof permissionMode !== 'string' || permissionMode.length === 0)) {
|
|
throw new TypeError('session/resume permissionMode must be a non-empty string')
|
|
}
|
|
return this.resume({ sessionId, ...permissionMode === undefined ? {} : { permissionMode } })
|
|
}
|
|
case 'session/wait': {
|
|
const sessionId = params?.sessionId
|
|
if (typeof sessionId !== 'string') throw new TypeError('session/wait requires a sessionId string')
|
|
return this.wait({ sessionId })
|
|
}
|
|
case 'session/working-directory/get':
|
|
case 'session/working-directory/set': {
|
|
if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) {
|
|
throw new TypeError('working-directory requests require a non-empty sessionId')
|
|
}
|
|
if (method === 'session/working-directory/get') {
|
|
return this.getWorkingDirectory({ sessionId: params.sessionId })
|
|
}
|
|
if (typeof params.path !== 'string') throw new TypeError('working-directory set requires a path string')
|
|
return this.setWorkingDirectory({ sessionId: params.sessionId, path: params.path })
|
|
}
|
|
case 'shutdown':
|
|
return this.shutdown()
|
|
default:
|
|
throw new Error(`unknown DeepSeek Harness SDK runtime method: ${method}`)
|
|
}
|
|
}
|
|
|
|
private async getOrCreateSession(sessionId: string): Promise<SessionRecord> {
|
|
if (this.shuttingDown) throw new Error('SDK server is shutting down')
|
|
this.scheduledSessions.delete(sessionId)
|
|
const existing = this.sessions.get(sessionId)
|
|
if (existing) return existing
|
|
const pending = this.sessionCreations.get(sessionId)
|
|
if (pending) return pending
|
|
return this.openSession(sessionId, false)
|
|
}
|
|
|
|
private openSession(sessionId: string, resume: boolean, permissionMode?: string): Promise<SessionRecord> {
|
|
const creation = this.createSession(sessionId, resume, permissionMode)
|
|
this.sessionCreations.set(sessionId, creation)
|
|
void creation.then(
|
|
() => { this.sessionCreations.delete(sessionId) },
|
|
() => { this.sessionCreations.delete(sessionId) },
|
|
)
|
|
return creation
|
|
}
|
|
|
|
private async createSession(sessionId: string, resume: boolean, permissionMode?: string): Promise<SessionRecord> {
|
|
const permissions = permissionMode === undefined ? undefined : this.ctx.get('permissionPresets')
|
|
if (permissionMode !== undefined) {
|
|
if (permissions === undefined) throw new Error('session/resume permissionMode requires the permission-presets service')
|
|
permissions.resolve(permissionMode)
|
|
}
|
|
if (resume && (await this.ctx.get('sessionPersistence')?.stat(brandString<SessionId>(sessionId)))?.header.origin === 'subagent') {
|
|
throw new Error(`subagent session "${sessionId}" cannot be resumed directly; resume its root session instead`)
|
|
}
|
|
// No preset composition: this server's compositions keep the model-facing
|
|
// rows in the host plane, so this agent reads them from the global layer. A
|
|
// deployment that configures a roster has to join one here first
|
|
// (@deepseek-ai/dsh-agent-preset-registry README, "Composing a child agent").
|
|
const agentOptions = {
|
|
provider: this.provider,
|
|
model: this.model,
|
|
...this.reasoningEffort === undefined ? {} : { reasoningEffort: this.reasoningEffort },
|
|
...this.maxTokens === undefined ? {} : { maxTokens: this.maxTokens },
|
|
}
|
|
// The header records the canonical spelling of the configured directory; see SessionHeader.cwd.
|
|
const fs = this.ctx.get('fs')
|
|
const cwd = fs === undefined ? this.cwd : fs.processPath(await fs.resolve(this.cwd))
|
|
const handle = await (resume ? this.ctx.agents.resume({
|
|
resumeSessionId: brandString<SessionId>(sessionId),
|
|
agentOptions,
|
|
// The initialized route replaces the restored Session's model selection.
|
|
setup: (_agentCtx, agent) => {
|
|
if (permissionMode !== undefined && permissions !== undefined) {
|
|
permissions.set(agent.session, permissionMode)
|
|
}
|
|
const previous = agent.model.current()
|
|
const selection = { ...agentOptions }
|
|
if (selection.reasoningEffort === undefined && previous !== undefined
|
|
&& previous.provider === selection.provider && previous.model === selection.model
|
|
&& previous.reasoningEffort !== undefined) {
|
|
selection.reasoningEffort = previous.reasoningEffort
|
|
}
|
|
agent.model.select(selection)
|
|
},
|
|
}) : this.ctx.agents.create({
|
|
sessionId: brandString<SessionId>(sessionId),
|
|
meta: { cwd },
|
|
agentOptions,
|
|
}))
|
|
const rec: SessionRecord = { handle, failure: undefined, disposal: undefined }
|
|
this.sessions.set(sessionId, rec)
|
|
return rec
|
|
}
|
|
|
|
private hasAdapterFor(provider: string): boolean {
|
|
return this.ctx.get('llm')?.listProviders().some(entry => entry.id === provider) ?? false
|
|
}
|
|
}
|