api-proxy.ts 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  1. /**
  2. * Host-side ApiProxy implementation. Signature discipline: unary takes the
  3. * narrow RpcRequest<P> and echoes request.rpcId on the RpcResponse<T>.
  4. */
  5. import { randomUUID } from 'node:crypto'
  6. import { mkdir, stat } from 'node:fs/promises'
  7. import { join } from 'node:path'
  8. import type { Context } from 'cordis'
  9. import { installAgentLlmTarget } from '@deepseek-ai/dsh-agent'
  10. import type {
  11. Agent, AgentLlmTarget, AgentLlmTargetRef, AgentStatus, InboxItem, InboxItemId,
  12. } from '@deepseek-ai/dsh-agent'
  13. import { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  14. import { errorChain } from '@deepseek-ai/dsh-llm'
  15. import type { MessageSource } from '@deepseek-ai/dsh-llm'
  16. import type { Session, SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session'
  17. import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
  18. import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace'
  19. import {
  20. workspaceDomainState, workspaceRecord, WorkspaceId as brandWorkspaceId,
  21. WorkspaceMoveInvalidError, WorkspaceNameConflictError,
  22. } from '@deepseek-ai/dsh-workspace'
  23. // Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters).
  24. import type {} from '@deepseek-ai/dsh-tools'
  25. import type {
  26. ApiProxy, CredentialView, GoalRef, HistoryEntry, HostFrame, ModelCatalogFailure, ModelProviderGroup,
  27. ModelReasoning, MuxFrame, QuestionResponsePayload, SessionProjectionsBlock, SessionSummary,
  28. SettingsNamespaceView, ToolEventView, WorkspaceId, WorkspaceView,
  29. } from './api/index.ts'
  30. // Type-only: resolves `ctx.get('sessionProjections')` to the projection registry.
  31. import type {} from '@deepseek-ai/dsh-session-projection'
  32. // Type-only: resolves `ctx.get('sessionProjectionCache')` (the cold listing column).
  33. import type {} from '@deepseek-ai/dsh-session-projection-cache'
  34. // GoalError narrows domain rejections to their stable codes at the wire boundary.
  35. import { GoalError } from '@deepseek-ai/dsh-goal'
  36. import type { GoalRef as CoreGoalRef } from '@deepseek-ai/dsh-goal'
  37. // Type-only edges: resolve `ctx.get('commands')`, the `commands/change` event, and `ctx.get('skills')`.
  38. import type {} from '@deepseek-ai/dsh-commands'
  39. import type {} from '@deepseek-ai/dsh-skill'
  40. // The settings/credentials seams: brand guards run at this wire boundary; the
  41. // service reads stay optional (`ctx.get`) so a composition without either
  42. // provider still serves every other domain.
  43. import { SettingsConflictError, settingsNamespace } from '@deepseek-ai/dsh-settings'
  44. import type { SettingsDescriptor, SettingsNamespace, SettingsPathOp } from '@deepseek-ai/dsh-settings'
  45. import { credentialRef } from '@deepseek-ai/dsh-credentials'
  46. // Value edge: the rename impl narrows the title service's validation failure; the import also resolves `ctx.get('sessionTitle')`.
  47. import { SessionTitleInvalidError } from '@deepseek-ai/dsh-session-title'
  48. import type { CallId } from '@deepseek-ai/dsh-llm/brand'
  49. import type { ApprovalOutcome, ApprovalRequestId } from '@deepseek-ai/dsh-user-approval'
  50. // Side-effect type import: resolves the `approval/request` waterfall and
  51. // `ctx.get('approval')` without a value dependency on the seam (optional composition).
  52. import type {} from '@deepseek-ai/dsh-user-approval'
  53. import { approvalResponsePayloadSchema } from './api/approvals.schema.ts'
  54. import { questionResponsePayloadSchema } from './api/questions.schema.ts'
  55. import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts'
  56. import { RpcId } from './api/rpc.ts'
  57. import type {
  58. AskUserQuestionAnswer, AskUserQuestionItem, AskUserQuestionRequest,
  59. } from '@deepseek-ai/dsh-user-interaction'
  60. import { UserInteractionError } from '@deepseek-ai/dsh-user-interaction'
  61. import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
  62. import { openNativePath } from './native-path-opener.ts'
  63. /** Page size when history is called without maxMessages. */
  64. const DEFAULT_MAX_MESSAGES = 50
  65. /** Surface message event types (the pagination counting unit). */
  66. const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message'])
  67. /**
  68. * Message-boundary pagination: count maxMessages surface messages backwards from
  69. * the window tail; the cut is the starting seq of the oldest message group
  70. * (chunks group via sourceEventSeqs — never cut mid-message). The tail page
  71. * naturally includes the in-progress partial.
  72. */
  73. function paginate(
  74. events: readonly SessionEvent[],
  75. beforeSeq: number | undefined,
  76. maxMessages: number,
  77. ): { events: SessionEvent[]; hasMore: boolean } {
  78. const window = beforeSeq === undefined ? [...events] : events.filter(event => event.seq < beforeSeq)
  79. let count = 0
  80. let cut = 0
  81. for (let i = window.length - 1; i >= 0; i--) {
  82. const event = window[i] as SessionEvent
  83. if (!MESSAGE_TYPES.has(event.type)) continue
  84. count++
  85. const sources = (event as { sourceEventSeqs?: number[] }).sourceEventSeqs
  86. const groupStart = sources !== undefined && sources.length > 0 ? Math.min(event.seq, ...sources) : event.seq
  87. if (count >= maxMessages) {
  88. cut = groupStart
  89. break
  90. }
  91. }
  92. const page = window.filter(event => event.seq >= cut)
  93. return { events: page, hasMore: cut > 0 }
  94. }
  95. /** Wrap an ok result echoing the request's rpcId. */
  96. function ok<T>(request: RpcRequest<unknown>, value: T): RpcResponse<T> {
  97. return { rpcId: request.rpcId, result: { ok: true, value } }
  98. }
  99. /**
  100. * Build the provider/model catalog over every registered route. Shared by the
  101. * session-scoped `session.models` (which passes the session's current target
  102. * so an unlisted current model still renders selectable) and the host-scoped
  103. * `llm.models` (no current). Per-provider failures ride `failures` without
  104. * failing the sound groups; groups that advertise nothing are dropped.
  105. */
  106. async function buildModelCatalog(
  107. ctx: Context,
  108. current?: { provider: string; model: string },
  109. ): Promise<{ groups: ModelProviderGroup[]; failures: ModelCatalogFailure[] }> {
  110. const catalog = await Promise.all(ctx.llm.listProviders().map(async (provider) => {
  111. try {
  112. const advertised = await ctx.llm.listModels(provider.id)
  113. const models = [...advertised]
  114. if (
  115. current !== undefined
  116. && provider.id === current.provider
  117. && !models.some(model => model.id === current.model)
  118. ) {
  119. models.push({
  120. provider: provider.id,
  121. id: current.model,
  122. name: current.model,
  123. })
  124. }
  125. const entries = await Promise.all(models.map(async (model) => {
  126. const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id)
  127. const reasoning: ModelReasoning | undefined = resolved.reasoning === undefined
  128. ? undefined
  129. : {
  130. efforts: resolved.reasoning.efforts.map(effort => ({
  131. id: effort.id,
  132. name: effort.name,
  133. ...effort.description === undefined
  134. ? {}
  135. : { description: effort.description },
  136. })),
  137. ...resolved.reasoning.defaultEffort === undefined
  138. ? {}
  139. : { defaultEffort: resolved.reasoning.defaultEffort },
  140. }
  141. return {
  142. id: model.id,
  143. name: model.name,
  144. ...model.description === undefined ? {} : { description: model.description },
  145. ...current !== undefined
  146. && provider.id === current.provider
  147. && model.id === current.model
  148. && !advertised.some(candidate => candidate.id === current.model)
  149. ? { unlisted: true as const }
  150. : {},
  151. ...reasoning === undefined ? {} : { reasoning },
  152. }
  153. }))
  154. const group: ModelProviderGroup = {
  155. id: provider.id,
  156. name: provider.name,
  157. models: entries,
  158. }
  159. return { kind: 'group' as const, group }
  160. } catch (error: unknown) {
  161. const failure: ModelCatalogFailure = {
  162. id: provider.id,
  163. name: provider.name,
  164. message: error instanceof Error ? error.message : String(error),
  165. }
  166. return { kind: 'failure' as const, failure }
  167. }
  168. }))
  169. return {
  170. groups: catalog.flatMap(item => item.kind === 'group' ? [item.group] : []).filter(group => group.models.length > 0),
  171. failures: catalog.flatMap(item => item.kind === 'failure' ? [item.failure] : []),
  172. }
  173. }
  174. /** Wrap an error result echoing the request's rpcId. */
  175. function err<T>(request: RpcRequest<unknown>, error: RpcError): RpcResponse<T> {
  176. return { rpcId: request.rpcId, result: { ok: false, error } }
  177. }
  178. /** Simple async queue: core callbacks push, the AsyncIterable pulls; abort/return cleans up. */
  179. class FrameQueue<F> {
  180. private buffer: F[] = []
  181. private waiter: (() => void) | undefined
  182. private done = false
  183. push(item: F): void {
  184. if (this.done) return
  185. this.buffer.push(item)
  186. this.waiter?.()
  187. }
  188. end(): void {
  189. this.done = true
  190. this.waiter?.()
  191. }
  192. async *iterate(signal: AbortSignal, cleanup: () => void): AsyncGenerator<F> {
  193. const onAbort = (): void => { this.end() }
  194. signal.addEventListener('abort', onAbort, { once: true })
  195. try {
  196. while (true) {
  197. while (this.buffer.length > 0) yield this.buffer.shift() as F
  198. if (this.done || signal.aborted) return
  199. await new Promise<void>((resolve) => { this.waiter = resolve })
  200. this.waiter = undefined
  201. }
  202. } finally {
  203. signal.removeEventListener('abort', onAbort)
  204. cleanup()
  205. }
  206. }
  207. }
  208. /**
  209. * Server-side frame mint: pure pushes get a fresh rpcId per frame (answerable
  210. * frames — approval/question requested — mint their stable id in their
  211. * pending registries instead).
  212. */
  213. function frame<F>(payload: F): RpcRequest<F> {
  214. return { rpcId: RpcId(randomUUID()), payload }
  215. }
  216. /** Queue the subscription baseline frame. */
  217. function subscribeSession(queue: FrameQueue<RpcRequest<MuxFrame>>, session: Session): void {
  218. queue.push(frame({ type: 'session/subscribed', sessionId: session.id, lastSeq: session.seq - 1 }))
  219. }
  220. /**
  221. * Whether the session's conversation has started: no turn has run yet (a
  222. * turn is one model-loop execution). Standalone plugin events — command
  223. * lifecycle records, plan/mode, titles, goals — never open a turn, so
  224. * running `/plan` or `/goal` on a fresh session keeps it blank
  225. * (list-hidden, reusable).
  226. */
  227. function sessionBlank(session: Session): boolean {
  228. return !session.events.some(event => event.type === 'turn/start')
  229. }
  230. /** SessionSummary projection for attached (in-memory) sessions. */
  231. function summarize(session: Session, running: boolean): SessionSummary {
  232. return {
  233. sessionId: session.id,
  234. updatedAt: session.events.at(-1)?.time ?? session.header.createdAt,
  235. running,
  236. blank: sessionBlank(session),
  237. ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession },
  238. ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd },
  239. }
  240. }
  241. /**
  242. * SessionSummary projection for cold (persisted, unattached) sessions.
  243. * updatedAt is the log file's mtime; backends without a per-session file
  244. * (locate() undefined) fall back to the header's createdAt.
  245. */
  246. async function summarizeCold(persistence: SessionPersistence, meta: SessionHeader): Promise<SessionSummary> {
  247. let updatedAt = meta.createdAt
  248. const location = persistence.locate(meta)
  249. if (location !== undefined) {
  250. try {
  251. updatedAt = (await stat(location.path)).mtimeMs
  252. } catch {
  253. // The log vanished between list() and stat() (concurrent cleanup); createdAt stands in.
  254. }
  255. }
  256. return {
  257. sessionId: meta.id,
  258. updatedAt,
  259. running: false,
  260. // Lazy persistence keeps never-appended sessions out of list(); reading
  261. // a cold log to check for turns would defeat the index read, so a listed
  262. // cold session is served as not-blank (its log holds its conversation).
  263. blank: false,
  264. ...meta.parentSession === undefined ? {} : { parentSessionId: meta.parentSession },
  265. /* v8 ignore next -- the empty arm needs a cwd-less meta, but list()
  266. filters those out (legacy logs are not served); the conditional mirrors
  267. summarize() shape. */
  268. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  269. }
  270. }
  271. /** Map a browse-primitive failure onto the wire error vocabulary (unknown throws stay internal). */
  272. function directoryError(error: unknown): RpcError {
  273. if (error instanceof DirectoryPickerError) {
  274. return { code: error.code, message: error.message, details: { path: error.path } }
  275. }
  276. return { code: 'internal', message: error instanceof Error ? error.message : String(error), details: {} }
  277. }
  278. /** Resolved Host routing and project-directory defaults consumed by the API implementation. */
  279. export interface ApiProxyDefaults {
  280. provider: string
  281. model: string
  282. /** Default project directory for new sessions whose create request carries no cwd. */
  283. cwd: string
  284. /** Parent directory for name-created workspaces. */
  285. workspaceRoot: string
  286. /** Native open-with-default-application; injectable for carrier tests. */
  287. openPath?: (path: string, signal: AbortSignal) => Promise<void>
  288. }
  289. /** The tool/call payload fields the presenter path reads. */
  290. interface ToolCallData { callId: string; name: string; arguments: string }
  291. /**
  292. * One outstanding approval question: the stable server-request id, the frame
  293. * material replayed to late mux subscribers, and the resolver that settles the
  294. * answerer's promise back into `ctx.approval`.
  295. */
  296. interface PendingApproval {
  297. rpcId: RpcId
  298. sessionId: SessionId
  299. approvalId: ApprovalRequestId
  300. toolName: string
  301. callId?: CallId
  302. reason?: string
  303. resolve(outcome: ApprovalOutcome): void
  304. }
  305. /** Project a pending entry into its answerable mux frame (initial push and mux-open replay share it). */
  306. function requestedFrame(pending: PendingApproval): RpcRequest<MuxFrame> {
  307. return {
  308. rpcId: pending.rpcId,
  309. payload: {
  310. type: 'approval/requested',
  311. sessionId: pending.sessionId,
  312. approvalId: pending.approvalId,
  313. toolName: pending.toolName,
  314. ...pending.callId === undefined ? {} : { callId: pending.callId },
  315. ...pending.reason === undefined ? {} : { reason: pending.reason },
  316. },
  317. }
  318. }
  319. /** One host-owned question wait, addressed by the stable server-request id. */
  320. interface PendingQuestion {
  321. rpcId: RpcId
  322. sessionId: SessionId
  323. questions: AskUserQuestionItem[]
  324. resolve: (answer: AskUserQuestionAnswer) => void
  325. reject: (error: UserInteractionError) => void
  326. signal?: AbortSignal
  327. onAbort?: () => void
  328. }
  329. /** Validate one answer batch against the exact question request it resolves. */
  330. function matchesQuestions(payload: QuestionResponsePayload, pending: PendingQuestion): boolean {
  331. if (payload.sessionId !== pending.sessionId) return false
  332. const answers = payload.answer.answers
  333. if (answers.length !== pending.questions.length) return false
  334. return answers.every((answer, index) => {
  335. const question = pending.questions[index] as AskUserQuestionItem
  336. if (answer.id !== question.id) return false
  337. if (new Set(answer.selected).size !== answer.selected.length) return false
  338. const custom = answer.custom?.trim()
  339. if (custom !== undefined && custom === '') return false
  340. if (custom !== undefined && answer.selected.length > 0) return false
  341. if (question.multiSelect !== true && answer.selected.length > 1) return false
  342. const labels = new Set(question.options?.map(option => option.label) ?? [])
  343. return answer.selected.every(label => labels.has(label))
  344. })
  345. }
  346. /**
  347. * Compute the render intent for a tool/call or tool/result event through the
  348. * presenters registered at this moment; every other event type gets none. A
  349. * result's presenter needs its call's parsed args — `argsFor` supplies them
  350. * (live: the per-session call table; history: an in-page backscan), returning
  351. * undefined when the pairing is unavailable (e.g. the call fell off the page),
  352. * which soft-falls to no view. Presenter or JSON.parse throws also soft-fall:
  353. * the client's documented default (generic JSON card) covers every miss.
  354. */
  355. function viewFor(ctx: Context, event: SessionEvent, argsFor: (callId: string) => unknown): ToolEventView | undefined {
  356. try {
  357. if (event.type === 'tool/call') {
  358. const { name, arguments: raw } = event.data as ToolCallData
  359. const view = ctx.tools.get(name)?.presentCall?.(JSON.parse(raw))
  360. return view === undefined ? undefined : { for: 'call', view }
  361. }
  362. if (event.type === 'tool/result') {
  363. const { message, meta } = event.data
  364. const [result] = message.content
  365. const callId = message.source.callId
  366. const call = argsFor(callId) as { name: string; args: unknown } | undefined
  367. if (call === undefined) return undefined
  368. const view = ctx.tools.get(call.name)?.presentResult?.(call.args, {
  369. content: result.content,
  370. isError: result.isError === true,
  371. ...meta === undefined ? {} : { meta },
  372. })
  373. return view === undefined ? undefined : { for: 'result', view }
  374. }
  375. } catch (error: unknown) {
  376. // A throwing presenter (or unparseable arguments) must not break delivery;
  377. // the event still ships, just without a view.
  378. console.error(`api-proxy: presenter failed for ${event.type}, falling back to generic: ${String(error)}`)
  379. }
  380. return undefined
  381. }
  382. /**
  383. * Resolve a tool/result's call pairing by scanning a window of events backwards
  384. * for the matching tool/call. Used by the history path (the page is the
  385. * window — a cross-page pairing soft-falls to no view) and by live-path table
  386. * misses after a reconnect-eviction.
  387. */
  388. function backscanArgs(events: readonly SessionEvent[], callId: string): { name: string; args: unknown } | undefined {
  389. for (let i = events.length - 1; i >= 0; i--) {
  390. const event = events[i] as SessionEvent
  391. if (event.type !== 'tool/call') continue
  392. const data = event.data as ToolCallData
  393. if (data.callId !== callId) continue
  394. try {
  395. return { name: data.name, args: JSON.parse(data.arguments) }
  396. } catch {
  397. // Unparseable stored arguments: same soft-fall as a live parse failure.
  398. return undefined
  399. }
  400. }
  401. return undefined
  402. }
  403. /**
  404. * The projection baseline for one history tail page: the registry's
  405. * watermark-cache snapshot — one fully synchronous read (no await between the
  406. * page slice and this), so all values and `asOfSeq` form a single consistent
  407. * cut and `asOfSeq` equals the window tail event seq. The carrier holds zero
  408. * domain knowledge (each value passed its unit's own schema inside the
  409. * registry). An absent registry means the deployment has no projection seam:
  410. * the whole block is absent and clients treat every key as capability-absent.
  411. */
  412. function projectionsFor(ctx: Context, agent: Agent): SessionProjectionsBlock | undefined {
  413. const registry = ctx.get('sessionProjections')
  414. if (registry === undefined) return undefined
  415. return registry.snapshot(agent.session)
  416. }
  417. /**
  418. * The projection baseline of one session.list row, fail-soft: attached
  419. * sessions cut the registry's live watermark cache; cold sessions view the
  420. * persisted projection cache's identity-checked stored rows (zero log loads
  421. * either way — the listing use case the cache exists for). The block shape
  422. * (values + asOfSeq) matches the history tail's, so a client seeds its
  423. * value store under the same higher-seq-wins rule. Any failure — and an
  424. * empty value set — yields an absent block: a listing without projections
  425. * is degraded, never broken.
  426. */
  427. function listProjectionsFor(ctx: Context, meta: SessionHeader, session: Session | undefined): SessionProjectionsBlock | undefined {
  428. try {
  429. const block = session !== undefined
  430. ? ctx.get('sessionProjections')?.snapshot(session)
  431. : ctx.get('sessionProjectionCache')?.cachedSnapshot(meta)
  432. return block !== undefined && Object.keys(block.values).length > 0 ? block : undefined
  433. } catch (error) {
  434. ctx.logger.warn(`session.list: projection column for "${meta.id}" failed (serving the row without it): ${String(error)}`)
  435. return undefined
  436. }
  437. }
  438. /**
  439. * Thrown by the cold-resume path when the id names no servable session
  440. * (absent from the store, or a pre-project legacy log without a cwd).
  441. */
  442. class SessionNotFound extends Error {}
  443. /** Requested identity already belongs to a session with another project cwd. */
  444. class SessionCwdConflict extends Error {
  445. constructor(
  446. readonly sessionId: SessionId,
  447. readonly requestedCwd: string,
  448. readonly existingCwd: string | undefined,
  449. ) {
  450. super(
  451. `session "${sessionId}" already exists with cwd ${JSON.stringify(existingCwd)}; `
  452. + `requested ${JSON.stringify(requestedCwd)}`,
  453. )
  454. }
  455. }
  456. /** Host failed before the registry could adopt a name-created directory. */
  457. class WorkspaceDirectoryCreationError extends Error {}
  458. /** Shared workspace-not-found error response of the workspace.* mutation rows. */
  459. function workspaceNotFound<T>(request: RpcRequest<unknown>, workspaceId: string): RpcResponse<T> {
  460. return err(request, {
  461. code: 'workspace-not-found',
  462. message: `workspace "${workspaceId}" not found`,
  463. details: { workspaceId },
  464. })
  465. }
  466. /** Wire projection of one workspace entity (the workspace.* value row). */
  467. function workspaceView(workspace: Workspace): WorkspaceView {
  468. return {
  469. workspaceId: workspace.id,
  470. path: workspace.path,
  471. title: workspace.title,
  472. sessionIds: [...workspace.sessionIds],
  473. createdAt: workspace.createdAt,
  474. updatedAt: workspace.updatedAt,
  475. }
  476. }
  477. /** Wire projection of the durable record carried by `domain/changed`. */
  478. function changedWorkspaceView(workspaceId: string, value: unknown): WorkspaceView {
  479. const record: WorkspaceRecord = workspaceRecord.parse(value)
  480. return {
  481. workspaceId: workspaceId as WorkspaceId,
  482. path: record.path,
  483. title: record.title,
  484. sessionIds: [...record.sessionIds],
  485. createdAt: record.createdAt,
  486. updatedAt: record.updatedAt,
  487. }
  488. }
  489. /**
  490. * Implement ApiProxy over a composed host context.
  491. * @param ctx - a context with the Host spine and Workspace registry mounted.
  492. * @param defaults - host routing and project-directory defaults.
  493. * @returns the ApiProxy implementation.
  494. */
  495. export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiProxy {
  496. const agentOptions = { provider: defaults.provider, model: defaults.model }
  497. type WebLlmTargetRef = AgentLlmTargetRef & { current: AgentLlmTarget }
  498. const targets = new WeakMap<Agent, WebLlmTargetRef>()
  499. /** Implicit resume of cold sessions, deduplicating concurrent calls (follows the jsonrpc sessionCreations precedent). */
  500. const resumes = new Map<SessionId, Promise<Agent>>()
  501. /** Client-chosen identity creation/resume, deduplicated across concurrent retries. */
  502. const sessionCreations = new Map<SessionId, Promise<Agent>>()
  503. /** Serializes path ownership checks with record creation across spellings. */
  504. let workspaceCreationChain = Promise.resolve()
  505. const pendingQuestions = new Map<RpcId, PendingQuestion>()
  506. const pendingApprovals = new Map<RpcId, PendingApproval>()
  507. const muxQueues = new Set<FrameQueue<RpcRequest<MuxFrame>>>()
  508. /**
  509. * Install or return the session-local target that prompt assembly snapshots.
  510. * Seed order: latest logged request/header, else the host default routing.
  511. * There is no create-time per-session override tier on this wire — if one
  512. * returns (a create-options contribution), it must fold in between the two.
  513. */
  514. function targetFor(agent: Agent): WebLlmTargetRef {
  515. const installed = targets.get(agent)
  516. if (installed !== undefined) return installed
  517. const logged = agent.session.requestHeader()?.config
  518. const target: WebLlmTargetRef = {
  519. current: logged === undefined
  520. ? { provider: defaults.provider, model: defaults.model }
  521. : {
  522. provider: logged.provider,
  523. model: logged.model,
  524. ...logged.reasoningEffort === undefined
  525. ? {}
  526. : { reasoningEffort: logged.reasoningEffort },
  527. },
  528. assembled: undefined,
  529. }
  530. installAgentLlmTarget(agent.ctx, target)
  531. targets.set(agent, target)
  532. return target
  533. }
  534. /** Pre-publication setup used by both fresh and resumed Web agents. */
  535. function installTarget(agentCtx: Context): void {
  536. const agent = agentCtx.agent
  537. if (agent === undefined) throw new Error('api-proxy: agent setup has no scoped agent')
  538. targetFor(agent)
  539. }
  540. /** Send one transient frame to every connected mux consumer. */
  541. function broadcast(payload: MuxFrame): void {
  542. const envelope = frame(payload)
  543. for (const queue of muxQueues) queue.push(envelope)
  544. }
  545. // Projection change feed → session/projection push frames. The carrier
  546. // mints the wire frame (the seam package holds no wire vocabulary); the
  547. // child activates only when a projection registry is composed, and the
  548. // subscription unwinds with this gateway's fiber.
  549. ctx.inject(['sessionProjections'], (projectionCtx) => {
  550. projectionCtx.sessionProjections.onChanged((session, key, value, seq) => {
  551. broadcast({ type: 'session/projection', sessionId: session.id, key, value, seq })
  552. })
  553. })
  554. /**
  555. * Per-session queued-occurrence mirror serving the mux-open queue snapshot
  556. * (the same refresh-recovery baseline as pending questions). Each terminal
  557. * queue event retires one matching occurrence, so repeated sends of the same
  558. * identified message remain visible until every occurrence is claimed.
  559. */
  560. const queuedMirror = new Map<SessionId, InboxItem[]>()
  561. type UnseenQueueEvent =
  562. | { readonly kind: 'update'; readonly item: InboxItem }
  563. | { readonly kind: 'terminal' }
  564. const unseenQueueEvents = new Map<SessionId, Map<InboxItemId, UnseenQueueEvent>>()
  565. const rememberUnseen = (sessionId: SessionId, itemId: InboxItemId, event: UnseenQueueEvent): void => {
  566. let events = unseenQueueEvents.get(sessionId)
  567. if (events === undefined) {
  568. events = new Map()
  569. unseenQueueEvents.set(sessionId, events)
  570. }
  571. events.set(itemId, event)
  572. // Only synchronous re-entrancy may deliver a mutation before its outer
  573. // enqueue observer. Drop unmatched protocol-invalid observations instead
  574. // of retaining process-local ids indefinitely.
  575. queueMicrotask(() => {
  576. const current = unseenQueueEvents.get(sessionId)
  577. if (current?.get(itemId) !== event) return
  578. current.delete(itemId)
  579. if (current.size === 0) unseenQueueEvents.delete(sessionId)
  580. })
  581. }
  582. const takeUnseen = (sessionId: SessionId, itemId: InboxItemId): UnseenQueueEvent | undefined => {
  583. const events = unseenQueueEvents.get(sessionId)
  584. const event = events?.get(itemId)
  585. if (event === undefined) return undefined
  586. events?.delete(itemId)
  587. if (events?.size === 0) unseenQueueEvents.delete(sessionId)
  588. return event
  589. }
  590. const publishQueue = (sessionId: SessionId): void => {
  591. const items = queuedMirror.get(sessionId) ?? []
  592. broadcast({
  593. type: 'session/queue',
  594. sessionId,
  595. items: items.map(item => ({
  596. id: item.id,
  597. message: item.message,
  598. })),
  599. })
  600. }
  601. ctx.effect(() => {
  602. const retire = (agent: Agent, item: InboxItem): boolean => {
  603. const entries = queuedMirror.get(agent.id)
  604. if (entries === undefined) {
  605. rememberUnseen(agent.id, item.id, { kind: 'terminal' })
  606. return false
  607. }
  608. const index = entries.findIndex(entry => entry.id === item.id)
  609. if (index === -1) {
  610. rememberUnseen(agent.id, item.id, { kind: 'terminal' })
  611. return false
  612. }
  613. entries.splice(index, 1)
  614. if (entries.length === 0) queuedMirror.delete(agent.id)
  615. return true
  616. }
  617. const disposers = [
  618. ctx.on('agent/inbox/enqueue', (agent: Agent, item: InboxItem) => {
  619. if (item.placement !== 'queued') return
  620. const unseen = takeUnseen(agent.id, item.id)
  621. if (unseen?.kind === 'terminal') return
  622. let entries = queuedMirror.get(agent.id)
  623. if (entries === undefined) {
  624. entries = []
  625. queuedMirror.set(agent.id, entries)
  626. }
  627. entries.push(unseen?.kind === 'update' ? unseen.item : item)
  628. publishQueue(agent.id)
  629. }),
  630. ctx.on('agent/inbox/update', (agent: Agent, item: InboxItem) => {
  631. const entries = queuedMirror.get(agent.id)
  632. if (entries === undefined) {
  633. rememberUnseen(agent.id, item.id, { kind: 'update', item })
  634. return
  635. }
  636. const index = entries.findIndex(entry => entry.id === item.id)
  637. if (index === -1) {
  638. rememberUnseen(agent.id, item.id, { kind: 'update', item })
  639. return
  640. }
  641. entries.splice(index, 1, item)
  642. publishQueue(agent.id)
  643. }),
  644. ctx.on('agent/inbox/dequeue', (agent: Agent, item: InboxItem) => {
  645. if (retire(agent, item)) publishQueue(agent.id)
  646. }),
  647. ctx.on('agent/inbox/discard', (agent: Agent, items: InboxItem[]) => {
  648. let changed = false
  649. for (const item of items) changed = retire(agent, item) || changed
  650. if (changed) publishQueue(agent.id)
  651. }),
  652. ctx.on('session/disposed', (session: Session) => {
  653. queuedMirror.delete(session.id)
  654. unseenQueueEvents.delete(session.id)
  655. }),
  656. ]
  657. return () => { for (const dispose of disposers) dispose() }
  658. }, 'api-proxy: queued mirror')
  659. /** Remove a wait before settling it: synchronous deletion makes the first claimant win. */
  660. function claimQuestion(pending: PendingQuestion, outcome: 'answered' | 'cancelled'): void {
  661. pendingQuestions.delete(pending.rpcId)
  662. if (pending.signal !== undefined && pending.onAbort !== undefined) {
  663. pending.signal.removeEventListener('abort', pending.onAbort)
  664. }
  665. broadcast({
  666. type: 'question/resolved', sessionId: pending.sessionId,
  667. questionRpcId: pending.rpcId, outcome,
  668. })
  669. }
  670. const disposeProvider = ctx.userInteraction.registerProvider({
  671. ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> {
  672. const sessionId = request.agent?.id
  673. if (sessionId === undefined) {
  674. return Promise.reject(new UserInteractionError(
  675. 'web user interaction requires an agent-owned session', 'ASK_MISSING_AGENT'))
  676. }
  677. return new Promise<AskUserQuestionAnswer>((resolve, reject) => {
  678. const rpcId = RpcId(randomUUID())
  679. const pending: PendingQuestion = {
  680. rpcId, sessionId, questions: request.questions, resolve, reject,
  681. ...(request.signal === undefined ? {} : { signal: request.signal }),
  682. }
  683. const onAbort = (): void => {
  684. claimQuestion(pending, 'cancelled')
  685. reject(new UserInteractionError(
  686. 'ask_user_question was aborted before the user answered', 'ASK_ABORTED'))
  687. }
  688. pending.onAbort = onAbort
  689. pendingQuestions.set(rpcId, pending)
  690. request.signal?.addEventListener('abort', onAbort, { once: true })
  691. const envelope: RpcRequest<MuxFrame> = {
  692. rpcId,
  693. payload: { type: 'question/requested', sessionId, questions: request.questions },
  694. }
  695. for (const queue of muxQueues) queue.push(envelope)
  696. })
  697. },
  698. })
  699. ctx.effect(() => () => {
  700. disposeProvider()
  701. for (const pending of [...pendingQuestions.values()]) {
  702. claimQuestion(pending, 'cancelled')
  703. pending.reject(new UserInteractionError(
  704. 'web user-interaction provider was disposed', 'ASK_ABORTED'))
  705. }
  706. }, 'api-proxy: user-interaction provider')
  707. // --- Approval pending registry ------------------------------------------
  708. // The proxy is the approval channel for every agent this host owns: an ask
  709. // through `ctx.approval` becomes an answerable server-request on the mux
  710. // stream (stable rpcId), settled by POST /api/respond. The entry survives
  711. // client disconnects — mux-open replays still-pending requested frames with
  712. // the same rpcId (the refresh-recovery baseline) — and withdraws on the
  713. // ask's own abort signal (turn cancel), pushing `cancelled` to subscribers.
  714. if (ctx.get('approval') !== undefined) {
  715. // Teardown parity with the question provider above: a gateway disposed
  716. // while approvals are pending settles every entry as 'cancelled' (the
  717. // service's fail-closed vocabulary), so no ask promise dangles past the
  718. // proxy's lifetime and subscribers see the withdrawal.
  719. ctx.effect(() => () => {
  720. for (const pending of [...pendingApprovals.values()]) pending.resolve('cancelled')
  721. }, 'api-proxy: approval registry teardown')
  722. ctx.on('approval/request', (req, next) => {
  723. // Dispatch rides a microtask behind the service's own signal check: an
  724. // abort landing in that window would register the abort listener AFTER
  725. // the signal fired — never invoked, entry pending forever, zombie frame
  726. // on every mux replay. Settle synchronously instead of publishing.
  727. if (req.signal?.aborted === true) return Promise.resolve<ApprovalOutcome>('cancelled')
  728. // The audit pair `approval/asked` is already appended by the service
  729. // before dispatch, but dispatch rides a microtask: parallel tool calls
  730. // can append several asked events before any answerer runs. THIS
  731. // request's event is therefore the newest asked event that is still
  732. // undecided, unclaimed by another pending entry, and — when the ask
  733. // names a call — carries the same callId.
  734. const events = req.agent.session.events
  735. const claimed = new Set<ApprovalRequestId>()
  736. for (const entry of pendingApprovals.values()) claimed.add(entry.approvalId)
  737. const decided = new Set<ApprovalRequestId>()
  738. let approvalId: ApprovalRequestId | undefined
  739. for (let i = events.length - 1; i >= 0; i -= 1) {
  740. const event = events[i] as SessionEvent
  741. if (event.type === 'approval/decided') {
  742. decided.add(event.data.id)
  743. } else if (event.type === 'approval/asked') {
  744. if (decided.has(event.data.id) || claimed.has(event.data.id)) continue
  745. // Symmetric pairing: a callId-bearing ask only takes its own call's
  746. // record, and a callId-less ask only takes a callId-less record —
  747. // so neither shape can steal the other's audit id under parallel
  748. // asks. (Today every producer — the tool executor — passes callId;
  749. // the callId-less arm guards any future non-tool asker.)
  750. if ((req.callId ?? null) !== (event.data.callId ?? null)) continue
  751. approvalId = event.data.id
  752. break
  753. }
  754. }
  755. // No asked event means the request bypassed the service's audit path —
  756. // not this channel's question; delegate to the fail-closed default.
  757. if (approvalId === undefined) return next()
  758. const id = approvalId
  759. return new Promise<ApprovalOutcome>((resolve) => {
  760. const settle = (outcome: ApprovalOutcome): void => {
  761. /* v8 ignore next 3 -- defensive double-settle guard: respond() routes
  762. through the pending table (a settled id is not-pending before it can
  763. re-settle) and the first settle removes the abort listener, so no
  764. reachable path settles twice; kept against future settle callers. */
  765. if (!pendingApprovals.delete(pending.rpcId)) return
  766. req.signal?.removeEventListener('abort', onAbort)
  767. broadcast({ type: 'approval/resolved', sessionId: pending.sessionId, approvalId: id, outcome })
  768. // A cancelled ask was already settled by the service's own signal
  769. // race, which discards this late resolution; resolving is a no-op
  770. // there and keeps this promise from dangling forever.
  771. resolve(outcome)
  772. }
  773. const onAbort = (): void => { settle('cancelled') }
  774. const pending: PendingApproval = {
  775. rpcId: RpcId(randomUUID()),
  776. sessionId: req.agent.session.id,
  777. approvalId: id,
  778. toolName: req.toolName,
  779. ...req.callId === undefined ? {} : { callId: req.callId },
  780. ...req.reason === undefined ? {} : { reason: req.reason },
  781. resolve: settle,
  782. }
  783. pendingApprovals.set(pending.rpcId, pending)
  784. req.signal?.addEventListener('abort', onAbort, { once: true })
  785. const envelope = requestedFrame(pending)
  786. for (const queue of muxQueues) queue.push(envelope)
  787. })
  788. })
  789. }
  790. /**
  791. * Gate the cold path on the store: an id absent from it, or naming a legacy
  792. * log without a cwd (pre-release stance: not served, no compatibility), is
  793. * not-found before any resume is attempted. With the gate passed, a later
  794. * resume failure is genuinely internal. No persistence configured skips the
  795. * gate — resume itself then fails loud with its own diagnostic.
  796. */
  797. async function assertServable(sessionId: SessionId): Promise<void> {
  798. const persistence = ctx.get('sessionPersistence')
  799. if (persistence === undefined) return
  800. const meta = (await persistence.list()).find(m => m.id === sessionId)
  801. if (meta === undefined || meta.cwd === undefined) throw new SessionNotFound(`session "${sessionId}" not found`)
  802. }
  803. async function agentFor(sessionId: SessionId): Promise<{ agent: Agent } | { error: RpcError }> {
  804. const live = ctx.agents.get(sessionId)
  805. if (live !== undefined) return { agent: live }
  806. let resume = resumes.get(sessionId)
  807. if (resume === undefined) {
  808. resume = (async () => {
  809. try {
  810. await assertServable(sessionId)
  811. const handle = await ctx.agents.resume({
  812. resumeSessionId: sessionId,
  813. agentOptions,
  814. setup: installTarget,
  815. })
  816. return handle.agent
  817. } finally {
  818. resumes.delete(sessionId)
  819. }
  820. })()
  821. resumes.set(sessionId, resume)
  822. }
  823. try {
  824. return { agent: await resume }
  825. } catch (error: unknown) {
  826. if (error instanceof SessionNotFound) {
  827. return { error: { code: 'session-not-found', message: error.message, details: { sessionId } } }
  828. }
  829. // The internal details slot is contractually {}; the reason rides the message.
  830. return { error: { code: 'internal', message: `resume failed for session "${sessionId}": ${String(error)}`, details: {} } }
  831. }
  832. }
  833. /** Resolve one requested identity to a live agent, creating or resuming it once. */
  834. async function ensureSession(sessionId: SessionId, cwd: string, checkPersistedIdentity: boolean): Promise<Agent> {
  835. let creation = sessionCreations.get(sessionId)
  836. if (creation === undefined) {
  837. creation = (async () => {
  838. const live = ctx.agents.get(sessionId)
  839. if (live !== undefined) return live
  840. const persistence = checkPersistedIdentity ? ctx.get('sessionPersistence') : undefined
  841. const stored = persistence === undefined
  842. ? undefined
  843. : (await persistence.list()).find(header => header.id === sessionId)
  844. if (stored !== undefined) {
  845. if (stored.cwd !== cwd) {
  846. throw new SessionCwdConflict(sessionId, cwd, stored.cwd)
  847. }
  848. return (await ctx.agents.resume({
  849. resumeSessionId: sessionId,
  850. agentOptions,
  851. setup: installTarget,
  852. })).agent
  853. }
  854. try {
  855. await mkdir(cwd, { recursive: true })
  856. } catch (error: unknown) {
  857. throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
  858. }
  859. return (await ctx.agents.create({
  860. sessionId,
  861. agentOptions,
  862. meta: { cwd },
  863. setup: installTarget,
  864. })).agent
  865. })().catch((error: unknown) => {
  866. // Another Host entry path may have published the same identity while
  867. // this operation crossed an asynchronous persistence/filesystem step.
  868. const live = ctx.agents.get(sessionId)
  869. if (live !== undefined) return live
  870. throw error
  871. }).finally(() => {
  872. sessionCreations.delete(sessionId)
  873. })
  874. sessionCreations.set(sessionId, creation)
  875. }
  876. const agent = await creation
  877. if (agent.session.header.cwd !== cwd) {
  878. throw new SessionCwdConflict(sessionId, cwd, agent.session.header.cwd)
  879. }
  880. return agent
  881. }
  882. /** Resolve or create one path while holding the Host's workspace-create chain. */
  883. function ensureWorkspace(
  884. path: string,
  885. title: string | undefined,
  886. rejectExistingName = false,
  887. createDirectory = false,
  888. ): Promise<{ workspace: Workspace; created: boolean }> {
  889. const operation = workspaceCreationChain.then(async () => {
  890. if (rejectExistingName && title !== undefined
  891. && ctx.workspace.list().some(workspace => workspace.title === title)) {
  892. throw new WorkspaceNameConflictError(title)
  893. }
  894. if (createDirectory) {
  895. try {
  896. await mkdir(path, { recursive: true })
  897. } catch (error: unknown) {
  898. throw new WorkspaceDirectoryCreationError(
  899. `failed to create workspace directory "${path}": ${String(error)}`,
  900. )
  901. }
  902. }
  903. const existing = await ctx.workspace.resolveByPath(path)
  904. if (existing !== undefined) return { workspace: existing, created: false }
  905. return { workspace: await ctx.workspace.create(path, title), created: true }
  906. })
  907. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  908. return operation
  909. }
  910. /** Resolve the goal service; absent = the deployment did not compose @deepseek-ai/dsh-goal. */
  911. function goalService(): NonNullable<ReturnType<typeof ctx.get<'goals'>>> | { error: RpcError } {
  912. const goals = ctx.get('goals')
  913. if (goals === undefined) {
  914. return { error: { code: 'internal', message: 'goal service is absent: this deployment does not mount @deepseek-ai/dsh-goal in its composition (cordis.yml or explicit assembly)', details: {} } }
  915. }
  916. return goals
  917. }
  918. /** Map one goal-domain rejection to the wire error (stable GoalError codes ride in details). */
  919. function goalError(request: RpcRequest<unknown>, error: unknown): RpcResponse<never> {
  920. const details = error instanceof GoalError ? { goalCode: error.code } : {}
  921. return err(request, { code: 'internal', message: String(error), details })
  922. }
  923. /** Resolve a session's agent, apply one goal mutation, and acknowledge with the new CAS ref. */
  924. async function mutateGoal(
  925. request: RpcRequest<{ sessionId: SessionId }>,
  926. mutation: (goals: NonNullable<ReturnType<typeof ctx.get<'goals'>>>, agent: Agent) => CoreGoalRef,
  927. ): Promise<RpcResponse<{ ref: GoalRef }>> {
  928. const goals = goalService()
  929. if ('error' in goals) return err(request, goals.error)
  930. const found = await agentFor(request.payload.sessionId)
  931. if ('error' in found) return err(request, found.error)
  932. try {
  933. const ref = mutation(goals, found.agent)
  934. return ok(request, { ref: { id: ref.id, revision: ref.revision } })
  935. } catch (error: unknown) {
  936. return goalError(request, error)
  937. }
  938. }
  939. /** Missing-service report shared by the settings domain (skills-domain stance). */
  940. function settingsAbsent(): RpcError {
  941. return { code: 'internal', message: 'settings service is absent: this deployment does not mount a settings provider (e.g. @deepseek-ai/dsh-settings-local) in its composition', details: {} }
  942. }
  943. /** Missing-service report shared by the credentials domain. */
  944. function credentialsAbsent(): RpcError {
  945. return { code: 'internal', message: 'credentials service is absent: this deployment does not mount a credential provider (e.g. @deepseek-ai/dsh-credentials-local) in its composition', details: {} }
  946. }
  947. /** Map one redacted seam descriptor to its wire view. */
  948. function namespaceView(descriptor: SettingsDescriptor): SettingsNamespaceView {
  949. return {
  950. ns: String(descriptor.ns),
  951. schema: descriptor.schema,
  952. value: descriptor.value,
  953. ...descriptor.base === undefined ? {} : { base: descriptor.base },
  954. ...descriptor.user === undefined ? {} : { user: descriptor.user },
  955. applies: descriptor.applies,
  956. secrets: (descriptor.secrets ?? []).map(secret => ({ path: [...secret.path], set: secret.set })),
  957. revision: descriptor.revision,
  958. }
  959. }
  960. /**
  961. * The settings namespaces this proxy serves: exactly those a registered
  962. * configurable provider addresses. The settings seam itself is general —
  963. * any plugin may register a namespace for its own configuration — but the
  964. * Web configuration plane is scoped to model providers, and that boundary
  965. * has to be enforced here rather than assumed from the current plugin set.
  966. * Without it, every future `settings.register()` would silently become
  967. * remotely readable and writable configuration.
  968. */
  969. function exposedNamespaces(): Set<string> {
  970. return new Set(ctx.llm.listConfigurableProviders().map(entry => entry.settingsNs))
  971. }
  972. /** Refuse a namespace outside the model-provider boundary, naming why. */
  973. function notExposed(request: RpcRequest<unknown>, ns: string): RpcResponse<SettingsNamespaceView> {
  974. return err(request, {
  975. code: 'settings-not-exposed',
  976. message: `settings namespace "${ns}" is not exposed to configuration clients; only a namespace a registered model provider addresses is`,
  977. details: { ns },
  978. })
  979. }
  980. /**
  981. * Run one settings write (merge or wholesale replace) and acknowledge with
  982. * the namespace's new redacted view. A namespace outside the model-provider
  983. * boundary is refused before the seam is touched; every seam refusal —
  984. * unknown or invalid namespace, read-only provider, schema validation,
  985. * storage — becomes one `settings-rejected` carrying the seam's own message.
  986. */
  987. async function settingsWrite(
  988. request: RpcRequest<unknown>,
  989. ns: string,
  990. mode: 'update' | 'replace' | 'mutate',
  991. section: object,
  992. expectedRevision?: number,
  993. ): Promise<RpcResponse<SettingsNamespaceView>> {
  994. const settings = ctx.get('settings')
  995. if (settings === undefined) return err(request, settingsAbsent())
  996. const rejected = (error: unknown): RpcResponse<SettingsNamespaceView> => {
  997. // A stale writer is its own outcome, not a malformed request: the client
  998. // must re-read and re-apply rather than treat the write as invalid.
  999. if (error instanceof SettingsConflictError) {
  1000. return err(request, {
  1001. code: 'settings-conflict',
  1002. message: error.message,
  1003. details: { ns, expected: error.expected, actual: error.actual },
  1004. })
  1005. }
  1006. return err(request, {
  1007. code: 'settings-rejected',
  1008. message: error instanceof Error ? error.message : String(error),
  1009. details: { ns },
  1010. })
  1011. }
  1012. let branded: SettingsNamespace
  1013. try {
  1014. branded = settingsNamespace(ns)
  1015. } catch (error: unknown) {
  1016. // A malformed name is a client bug, reported as such; it could never be
  1017. // in the exposed set either, so naming the real fault costs no ground.
  1018. return rejected(error)
  1019. }
  1020. if (!exposedNamespaces().has(ns)) return notExposed(request, ns)
  1021. try {
  1022. if (mode === 'update') await settings.update(branded, section, expectedRevision)
  1023. else if (mode === 'replace') await settings.replace(branded, section, expectedRevision)
  1024. else await settings.mutate(branded, section as SettingsPathOp[], expectedRevision)
  1025. } catch (error: unknown) {
  1026. return rejected(error)
  1027. }
  1028. const descriptor = settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === branded)
  1029. if (descriptor === undefined) {
  1030. // The write committed but the namespace vanished before this read: only
  1031. // a concurrent registrant disposal can produce it.
  1032. return err(request, { code: 'internal', message: `settings namespace "${ns}" was disposed after the ${mode}`, details: {} })
  1033. }
  1034. return ok(request, namespaceView(descriptor))
  1035. }
  1036. return {
  1037. sessions: {
  1038. // Attached sessions summarize from memory; persisted-but-unattached (cold)
  1039. // sessions merge in from the persistence store so history survives restarts.
  1040. // Legacy logs without a cwd (pre-project stance) are not served — every
  1041. // session now records its project at create time.
  1042. async list(request) {
  1043. const items = ctx.sessions.list().map((session) => {
  1044. const agent = ctx.agents.get(session.id)
  1045. const projections = listProjectionsFor(ctx, session.header, session)
  1046. return {
  1047. ...summarize(session, agent?.status === 'running'),
  1048. ...projections === undefined ? {} : { projections },
  1049. }
  1050. })
  1051. const attached = new Set(items.map(item => item.sessionId))
  1052. const persistence = ctx.get('sessionPersistence')
  1053. if (persistence !== undefined) {
  1054. const cold = (await persistence.list()).filter(meta => !attached.has(meta.id) && meta.cwd !== undefined)
  1055. items.push(...await Promise.all(cold.map(async (meta) => {
  1056. // Cold rows read the persisted projection cache only — never a
  1057. // log load; a session without a cache row simply has no column.
  1058. const projections = listProjectionsFor(ctx, meta, undefined)
  1059. return {
  1060. ...await summarizeCold(persistence, meta),
  1061. ...projections === undefined ? {} : { projections },
  1062. }
  1063. })))
  1064. }
  1065. items.sort((a, b) => b.updatedAt - a.updatedAt)
  1066. return ok(request, { items })
  1067. },
  1068. async create(request) {
  1069. const sessionId = request.payload.sessionId ?? `session-${randomUUID()}` as SessionId
  1070. let workspace: Workspace | undefined
  1071. if (request.payload.workspaceId !== undefined) {
  1072. workspace = ctx.workspace.get(brandWorkspaceId(request.payload.workspaceId))
  1073. if (workspace === undefined) {
  1074. return err(request, {
  1075. code: 'workspace-not-found',
  1076. message: `workspace "${request.payload.workspaceId}" not found`,
  1077. details: { workspaceId: request.payload.workspaceId },
  1078. })
  1079. }
  1080. }
  1081. const cwd = workspace?.path ?? request.payload.cwd ?? defaults.cwd
  1082. try {
  1083. await ensureSession(sessionId, cwd, request.payload.sessionId !== undefined)
  1084. } catch (error: unknown) {
  1085. if (error instanceof SessionCwdConflict) {
  1086. return err(request, {
  1087. code: 'session-conflict',
  1088. message: error.message,
  1089. details: {
  1090. sessionId: error.sessionId,
  1091. requestedCwd: error.requestedCwd,
  1092. ...error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd },
  1093. },
  1094. })
  1095. }
  1096. return err(request, {
  1097. code: 'internal',
  1098. message: `failed to create session "${sessionId}": ${String(error)}`,
  1099. details: {},
  1100. })
  1101. }
  1102. if (workspace !== undefined) {
  1103. try {
  1104. await workspace.attachSession(sessionId)
  1105. } catch (error: unknown) {
  1106. return err(request, {
  1107. code: 'workspace-attach-failed',
  1108. message: `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`,
  1109. details: { sessionId, workspaceId: workspace.id },
  1110. })
  1111. }
  1112. }
  1113. return ok(request, { sessionId })
  1114. },
  1115. async history(request) {
  1116. const { sessionId, beforeSeq, maxMessages } = request.payload
  1117. const found = await agentFor(sessionId)
  1118. if ('error' in found) return err(request, found.error)
  1119. // Everything below the resume above is synchronous: the page slice,
  1120. // the seq read, and the projection walk see one un-torn session state.
  1121. const page = paginate(found.agent.session.events, beforeSeq, maxMessages ?? DEFAULT_MAX_MESSAGES)
  1122. // Views are computed against the registry at pagination time; result
  1123. // pairing scans within the page only (message-boundary pagination keeps
  1124. // a call and its result on one page — a cross-page miss soft-falls).
  1125. const entries: HistoryEntry[] = page.events.map((event) => {
  1126. const view = viewFor(ctx, event, callId => backscanArgs(page.events, callId))
  1127. return { event, ...view === undefined ? {} : { view } }
  1128. })
  1129. // Baseline rider: tail page only — loadOlder (beforeSeq present) is
  1130. // the one path that never needs a fresh projection baseline.
  1131. const projections = beforeSeq === undefined ? projectionsFor(ctx, found.agent) : undefined
  1132. return ok(request, {
  1133. events: entries,
  1134. hasMore: page.hasMore,
  1135. ...projections === undefined ? {} : { projections },
  1136. })
  1137. },
  1138. async models(request) {
  1139. const { sessionId } = request.payload
  1140. const found = await agentFor(sessionId)
  1141. if ('error' in found) return err(request, found.error)
  1142. const current = targetFor(found.agent).current
  1143. const { groups, failures } = await buildModelCatalog(ctx, current)
  1144. return ok(request, { current: { ...current }, groups, failures })
  1145. },
  1146. async selectModel(request) {
  1147. const { sessionId, provider, model, reasoningEffort } = request.payload
  1148. const found = await agentFor(sessionId)
  1149. if ('error' in found) return err(request, found.error)
  1150. try {
  1151. const resolved = await ctx.llm.resolveCallConfig({
  1152. provider,
  1153. model,
  1154. ...reasoningEffort === undefined
  1155. ? {}
  1156. : { reasoningEffort: ReasoningEffortId(reasoningEffort) },
  1157. })
  1158. const selected: AgentLlmTarget = {
  1159. provider: resolved.provider,
  1160. model: resolved.model,
  1161. ...resolved.reasoningEffort === undefined
  1162. ? {}
  1163. : { reasoningEffort: resolved.reasoningEffort },
  1164. }
  1165. targetFor(found.agent).current = selected
  1166. return ok(request, { selected: { ...selected } })
  1167. } catch (error: unknown) {
  1168. return err(request, {
  1169. code: 'model-unavailable',
  1170. message: error instanceof Error ? error.message : String(error),
  1171. details: { provider, model },
  1172. })
  1173. }
  1174. },
  1175. async rename(request) {
  1176. const { sessionId, title } = request.payload
  1177. const found = await agentFor(sessionId)
  1178. if ('error' in found) return err(request, found.error)
  1179. const titles = ctx.get('sessionTitle')
  1180. if (titles === undefined) {
  1181. return err(request, { code: 'internal', message: 'renaming is unavailable: this deployment mounts no session-title service', details: {} })
  1182. }
  1183. try {
  1184. const accepted = titles.rename(found.agent.session, title)
  1185. return ok(request, { title: accepted.title, seq: accepted.eventSeq })
  1186. } catch (error: unknown) {
  1187. // Only the input's fault maps to title-invalid (the message is
  1188. // product-user-visible in the rename dialog); liveness and disposal
  1189. // races are deployment trouble, not a bad title.
  1190. if (error instanceof SessionTitleInvalidError) {
  1191. return err(request, {
  1192. code: 'title-invalid',
  1193. message: error.message,
  1194. details: { sessionId },
  1195. })
  1196. }
  1197. return err(request, {
  1198. code: 'internal',
  1199. message: `failed to rename session "${sessionId}": ${String(error)}`,
  1200. details: {},
  1201. })
  1202. }
  1203. },
  1204. async prompt(request) {
  1205. const { sessionId, mode, content } = request.payload
  1206. const found = await agentFor(sessionId)
  1207. if ('error' in found) return err(request, found.error)
  1208. const agent = found.agent
  1209. // The rpcId rides MessageSource into user/message (merge declaration in api/sessions.ts; provisional correlation).
  1210. const source: MessageSource = { kind: 'user', rpcId: request.rpcId }
  1211. try {
  1212. const message: UserMessage = createUserMessage({ content, source })
  1213. if (mode === 'steer') agent.steer(message)
  1214. else agent.followup(message)
  1215. } catch (error: unknown) {
  1216. // A synchronous throw from steer/followup means disposed or invalid input; surface as agent-busy with the reason attached.
  1217. return err(request, { code: 'agent-busy', message: 'prompt rejected', details: { reason: String(error) } })
  1218. }
  1219. return ok(request, { accepted: true as const })
  1220. },
  1221. updateQueue(request) {
  1222. const { sessionId, itemId, action } = request.payload
  1223. const agent = ctx.agents.get(sessionId)
  1224. if (agent === undefined || agent.updateInbox(itemId, action) === 'not-found') {
  1225. return Promise.resolve(err(request, {
  1226. code: 'queue-item-not-found',
  1227. message: 'queued item is no longer pending',
  1228. details: { itemId },
  1229. }))
  1230. }
  1231. return Promise.resolve(ok(request, { accepted: true as const }))
  1232. },
  1233. cancel(request) {
  1234. const { sessionId } = request.payload
  1235. const agent = ctx.agents.get(sessionId)
  1236. if (agent === undefined) {
  1237. return Promise.resolve(err(request, {
  1238. code: 'session-not-found',
  1239. message: `session "${sessionId}" not found (not attached)`,
  1240. details: { sessionId },
  1241. }))
  1242. }
  1243. agent.cancel({ kind: 'user' })
  1244. return Promise.resolve(ok(request, { accepted: true as const }))
  1245. },
  1246. },
  1247. workspace: {
  1248. list(request) {
  1249. return Promise.resolve(ok(request, { items: ctx.workspace.list().map(workspaceView) }))
  1250. },
  1251. // Exactly one of path/name arrives (schema refine). Existing-folder
  1252. // adoption reuses its canonical path; create-by-name rejects a name
  1253. // already present in the registry.
  1254. async create(request) {
  1255. const { payload } = request
  1256. let path: string
  1257. if (payload.name !== undefined) {
  1258. const name = payload.name.trim()
  1259. if (name === '' || name === '.' || name === '..' || /[/\\]/.test(name)) {
  1260. return err(request, {
  1261. code: 'workspace-invalid-path',
  1262. message: `workspace name must be one non-empty path segment, got "${payload.name}"`,
  1263. details: { path: payload.name },
  1264. })
  1265. }
  1266. path = join(defaults.workspaceRoot, name)
  1267. } else {
  1268. path = payload.path as string
  1269. }
  1270. try {
  1271. const name = payload.name?.trim()
  1272. const { workspace, created } = await ensureWorkspace(
  1273. path,
  1274. name,
  1275. name !== undefined,
  1276. name !== undefined,
  1277. )
  1278. return ok(request, { workspace: workspaceView(workspace), created })
  1279. } catch (error: unknown) {
  1280. if (error instanceof WorkspaceNameConflictError) {
  1281. return err(request, {
  1282. code: 'workspace-name-conflict',
  1283. message: error.message,
  1284. details: { name: error.workspaceName },
  1285. })
  1286. }
  1287. if (error instanceof WorkspaceDirectoryCreationError) {
  1288. return err(request, { code: 'internal', message: error.message, details: {} })
  1289. }
  1290. // The registry rejects a path that does not resolve to an existing
  1291. // directory (realpath ENOENT / not-a-directory) — the business
  1292. // error of the typed-path flow, surfaced as a validation failure.
  1293. return err(request, {
  1294. code: 'workspace-invalid-path',
  1295. message: `cannot create a workspace at "${path}": ${error instanceof Error ? error.message : String(error)}`,
  1296. details: { path },
  1297. })
  1298. }
  1299. },
  1300. async rename(request) {
  1301. const { payload } = request
  1302. const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
  1303. if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
  1304. const title = payload.title.trim()
  1305. // Uniqueness AND the same-title no-op both ride the create chain so
  1306. // they observe the state left by earlier queued renames — checked
  1307. // up front, a queued A→A could report success while an earlier A→B
  1308. // still lands afterwards.
  1309. const operation = workspaceCreationChain.then(async () => {
  1310. if (title === workspace.title) return
  1311. if (ctx.workspace.list().some(other => other.id !== workspace.id && other.title === title)) {
  1312. throw new WorkspaceNameConflictError(title)
  1313. }
  1314. await workspace.setTitle(title)
  1315. })
  1316. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  1317. try {
  1318. await operation
  1319. } catch (error: unknown) {
  1320. if (error instanceof WorkspaceNameConflictError) {
  1321. return err(request, {
  1322. code: 'workspace-name-conflict',
  1323. message: error.message,
  1324. details: { name: error.workspaceName },
  1325. })
  1326. }
  1327. throw error
  1328. }
  1329. return ok(request, { workspace: workspaceView(workspace) })
  1330. },
  1331. async delete(request) {
  1332. const { workspaceId } = request.payload
  1333. const operation = workspaceCreationChain.then(() =>
  1334. ctx.workspace.delete(brandWorkspaceId(workspaceId)))
  1335. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  1336. if (!await operation) return workspaceNotFound(request, workspaceId)
  1337. return ok(request, { deleted: true as const })
  1338. },
  1339. async insertSessionBefore(request) {
  1340. const { payload } = request
  1341. const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
  1342. if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
  1343. try {
  1344. await workspace.insertSessionBefore(payload.sessionId, payload.beforeSessionId)
  1345. } catch (error: unknown) {
  1346. // Only the entity's unaccounted-id rejection is the business code;
  1347. // storage/durability failures propagate as internal errors.
  1348. if (!(error instanceof WorkspaceMoveInvalidError)) throw error
  1349. return err(request, {
  1350. code: 'workspace-move-invalid',
  1351. message: error.message,
  1352. details: {
  1353. workspaceId: payload.workspaceId,
  1354. sessionId: payload.sessionId,
  1355. ...payload.beforeSessionId === undefined ? {} : { beforeSessionId: payload.beforeSessionId },
  1356. },
  1357. })
  1358. }
  1359. return ok(request, { workspace: workspaceView(workspace) })
  1360. },
  1361. },
  1362. host: {
  1363. describe(request) {
  1364. // TODO(step2): version should read apps/cli's package.json; placeholder for now.
  1365. return Promise.resolve(ok(request, {
  1366. version: '0.0.1',
  1367. // Same source as session.create's fallback: the UI's default project
  1368. // must match where an unspecified-cwd session actually lands.
  1369. cwd: defaults.cwd,
  1370. provider: defaults.provider,
  1371. model: defaults.model,
  1372. attachedSessions: ctx.agents.list().length,
  1373. }))
  1374. },
  1375. async pickDirectory(request, signal) {
  1376. const capability = ctx.directoryPicker.capability()
  1377. if (capability.kind !== 'native') {
  1378. return err(request, {
  1379. code: 'directory-picker-unavailable',
  1380. message: `host.pickDirectory needs the native capability; the composed picker serves "${capability.kind}"`,
  1381. details: { capability: capability.kind },
  1382. })
  1383. }
  1384. try {
  1385. const path = await capability.pick(signal)
  1386. return ok(request, { path })
  1387. } catch (error: unknown) {
  1388. if (signal.aborted) {
  1389. return err(request, {
  1390. code: 'cancelled',
  1391. message: 'directory picker was aborted',
  1392. details: {},
  1393. })
  1394. }
  1395. return err(request, {
  1396. code: 'internal',
  1397. message: `directory picker failed: ${error instanceof Error ? error.message : String(error)}`,
  1398. details: {},
  1399. })
  1400. }
  1401. },
  1402. async listDirectory(request, signal) {
  1403. const capability = ctx.directoryPicker.capability()
  1404. if (capability.kind !== 'browse') {
  1405. return err(request, {
  1406. code: 'directory-picker-unavailable',
  1407. message: `host.listDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
  1408. details: { capability: capability.kind },
  1409. })
  1410. }
  1411. try {
  1412. // The carrier's signal follows the caller: a disconnect or timeout
  1413. // stops the backend's directory scan instead of outliving it.
  1414. return ok(request, await capability.list(request.payload.path, signal))
  1415. } catch (error: unknown) {
  1416. // An abort is the caller's own timeout/disconnect, not a server
  1417. // failure — same code pickDirectory and command.execute report.
  1418. if (signal.aborted) {
  1419. return err(request, { code: 'cancelled', message: 'directory listing was aborted', details: {} })
  1420. }
  1421. return err(request, directoryError(error))
  1422. }
  1423. },
  1424. async createDirectory(request) {
  1425. const capability = ctx.directoryPicker.capability()
  1426. if (capability.kind !== 'browse') {
  1427. return err(request, {
  1428. code: 'directory-picker-unavailable',
  1429. message: `host.createDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
  1430. details: { capability: capability.kind },
  1431. })
  1432. }
  1433. try {
  1434. return ok(request, { path: await capability.createDirectory(request.payload.path, request.payload.name) })
  1435. } catch (error: unknown) {
  1436. return err(request, directoryError(error))
  1437. }
  1438. },
  1439. async openPath(request, signal) {
  1440. try {
  1441. const open = defaults.openPath
  1442. ?? ((path: string, openSignal: AbortSignal) => openNativePath(path, openSignal))
  1443. await open(request.payload.path, signal)
  1444. return ok(request, { opened: true as const })
  1445. } catch (error: unknown) {
  1446. if (signal.aborted) {
  1447. return err(request, {
  1448. code: 'cancelled',
  1449. message: 'path open was aborted',
  1450. details: {},
  1451. })
  1452. }
  1453. return err(request, {
  1454. code: 'internal',
  1455. message: `path open failed: ${error instanceof Error ? error.message : String(error)}`,
  1456. details: {},
  1457. })
  1458. }
  1459. },
  1460. },
  1461. commands: {
  1462. // Both methods address one session's agent (agentFor keeps its
  1463. // resume-on-miss: clients only send a sessionId for a published
  1464. // session, and resume restores an existing entity).
  1465. async list(request) {
  1466. // Missing service = the deployment omitted dsh-commands from its
  1467. // composition, not an empty catalog: fail loud instead of serving [].
  1468. const commands = ctx.get('commands')
  1469. if (commands === undefined) {
  1470. return err(request, { code: 'internal', message: 'command registry is absent: this deployment does not mount @deepseek-ai/dsh-commands in its composition (cordis.yml or explicit assembly)', details: {} })
  1471. }
  1472. const found = await agentFor(request.payload.sessionId)
  1473. if ('error' in found) return err(request, found.error)
  1474. return ok(request, { commands: commands.list(found.agent) })
  1475. },
  1476. async execute(request, signal) {
  1477. const commands = ctx.get('commands')
  1478. if (commands === undefined) {
  1479. return err(request, { code: 'internal', message: 'command registry is absent: this deployment does not mount @deepseek-ai/dsh-commands in its composition (cordis.yml or explicit assembly)', details: {} })
  1480. }
  1481. const { sessionId, line } = request.payload
  1482. const found = await agentFor(sessionId)
  1483. if ('error' in found) return err(request, found.error)
  1484. try {
  1485. // Pure admission: the executor's durable command/run + command/done
  1486. // pair (broadcast on the mux stream) carries the outcome; the
  1487. // response reports whether the line resolved to a handler, plus the
  1488. // minted pairing id so the issuing client can correlate its request
  1489. // with the flow node the lifecycle events produce.
  1490. const execution = await commands.execute(found.agent, line, signal)
  1491. return ok(request, execution === undefined
  1492. ? { matched: false }
  1493. : { matched: true, commandId: execution.commandId })
  1494. } catch (error: unknown) {
  1495. if (signal.aborted) return err(request, { code: 'cancelled', message: 'command execution was aborted', details: {} })
  1496. return err(request, { code: 'internal', message: `command failed: ${String(error)}`, details: {} })
  1497. }
  1498. },
  1499. },
  1500. goals: {
  1501. // Mutations only — the read side is the 'goal' session projection.
  1502. // Every verb resolves the session's agent (agentFor: implicit cold
  1503. // resume, the command.* precedent) and acknowledges with the new CAS
  1504. // ref; the committed goal/change event carries the whole value to every
  1505. // client through the projection frames.
  1506. async create(request) {
  1507. const { objective, maxGoalRounds } = request.payload
  1508. return mutateGoal(request, (goals, agent) => goals.create(agent, {
  1509. objective,
  1510. ...(maxGoalRounds !== undefined ? { maxGoalRounds } : {}),
  1511. }))
  1512. },
  1513. async edit(request) {
  1514. const { ref, objective, maxGoalRounds } = request.payload
  1515. return mutateGoal(request, (goals, agent) => goals.edit(agent, ref, {
  1516. ...(objective !== undefined ? { objective } : {}),
  1517. ...(maxGoalRounds !== undefined ? { maxGoalRounds } : {}),
  1518. }))
  1519. },
  1520. async pause(request) {
  1521. return mutateGoal(request, (goals, agent) => goals.pause(agent, request.payload.ref))
  1522. },
  1523. async resume(request) {
  1524. return mutateGoal(request, (goals, agent) => goals.resume(agent, request.payload.ref))
  1525. },
  1526. async complete(request) {
  1527. return mutateGoal(request, (goals, agent) => goals.complete(agent, request.payload.ref))
  1528. },
  1529. async clear(request) {
  1530. const goals = goalService()
  1531. if ('error' in goals) return err(request, goals.error)
  1532. const found = await agentFor(request.payload.sessionId)
  1533. if ('error' in found) return err(request, found.error)
  1534. try {
  1535. goals.clear(found.agent, request.payload.ref)
  1536. return ok(request, { cleared: true as const })
  1537. } catch (error: unknown) {
  1538. return goalError(request, error)
  1539. }
  1540. },
  1541. },
  1542. skills: {
  1543. // Skill lookup never touches the Agent registry: the session address
  1544. // resolves to a canonical cwd from the host-resident session header, so
  1545. // listing skills cannot create or resume an agent as a side effect.
  1546. async list(request) {
  1547. const { sessionId } = request.payload
  1548. const session = ctx.sessions.get(sessionId)
  1549. if (session === undefined) {
  1550. return err(request, {
  1551. code: 'session-not-found',
  1552. message: `session "${sessionId}" not found (not attached)`,
  1553. details: { sessionId },
  1554. })
  1555. }
  1556. if (session.header.cwd === undefined) {
  1557. // Every served session records its project at create time; a
  1558. // cwd-less header is a pre-project legacy log (not served).
  1559. return err(request, { code: 'internal', message: `session "${sessionId}" has no project cwd`, details: {} })
  1560. }
  1561. const cwd = session.header.cwd
  1562. // Same stance as the commands domain: a missing service means the
  1563. // deployment omitted dsh-skill from its composition, not an empty
  1564. // catalog. ctx.get also keeps this handler independent of the gateway
  1565. // plugin's inject list (an undeclared `ctx.skills` property read
  1566. // fails the reflect proxy).
  1567. const skillRegistry = ctx.get('skills')
  1568. if (skillRegistry === undefined) {
  1569. return err(request, { code: 'internal', message: 'skill registry is absent: this deployment does not mount @deepseek-ai/dsh-skill in its composition (cordis.yml or explicit assembly)', details: {} })
  1570. }
  1571. try {
  1572. const skills = (await skillRegistry.list({ cwd }))
  1573. .filter(skill => skill.invocation.modelInvocable && skill.invocation.userInvocable)
  1574. return ok(request, {
  1575. skills: skills.map(skill => ({
  1576. name: skill.name,
  1577. description: skill.description,
  1578. ...skill.whenToUse === undefined ? {} : { whenToUse: skill.whenToUse },
  1579. })),
  1580. })
  1581. } catch (error: unknown) {
  1582. return err(request, { code: 'internal', message: `skill listing failed: ${String(error)}`, details: {} })
  1583. }
  1584. },
  1585. },
  1586. settings: {
  1587. describe(request) {
  1588. const settings = ctx.get('settings')
  1589. if (settings === undefined) return Promise.resolve(err(request, settingsAbsent()))
  1590. const exposed = exposedNamespaces()
  1591. return Promise.resolve(ok(request, {
  1592. writable: settings.writable,
  1593. namespaces: settings.describe({ redactSecrets: true })
  1594. .filter(descriptor => exposed.has(String(descriptor.ns)))
  1595. .map(namespaceView),
  1596. }))
  1597. },
  1598. update: request => settingsWrite(request, request.payload.ns, 'update', request.payload.patch, request.payload.expectedRevision),
  1599. replace: request => settingsWrite(request, request.payload.ns, 'replace', request.payload.section, request.payload.expectedRevision),
  1600. mutate: request => settingsWrite(request, request.payload.ns, 'mutate', request.payload.ops, request.payload.expectedRevision),
  1601. },
  1602. credentials: {
  1603. async describe(request) {
  1604. const credentials = ctx.get('credentials')
  1605. if (credentials === undefined) return err(request, credentialsAbsent())
  1606. const entries = await Promise.all(request.payload.refs.map(async (ref) => {
  1607. const info = await credentials.describe(credentialRef(ref))
  1608. const view: CredentialView = {
  1609. configured: info.configured,
  1610. ...info.source === undefined ? {} : { source: info.source },
  1611. writable: info.writable,
  1612. }
  1613. return [ref, view] as const
  1614. }))
  1615. return ok(request, { credentials: Object.fromEntries(entries) })
  1616. },
  1617. async set(request) {
  1618. const credentials = ctx.get('credentials')
  1619. if (credentials === undefined) return err(request, credentialsAbsent())
  1620. const { ref, value } = request.payload
  1621. try {
  1622. await credentials.set(credentialRef(ref), value)
  1623. } catch (error: unknown) {
  1624. return err(request, {
  1625. code: 'credential-rejected',
  1626. message: error instanceof Error ? error.message : String(error),
  1627. details: { ref },
  1628. })
  1629. }
  1630. return ok(request, {})
  1631. },
  1632. async unset(request) {
  1633. const credentials = ctx.get('credentials')
  1634. if (credentials === undefined) return err(request, credentialsAbsent())
  1635. const { ref } = request.payload
  1636. try {
  1637. await credentials.unset(credentialRef(ref))
  1638. } catch (error: unknown) {
  1639. return err(request, {
  1640. code: 'credential-rejected',
  1641. message: error instanceof Error ? error.message : String(error),
  1642. details: { ref },
  1643. })
  1644. }
  1645. return ok(request, {})
  1646. },
  1647. },
  1648. llm: {
  1649. providers(request) {
  1650. const registered = ctx.llm.listProviders()
  1651. const active = new Set(registered.map(provider => provider.id))
  1652. const directory = ctx.llm.listConfigurableProviders()
  1653. const declared = new Set(directory.map(entry => entry.provider))
  1654. const views = directory.map(entry => ({
  1655. provider: entry.provider,
  1656. displayName: entry.displayName,
  1657. settingsNs: entry.settingsNs,
  1658. settingsPath: [...entry.settingsPath],
  1659. active: active.has(entry.provider),
  1660. }))
  1661. // Routes registered without a directory declaration still appear —
  1662. // they exist and serve models — just with no settings address.
  1663. for (const provider of registered) {
  1664. if (declared.has(provider.id)) continue
  1665. views.push({
  1666. provider: provider.id,
  1667. displayName: provider.name,
  1668. settingsNs: '',
  1669. settingsPath: [],
  1670. active: true,
  1671. })
  1672. }
  1673. return Promise.resolve(ok(request, { providers: views }))
  1674. },
  1675. async models(request) {
  1676. return ok(request, await buildModelCatalog(ctx))
  1677. },
  1678. },
  1679. events: {
  1680. mux(_request, signal) {
  1681. const queue = new FrameQueue<RpcRequest<MuxFrame>>()
  1682. muxQueues.add(queue)
  1683. for (const session of ctx.sessions.list()) {
  1684. subscribeSession(queue, session)
  1685. }
  1686. for (const pending of pendingQuestions.values()) {
  1687. queue.push({
  1688. rpcId: pending.rpcId,
  1689. payload: {
  1690. type: 'question/requested', sessionId: pending.sessionId,
  1691. questions: pending.questions,
  1692. },
  1693. })
  1694. }
  1695. // Refresh recovery: still-pending approval questions replay with their
  1696. // stable rpcId so a reconnecting client can still answer them.
  1697. for (const pending of pendingApprovals.values()) queue.push(requestedFrame(pending))
  1698. // Queue snapshot baseline (pendingQuestions precedent): frames replayed
  1699. // in arrival order per session; a reconnecting client rebuilds its
  1700. // queue view from these alone.
  1701. for (const [sessionId, items] of queuedMirror) {
  1702. queue.push(frame({
  1703. type: 'session/queue',
  1704. sessionId,
  1705. items: items.map(item => ({
  1706. id: item.id,
  1707. message: item.message,
  1708. })),
  1709. }))
  1710. }
  1711. // Per-session open-call table for result-view pairing. Bounded by the
  1712. // per-turn call count: entries clear on turn/end; a table miss (stream
  1713. // opened mid-turn) backscans the session's in-memory events instead.
  1714. const openCalls = new Map<SessionId, Map<string, { name: string; args: unknown }>>()
  1715. const disposers = [
  1716. ctx.on('session/event', (session: Session, event: SessionEvent) => {
  1717. if (event.type === 'tool/call') {
  1718. const data = event.data as ToolCallData
  1719. try {
  1720. let table = openCalls.get(session.id)
  1721. if (table === undefined) openCalls.set(session.id, table = new Map<string, { name: string; args: unknown }>())
  1722. table.set(data.callId, { name: data.name, args: JSON.parse(data.arguments) })
  1723. } catch {
  1724. // Unparseable model arguments: leave the table unset; the result view soft-falls.
  1725. }
  1726. } else if (event.type === 'turn/end') {
  1727. openCalls.delete(session.id)
  1728. }
  1729. const view = viewFor(ctx, event, callId =>
  1730. openCalls.get(session.id)?.get(callId) ?? backscanArgs(session.events, callId))
  1731. queue.push(frame({ type: 'session/event', sessionId: session.id, event, ...view === undefined ? {} : { view } }))
  1732. }),
  1733. ctx.on('session/created', (session: Session) => {
  1734. subscribeSession(queue, session)
  1735. }),
  1736. ctx.on('session/disposed', (session: Session) => {
  1737. openCalls.delete(session.id)
  1738. }),
  1739. ]
  1740. return queue.iterate(signal, () => {
  1741. muxQueues.delete(queue)
  1742. for (const dispose of disposers) dispose()
  1743. })
  1744. },
  1745. host(_request, signal) {
  1746. const queue = new FrameQueue<RpcRequest<HostFrame>>()
  1747. const committedWorkspaceIds = new Set(
  1748. ctx.workspace.list().map(workspace => String(workspace.id)),
  1749. )
  1750. const disposers = [
  1751. ctx.on('session/created', (session: Session) => {
  1752. queue.push(frame({
  1753. type: 'host/session-added',
  1754. sessionId: session.id,
  1755. // Derived at frame time like summarize(); a just-created session
  1756. // has run no turn yet, so this is constantly true in practice.
  1757. blank: sessionBlank(session),
  1758. ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession },
  1759. // cwd rides the frame so the client list needs no refresh to group the new session.
  1760. ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd },
  1761. }))
  1762. }),
  1763. ctx.on('session/disposed', (session: Session) => {
  1764. queue.push(frame({ type: 'host/session-removed', sessionId: session.id }))
  1765. }),
  1766. ctx.on('agent/status', (agent: Agent, status: AgentStatus) => {
  1767. queue.push(frame({ type: 'host/session-status', sessionId: agent.id, running: status === 'running' }))
  1768. }),
  1769. ctx.on('agent/error', (agent: Agent, _turn: number, _step: number, error: unknown) => {
  1770. queue.push(frame({ type: 'host/agent-error', sessionId: agent.id, message: errorChain(error) }))
  1771. }),
  1772. ctx.on('domain/changed', (change) => {
  1773. if (change.domain !== 'workspace') return
  1774. if (change.table === '') {
  1775. if (change.operation !== 'put') return
  1776. const state = workspaceDomainState.parse(change.value)
  1777. for (const workspaceId of state.workspaceIds) {
  1778. if (committedWorkspaceIds.has(workspaceId)) continue
  1779. const workspace = ctx.workspace.get(workspaceId)
  1780. if (workspace === undefined) {
  1781. throw new Error(`committed workspace registry references missing workspace "${workspaceId}"`)
  1782. }
  1783. committedWorkspaceIds.add(workspaceId)
  1784. queue.push(frame({ type: 'host/workspace-changed', workspace: workspaceView(workspace) }))
  1785. }
  1786. return
  1787. }
  1788. if (change.table !== 'workspaces') return
  1789. if (change.operation === 'deleted') {
  1790. if (!committedWorkspaceIds.delete(change.key)) return
  1791. queue.push(frame({
  1792. type: 'host/workspace-removed',
  1793. workspaceId: change.key as WorkspaceId,
  1794. }))
  1795. return
  1796. }
  1797. if (!committedWorkspaceIds.has(change.key)) return
  1798. // Existing-entity table writes are complete attach/touch commits.
  1799. // A new entity's first put waits for the global registry write above.
  1800. queue.push(frame({
  1801. type: 'host/workspace-changed',
  1802. workspace: changedWorkspaceView(change.key, change.value),
  1803. }))
  1804. }),
  1805. ctx.on('commands/change', () => {
  1806. queue.push(frame({ type: 'host/commands-changed' }))
  1807. }),
  1808. ctx.on('settings/document-updated', (ns) => {
  1809. // The RAW-section event, not the resolved one: a field going from
  1810. // inherited to overridden leaves the resolved value equal, and a
  1811. // configuration client still has to re-read (its held revision is
  1812. // stale, and the field's meaning changed).
  1813. queue.push(frame({ type: 'host/settings-changed', ns: String(ns) }))
  1814. // A provider's own settings carry its model catalog and endpoint,
  1815. // so a change there invalidates the model list even when the route
  1816. // set is untouched — `llm/adapters-updated` alone misses it.
  1817. if (exposedNamespaces().has(String(ns))) queue.push(frame({ type: 'host/models-changed' }))
  1818. }),
  1819. ctx.on('credentials/updated', (ref) => {
  1820. queue.push(frame({ type: 'host/credentials-changed', ref: String(ref) }))
  1821. }),
  1822. ctx.on('llm/adapters-updated', () => {
  1823. queue.push(frame({ type: 'host/models-changed' }))
  1824. }),
  1825. ]
  1826. return queue.iterate(signal, () => { for (const dispose of disposers) dispose() })
  1827. },
  1828. },
  1829. respond(message: ClientResponse): Promise<RpcReceipt> {
  1830. // Route by the echoed rpcId (the wire correlation): approvals first,
  1831. // then questions — the two registries share one id space of UUIDs.
  1832. const approval = pendingApprovals.get(message.rpcId)
  1833. if (approval !== undefined) {
  1834. if (!message.result.ok) return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1835. const parsed = approvalResponsePayloadSchema.safeParse(message.result.value)
  1836. // The payload's audit correlation must match the entry the rpcId routed
  1837. // to — a mismatched answer is malformed, not merely late.
  1838. if (!parsed.success || parsed.data.approvalId !== approval.approvalId || parsed.data.sessionId !== approval.sessionId) {
  1839. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1840. }
  1841. approval.resolve(parsed.data.outcome)
  1842. return Promise.resolve({ accepted: true })
  1843. }
  1844. const pending = pendingQuestions.get(message.rpcId)
  1845. if (pending === undefined) return Promise.resolve({ accepted: false, reason: 'not-pending' })
  1846. if (!message.result.ok) {
  1847. if (message.result.error.code !== 'cancelled') {
  1848. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1849. }
  1850. claimQuestion(pending, 'cancelled')
  1851. pending.reject(new UserInteractionError(
  1852. 'the user cancelled ask_user_question', 'ASK_CANCELLED'))
  1853. return Promise.resolve({ accepted: true })
  1854. }
  1855. const parsed = questionResponsePayloadSchema.safeParse(message.result.value)
  1856. if (!parsed.success) {
  1857. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1858. }
  1859. const payload: QuestionResponsePayload = {
  1860. sessionId: parsed.data.sessionId,
  1861. answer: {
  1862. answers: parsed.data.answer.answers.map(answer => ({
  1863. id: answer.id,
  1864. selected: answer.selected,
  1865. ...(answer.custom === undefined ? {} : { custom: answer.custom }),
  1866. })),
  1867. },
  1868. }
  1869. if (!matchesQuestions(payload, pending)) {
  1870. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1871. }
  1872. claimQuestion(pending, 'answered')
  1873. pending.resolve(payload.answer)
  1874. return Promise.resolve({ accepted: true })
  1875. },
  1876. }
  1877. }