api-proxy.ts 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  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 { isAppendSurfaceEvent, lastActivityTime } from '@deepseek-ai/dsh-session'
  17. import type { Session, SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session'
  18. import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
  19. import { SessionQueryError, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query'
  20. import { SubagentError } from '@deepseek-ai/dsh-subagent'
  21. import type { SubagentListEntry as CatalogSubagentListEntry } from '@deepseek-ai/dsh-subagent'
  22. import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace'
  23. import {
  24. workspaceDomainState, workspaceRecord, WorkspaceId as brandWorkspaceId,
  25. WorkspaceMoveInvalidError, WorkspaceUnknownSessionError,
  26. } from '@deepseek-ai/dsh-workspace'
  27. // Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters).
  28. import type {} from '@deepseek-ai/dsh-tools'
  29. import type {
  30. ApiProxy, CredentialView, GoalRef, HistoryEntry, HostFrame, ModelCatalogFailure, ModelProviderGroup,
  31. ModelReasoning, MuxFrame, QuestionResponsePayload, SessionProjectionsBlock, SessionSearchItem,
  32. SessionSummary, SettingsNamespaceView, SubagentAddress, ToolEventView,
  33. WorkspaceId, WorkspaceView,
  34. } from './api/index.ts'
  35. import {
  36. SESSION_SEARCH_RESULT_LIMIT,
  37. SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS,
  38. truncateUnicodeCodePoints,
  39. } from './api/session-search.ts'
  40. // Type-only: resolves `ctx.get('sessionProjections')` to the projection registry.
  41. import type {} from '@deepseek-ai/dsh-session-projection'
  42. // Type-only: resolves `ctx.get('sessionProjectionCache')` (the cold listing column).
  43. import type {} from '@deepseek-ai/dsh-session-projection-cache'
  44. // GoalError narrows domain rejections to their stable codes at the wire boundary.
  45. import { GoalError } from '@deepseek-ai/dsh-goal'
  46. import type { GoalRef as CoreGoalRef } from '@deepseek-ai/dsh-goal'
  47. // Type-only edges: resolve `ctx.get('commands')`, the `commands/change` event, and `ctx.get('skills')`.
  48. import type {} from '@deepseek-ai/dsh-commands'
  49. import type {} from '@deepseek-ai/dsh-skill'
  50. // The settings/credentials seams: brand guards run at this wire boundary; the
  51. // service reads stay optional (`ctx.get`) so a composition without either
  52. // provider still serves every other domain.
  53. import { SettingsConflictError, settingsNamespace } from '@deepseek-ai/dsh-settings'
  54. import type { SettingsDescriptor, SettingsNamespace, SettingsPathOp } from '@deepseek-ai/dsh-settings'
  55. import { credentialRef } from '@deepseek-ai/dsh-credentials'
  56. // Value edge: the rename impl narrows the title service's validation failure; the import also resolves `ctx.get('sessionTitle')`.
  57. import { SessionTitleInvalidError } from '@deepseek-ai/dsh-session-title'
  58. import type { CallId } from '@deepseek-ai/dsh-llm/brand'
  59. import type { ApprovalOutcome, ApprovalRequestId } from '@deepseek-ai/dsh-user-approval'
  60. // Side-effect type import: resolves the `approval/request` waterfall and
  61. // `ctx.get('approval')` without a value dependency on the seam (optional composition).
  62. import type {} from '@deepseek-ai/dsh-user-approval'
  63. import { approvalResponsePayloadSchema } from './api/approvals.schema.ts'
  64. import { questionResponsePayloadSchema } from './api/questions.schema.ts'
  65. import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts'
  66. import { RpcId } from './api/rpc.ts'
  67. import type {
  68. AskUserQuestionAnswer, AskUserQuestionItem, AskUserQuestionRequest,
  69. } from '@deepseek-ai/dsh-user-interaction'
  70. import { UserInteractionError } from '@deepseek-ai/dsh-user-interaction'
  71. import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
  72. import { openNativePath } from './native-path-opener.ts'
  73. /** Page size when history is called without maxMessages. */
  74. const DEFAULT_MAX_MESSAGES = 50
  75. /** Non-model settings namespaces intentionally served to the Web client. */
  76. const WEB_SETTINGS_NAMESPACES = ['permission'] as const
  77. /** Provider work budget: at most 100 calls and 2,000 inspected hits. */
  78. const SESSION_SEARCH_PROVIDER_CALL_LIMIT = 100
  79. /** Bound cold-log stat fan-out and settle each started batch before cancellation returns. */
  80. const COLD_SUMMARY_BATCH_SIZE = 16
  81. /** Conversation message event types (the pagination counting unit). */
  82. const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message'])
  83. /** Product settings intentionally exposed beside model-provider namespaces. */
  84. const PRODUCT_SETTINGS_NAMESPACES = new Set(['ui-onboarding'])
  85. /** Read live abort state across awaits without treating it as synchronously immutable. */
  86. function isAborted(signal: AbortSignal): boolean {
  87. return signal.aborted
  88. }
  89. /**
  90. * Message-boundary pagination: count maxMessages append-origin messages
  91. * backwards from the window tail. Replacement copies never entered the
  92. * conversation a reader sees — they restate a shadowed range for the model
  93. * alone — so they consume no quota; the page stays one contiguous raw range,
  94. * which keeps a compaction's log-only provenance on the same page as its
  95. * replacement. The cut is the starting seq of the oldest message group (chunks
  96. * group via sourceEventSeqs — never cut mid-message). The tail page naturally
  97. * includes the in-progress partial.
  98. */
  99. function paginate(
  100. events: readonly SessionEvent[],
  101. beforeSeq: number | undefined,
  102. maxMessages: number,
  103. ): { events: SessionEvent[]; hasMore: boolean } {
  104. const window = beforeSeq === undefined ? [...events] : events.filter(event => event.seq < beforeSeq)
  105. let count = 0
  106. let cut = 0
  107. for (let i = window.length - 1; i >= 0; i--) {
  108. const event = window[i] as SessionEvent
  109. if (!MESSAGE_TYPES.has(event.type) || !isAppendSurfaceEvent(event)) continue
  110. count++
  111. const sources = (event as { sourceEventSeqs?: number[] }).sourceEventSeqs
  112. const groupStart = sources !== undefined && sources.length > 0 ? Math.min(event.seq, ...sources) : event.seq
  113. if (count >= maxMessages) {
  114. cut = groupStart
  115. break
  116. }
  117. }
  118. const page = window.filter(event => event.seq >= cut)
  119. return { events: page, hasMore: cut > 0 }
  120. }
  121. /** Wrap an ok result echoing the request's rpcId. */
  122. function ok<T>(request: RpcRequest<unknown>, value: T): RpcResponse<T> {
  123. return { rpcId: request.rpcId, result: { ok: true, value } }
  124. }
  125. /**
  126. * Build the provider/model catalog over every registered route. Shared by the
  127. * session-scoped `session.models` (which passes the session's current target
  128. * so an unlisted current model still renders selectable) and the host-scoped
  129. * `llm.models` (no current). Per-provider failures ride `failures` without
  130. * failing the sound groups; groups that advertise nothing are dropped.
  131. */
  132. async function buildModelCatalog(
  133. ctx: Context,
  134. current?: { provider: string; model: string },
  135. ): Promise<{ groups: ModelProviderGroup[]; failures: ModelCatalogFailure[] }> {
  136. const catalog = await Promise.all(ctx.llm.listProviders().map(async (provider) => {
  137. try {
  138. const advertised = await ctx.llm.listModels(provider.id)
  139. const models = [...advertised]
  140. if (
  141. current !== undefined
  142. && provider.id === current.provider
  143. && !models.some(model => model.id === current.model)
  144. ) {
  145. models.push({
  146. provider: provider.id,
  147. id: current.model,
  148. name: current.model,
  149. })
  150. }
  151. const entries = await Promise.all(models.map(async (model) => {
  152. const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id)
  153. const reasoning: ModelReasoning | undefined = resolved.reasoning === undefined
  154. ? undefined
  155. : {
  156. efforts: resolved.reasoning.efforts.map(effort => ({
  157. id: effort.id,
  158. name: effort.name,
  159. ...effort.description === undefined
  160. ? {}
  161. : { description: effort.description },
  162. })),
  163. ...resolved.reasoning.defaultEffort === undefined
  164. ? {}
  165. : { defaultEffort: resolved.reasoning.defaultEffort },
  166. }
  167. return {
  168. id: model.id,
  169. name: model.name,
  170. ...model.description === undefined ? {} : { description: model.description },
  171. ...current !== undefined
  172. && provider.id === current.provider
  173. && model.id === current.model
  174. && !advertised.some(candidate => candidate.id === current.model)
  175. ? { unlisted: true as const }
  176. : {},
  177. ...reasoning === undefined ? {} : { reasoning },
  178. }
  179. }))
  180. const group: ModelProviderGroup = {
  181. id: provider.id,
  182. name: provider.name,
  183. models: entries,
  184. }
  185. return { kind: 'group' as const, group }
  186. } catch (error: unknown) {
  187. const failure: ModelCatalogFailure = {
  188. id: provider.id,
  189. name: provider.name,
  190. message: error instanceof Error ? error.message : String(error),
  191. }
  192. return { kind: 'failure' as const, failure }
  193. }
  194. }))
  195. return {
  196. groups: catalog.flatMap(item => item.kind === 'group' ? [item.group] : []).filter(group => group.models.length > 0),
  197. failures: catalog.flatMap(item => item.kind === 'failure' ? [item.failure] : []),
  198. }
  199. }
  200. /** Wrap an error result echoing the request's rpcId. */
  201. function err<T>(request: RpcRequest<unknown>, error: RpcError): RpcResponse<T> {
  202. return { rpcId: request.rpcId, result: { ok: false, error } }
  203. }
  204. /** Simple async queue: core callbacks push, the AsyncIterable pulls; abort/return cleans up. */
  205. class FrameQueue<F> {
  206. private buffer: F[] = []
  207. private waiter: (() => void) | undefined
  208. private done = false
  209. push(item: F): void {
  210. if (this.done) return
  211. this.buffer.push(item)
  212. this.waiter?.()
  213. }
  214. end(): void {
  215. this.done = true
  216. this.waiter?.()
  217. }
  218. async *iterate(signal: AbortSignal, cleanup: () => void): AsyncGenerator<F> {
  219. const onAbort = (): void => { this.end() }
  220. signal.addEventListener('abort', onAbort, { once: true })
  221. try {
  222. while (true) {
  223. while (this.buffer.length > 0) yield this.buffer.shift() as F
  224. if (this.done || signal.aborted) return
  225. await new Promise<void>((resolve) => { this.waiter = resolve })
  226. this.waiter = undefined
  227. }
  228. } finally {
  229. signal.removeEventListener('abort', onAbort)
  230. cleanup()
  231. }
  232. }
  233. }
  234. /**
  235. * Server-side frame mint: pure pushes get a fresh rpcId per frame (answerable
  236. * frames — approval/question requested — mint their stable id in their
  237. * pending registries instead).
  238. */
  239. function frame<F>(payload: F): RpcRequest<F> {
  240. return { rpcId: RpcId(randomUUID()), payload }
  241. }
  242. /** Queue the subscription baseline frame. */
  243. function subscribeSession(queue: FrameQueue<RpcRequest<MuxFrame>>, session: Session): void {
  244. queue.push(frame({ type: 'session/subscribed', sessionId: session.id, lastSeq: session.seq - 1 }))
  245. }
  246. /**
  247. * Whether the session's conversation has started: no turn has run yet (a
  248. * turn is one model-loop execution). Standalone plugin events — command
  249. * lifecycle records, plan/mode, titles, goals — never open a turn, so
  250. * running `/plan` or `/goal` on a fresh session keeps it blank
  251. * (list-hidden, reusable).
  252. */
  253. function sessionBlank(session: Session): boolean {
  254. return !session.events.some(event => event.type === 'turn/start')
  255. }
  256. /** Shared Session-header projection for list baselines and creation frames. */
  257. function sessionListFields(header: SessionHeader): {
  258. parentSessionId?: SessionId
  259. origin?: 'subagent'
  260. cwd?: string
  261. } {
  262. return {
  263. ...header.parentSession === undefined ? {} : { parentSessionId: header.parentSession },
  264. ...header.origin === undefined ? {} : { origin: header.origin },
  265. ...header.cwd === undefined ? {} : { cwd: header.cwd },
  266. }
  267. }
  268. /** SessionSummary projection for attached (in-memory) sessions. */
  269. function summarize(session: Session, running: boolean): SessionSummary {
  270. return {
  271. sessionId: session.id,
  272. // Excludes end-seed: a resumed-but-untouched session
  273. // must not sort as freshly worked in.
  274. updatedAt: lastActivityTime(session.events) ?? session.header.createdAt,
  275. running,
  276. blank: sessionBlank(session),
  277. ...sessionListFields(session.header),
  278. }
  279. }
  280. /**
  281. * SessionSummary projection for cold (persisted, unattached) sessions.
  282. * updatedAt is the log file's mtime; backends without a per-session file
  283. * (locate() undefined) fall back to the header's createdAt.
  284. */
  285. async function summarizeCold(
  286. persistence: SessionPersistence,
  287. meta: SessionHeader,
  288. signal?: AbortSignal,
  289. ): Promise<SessionSummary> {
  290. signal?.throwIfAborted()
  291. let updatedAt = meta.createdAt
  292. const location = persistence.locate(meta)
  293. signal?.throwIfAborted()
  294. if (location !== undefined) {
  295. try {
  296. updatedAt = (await stat(location.path)).mtimeMs
  297. } catch {
  298. // The log vanished between list() and stat() (concurrent cleanup); createdAt stands in.
  299. }
  300. signal?.throwIfAborted()
  301. }
  302. return {
  303. sessionId: meta.id,
  304. updatedAt,
  305. running: false,
  306. // Lazy persistence keeps never-appended sessions out of list(); reading
  307. // a cold log to check for turns would defeat the index read, so a listed
  308. // cold session is served as not-blank (its log holds its conversation).
  309. blank: false,
  310. ...meta.parentSession === undefined ? {} : { parentSessionId: meta.parentSession },
  311. ...meta.origin === undefined ? {} : { origin: meta.origin },
  312. /* v8 ignore next -- the empty arm needs a cwd-less meta, but list()
  313. filters those out (legacy logs are not served); the conditional mirrors
  314. summarize() shape. */
  315. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  316. }
  317. }
  318. /** Map a browse-primitive failure onto the wire error vocabulary (unknown throws stay internal). */
  319. function directoryError(error: unknown): RpcError {
  320. if (error instanceof DirectoryPickerError) {
  321. return { code: error.code, message: error.message, details: { path: error.path } }
  322. }
  323. return { code: 'internal', message: error instanceof Error ? error.message : String(error), details: {} }
  324. }
  325. /** Resolved Host routing and project-directory defaults consumed by the API implementation. */
  326. export interface ApiProxyDefaults {
  327. provider: string
  328. model: string
  329. /** Default project directory for new sessions whose create request carries no cwd. */
  330. cwd: string
  331. /** Parent directory for name-created workspaces. */
  332. workspaceRoot: string
  333. /** Native open-with-default-application; injectable for carrier tests. */
  334. openPath?: (path: string, signal: AbortSignal) => Promise<void>
  335. }
  336. /** The tool/call payload fields the presenter path reads. */
  337. interface ToolCallData { callId: string; name: string; arguments: string }
  338. /**
  339. * One outstanding approval question: the stable server-request id, the frame
  340. * material replayed to late mux subscribers, and the resolver that settles the
  341. * answerer's promise back into `ctx.approval`.
  342. */
  343. interface PendingApproval {
  344. rpcId: RpcId
  345. sessionId: SessionId
  346. approvalId: ApprovalRequestId
  347. toolName: string
  348. callId?: CallId
  349. reason?: string
  350. resolve(outcome: ApprovalOutcome): void
  351. }
  352. /** Project a pending entry into its answerable mux frame (initial push and mux-open replay share it). */
  353. function requestedFrame(pending: PendingApproval): RpcRequest<MuxFrame> {
  354. return {
  355. rpcId: pending.rpcId,
  356. payload: {
  357. type: 'approval/requested',
  358. sessionId: pending.sessionId,
  359. approvalId: pending.approvalId,
  360. toolName: pending.toolName,
  361. ...pending.callId === undefined ? {} : { callId: pending.callId },
  362. ...pending.reason === undefined ? {} : { reason: pending.reason },
  363. },
  364. }
  365. }
  366. /** One host-owned question wait, addressed by the stable server-request id. */
  367. interface PendingQuestion {
  368. rpcId: RpcId
  369. sessionId: SessionId
  370. questions: AskUserQuestionItem[]
  371. resolve: (answer: AskUserQuestionAnswer) => void
  372. reject: (error: UserInteractionError) => void
  373. signal?: AbortSignal
  374. onAbort?: () => void
  375. }
  376. /** Validate one answer batch against the exact question request it resolves. */
  377. function matchesQuestions(payload: QuestionResponsePayload, pending: PendingQuestion): boolean {
  378. if (payload.sessionId !== pending.sessionId) return false
  379. const answers = payload.answer.answers
  380. if (answers.length !== pending.questions.length) return false
  381. return answers.every((answer, index) => {
  382. const question = pending.questions[index] as AskUserQuestionItem
  383. if (answer.id !== question.id) return false
  384. if (new Set(answer.selected).size !== answer.selected.length) return false
  385. const custom = answer.custom?.trim()
  386. if (custom !== undefined && custom === '') return false
  387. if (custom !== undefined && answer.selected.length > 0) return false
  388. if (question.multiSelect !== true && answer.selected.length > 1) return false
  389. const labels = new Set(question.options?.map(option => option.label) ?? [])
  390. return answer.selected.every(label => labels.has(label))
  391. })
  392. }
  393. /**
  394. * Compute the render intent for a tool/call or tool/result event through the
  395. * presenters registered at this moment; every other event type gets none. A
  396. * result's presenter needs its call's parsed args — `argsFor` supplies them
  397. * (live: the per-session call table; history: an in-page backscan), returning
  398. * undefined when the pairing is unavailable (e.g. the call fell off the page),
  399. * which soft-falls to no view. Presenter or JSON.parse throws also soft-fall:
  400. * the client's documented default (generic JSON card) covers every miss.
  401. */
  402. function viewFor(ctx: Context, event: SessionEvent, argsFor: (callId: string) => unknown): ToolEventView | undefined {
  403. try {
  404. if (event.type === 'tool/call') {
  405. const { name, arguments: raw } = event.data as ToolCallData
  406. const view = ctx.tools.get(name)?.presentCall?.(JSON.parse(raw))
  407. return view === undefined ? undefined : { for: 'call', view }
  408. }
  409. if (event.type === 'tool/result') {
  410. const { message, meta } = event.data
  411. const [result] = message.content
  412. const callId = message.source.callId
  413. const call = argsFor(callId) as { name: string; args: unknown } | undefined
  414. if (call === undefined) return undefined
  415. const view = ctx.tools.get(call.name)?.presentResult?.(call.args, {
  416. content: result.content,
  417. isError: result.isError === true,
  418. ...meta === undefined ? {} : { meta },
  419. })
  420. return view === undefined ? undefined : { for: 'result', view }
  421. }
  422. } catch (error: unknown) {
  423. // A throwing presenter (or unparseable arguments) must not break delivery;
  424. // the event still ships, just without a view.
  425. console.error(`api-proxy: presenter failed for ${event.type}, falling back to generic: ${String(error)}`)
  426. }
  427. return undefined
  428. }
  429. /**
  430. * Resolve a tool/result's call pairing by scanning a window of events backwards
  431. * for the matching tool/call. Used by the history path (the page is the
  432. * window — a cross-page pairing soft-falls to no view) and by live-path table
  433. * misses after a reconnect-eviction.
  434. */
  435. function backscanArgs(events: readonly SessionEvent[], callId: string): { name: string; args: unknown } | undefined {
  436. for (let i = events.length - 1; i >= 0; i--) {
  437. const event = events[i] as SessionEvent
  438. if (event.type !== 'tool/call') continue
  439. const data = event.data as ToolCallData
  440. if (data.callId !== callId) continue
  441. try {
  442. return { name: data.name, args: JSON.parse(data.arguments) }
  443. } catch {
  444. // Unparseable stored arguments: same soft-fall as a live parse failure.
  445. return undefined
  446. }
  447. }
  448. return undefined
  449. }
  450. /** Render one detached history page through the same presenter path as ordinary history. */
  451. function historyPage(
  452. ctx: Context,
  453. events: readonly SessionEvent[],
  454. beforeSeq: number | undefined,
  455. maxMessages: number | undefined,
  456. ): { events: HistoryEntry[]; hasMore: boolean } {
  457. const page = paginate(events, beforeSeq, maxMessages ?? DEFAULT_MAX_MESSAGES)
  458. return {
  459. events: page.events.map((event) => {
  460. const view = viewFor(ctx, event, callId => backscanArgs(page.events, callId))
  461. return { event, ...view === undefined ? {} : { view } }
  462. }),
  463. hasMore: page.hasMore,
  464. }
  465. }
  466. /**
  467. * The projection baseline for one history tail page: the registry's
  468. * watermark-cache snapshot — one fully synchronous read (no await between the
  469. * page slice and this), so all values and `asOfSeq` form a single consistent
  470. * cut and `asOfSeq` equals the window tail event seq. The carrier holds zero
  471. * domain knowledge (each value passed its unit's own schema inside the
  472. * registry). An absent registry means the deployment has no projection seam:
  473. * the whole block is absent and clients treat every key as capability-absent.
  474. */
  475. function projectionsFor(ctx: Context, session: Session): SessionProjectionsBlock | undefined {
  476. const registry = ctx.get('sessionProjections')
  477. if (registry === undefined) return undefined
  478. return registry.snapshot(session)
  479. }
  480. /**
  481. * The projection baseline of one session.list row, fail-soft: attached
  482. * sessions cut the registry's live watermark cache; cold sessions view the
  483. * persisted projection cache's identity-checked stored rows (zero log loads
  484. * either way — the listing use case the cache exists for). The block shape
  485. * (values + asOfSeq) matches the history tail's, so a client seeds its
  486. * value store under the same higher-seq-wins rule. Any failure — and an
  487. * empty value set — yields an absent block: a listing without projections
  488. * is degraded, never broken.
  489. */
  490. function listProjectionsFor(ctx: Context, meta: SessionHeader, session: Session | undefined): SessionProjectionsBlock | undefined {
  491. try {
  492. const block = session !== undefined
  493. ? ctx.get('sessionProjections')?.snapshot(session)
  494. : ctx.get('sessionProjectionCache')?.cachedSnapshot(meta)
  495. return block !== undefined && Object.keys(block.values).length > 0 ? block : undefined
  496. } catch (error) {
  497. ctx.logger.warn(`session.list: projection column for "${meta.id}" failed (serving the row without it): ${String(error)}`)
  498. return undefined
  499. }
  500. }
  501. /** Projection baseline for a detached history tail without Agent activation. */
  502. function detachedProjectionsFor(
  503. ctx: Context,
  504. events: readonly SessionEvent[],
  505. ): SessionProjectionsBlock | undefined {
  506. const registry = ctx.get('sessionProjections')
  507. if (registry === undefined) return undefined
  508. return registry.restore({}, events, 0).snapshot
  509. }
  510. /** Map continuation admission failures without exposing provider details. */
  511. function subagentPromptError(
  512. request: RpcRequest<{ childSessionId: SessionId }>,
  513. error: unknown,
  514. signal: AbortSignal,
  515. ): RpcResponse<never> {
  516. const childSessionId = request.payload.childSessionId
  517. if (signal.aborted) {
  518. return err(request, { code: 'cancelled', message: 'subagent prompt was cancelled', details: {} })
  519. }
  520. if (error instanceof SubagentError) {
  521. switch (error.code) {
  522. case 'NOT_RESUMABLE':
  523. return err(request, {
  524. code: 'subagent-not-resumable',
  525. message: 'subagent cannot be resumed',
  526. details: { childSessionId },
  527. })
  528. case 'UNAUTHORIZED':
  529. return err(request, {
  530. code: 'subagent-unauthorized',
  531. message: 'subagent does not belong to this parent',
  532. details: { childSessionId },
  533. })
  534. case 'DRAINING':
  535. case 'ACTIVATION_CLOSING':
  536. case 'CONTINUATION_UNAVAILABLE':
  537. case 'PERSISTENCE_UNAVAILABLE':
  538. return err(request, {
  539. code: 'subagent-delivery-unavailable',
  540. message: 'subagent follow-up is temporarily unavailable',
  541. details: { childSessionId },
  542. })
  543. default:
  544. break
  545. }
  546. }
  547. return err(request, { code: 'internal', message: 'subagent prompt failed', details: {} })
  548. }
  549. /** Verify one address and mode against the complete direct-child catalog. */
  550. async function catalogChild(
  551. ctx: Context,
  552. address: SubagentAddress,
  553. signal?: AbortSignal,
  554. ): Promise<{
  555. entry?: Extract<CatalogSubagentListEntry, { kind: 'child' }>
  556. error?: RpcError
  557. }> {
  558. const { parentSessionId, childSessionId, mode } = address
  559. try {
  560. const entries = await ctx.subagents.listChildren(parentSessionId, signal)
  561. const entry = entries.find(candidate => candidate.id === childSessionId)
  562. if (entry === undefined || (entry.kind === 'child' && entry.mode !== mode)) {
  563. return {
  564. error: {
  565. code: 'subagent-not-found',
  566. message: `session "${childSessionId}" is not a ${mode} direct child of "${parentSessionId}"`,
  567. details: { parentSessionId, childSessionId },
  568. },
  569. }
  570. }
  571. if (entry.kind === 'diagnostic') {
  572. return {
  573. error: {
  574. code: 'subagent-catalog-diagnostic',
  575. message: `subagent "${childSessionId}" is ${entry.reason}`,
  576. details: { parentSessionId, childSessionId, reason: entry.reason },
  577. },
  578. }
  579. }
  580. return { entry }
  581. } catch (error: unknown) {
  582. if (signal?.aborted
  583. || (error instanceof SubagentError && error.code === 'CANCELLED')
  584. || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) {
  585. return { error: { code: 'cancelled', message: 'subagent catalog read was cancelled', details: {} } }
  586. }
  587. if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
  588. return {
  589. error: {
  590. code: 'subagent-not-found',
  591. message: `parent session "${parentSessionId}" was not found`,
  592. details: { parentSessionId, childSessionId },
  593. },
  594. }
  595. }
  596. return { error: { code: 'internal', message: 'subagent catalog read failed', details: {} } }
  597. }
  598. }
  599. /**
  600. * Thrown by the cold-resume path when the id names no servable session
  601. * (absent from the store, or a pre-project legacy log without a cwd).
  602. */
  603. class SessionNotFound extends Error {}
  604. /** Session identity whose lifecycle belongs to subagent routing, not generic Host resume. */
  605. class SubagentSessionOwnership extends Error {
  606. constructor(readonly sessionId: SessionId) {
  607. super(`session "${sessionId}" is a subagent session; use subagent delivery`)
  608. }
  609. }
  610. /** Requested identity already belongs to a session with another project cwd. */
  611. class SessionCwdConflict extends Error {
  612. constructor(
  613. readonly sessionId: SessionId,
  614. readonly requestedCwd: string,
  615. readonly existingCwd: string | undefined,
  616. ) {
  617. super(
  618. `session "${sessionId}" already exists with cwd ${JSON.stringify(existingCwd)}; `
  619. + `requested ${JSON.stringify(requestedCwd)}`,
  620. )
  621. }
  622. }
  623. /** Host failed before the registry could adopt a name-created directory. */
  624. class WorkspaceDirectoryCreationError extends Error {}
  625. /** An explicit Host naming operation would duplicate another Workspace title. */
  626. class WorkspaceNameConflictError extends Error {
  627. constructor(readonly workspaceName: string) {
  628. super(`workspace name '${workspaceName}' is already in use`)
  629. this.name = 'WorkspaceNameConflictError'
  630. }
  631. }
  632. /** Shared workspace-not-found error response of the workspace.* mutation rows. */
  633. function workspaceNotFound<T>(request: RpcRequest<unknown>, workspaceId: string): RpcResponse<T> {
  634. return err(request, {
  635. code: 'workspace-not-found',
  636. message: `workspace "${workspaceId}" not found`,
  637. details: { workspaceId },
  638. })
  639. }
  640. /** Wire projection of one workspace entity (the workspace.* value row). */
  641. function workspaceView(workspace: Workspace): WorkspaceView {
  642. return {
  643. workspaceId: workspace.id,
  644. path: workspace.path,
  645. title: workspace.title,
  646. sessionIds: [...workspace.sessionIds],
  647. createdAt: workspace.createdAt,
  648. updatedAt: workspace.updatedAt,
  649. }
  650. }
  651. /** Wire projection of the durable record carried by `domain/changed`. */
  652. function changedWorkspaceView(workspaceId: string, value: unknown): WorkspaceView {
  653. const record: WorkspaceRecord = workspaceRecord.parse(value)
  654. return {
  655. workspaceId: workspaceId as WorkspaceId,
  656. path: record.path,
  657. title: record.title,
  658. sessionIds: [...record.sessionIds],
  659. createdAt: record.createdAt,
  660. updatedAt: record.updatedAt,
  661. }
  662. }
  663. /**
  664. * Implement ApiProxy over a composed host context.
  665. * @param ctx - a context with the Host spine and Workspace registry mounted.
  666. * @param defaults - host routing and project-directory defaults.
  667. * @returns the ApiProxy implementation.
  668. */
  669. export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiProxy {
  670. const agentOptions = { provider: defaults.provider, model: defaults.model }
  671. type WebLlmTargetRef = AgentLlmTargetRef & { current: AgentLlmTarget }
  672. const targets = new WeakMap<Agent, WebLlmTargetRef>()
  673. /** Implicit resume of cold sessions, deduplicating concurrent calls (follows the jsonrpc sessionCreations precedent). */
  674. const resumes = new Map<SessionId, Promise<Agent>>()
  675. /** Client-chosen identity creation/resume, deduplicated across concurrent retries. */
  676. const sessionCreations = new Map<SessionId, Promise<Agent>>()
  677. /** Serializes path ownership and explicit title checks with Workspace mutations. */
  678. let workspaceCreationChain = Promise.resolve()
  679. const pendingQuestions = new Map<RpcId, PendingQuestion>()
  680. const pendingApprovals = new Map<RpcId, PendingApproval>()
  681. const muxQueues = new Set<FrameQueue<RpcRequest<MuxFrame>>>()
  682. /**
  683. * Install or return the session-local target that prompt assembly snapshots.
  684. * Seed order: latest logged request/header, else the host default routing.
  685. * There is no create-time per-session override tier on this wire — if one
  686. * returns (a create-options contribution), it must fold in between the two.
  687. */
  688. function targetFor(agent: Agent): WebLlmTargetRef {
  689. const installed = targets.get(agent)
  690. if (installed !== undefined) return installed
  691. const logged = agent.session.requestHeader()?.config
  692. const target: WebLlmTargetRef = {
  693. current: logged === undefined
  694. ? { provider: defaults.provider, model: defaults.model }
  695. : {
  696. provider: logged.provider,
  697. model: logged.model,
  698. ...logged.reasoningEffort === undefined
  699. ? {}
  700. : { reasoningEffort: logged.reasoningEffort },
  701. },
  702. assembled: undefined,
  703. }
  704. installAgentLlmTarget(agent.ctx, target)
  705. targets.set(agent, target)
  706. return target
  707. }
  708. /** Pre-publication setup used by both fresh and resumed Web agents. */
  709. function installTarget(agentCtx: Context): void {
  710. const agent = agentCtx.agent
  711. if (agent === undefined) throw new Error('api-proxy: agent setup has no scoped agent')
  712. targetFor(agent)
  713. }
  714. /** Send one transient frame to every connected mux consumer. */
  715. function broadcast(payload: MuxFrame): void {
  716. const envelope = frame(payload)
  717. for (const queue of muxQueues) queue.push(envelope)
  718. }
  719. // Projection change feed → session/projection push frames. The carrier
  720. // mints the wire frame (the seam package holds no wire vocabulary); the
  721. // child activates only when a projection registry is composed, and the
  722. // subscription unwinds with this gateway's fiber.
  723. ctx.inject(['sessionProjections'], (projectionCtx) => {
  724. projectionCtx.sessionProjections.onChanged((session, key, value, seq) => {
  725. broadcast({ type: 'session/projection', sessionId: session.id, key, value, seq })
  726. })
  727. })
  728. /**
  729. * Per-session queued-occurrence mirror serving the mux-open queue snapshot
  730. * (the same refresh-recovery baseline as pending questions). Each terminal
  731. * queue event retires one matching occurrence, so repeated sends of the same
  732. * identified message remain visible until every occurrence is claimed.
  733. */
  734. const queuedMirror = new Map<SessionId, InboxItem[]>()
  735. type UnseenQueueEvent =
  736. | { readonly kind: 'update'; readonly item: InboxItem }
  737. | { readonly kind: 'terminal' }
  738. const unseenQueueEvents = new Map<SessionId, Map<InboxItemId, UnseenQueueEvent>>()
  739. const rememberUnseen = (sessionId: SessionId, itemId: InboxItemId, event: UnseenQueueEvent): void => {
  740. let events = unseenQueueEvents.get(sessionId)
  741. if (events === undefined) {
  742. events = new Map()
  743. unseenQueueEvents.set(sessionId, events)
  744. }
  745. events.set(itemId, event)
  746. // Only synchronous re-entrancy may deliver a mutation before its outer
  747. // enqueue observer. Drop unmatched protocol-invalid observations instead
  748. // of retaining process-local ids indefinitely.
  749. queueMicrotask(() => {
  750. const current = unseenQueueEvents.get(sessionId)
  751. if (current?.get(itemId) !== event) return
  752. current.delete(itemId)
  753. if (current.size === 0) unseenQueueEvents.delete(sessionId)
  754. })
  755. }
  756. const takeUnseen = (sessionId: SessionId, itemId: InboxItemId): UnseenQueueEvent | undefined => {
  757. const events = unseenQueueEvents.get(sessionId)
  758. const event = events?.get(itemId)
  759. if (event === undefined) return undefined
  760. events?.delete(itemId)
  761. if (events?.size === 0) unseenQueueEvents.delete(sessionId)
  762. return event
  763. }
  764. const publishQueue = (sessionId: SessionId): void => {
  765. const items = queuedMirror.get(sessionId) ?? []
  766. broadcast({
  767. type: 'session/queue',
  768. sessionId,
  769. items: items.map(item => ({
  770. id: item.id,
  771. message: item.message,
  772. })),
  773. })
  774. }
  775. ctx.effect(() => {
  776. const retire = (agent: Agent, item: InboxItem): boolean => {
  777. const entries = queuedMirror.get(agent.id)
  778. if (entries === undefined) {
  779. rememberUnseen(agent.id, item.id, { kind: 'terminal' })
  780. return false
  781. }
  782. const index = entries.findIndex(entry => entry.id === item.id)
  783. if (index === -1) {
  784. rememberUnseen(agent.id, item.id, { kind: 'terminal' })
  785. return false
  786. }
  787. entries.splice(index, 1)
  788. if (entries.length === 0) queuedMirror.delete(agent.id)
  789. return true
  790. }
  791. const disposers = [
  792. ctx.on('agent/inbox/enqueue', (agent: Agent, item: InboxItem) => {
  793. if (item.placement !== 'queued') return
  794. const unseen = takeUnseen(agent.id, item.id)
  795. if (unseen?.kind === 'terminal') return
  796. let entries = queuedMirror.get(agent.id)
  797. if (entries === undefined) {
  798. entries = []
  799. queuedMirror.set(agent.id, entries)
  800. }
  801. entries.push(unseen?.kind === 'update' ? unseen.item : item)
  802. publishQueue(agent.id)
  803. }),
  804. ctx.on('agent/inbox/update', (agent: Agent, item: InboxItem) => {
  805. const entries = queuedMirror.get(agent.id)
  806. if (entries === undefined) {
  807. rememberUnseen(agent.id, item.id, { kind: 'update', item })
  808. return
  809. }
  810. const index = entries.findIndex(entry => entry.id === item.id)
  811. if (index === -1) {
  812. rememberUnseen(agent.id, item.id, { kind: 'update', item })
  813. return
  814. }
  815. entries.splice(index, 1, item)
  816. publishQueue(agent.id)
  817. }),
  818. ctx.on('agent/inbox/dequeue', (agent: Agent, item: InboxItem) => {
  819. if (retire(agent, item)) publishQueue(agent.id)
  820. }),
  821. ctx.on('agent/inbox/discard', (agent: Agent, items: InboxItem[]) => {
  822. let changed = false
  823. for (const item of items) changed = retire(agent, item) || changed
  824. if (changed) publishQueue(agent.id)
  825. }),
  826. ctx.on('session/disposed', (session: Session) => {
  827. queuedMirror.delete(session.id)
  828. unseenQueueEvents.delete(session.id)
  829. }),
  830. ]
  831. return () => { for (const dispose of disposers) dispose() }
  832. }, 'api-proxy: queued mirror')
  833. /** Remove a wait before settling it: synchronous deletion makes the first claimant win. */
  834. function claimQuestion(pending: PendingQuestion, outcome: 'answered' | 'cancelled'): void {
  835. pendingQuestions.delete(pending.rpcId)
  836. if (pending.signal !== undefined && pending.onAbort !== undefined) {
  837. pending.signal.removeEventListener('abort', pending.onAbort)
  838. }
  839. broadcast({
  840. type: 'question/resolved', sessionId: pending.sessionId,
  841. questionRpcId: pending.rpcId, outcome,
  842. })
  843. }
  844. const disposeProvider = ctx.userInteraction.registerProvider({
  845. ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> {
  846. const sessionId = request.agent?.id
  847. if (sessionId === undefined) {
  848. return Promise.reject(new UserInteractionError(
  849. 'web user interaction requires an agent-owned session', 'ASK_MISSING_AGENT'))
  850. }
  851. return new Promise<AskUserQuestionAnswer>((resolve, reject) => {
  852. const rpcId = RpcId(randomUUID())
  853. const pending: PendingQuestion = {
  854. rpcId, sessionId, questions: request.questions, resolve, reject,
  855. ...(request.signal === undefined ? {} : { signal: request.signal }),
  856. }
  857. const onAbort = (): void => {
  858. claimQuestion(pending, 'cancelled')
  859. reject(new UserInteractionError(
  860. 'ask_user_question was aborted before the user answered', 'ASK_ABORTED'))
  861. }
  862. pending.onAbort = onAbort
  863. pendingQuestions.set(rpcId, pending)
  864. request.signal?.addEventListener('abort', onAbort, { once: true })
  865. const envelope: RpcRequest<MuxFrame> = {
  866. rpcId,
  867. payload: { type: 'question/requested', sessionId, questions: request.questions },
  868. }
  869. for (const queue of muxQueues) queue.push(envelope)
  870. })
  871. },
  872. })
  873. ctx.effect(() => () => {
  874. disposeProvider()
  875. for (const pending of [...pendingQuestions.values()]) {
  876. claimQuestion(pending, 'cancelled')
  877. pending.reject(new UserInteractionError(
  878. 'web user-interaction provider was disposed', 'ASK_ABORTED'))
  879. }
  880. }, 'api-proxy: user-interaction provider')
  881. // --- Approval pending registry ------------------------------------------
  882. // The proxy is the approval channel for every agent this host owns: an ask
  883. // through `ctx.approval` becomes an answerable server-request on the mux
  884. // stream (stable rpcId), settled by POST /api/respond. The entry survives
  885. // client disconnects — mux-open replays still-pending requested frames with
  886. // the same rpcId (the refresh-recovery baseline) — and withdraws on the
  887. // ask's own abort signal (turn cancel), pushing `cancelled` to subscribers.
  888. if (ctx.get('approval') !== undefined) {
  889. // Teardown parity with the question provider above: a gateway disposed
  890. // while approvals are pending settles every entry as 'cancelled' (the
  891. // service's fail-closed vocabulary), so no ask promise dangles past the
  892. // proxy's lifetime and subscribers see the withdrawal.
  893. ctx.effect(() => () => {
  894. for (const pending of [...pendingApprovals.values()]) pending.resolve('cancelled')
  895. }, 'api-proxy: approval registry teardown')
  896. ctx.on('approval/request', (req, next) => {
  897. // Dispatch rides a microtask behind the service's own signal check: an
  898. // abort landing in that window would register the abort listener AFTER
  899. // the signal fired — never invoked, entry pending forever, zombie frame
  900. // on every mux replay. Settle synchronously instead of publishing.
  901. if (req.signal?.aborted === true) return Promise.resolve<ApprovalOutcome>('cancelled')
  902. // The audit pair `approval/asked` is already appended by the service
  903. // before dispatch, but dispatch rides a microtask: parallel tool calls
  904. // can append several asked events before any answerer runs. THIS
  905. // request's event is therefore the newest asked event that is still
  906. // undecided, unclaimed by another pending entry, and — when the ask
  907. // names a call — carries the same callId.
  908. const events = req.agent.session.events
  909. const claimed = new Set<ApprovalRequestId>()
  910. for (const entry of pendingApprovals.values()) claimed.add(entry.approvalId)
  911. const decided = new Set<ApprovalRequestId>()
  912. let approvalId: ApprovalRequestId | undefined
  913. for (let i = events.length - 1; i >= 0; i -= 1) {
  914. const event = events[i] as SessionEvent
  915. if (event.type === 'approval/decided') {
  916. decided.add(event.data.id)
  917. } else if (event.type === 'approval/asked') {
  918. if (decided.has(event.data.id) || claimed.has(event.data.id)) continue
  919. // Symmetric pairing: a callId-bearing ask only takes its own call's
  920. // record, and a callId-less ask only takes a callId-less record —
  921. // so neither shape can steal the other's audit id under parallel
  922. // asks. (Today every producer — the tool executor — passes callId;
  923. // the callId-less arm guards any future non-tool asker.)
  924. if ((req.callId ?? null) !== (event.data.callId ?? null)) continue
  925. approvalId = event.data.id
  926. break
  927. }
  928. }
  929. // No asked event means the request bypassed the service's audit path —
  930. // not this channel's question; delegate to the fail-closed default.
  931. if (approvalId === undefined) return next()
  932. const id = approvalId
  933. return new Promise<ApprovalOutcome>((resolve) => {
  934. const settle = (outcome: ApprovalOutcome): void => {
  935. /* v8 ignore next 3 -- defensive double-settle guard: respond() routes
  936. through the pending table (a settled id is not-pending before it can
  937. re-settle) and the first settle removes the abort listener, so no
  938. reachable path settles twice; kept against future settle callers. */
  939. if (!pendingApprovals.delete(pending.rpcId)) return
  940. req.signal?.removeEventListener('abort', onAbort)
  941. broadcast({ type: 'approval/resolved', sessionId: pending.sessionId, approvalId: id, outcome })
  942. // A cancelled ask was already settled by the service's own signal
  943. // race, which discards this late resolution; resolving is a no-op
  944. // there and keeps this promise from dangling forever.
  945. resolve(outcome)
  946. }
  947. const onAbort = (): void => { settle('cancelled') }
  948. const pending: PendingApproval = {
  949. rpcId: RpcId(randomUUID()),
  950. sessionId: req.agent.session.id,
  951. approvalId: id,
  952. toolName: req.toolName,
  953. ...req.callId === undefined ? {} : { callId: req.callId },
  954. ...req.reason === undefined ? {} : { reason: req.reason },
  955. resolve: settle,
  956. }
  957. pendingApprovals.set(pending.rpcId, pending)
  958. req.signal?.addEventListener('abort', onAbort, { once: true })
  959. const envelope = requestedFrame(pending)
  960. for (const queue of muxQueues) queue.push(envelope)
  961. })
  962. })
  963. }
  964. /** Whether the session's own suffix carries the durable subagent discriminator. */
  965. function hasSubagentDescriptor(session: Pick<Session, 'events' | 'header'>): boolean {
  966. const ownStart = session.header.seedLength ?? 0
  967. return session.events.slice(ownStart).some(event => event.type === 'subagent/descriptor')
  968. }
  969. /**
  970. * Generic Host interaction cannot claim a durably classified subagent or an
  971. * Agent created through its live parent. The runtime-owner arm also covers
  972. * descriptor-less child publication windows and older stored headers.
  973. */
  974. function hasSubagentOwner(
  975. session: Pick<Session, 'events' | 'header'>,
  976. agent: Agent | undefined,
  977. ): boolean {
  978. if (session.header.origin === 'subagent' || hasSubagentDescriptor(session)) return true
  979. const parentId = session.header.parentSession
  980. if (parentId === undefined || agent === undefined) return false
  981. const parent = ctx.agents.get(parentId)
  982. return parent !== undefined && ctx.agents.isOwnedBy(agent.id, parent)
  983. }
  984. /** Stable generic-Host error for an identity reserved to subagent routing. */
  985. function subagentOwnershipError(sessionId: SessionId): RpcError {
  986. return {
  987. code: 'agent-busy',
  988. message: `session "${sessionId}" is owned by subagent routing`,
  989. details: { reason: 'use subagent delivery for this child session' },
  990. }
  991. }
  992. /** Inspect one cold served session without repairing, resuming, or publishing it. */
  993. async function inspectServable(sessionId: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  994. const persistence = ctx.get('sessionPersistence')
  995. if (persistence === undefined) {
  996. throw new Error('session persistence is not configured (load a dsh-session-persistence backend)')
  997. }
  998. const meta = (await persistence.list()).find(m => m.id === sessionId)
  999. if (meta === undefined || meta.cwd === undefined) throw new SessionNotFound(`session "${sessionId}" not found`)
  1000. const inspected = await persistence.inspect(sessionId)
  1001. if (inspected.meta.cwd === undefined) throw new SessionNotFound(`session "${sessionId}" not found`)
  1002. return inspected
  1003. }
  1004. async function agentFor(sessionId: SessionId): Promise<{ agent: Agent } | { error: RpcError }> {
  1005. const attached = ctx.sessions.get(sessionId)
  1006. const live = ctx.agents.get(sessionId)
  1007. if (attached !== undefined && hasSubagentOwner(attached, live)) {
  1008. return { error: subagentOwnershipError(sessionId) }
  1009. }
  1010. if (live !== undefined) return { agent: live }
  1011. let resume = resumes.get(sessionId)
  1012. if (resume === undefined) {
  1013. resume = (async () => {
  1014. try {
  1015. const inspected = await inspectServable(sessionId)
  1016. if (hasSubagentOwner({ header: inspected.meta, events: inspected.events }, undefined)) {
  1017. throw new SubagentSessionOwnership(sessionId)
  1018. }
  1019. const publishedSession = ctx.sessions.get(sessionId)
  1020. const publishedAgent = ctx.agents.get(sessionId)
  1021. if (publishedSession !== undefined && hasSubagentOwner(publishedSession, publishedAgent)) {
  1022. throw new SubagentSessionOwnership(sessionId)
  1023. }
  1024. const handle = await ctx.agents.resume({
  1025. resumeSessionId: sessionId,
  1026. agentOptions,
  1027. setup: installTarget,
  1028. })
  1029. return handle.agent
  1030. } finally {
  1031. resumes.delete(sessionId)
  1032. }
  1033. })()
  1034. resumes.set(sessionId, resume)
  1035. }
  1036. try {
  1037. return { agent: await resume }
  1038. } catch (error: unknown) {
  1039. if (error instanceof SessionNotFound) {
  1040. return { error: { code: 'session-not-found', message: error.message, details: { sessionId } } }
  1041. }
  1042. if (error instanceof SubagentSessionOwnership) {
  1043. return { error: subagentOwnershipError(error.sessionId) }
  1044. }
  1045. // The internal details slot is contractually {}; the reason rides the message.
  1046. return { error: { code: 'internal', message: `resume failed for session "${sessionId}": ${String(error)}`, details: {} } }
  1047. }
  1048. }
  1049. type SessionReadState = {
  1050. id: SessionId
  1051. header: SessionHeader
  1052. events: SessionEvent[]
  1053. }
  1054. /** Read one stable session prefix without acquiring an Agent owner. */
  1055. async function readSessionState(sessionId: SessionId): Promise<SessionReadState> {
  1056. const attached = ctx.sessions.get(sessionId)
  1057. if (attached !== undefined) {
  1058. return {
  1059. id: attached.id,
  1060. header: attached.header,
  1061. events: [...attached.events],
  1062. }
  1063. }
  1064. const inspected = await inspectServable(sessionId)
  1065. return { id: inspected.meta.id, header: inspected.meta, events: inspected.events }
  1066. }
  1067. /** Resolve the Workspace inherited by a fork without making ordinary loose lineage grouped. */
  1068. async function forkWorkspace(source: Pick<Session, 'id' | 'header'>): Promise<Workspace | undefined> {
  1069. const workspaces = ctx.workspace.list()
  1070. const direct = workspaces.find(workspace => workspace.sessionIds.includes(source.id))
  1071. if (direct !== undefined || source.header.origin !== 'subagent') return direct
  1072. const lineage = await ctx.sessionQuery.traceSession(source.id)
  1073. for (const ancestor of lineage.ancestors) {
  1074. const workspace = workspaces.find(candidate => candidate.sessionIds.includes(ancestor.header.id))
  1075. if (workspace !== undefined) return workspace
  1076. }
  1077. return undefined
  1078. }
  1079. /** Read one transcript cut and optional projection baseline without acquiring an Agent owner. */
  1080. async function historyStateFor(
  1081. sessionId: SessionId,
  1082. includeProjections: boolean,
  1083. ): Promise<{ events: SessionEvent[]; projections?: SessionProjectionsBlock }> {
  1084. const attached = ctx.sessions.get(sessionId)
  1085. if (attached !== undefined) {
  1086. const events = [...attached.events]
  1087. const projections = includeProjections ? projectionsFor(ctx, attached) : undefined
  1088. return { events, ...projections === undefined ? {} : { projections } }
  1089. }
  1090. const inspected = await inspectServable(sessionId)
  1091. const projections = includeProjections ? detachedProjectionsFor(ctx, inspected.events) : undefined
  1092. return {
  1093. events: inspected.events,
  1094. ...projections === undefined ? {} : { projections },
  1095. }
  1096. }
  1097. /** Resolve one requested identity to a live agent, creating or resuming it once. */
  1098. async function ensureSession(sessionId: SessionId, cwd: string, checkPersistedIdentity: boolean): Promise<Agent> {
  1099. let creation = sessionCreations.get(sessionId)
  1100. if (creation === undefined) {
  1101. creation = (async () => {
  1102. const attached = ctx.sessions.get(sessionId)
  1103. const live = ctx.agents.get(sessionId)
  1104. if (attached !== undefined && hasSubagentOwner(attached, live)) {
  1105. throw new SubagentSessionOwnership(sessionId)
  1106. }
  1107. if (live !== undefined) return live
  1108. const persistence = checkPersistedIdentity ? ctx.get('sessionPersistence') : undefined
  1109. const stored = persistence === undefined
  1110. ? undefined
  1111. : (await persistence.list()).find(header => header.id === sessionId)
  1112. if (persistence !== undefined && stored !== undefined) {
  1113. if (stored.cwd !== cwd) {
  1114. throw new SessionCwdConflict(sessionId, cwd, stored.cwd)
  1115. }
  1116. const inspected = await persistence.inspect(sessionId)
  1117. if (hasSubagentOwner({ header: inspected.meta, events: inspected.events }, undefined)) {
  1118. throw new SubagentSessionOwnership(sessionId)
  1119. }
  1120. return (await ctx.agents.resume({
  1121. resumeSessionId: sessionId,
  1122. agentOptions,
  1123. setup: installTarget,
  1124. })).agent
  1125. }
  1126. try {
  1127. await mkdir(cwd, { recursive: true })
  1128. } catch (error: unknown) {
  1129. throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
  1130. }
  1131. return (await ctx.agents.create({
  1132. sessionId,
  1133. agentOptions,
  1134. meta: { cwd },
  1135. setup: installTarget,
  1136. })).agent
  1137. })().catch((error: unknown) => {
  1138. // Another Host entry path may have published the same identity while
  1139. // this operation crossed an asynchronous persistence/filesystem step.
  1140. const live = ctx.agents.get(sessionId)
  1141. if (live !== undefined) {
  1142. if (hasSubagentOwner(live.session, live)) throw new SubagentSessionOwnership(sessionId)
  1143. return live
  1144. }
  1145. const attached = ctx.sessions.get(sessionId)
  1146. if (attached !== undefined && hasSubagentOwner(attached, undefined)) {
  1147. throw new SubagentSessionOwnership(sessionId)
  1148. }
  1149. throw error
  1150. }).finally(() => {
  1151. sessionCreations.delete(sessionId)
  1152. })
  1153. sessionCreations.set(sessionId, creation)
  1154. }
  1155. const agent = await creation
  1156. if (hasSubagentOwner(agent.session, agent)) throw new SubagentSessionOwnership(sessionId)
  1157. if (agent.session.header.cwd !== cwd) {
  1158. throw new SessionCwdConflict(sessionId, cwd, agent.session.header.cwd)
  1159. }
  1160. return agent
  1161. }
  1162. /** Resolve or create one path while holding the Host's workspace-create chain. */
  1163. function ensureWorkspace(
  1164. path: string,
  1165. title: string | undefined,
  1166. rejectExistingName = false,
  1167. createDirectory = false,
  1168. ): Promise<{ workspace: Workspace; created: boolean }> {
  1169. const operation = workspaceCreationChain.then(async () => {
  1170. if (rejectExistingName && title !== undefined
  1171. && ctx.workspace.list().some(workspace => workspace.title === title)) {
  1172. throw new WorkspaceNameConflictError(title)
  1173. }
  1174. if (createDirectory) {
  1175. try {
  1176. await mkdir(path, { recursive: true })
  1177. } catch (error: unknown) {
  1178. throw new WorkspaceDirectoryCreationError(
  1179. `failed to create workspace directory "${path}": ${String(error)}`,
  1180. )
  1181. }
  1182. }
  1183. const existing = await ctx.workspace.resolveByPath(path)
  1184. if (existing !== undefined) return { workspace: existing, created: false }
  1185. return { workspace: await ctx.workspace.create(path, title), created: true }
  1186. })
  1187. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  1188. return operation
  1189. }
  1190. /**
  1191. * Build the session.list baseline shared by listing and search visibility.
  1192. * Attached sessions come from memory; servable cold sessions merge from
  1193. * persistence, and the final order is newest-first.
  1194. */
  1195. async function listVisibleSessionSummaries(signal?: AbortSignal): Promise<SessionSummary[]> {
  1196. signal?.throwIfAborted()
  1197. const items = ctx.sessions.list().map((session) => {
  1198. const agent = ctx.agents.get(session.id)
  1199. const projections = listProjectionsFor(ctx, session.header, session)
  1200. return {
  1201. ...summarize(session, agent?.status === 'running'),
  1202. ...projections === undefined ? {} : { projections },
  1203. }
  1204. })
  1205. signal?.throwIfAborted()
  1206. const attached = new Set(items.map(item => item.sessionId))
  1207. const persistence = ctx.get('sessionPersistence')
  1208. if (persistence !== undefined) {
  1209. const cold = (await persistence.list(signal))
  1210. .filter(meta => !attached.has(meta.id) && meta.cwd !== undefined)
  1211. signal?.throwIfAborted()
  1212. for (let offset = 0; offset < cold.length; offset += COLD_SUMMARY_BATCH_SIZE) {
  1213. signal?.throwIfAborted()
  1214. const batch = cold.slice(offset, offset + COLD_SUMMARY_BATCH_SIZE)
  1215. const settled = await Promise.allSettled(
  1216. batch.map(async (meta) => {
  1217. // Cold rows read the persisted projection cache only — never a
  1218. // log load; a session without a cache row simply has no column.
  1219. const projections = listProjectionsFor(ctx, meta, undefined)
  1220. return {
  1221. ...await summarizeCold(persistence, meta, signal),
  1222. ...projections === undefined ? {} : { projections },
  1223. }
  1224. }),
  1225. )
  1226. const summaries: SessionSummary[] = []
  1227. let rejected = false
  1228. let failure: unknown
  1229. for (const result of settled) {
  1230. if (result.status === 'fulfilled') {
  1231. summaries.push(result.value)
  1232. } else if (!rejected) {
  1233. rejected = true
  1234. failure = result.reason
  1235. }
  1236. }
  1237. if (rejected) throw failure
  1238. signal?.throwIfAborted()
  1239. items.push(...summaries)
  1240. }
  1241. }
  1242. items.sort((a, b) => b.updatedAt - a.updatedAt)
  1243. return items
  1244. }
  1245. /** Resolve the goal service; absent = the deployment did not compose @deepseek-ai/dsh-goal. */
  1246. function goalService(): NonNullable<ReturnType<typeof ctx.get<'goals'>>> | { error: RpcError } {
  1247. const goals = ctx.get('goals')
  1248. if (goals === undefined) {
  1249. 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: {} } }
  1250. }
  1251. return goals
  1252. }
  1253. /** Map one goal-domain rejection to the wire error (stable GoalError codes ride in details). */
  1254. function goalError(request: RpcRequest<unknown>, error: unknown): RpcResponse<never> {
  1255. const details = error instanceof GoalError ? { goalCode: error.code } : {}
  1256. return err(request, { code: 'internal', message: String(error), details })
  1257. }
  1258. /** Resolve a session's agent, apply one goal mutation, and acknowledge with the new CAS ref. */
  1259. async function mutateGoal(
  1260. request: RpcRequest<{ sessionId: SessionId }>,
  1261. mutation: (goals: NonNullable<ReturnType<typeof ctx.get<'goals'>>>, agent: Agent) => CoreGoalRef,
  1262. ): Promise<RpcResponse<{ ref: GoalRef }>> {
  1263. const goals = goalService()
  1264. if ('error' in goals) return err(request, goals.error)
  1265. const found = await agentFor(request.payload.sessionId)
  1266. if ('error' in found) return err(request, found.error)
  1267. try {
  1268. const ref = mutation(goals, found.agent)
  1269. return ok(request, { ref: { id: ref.id, revision: ref.revision } })
  1270. } catch (error: unknown) {
  1271. return goalError(request, error)
  1272. }
  1273. }
  1274. /** Missing-service report shared by the settings domain (skills-domain stance). */
  1275. function settingsAbsent(): RpcError {
  1276. 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: {} }
  1277. }
  1278. /** Missing-service report shared by the credentials domain. */
  1279. function credentialsAbsent(): RpcError {
  1280. 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: {} }
  1281. }
  1282. /** Map one redacted seam descriptor to its wire view. */
  1283. function namespaceView(descriptor: SettingsDescriptor): SettingsNamespaceView {
  1284. return {
  1285. ns: String(descriptor.ns),
  1286. schema: descriptor.schema,
  1287. value: descriptor.value,
  1288. ...descriptor.base === undefined ? {} : { base: descriptor.base },
  1289. ...descriptor.user === undefined ? {} : { user: descriptor.user },
  1290. applies: descriptor.applies,
  1291. secrets: (descriptor.secrets ?? []).map(secret => ({ path: [...secret.path], set: secret.set })),
  1292. revision: descriptor.revision,
  1293. }
  1294. }
  1295. /** Settings namespaces whose changes can invalidate the model catalog. */
  1296. function modelProviderNamespaces(): Set<string> {
  1297. return new Set(ctx.llm.listConfigurableProviders().map(entry => entry.settingsNs))
  1298. }
  1299. /**
  1300. * The settings namespaces this proxy serves: configurable model providers
  1301. * plus the small explicit Web preference and product-owned allowlists. The
  1302. * settings seam remains general; a future registration does not become
  1303. * remotely readable or writable by default.
  1304. */
  1305. function exposedNamespaces(): Set<string> {
  1306. const exposed = modelProviderNamespaces()
  1307. for (const ns of WEB_SETTINGS_NAMESPACES) exposed.add(ns)
  1308. for (const ns of PRODUCT_SETTINGS_NAMESPACES) exposed.add(ns)
  1309. return exposed
  1310. }
  1311. /** Refuse a namespace outside the explicit configuration-client boundary. */
  1312. function notExposed(request: RpcRequest<unknown>, ns: string): RpcResponse<SettingsNamespaceView> {
  1313. return err(request, {
  1314. code: 'settings-not-exposed',
  1315. message: `settings namespace "${ns}" is not exposed to configuration clients`,
  1316. details: { ns },
  1317. })
  1318. }
  1319. /**
  1320. * Run one settings write (merge or wholesale replace) and acknowledge with
  1321. * the namespace's new redacted view. A namespace outside the configuration
  1322. * boundary is refused before the seam is touched; every seam refusal —
  1323. * unknown or invalid namespace, read-only provider, schema validation,
  1324. * storage — becomes one `settings-rejected` carrying the seam's own message.
  1325. */
  1326. async function settingsWrite(
  1327. request: RpcRequest<unknown>,
  1328. ns: string,
  1329. mode: 'update' | 'replace' | 'mutate',
  1330. section: object,
  1331. expectedRevision?: number,
  1332. ): Promise<RpcResponse<SettingsNamespaceView>> {
  1333. const settings = ctx.get('settings')
  1334. if (settings === undefined) return err(request, settingsAbsent())
  1335. const rejected = (error: unknown): RpcResponse<SettingsNamespaceView> => {
  1336. // A stale writer is its own outcome, not a malformed request: the client
  1337. // must re-read and re-apply rather than treat the write as invalid.
  1338. if (error instanceof SettingsConflictError) {
  1339. return err(request, {
  1340. code: 'settings-conflict',
  1341. message: error.message,
  1342. details: { ns, expected: error.expected, actual: error.actual },
  1343. })
  1344. }
  1345. return err(request, {
  1346. code: 'settings-rejected',
  1347. message: error instanceof Error ? error.message : String(error),
  1348. details: { ns },
  1349. })
  1350. }
  1351. let branded: SettingsNamespace
  1352. try {
  1353. branded = settingsNamespace(ns)
  1354. } catch (error: unknown) {
  1355. // A malformed name is a client bug, reported as such; it could never be
  1356. // in the exposed set either, so naming the real fault costs no ground.
  1357. return rejected(error)
  1358. }
  1359. if (!exposedNamespaces().has(ns)) return notExposed(request, ns)
  1360. try {
  1361. if (mode === 'update') await settings.update(branded, section, expectedRevision)
  1362. else if (mode === 'replace') await settings.replace(branded, section, expectedRevision)
  1363. else await settings.mutate(branded, section as SettingsPathOp[], expectedRevision)
  1364. } catch (error: unknown) {
  1365. return rejected(error)
  1366. }
  1367. const descriptor = settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === branded)
  1368. if (descriptor === undefined) {
  1369. // The write committed but the namespace vanished before this read: only
  1370. // a concurrent registrant disposal can produce it.
  1371. return err(request, { code: 'internal', message: `settings namespace "${ns}" was disposed after the ${mode}`, details: {} })
  1372. }
  1373. return ok(request, namespaceView(descriptor))
  1374. }
  1375. return {
  1376. sessions: {
  1377. // Attached sessions summarize from memory; persisted-but-unattached (cold)
  1378. // sessions merge in from the persistence store so history survives restarts.
  1379. // Legacy logs without a cwd (pre-project stance) are not served — every
  1380. // session now records its project at create time.
  1381. async list(request) {
  1382. return ok(request, { items: await listVisibleSessionSummaries() })
  1383. },
  1384. async search(request, signal) {
  1385. const cancelled = () => err<{ items: SessionSearchItem[]; hasMore: boolean }>(request, {
  1386. code: 'cancelled',
  1387. message: 'session search was aborted',
  1388. details: {},
  1389. })
  1390. if (isAborted(signal)) return cancelled()
  1391. const sessionQuery = ctx.get('sessionQuery')
  1392. if (sessionQuery === undefined) {
  1393. return err(request, {
  1394. code: 'internal',
  1395. message: 'session search is unavailable: this deployment does not mount @deepseek-ai/dsh-session-query',
  1396. details: {},
  1397. })
  1398. }
  1399. try {
  1400. const visible = await listVisibleSessionSummaries(signal)
  1401. if (isAborted(signal)) return cancelled()
  1402. if (visible.length === 0) return ok(request, { items: [], hasMore: false })
  1403. const visibleIds = new Set(visible.map(item => item.sessionId))
  1404. const authorized: SessionSearchItem[] = []
  1405. const acceptedIds = new Set<SessionId>()
  1406. const seenCursors = new Set<SessionSearchCursor>()
  1407. let cursor: SessionSearchCursor | undefined
  1408. let providerCallCount = 0
  1409. let providerPageLimit = SESSION_SEARCH_RESULT_LIMIT
  1410. while (authorized.length <= SESSION_SEARCH_RESULT_LIMIT) {
  1411. if (isAborted(signal)) return cancelled()
  1412. if (providerCallCount >= SESSION_SEARCH_PROVIDER_CALL_LIMIT) {
  1413. throw new Error(
  1414. `session search provider exceeded the ${SESSION_SEARCH_PROVIDER_CALL_LIMIT}-call work budget`,
  1415. )
  1416. }
  1417. providerCallCount++
  1418. const requestedCursor = cursor
  1419. const requestedPageLimit = providerPageLimit
  1420. let page
  1421. try {
  1422. page = await sessionQuery.searchSessions({
  1423. query: request.payload.query,
  1424. eventFilters: [
  1425. { kind: 'type', values: ['user/message', 'assistant/message', 'steering/message'] },
  1426. { kind: 'surface', values: ['current'] },
  1427. ],
  1428. limit: requestedPageLimit,
  1429. ...requestedCursor === undefined ? {} : { cursor: requestedCursor },
  1430. }, { signal })
  1431. } catch (error: unknown) {
  1432. if (isAborted(signal)) return cancelled()
  1433. if (
  1434. requestedCursor === undefined
  1435. && error instanceof SessionQueryError
  1436. && error.code === 'SESSION_QUERY_INVALID_LIMIT'
  1437. && requestedPageLimit > 1
  1438. ) {
  1439. providerPageLimit = Math.max(1, Math.floor(requestedPageLimit / 2))
  1440. continue
  1441. }
  1442. if (
  1443. requestedCursor !== undefined
  1444. && error instanceof SessionQueryError
  1445. && error.code === 'SESSION_QUERY_STALE_CURSOR'
  1446. ) {
  1447. authorized.length = 0
  1448. acceptedIds.clear()
  1449. seenCursors.clear()
  1450. cursor = undefined
  1451. continue
  1452. }
  1453. throw error
  1454. }
  1455. if (isAborted(signal)) return cancelled()
  1456. const providerItemCount = page.items.length
  1457. if (providerItemCount > requestedPageLimit) {
  1458. throw new Error(
  1459. `session search provider returned ${providerItemCount} items; maximum is ${requestedPageLimit}`,
  1460. )
  1461. }
  1462. // Host visibility is the authorization boundary. Consume the
  1463. // provider's globally ranked stream rather than binding every
  1464. // visible id into one SQLite statement, then re-check complete
  1465. // provenance before emitting any snippet.
  1466. for (const hit of page.items) {
  1467. if (authorized.length > SESSION_SEARCH_RESULT_LIMIT) continue
  1468. if (
  1469. !visibleIds.has(hit.header.id)
  1470. || hit.bestMatch.sessionId !== hit.header.id
  1471. || hit.bestMatch.surface !== 'current'
  1472. || !MESSAGE_TYPES.has(hit.bestMatch.type)
  1473. || acceptedIds.has(hit.header.id)
  1474. ) continue
  1475. const snippet = truncateUnicodeCodePoints(
  1476. hit.bestMatch.snippet,
  1477. SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS,
  1478. )
  1479. acceptedIds.add(hit.header.id)
  1480. authorized.push({
  1481. sessionId: hit.header.id,
  1482. snippet,
  1483. })
  1484. }
  1485. const nextCursor = page.nextCursor
  1486. if (nextCursor !== undefined) {
  1487. if (seenCursors.has(nextCursor)) {
  1488. throw new Error('session search provider repeated a continuation cursor')
  1489. }
  1490. seenCursors.add(nextCursor)
  1491. }
  1492. if (authorized.length > SESSION_SEARCH_RESULT_LIMIT || nextCursor === undefined) break
  1493. cursor = nextCursor
  1494. }
  1495. return ok(request, {
  1496. items: authorized.slice(0, SESSION_SEARCH_RESULT_LIMIT),
  1497. hasMore: authorized.length > SESSION_SEARCH_RESULT_LIMIT,
  1498. })
  1499. } catch (error: unknown) {
  1500. if (
  1501. isAborted(signal)
  1502. || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')
  1503. ) return cancelled()
  1504. // XXX: Redact provider details before exposing this gateway beyond
  1505. // its current single-user local deployment.
  1506. return err(request, {
  1507. code: 'internal',
  1508. message: `session search failed: ${String(error)}`,
  1509. details: {},
  1510. })
  1511. }
  1512. },
  1513. async create(request) {
  1514. const sessionId = request.payload.sessionId ?? `session-${randomUUID()}` as SessionId
  1515. let workspace: Workspace | undefined
  1516. if (request.payload.workspaceId !== undefined) {
  1517. workspace = ctx.workspace.get(brandWorkspaceId(request.payload.workspaceId))
  1518. if (workspace === undefined) {
  1519. return err(request, {
  1520. code: 'workspace-not-found',
  1521. message: `workspace "${request.payload.workspaceId}" not found`,
  1522. details: { workspaceId: request.payload.workspaceId },
  1523. })
  1524. }
  1525. }
  1526. const cwd = workspace?.path ?? request.payload.cwd ?? defaults.cwd
  1527. try {
  1528. await ensureSession(sessionId, cwd, request.payload.sessionId !== undefined)
  1529. } catch (error: unknown) {
  1530. if (error instanceof SessionCwdConflict) {
  1531. return err(request, {
  1532. code: 'session-conflict',
  1533. message: error.message,
  1534. details: {
  1535. sessionId: error.sessionId,
  1536. requestedCwd: error.requestedCwd,
  1537. ...error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd },
  1538. },
  1539. })
  1540. }
  1541. if (error instanceof SubagentSessionOwnership) {
  1542. return err(request, subagentOwnershipError(error.sessionId))
  1543. }
  1544. return err(request, {
  1545. code: 'internal',
  1546. message: `failed to create session "${sessionId}": ${String(error)}`,
  1547. details: {},
  1548. })
  1549. }
  1550. if (workspace !== undefined) {
  1551. try {
  1552. await workspace.attachSession(sessionId)
  1553. } catch (error: unknown) {
  1554. return err(request, {
  1555. code: 'workspace-attach-failed',
  1556. message: `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`,
  1557. details: { sessionId, workspaceId: workspace.id },
  1558. })
  1559. }
  1560. }
  1561. return ok(request, { sessionId })
  1562. },
  1563. async history(request) {
  1564. const { sessionId, beforeSeq, maxMessages } = request.payload
  1565. let state: { events: SessionEvent[]; projections?: SessionProjectionsBlock }
  1566. try {
  1567. state = await historyStateFor(sessionId, beforeSeq === undefined)
  1568. } catch (error: unknown) {
  1569. if (error instanceof SessionNotFound) {
  1570. return err(request, { code: 'session-not-found', message: error.message, details: { sessionId } })
  1571. }
  1572. return err(request, {
  1573. code: 'internal',
  1574. message: `history unavailable for session "${sessionId}": ${String(error)}`,
  1575. details: {},
  1576. })
  1577. }
  1578. const page = historyPage(ctx, state.events, beforeSeq, maxMessages)
  1579. return ok(request, {
  1580. events: page.events,
  1581. hasMore: page.hasMore,
  1582. ...state.projections === undefined ? {} : { projections: state.projections },
  1583. })
  1584. },
  1585. async models(request) {
  1586. const { sessionId } = request.payload
  1587. const found = await agentFor(sessionId)
  1588. if ('error' in found) return err(request, found.error)
  1589. const current = targetFor(found.agent).current
  1590. const { groups, failures } = await buildModelCatalog(ctx, current)
  1591. return ok(request, { current: { ...current }, groups, failures })
  1592. },
  1593. async selectModel(request) {
  1594. const { sessionId, provider, model, reasoningEffort } = request.payload
  1595. const found = await agentFor(sessionId)
  1596. if ('error' in found) return err(request, found.error)
  1597. try {
  1598. const resolved = await ctx.llm.resolveCallConfig({
  1599. provider,
  1600. model,
  1601. ...reasoningEffort === undefined
  1602. ? {}
  1603. : { reasoningEffort: ReasoningEffortId(reasoningEffort) },
  1604. })
  1605. const selected: AgentLlmTarget = {
  1606. provider: resolved.provider,
  1607. model: resolved.model,
  1608. ...resolved.reasoningEffort === undefined
  1609. ? {}
  1610. : { reasoningEffort: resolved.reasoningEffort },
  1611. }
  1612. targetFor(found.agent).current = selected
  1613. return ok(request, { selected: { ...selected } })
  1614. } catch (error: unknown) {
  1615. return err(request, {
  1616. code: 'model-unavailable',
  1617. message: error instanceof Error ? error.message : String(error),
  1618. details: { provider, model },
  1619. })
  1620. }
  1621. },
  1622. async rename(request) {
  1623. const { sessionId, title } = request.payload
  1624. const found = await agentFor(sessionId)
  1625. if ('error' in found) return err(request, found.error)
  1626. const titles = ctx.get('sessionTitle')
  1627. if (titles === undefined) {
  1628. return err(request, { code: 'internal', message: 'renaming is unavailable: this deployment mounts no session-title service', details: {} })
  1629. }
  1630. try {
  1631. const accepted = titles.rename(found.agent.session, title)
  1632. return ok(request, { title: accepted.title, seq: accepted.eventSeq })
  1633. } catch (error: unknown) {
  1634. // Only the input's fault maps to title-invalid (the message is
  1635. // product-user-visible in the rename dialog); liveness and disposal
  1636. // races are deployment trouble, not a bad title.
  1637. if (error instanceof SessionTitleInvalidError) {
  1638. return err(request, {
  1639. code: 'title-invalid',
  1640. message: error.message,
  1641. details: { sessionId },
  1642. })
  1643. }
  1644. return err(request, {
  1645. code: 'internal',
  1646. message: `failed to rename session "${sessionId}": ${String(error)}`,
  1647. details: {},
  1648. })
  1649. }
  1650. },
  1651. async fork(request) {
  1652. const { sessionId, atSeq } = request.payload
  1653. let source: SessionReadState
  1654. try {
  1655. source = await readSessionState(sessionId)
  1656. } catch (error: unknown) {
  1657. if (error instanceof SessionNotFound) {
  1658. return err(request, { code: 'session-not-found', message: error.message, details: { sessionId } })
  1659. }
  1660. return err(request, {
  1661. code: 'internal',
  1662. message: `fork source unavailable for session "${sessionId}": ${String(error)}`,
  1663. details: {},
  1664. })
  1665. }
  1666. const events = source.events
  1667. // An in-log anchor belongs to the turn containing it and must never
  1668. // clip backward to an earlier completed turn. Omitted and past-end
  1669. // anchors retain the last-completed-turn shortcut.
  1670. const lastSeq = events.at(-1)?.seq ?? -1
  1671. const anchoredBoundary = atSeq === undefined
  1672. ? undefined
  1673. : events.find(e => e.type === 'turn/end' && e.seq >= atSeq)
  1674. const boundary = anchoredBoundary
  1675. ?? (atSeq === undefined || atSeq > lastSeq
  1676. ? events.findLast(e => e.type === 'turn/end')
  1677. : undefined)
  1678. if (boundary === undefined) {
  1679. return err(request, {
  1680. code: 'fork-unavailable',
  1681. message: atSeq !== undefined && atSeq <= lastSeq
  1682. ? `session "${sessionId}" has not completed the turn containing event ${String(atSeq)}`
  1683. : `session "${sessionId}" has no completed turn to fork from`,
  1684. details: { sessionId },
  1685. })
  1686. }
  1687. // Extend the cut through trailing out-of-band appends (session/title,
  1688. // injections) up to the next turn/start: they are standalone events, so
  1689. // the seed stays balanced, and the child inherits a title generated
  1690. // right after the boundary turn.
  1691. let cut = boundary.seq + 1
  1692. while (cut < events.length && events[cut]?.type !== 'turn/start') cut++
  1693. let workspace: Workspace | undefined
  1694. try {
  1695. workspace = await forkWorkspace(source)
  1696. } catch (error: unknown) {
  1697. return err(request, {
  1698. code: 'internal',
  1699. message: `failed to resolve fork workspace for session "${sessionId}": ${String(error)}`,
  1700. details: {},
  1701. })
  1702. }
  1703. const childId = `session-${randomUUID()}` as SessionId
  1704. try {
  1705. await ctx.agents.create({
  1706. sessionId: childId,
  1707. seed: events.slice(0, cut),
  1708. meta: {
  1709. ...source.header.cwd === undefined ? {} : { cwd: source.header.cwd },
  1710. parentSession: source.id,
  1711. seedLength: cut,
  1712. },
  1713. agentOptions,
  1714. setup: installTarget,
  1715. })
  1716. } catch (error: unknown) {
  1717. return err(request, {
  1718. code: 'internal',
  1719. message: `failed to fork session "${sessionId}": ${String(error)}`,
  1720. details: {},
  1721. })
  1722. }
  1723. // An ordinary source keeps its direct Workspace. A subagent source is
  1724. // not listed there, so its ordinary fork joins the nearest owning
  1725. // ancestor instead. The child is already published if attach fails.
  1726. if (workspace !== undefined) {
  1727. try {
  1728. await workspace.attachSession(childId)
  1729. } catch (error: unknown) {
  1730. return err(request, {
  1731. code: 'workspace-attach-failed',
  1732. message: `session "${childId}" was forked but could not attach to workspace "${workspace.id}": ${String(error)}`,
  1733. details: { sessionId: childId, workspaceId: workspace.id },
  1734. })
  1735. }
  1736. }
  1737. return ok(request, { sessionId: childId })
  1738. },
  1739. async prompt(request) {
  1740. const { sessionId, mode, content } = request.payload
  1741. const found = await agentFor(sessionId)
  1742. if ('error' in found) return err(request, found.error)
  1743. const agent = found.agent
  1744. // The rpcId rides MessageSource into user/message (merge declaration in api/sessions.ts; provisional correlation).
  1745. const source: MessageSource = { kind: 'user', rpcId: request.rpcId }
  1746. try {
  1747. const message: UserMessage = createUserMessage({ content, source })
  1748. if (mode === 'steer') agent.steer(message)
  1749. else agent.followup(message)
  1750. } catch (error: unknown) {
  1751. // A synchronous throw from steer/followup means disposed or invalid input; surface as agent-busy with the reason attached.
  1752. return err(request, { code: 'agent-busy', message: 'prompt rejected', details: { reason: String(error) } })
  1753. }
  1754. return ok(request, { accepted: true as const })
  1755. },
  1756. updateQueue(request) {
  1757. const { sessionId, itemId, action } = request.payload
  1758. const agent = ctx.agents.get(sessionId)
  1759. if (agent !== undefined && hasSubagentOwner(agent.session, agent)) {
  1760. return Promise.resolve(err(request, subagentOwnershipError(sessionId)))
  1761. }
  1762. if (agent === undefined || agent.updateInbox(itemId, action) === 'not-found') {
  1763. return Promise.resolve(err(request, {
  1764. code: 'queue-item-not-found',
  1765. message: 'queued item is no longer pending',
  1766. details: { itemId },
  1767. }))
  1768. }
  1769. return Promise.resolve(ok(request, { accepted: true as const }))
  1770. },
  1771. cancel(request) {
  1772. const { sessionId } = request.payload
  1773. const agent = ctx.agents.get(sessionId)
  1774. if (agent === undefined) {
  1775. return Promise.resolve(err(request, {
  1776. code: 'session-not-found',
  1777. message: `session "${sessionId}" not found (not attached)`,
  1778. details: { sessionId },
  1779. }))
  1780. }
  1781. if (hasSubagentOwner(agent.session, agent)) {
  1782. return Promise.resolve(err(request, subagentOwnershipError(sessionId)))
  1783. }
  1784. agent.cancel({ kind: 'user' }, { keepInbox: true })
  1785. return Promise.resolve(ok(request, { accepted: true as const }))
  1786. },
  1787. },
  1788. subagents: {
  1789. async list(request, signal) {
  1790. try {
  1791. const entries = await ctx.subagents.listChildren(request.payload.parentSessionId, signal)
  1792. return ok(request, {
  1793. entries: entries.map(entry => entry.kind === 'child'
  1794. ? {
  1795. ...entry,
  1796. activity: ctx.agents.get(entry.id)?.status === 'running' ? 'running' : 'inactive',
  1797. }
  1798. : entry),
  1799. parentAvailable: ctx.agents.get(request.payload.parentSessionId) !== undefined,
  1800. })
  1801. } catch (error: unknown) {
  1802. if (signal?.aborted
  1803. || (error instanceof SubagentError && error.code === 'CANCELLED')
  1804. || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) {
  1805. return err(request, {
  1806. code: 'cancelled',
  1807. message: 'subagent catalog read was cancelled',
  1808. details: {},
  1809. })
  1810. }
  1811. return err(request, {
  1812. code: 'internal',
  1813. message: 'subagent catalog read failed',
  1814. details: {},
  1815. })
  1816. }
  1817. },
  1818. async history(request, signal) {
  1819. const {
  1820. parentSessionId, childSessionId, mode, beforeSeq, maxMessages,
  1821. } = request.payload
  1822. const verified = await catalogChild(ctx, {
  1823. parentSessionId, childSessionId, mode,
  1824. }, signal)
  1825. if (verified.error !== undefined) return err(request, verified.error)
  1826. try {
  1827. const snapshot = await ctx.sessionQuery.readSession(childSessionId)
  1828. signal?.throwIfAborted()
  1829. if (snapshot.session.parentSession !== parentSessionId) {
  1830. return err(request, {
  1831. code: 'subagent-unauthorized',
  1832. message: 'subagent parent changed during history read',
  1833. details: { childSessionId },
  1834. })
  1835. }
  1836. const page = historyPage(ctx, snapshot.events, beforeSeq, maxMessages)
  1837. const projections = beforeSeq === undefined
  1838. ? detachedProjectionsFor(ctx, snapshot.events)
  1839. : undefined
  1840. return ok(request, { ...page, ...projections === undefined ? {} : { projections } })
  1841. } catch (error: unknown) {
  1842. if (signal?.aborted
  1843. || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) {
  1844. return err(request, {
  1845. code: 'cancelled',
  1846. message: 'subagent history read was cancelled',
  1847. details: {},
  1848. })
  1849. }
  1850. if (error instanceof SessionQueryError
  1851. && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
  1852. return err(request, {
  1853. code: 'subagent-not-found',
  1854. message: 'subagent disappeared during history read',
  1855. details: { parentSessionId, childSessionId },
  1856. })
  1857. }
  1858. return err(request, {
  1859. code: 'internal',
  1860. message: 'subagent history read failed',
  1861. details: {},
  1862. })
  1863. }
  1864. },
  1865. async prompt(request, signal) {
  1866. const { parentSessionId, childSessionId, content } = request.payload
  1867. const parent = ctx.agents.get(parentSessionId)
  1868. if (parent === undefined) {
  1869. return err(request, {
  1870. code: 'subagent-parent-unavailable',
  1871. message: `parent session "${parentSessionId}" is not live`,
  1872. details: { parentSessionId },
  1873. })
  1874. }
  1875. const verified = await catalogChild(ctx, {
  1876. parentSessionId, childSessionId, mode: 'continuable',
  1877. }, signal)
  1878. if (verified.error !== undefined) return err(request, verified.error)
  1879. try {
  1880. const messageId = await ctx.subagents.followup(parent, childSessionId, content, {
  1881. source: { kind: 'user', rpcId: request.rpcId },
  1882. signal,
  1883. })
  1884. return ok(request, { messageId })
  1885. } catch (error: unknown) {
  1886. return subagentPromptError(request, error, signal)
  1887. }
  1888. },
  1889. },
  1890. workspace: {
  1891. list(request) {
  1892. return Promise.resolve(ok(request, {
  1893. items: ctx.workspace.list().map(workspaceView),
  1894. archivedSessionIds: [...ctx.workspace.archivedSessionIds],
  1895. }))
  1896. },
  1897. // Exactly one of path/name arrives (schema refine). Existing-folder
  1898. // adoption reuses its canonical path; create-by-name rejects a name
  1899. // already present in the registry.
  1900. // TODO: the create-by-name branch lost its last product consumer when
  1901. // the Web picker collapsed onto the directory flow
  1902. // (.agents/notes/implemented/simplification/2026-07-31-one-route-to-add-a-workspace.md).
  1903. // Delete it with the wire schema's `name` member, this
  1904. // `defaults.workspaceRoot`, the client seam that carried the name
  1905. // (`WorkspaceCreateInput`, `WorkspacesService.create`'s `{ name }` arm,
  1906. // `intentName`'s name branch, the manager's "name under workspaceRoot"
  1907. // contract), and the `dsh web --workspace-root` flag plus its apps/cli
  1908. // README lines, which exist only to feed it.
  1909. async create(request) {
  1910. const { payload } = request
  1911. let path: string
  1912. if (payload.name !== undefined) {
  1913. const name = payload.name.trim()
  1914. if (name === '' || name === '.' || name === '..' || /[/\\]/.test(name)) {
  1915. return err(request, {
  1916. code: 'workspace-invalid-path',
  1917. message: `workspace name must be one non-empty path segment, got "${payload.name}"`,
  1918. details: { path: payload.name },
  1919. })
  1920. }
  1921. path = join(defaults.workspaceRoot, name)
  1922. } else {
  1923. path = payload.path as string
  1924. }
  1925. try {
  1926. const name = payload.name?.trim()
  1927. const { workspace, created } = await ensureWorkspace(
  1928. path,
  1929. name,
  1930. name !== undefined,
  1931. name !== undefined,
  1932. )
  1933. return ok(request, { workspace: workspaceView(workspace), created })
  1934. } catch (error: unknown) {
  1935. if (error instanceof WorkspaceNameConflictError) {
  1936. return err(request, {
  1937. code: 'workspace-name-conflict',
  1938. message: error.message,
  1939. details: { name: error.workspaceName },
  1940. })
  1941. }
  1942. if (error instanceof WorkspaceDirectoryCreationError) {
  1943. return err(request, { code: 'internal', message: error.message, details: {} })
  1944. }
  1945. // The registry rejects a path that does not resolve to an existing
  1946. // directory (realpath ENOENT / not-a-directory) — the business
  1947. // error of the typed-path flow, surfaced as a validation failure.
  1948. return err(request, {
  1949. code: 'workspace-invalid-path',
  1950. message: `cannot create a workspace at "${path}": ${error instanceof Error ? error.message : String(error)}`,
  1951. details: { path },
  1952. })
  1953. }
  1954. },
  1955. async rename(request) {
  1956. const { payload } = request
  1957. const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
  1958. if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
  1959. const title = payload.title.trim()
  1960. // Uniqueness AND the same-title no-op both ride the create chain so
  1961. // they observe the state left by earlier queued renames — checked
  1962. // up front, a queued A→A could report success while an earlier A→B
  1963. // still lands afterwards.
  1964. const operation = workspaceCreationChain.then(async () => {
  1965. if (title === workspace.title) return
  1966. if (ctx.workspace.list().some(other => other.id !== workspace.id && other.title === title)) {
  1967. throw new WorkspaceNameConflictError(title)
  1968. }
  1969. await workspace.setTitle(title)
  1970. })
  1971. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  1972. try {
  1973. await operation
  1974. } catch (error: unknown) {
  1975. if (error instanceof WorkspaceNameConflictError) {
  1976. return err(request, {
  1977. code: 'workspace-name-conflict',
  1978. message: error.message,
  1979. details: { name: error.workspaceName },
  1980. })
  1981. }
  1982. throw error
  1983. }
  1984. return ok(request, { workspace: workspaceView(workspace) })
  1985. },
  1986. async delete(request) {
  1987. const { workspaceId } = request.payload
  1988. const operation = workspaceCreationChain.then(() =>
  1989. ctx.workspace.delete(brandWorkspaceId(workspaceId)))
  1990. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  1991. if (!await operation) return workspaceNotFound(request, workspaceId)
  1992. return ok(request, { deleted: true as const })
  1993. },
  1994. async insertSessionBefore(request) {
  1995. const { payload } = request
  1996. const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
  1997. if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
  1998. try {
  1999. await workspace.insertSessionBefore(payload.sessionId, payload.beforeSessionId)
  2000. } catch (error: unknown) {
  2001. // Only the entity's unaccounted-id rejection is the business code;
  2002. // storage/durability failures propagate as internal errors.
  2003. if (!(error instanceof WorkspaceMoveInvalidError)) throw error
  2004. return err(request, {
  2005. code: 'workspace-move-invalid',
  2006. message: error.message,
  2007. details: {
  2008. workspaceId: payload.workspaceId,
  2009. sessionId: payload.sessionId,
  2010. ...payload.beforeSessionId === undefined ? {} : { beforeSessionId: payload.beforeSessionId },
  2011. },
  2012. })
  2013. }
  2014. return ok(request, { workspace: workspaceView(workspace) })
  2015. },
  2016. async archiveSession(request) {
  2017. const { sessionId } = request.payload
  2018. try {
  2019. await ctx.workspace.archiveSession(sessionId)
  2020. } catch (error: unknown) {
  2021. // Only the registry's unknown-session rejection is the business
  2022. // code; storage/durability failures propagate as internal errors.
  2023. if (!(error instanceof WorkspaceUnknownSessionError)) throw error
  2024. return err(request, {
  2025. code: 'session-not-found',
  2026. message: error.message,
  2027. details: { sessionId },
  2028. })
  2029. }
  2030. return ok(request, { archivedSessionIds: [...ctx.workspace.archivedSessionIds] })
  2031. },
  2032. },
  2033. host: {
  2034. describe(request) {
  2035. // TODO(step2): version should read apps/cli's package.json; placeholder for now.
  2036. return Promise.resolve(ok(request, {
  2037. version: '0.0.1',
  2038. // Same source as session.create's fallback: the UI's default project
  2039. // must match where an unspecified-cwd session actually lands.
  2040. cwd: defaults.cwd,
  2041. provider: defaults.provider,
  2042. model: defaults.model,
  2043. attachedSessions: ctx.agents.list().length,
  2044. }))
  2045. },
  2046. async pickDirectory(request, signal) {
  2047. const capability = ctx.directoryPicker.capability()
  2048. if (capability.kind !== 'native') {
  2049. return err(request, {
  2050. code: 'directory-picker-unavailable',
  2051. message: `host.pickDirectory needs the native capability; the composed picker serves "${capability.kind}"`,
  2052. details: { capability: capability.kind },
  2053. })
  2054. }
  2055. try {
  2056. const path = await capability.pick(signal)
  2057. return ok(request, { path })
  2058. } catch (error: unknown) {
  2059. if (signal.aborted) {
  2060. return err(request, {
  2061. code: 'cancelled',
  2062. message: 'directory picker was aborted',
  2063. details: {},
  2064. })
  2065. }
  2066. return err(request, {
  2067. code: 'internal',
  2068. message: `directory picker failed: ${error instanceof Error ? error.message : String(error)}`,
  2069. details: {},
  2070. })
  2071. }
  2072. },
  2073. async listDirectory(request, signal) {
  2074. const capability = ctx.directoryPicker.capability()
  2075. if (capability.kind !== 'browse') {
  2076. return err(request, {
  2077. code: 'directory-picker-unavailable',
  2078. message: `host.listDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
  2079. details: { capability: capability.kind },
  2080. })
  2081. }
  2082. try {
  2083. // The carrier's signal follows the caller: a disconnect or timeout
  2084. // stops the backend's directory scan instead of outliving it.
  2085. return ok(request, await capability.list(request.payload.path, signal))
  2086. } catch (error: unknown) {
  2087. // An abort is the caller's own timeout/disconnect, not a server
  2088. // failure — same code pickDirectory and command.execute report.
  2089. if (signal.aborted) {
  2090. return err(request, { code: 'cancelled', message: 'directory listing was aborted', details: {} })
  2091. }
  2092. return err(request, directoryError(error))
  2093. }
  2094. },
  2095. async createDirectory(request) {
  2096. const capability = ctx.directoryPicker.capability()
  2097. if (capability.kind !== 'browse') {
  2098. return err(request, {
  2099. code: 'directory-picker-unavailable',
  2100. message: `host.createDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
  2101. details: { capability: capability.kind },
  2102. })
  2103. }
  2104. try {
  2105. return ok(request, { path: await capability.createDirectory(request.payload.path, request.payload.name) })
  2106. } catch (error: unknown) {
  2107. return err(request, directoryError(error))
  2108. }
  2109. },
  2110. async openPath(request, signal) {
  2111. try {
  2112. const open = defaults.openPath
  2113. ?? ((path: string, openSignal: AbortSignal) => openNativePath(path, openSignal))
  2114. await open(request.payload.path, signal)
  2115. return ok(request, { opened: true as const })
  2116. } catch (error: unknown) {
  2117. if (signal.aborted) {
  2118. return err(request, {
  2119. code: 'cancelled',
  2120. message: 'path open was aborted',
  2121. details: {},
  2122. })
  2123. }
  2124. return err(request, {
  2125. code: 'internal',
  2126. message: `path open failed: ${error instanceof Error ? error.message : String(error)}`,
  2127. details: {},
  2128. })
  2129. }
  2130. },
  2131. },
  2132. commands: {
  2133. // Both methods address one session's agent (agentFor keeps its
  2134. // resume-on-miss: clients only send a sessionId for a published
  2135. // session, and resume restores an existing entity).
  2136. async list(request) {
  2137. // Missing service = the deployment omitted dsh-commands from its
  2138. // composition, not an empty catalog: fail loud instead of serving [].
  2139. const commands = ctx.get('commands')
  2140. if (commands === undefined) {
  2141. 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: {} })
  2142. }
  2143. const found = await agentFor(request.payload.sessionId)
  2144. if ('error' in found) return err(request, found.error)
  2145. return ok(request, { commands: commands.list(found.agent) })
  2146. },
  2147. async execute(request, signal) {
  2148. const commands = ctx.get('commands')
  2149. if (commands === undefined) {
  2150. 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: {} })
  2151. }
  2152. const { sessionId, line } = request.payload
  2153. const found = await agentFor(sessionId)
  2154. if ('error' in found) return err(request, found.error)
  2155. try {
  2156. // Pure admission: the executor's durable command/run + command/done
  2157. // pair (broadcast on the mux stream) carries the outcome; the
  2158. // response reports whether the line resolved to a handler, plus the
  2159. // minted pairing id so the issuing client can correlate its request
  2160. // with the flow node the lifecycle events produce.
  2161. const execution = await commands.execute(found.agent, line, signal)
  2162. return ok(request, execution === undefined
  2163. ? { matched: false }
  2164. : { matched: true, commandId: execution.commandId })
  2165. } catch (error: unknown) {
  2166. if (signal.aborted) return err(request, { code: 'cancelled', message: 'command execution was aborted', details: {} })
  2167. return err(request, { code: 'internal', message: `command failed: ${String(error)}`, details: {} })
  2168. }
  2169. },
  2170. },
  2171. goals: {
  2172. // Mutations only — the read side is the 'goal' session projection.
  2173. // Every verb resolves the session's agent (agentFor: implicit cold
  2174. // resume, the command.* precedent) and acknowledges with the new CAS
  2175. // ref; the committed goal/change event carries the whole value to every
  2176. // client through the projection frames.
  2177. async create(request) {
  2178. const { objective, maxGoalRounds } = request.payload
  2179. return mutateGoal(request, (goals, agent) => goals.create(agent, {
  2180. objective,
  2181. ...(maxGoalRounds !== undefined ? { maxGoalRounds } : {}),
  2182. }))
  2183. },
  2184. async edit(request) {
  2185. const { ref, objective, maxGoalRounds } = request.payload
  2186. return mutateGoal(request, (goals, agent) => goals.edit(agent, ref, {
  2187. ...(objective !== undefined ? { objective } : {}),
  2188. ...(maxGoalRounds !== undefined ? { maxGoalRounds } : {}),
  2189. }))
  2190. },
  2191. async pause(request) {
  2192. return mutateGoal(request, (goals, agent) => goals.pause(agent, request.payload.ref))
  2193. },
  2194. async resume(request) {
  2195. return mutateGoal(request, (goals, agent) => goals.resume(agent, request.payload.ref))
  2196. },
  2197. async complete(request) {
  2198. return mutateGoal(request, (goals, agent) => goals.complete(agent, request.payload.ref))
  2199. },
  2200. async clear(request) {
  2201. const goals = goalService()
  2202. if ('error' in goals) return err(request, goals.error)
  2203. const found = await agentFor(request.payload.sessionId)
  2204. if ('error' in found) return err(request, found.error)
  2205. try {
  2206. goals.clear(found.agent, request.payload.ref)
  2207. return ok(request, { cleared: true as const })
  2208. } catch (error: unknown) {
  2209. return goalError(request, error)
  2210. }
  2211. },
  2212. },
  2213. skills: {
  2214. // Skill lookup never touches the Agent registry: the session address
  2215. // resolves to a canonical cwd from the host-resident session header, so
  2216. // listing skills cannot create or resume an agent as a side effect.
  2217. async list(request) {
  2218. const { sessionId } = request.payload
  2219. const session = ctx.sessions.get(sessionId)
  2220. if (session === undefined) {
  2221. return err(request, {
  2222. code: 'session-not-found',
  2223. message: `session "${sessionId}" not found (not attached)`,
  2224. details: { sessionId },
  2225. })
  2226. }
  2227. if (session.header.cwd === undefined) {
  2228. // Every served session records its project at create time; a
  2229. // cwd-less header is a pre-project legacy log (not served).
  2230. return err(request, { code: 'internal', message: `session "${sessionId}" has no project cwd`, details: {} })
  2231. }
  2232. const cwd = session.header.cwd
  2233. // Same stance as the commands domain: a missing service means the
  2234. // deployment omitted dsh-skill from its composition, not an empty
  2235. // catalog. ctx.get also keeps this handler independent of the gateway
  2236. // plugin's inject list (an undeclared `ctx.skills` property read
  2237. // fails the reflect proxy).
  2238. const skillRegistry = ctx.get('skills')
  2239. if (skillRegistry === undefined) {
  2240. 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: {} })
  2241. }
  2242. try {
  2243. const skills = (await skillRegistry.list({ cwd }))
  2244. .filter(skill => skill.invocation.modelInvocable && skill.invocation.userInvocable)
  2245. return ok(request, {
  2246. skills: skills.map(skill => ({
  2247. name: skill.name,
  2248. description: skill.description,
  2249. ...skill.whenToUse === undefined ? {} : { whenToUse: skill.whenToUse },
  2250. })),
  2251. })
  2252. } catch (error: unknown) {
  2253. return err(request, { code: 'internal', message: `skill listing failed: ${String(error)}`, details: {} })
  2254. }
  2255. },
  2256. },
  2257. settings: {
  2258. describe(request) {
  2259. const settings = ctx.get('settings')
  2260. if (settings === undefined) return Promise.resolve(err(request, settingsAbsent()))
  2261. const exposed = exposedNamespaces()
  2262. return Promise.resolve(ok(request, {
  2263. writable: settings.writable,
  2264. namespaces: settings.describe({ redactSecrets: true })
  2265. .filter(descriptor => exposed.has(String(descriptor.ns)))
  2266. .map(namespaceView),
  2267. }))
  2268. },
  2269. update: request => settingsWrite(request, request.payload.ns, 'update', request.payload.patch, request.payload.expectedRevision),
  2270. replace: request => settingsWrite(request, request.payload.ns, 'replace', request.payload.section, request.payload.expectedRevision),
  2271. mutate: request => settingsWrite(request, request.payload.ns, 'mutate', request.payload.ops, request.payload.expectedRevision),
  2272. },
  2273. credentials: {
  2274. async describe(request) {
  2275. const credentials = ctx.get('credentials')
  2276. if (credentials === undefined) return err(request, credentialsAbsent())
  2277. const entries = await Promise.all(request.payload.refs.map(async (ref) => {
  2278. const info = await credentials.describe(credentialRef(ref))
  2279. const view: CredentialView = {
  2280. configured: info.configured,
  2281. ...info.source === undefined ? {} : { source: info.source },
  2282. writable: info.writable,
  2283. }
  2284. return [ref, view] as const
  2285. }))
  2286. return ok(request, { credentials: Object.fromEntries(entries) })
  2287. },
  2288. async set(request) {
  2289. const credentials = ctx.get('credentials')
  2290. if (credentials === undefined) return err(request, credentialsAbsent())
  2291. const { ref, value } = request.payload
  2292. try {
  2293. await credentials.set(credentialRef(ref), value)
  2294. } catch (error: unknown) {
  2295. return err(request, {
  2296. code: 'credential-rejected',
  2297. message: error instanceof Error ? error.message : String(error),
  2298. details: { ref },
  2299. })
  2300. }
  2301. return ok(request, {})
  2302. },
  2303. async unset(request) {
  2304. const credentials = ctx.get('credentials')
  2305. if (credentials === undefined) return err(request, credentialsAbsent())
  2306. const { ref } = request.payload
  2307. try {
  2308. await credentials.unset(credentialRef(ref))
  2309. } catch (error: unknown) {
  2310. return err(request, {
  2311. code: 'credential-rejected',
  2312. message: error instanceof Error ? error.message : String(error),
  2313. details: { ref },
  2314. })
  2315. }
  2316. return ok(request, {})
  2317. },
  2318. },
  2319. llm: {
  2320. providers(request) {
  2321. const registered = ctx.llm.listProviders()
  2322. const active = new Set(registered.map(provider => provider.id))
  2323. const directory = ctx.llm.listConfigurableProviders()
  2324. const declared = new Set(directory.map(entry => entry.provider))
  2325. const views = directory.map(entry => ({
  2326. provider: entry.provider,
  2327. displayName: entry.displayName,
  2328. settingsNs: entry.settingsNs,
  2329. settingsPath: [...entry.settingsPath],
  2330. active: active.has(entry.provider),
  2331. }))
  2332. // Routes registered without a directory declaration still appear —
  2333. // they exist and serve models — just with no settings address.
  2334. for (const provider of registered) {
  2335. if (declared.has(provider.id)) continue
  2336. views.push({
  2337. provider: provider.id,
  2338. displayName: provider.name,
  2339. settingsNs: '',
  2340. settingsPath: [],
  2341. active: true,
  2342. })
  2343. }
  2344. return Promise.resolve(ok(request, { providers: views }))
  2345. },
  2346. async models(request) {
  2347. return ok(request, await buildModelCatalog(ctx))
  2348. },
  2349. },
  2350. events: {
  2351. mux(_request, signal) {
  2352. const queue = new FrameQueue<RpcRequest<MuxFrame>>()
  2353. muxQueues.add(queue)
  2354. for (const session of ctx.sessions.list()) {
  2355. subscribeSession(queue, session)
  2356. }
  2357. for (const pending of pendingQuestions.values()) {
  2358. queue.push({
  2359. rpcId: pending.rpcId,
  2360. payload: {
  2361. type: 'question/requested', sessionId: pending.sessionId,
  2362. questions: pending.questions,
  2363. },
  2364. })
  2365. }
  2366. // Refresh recovery: still-pending approval questions replay with their
  2367. // stable rpcId so a reconnecting client can still answer them.
  2368. for (const pending of pendingApprovals.values()) queue.push(requestedFrame(pending))
  2369. // Queue snapshot baseline (pendingQuestions precedent): frames replayed
  2370. // in arrival order per session; a reconnecting client rebuilds its
  2371. // queue view from these alone.
  2372. for (const [sessionId, items] of queuedMirror) {
  2373. queue.push(frame({
  2374. type: 'session/queue',
  2375. sessionId,
  2376. items: items.map(item => ({
  2377. id: item.id,
  2378. message: item.message,
  2379. })),
  2380. }))
  2381. }
  2382. // Per-session open-call table for result-view pairing. Bounded by the
  2383. // per-turn call count: entries clear on turn/end; a table miss (stream
  2384. // opened mid-turn) backscans the session's in-memory events instead.
  2385. const openCalls = new Map<SessionId, Map<string, { name: string; args: unknown }>>()
  2386. const disposers = [
  2387. ctx.on('session/event', (session: Session, event: SessionEvent) => {
  2388. if (event.type === 'tool/call') {
  2389. const data = event.data as ToolCallData
  2390. try {
  2391. let table = openCalls.get(session.id)
  2392. if (table === undefined) openCalls.set(session.id, table = new Map<string, { name: string; args: unknown }>())
  2393. table.set(data.callId, { name: data.name, args: JSON.parse(data.arguments) })
  2394. } catch {
  2395. // Unparseable model arguments: leave the table unset; the result view soft-falls.
  2396. }
  2397. } else if (event.type === 'turn/end') {
  2398. openCalls.delete(session.id)
  2399. }
  2400. const view = viewFor(ctx, event, callId =>
  2401. openCalls.get(session.id)?.get(callId) ?? backscanArgs(session.events, callId))
  2402. queue.push(frame({ type: 'session/event', sessionId: session.id, event, ...view === undefined ? {} : { view } }))
  2403. }),
  2404. ctx.on('session/created', (session: Session) => {
  2405. subscribeSession(queue, session)
  2406. }),
  2407. ctx.on('session/disposed', (session: Session) => {
  2408. openCalls.delete(session.id)
  2409. }),
  2410. ]
  2411. return queue.iterate(signal, () => {
  2412. muxQueues.delete(queue)
  2413. for (const dispose of disposers) dispose()
  2414. })
  2415. },
  2416. host(_request, signal) {
  2417. const queue = new FrameQueue<RpcRequest<HostFrame>>()
  2418. const committedWorkspaceIds = new Set(
  2419. ctx.workspace.list().map(workspace => String(workspace.id)),
  2420. )
  2421. // Frame-dedup baseline, same posture as committedWorkspaceIds: the
  2422. // stream opens against the current set; workspace.list re-baselines
  2423. // reconnecting clients, so only later changes need frames.
  2424. let archivedSessionIds = ctx.workspace.archivedSessionIds
  2425. const disposers = [
  2426. ctx.on('session/created', (session: Session) => {
  2427. queue.push(frame({
  2428. type: 'host/session-added',
  2429. sessionId: session.id,
  2430. // Derived at frame time like summarize(); a just-created session
  2431. // has run no turn yet, so this is constantly true in practice.
  2432. blank: sessionBlank(session),
  2433. // Including cwd lets the client group the new session without refreshing the list.
  2434. ...sessionListFields(session.header),
  2435. }))
  2436. }),
  2437. ctx.on('session/disposed', (session: Session) => {
  2438. queue.push(frame({ type: 'host/session-removed', sessionId: session.id }))
  2439. }),
  2440. ctx.on('agent/status', (agent: Agent, status: AgentStatus) => {
  2441. queue.push(frame({ type: 'host/session-status', sessionId: agent.id, running: status === 'running' }))
  2442. }),
  2443. ctx.on('agent/error', (agent: Agent, _turn: number, _step: number, error: unknown) => {
  2444. queue.push(frame({ type: 'host/agent-error', sessionId: agent.id, message: errorChain(error) }))
  2445. }),
  2446. ctx.on('domain/changed', (change) => {
  2447. if (change.domain !== 'workspace') return
  2448. if (change.table === '') {
  2449. if (change.operation !== 'put') return
  2450. const state = workspaceDomainState.parse(change.value)
  2451. for (const workspaceId of state.workspaceIds) {
  2452. if (committedWorkspaceIds.has(workspaceId)) continue
  2453. const workspace = ctx.workspace.get(workspaceId)
  2454. if (workspace === undefined) {
  2455. throw new Error(`committed workspace registry references missing workspace "${workspaceId}"`)
  2456. }
  2457. committedWorkspaceIds.add(workspaceId)
  2458. queue.push(frame({ type: 'host/workspace-changed', workspace: workspaceView(workspace) }))
  2459. }
  2460. if (state.archivedSessionIds.length !== archivedSessionIds.length
  2461. || state.archivedSessionIds.some((id, index) => id !== archivedSessionIds[index])) {
  2462. archivedSessionIds = state.archivedSessionIds
  2463. queue.push(frame({
  2464. type: 'host/archived-sessions-changed',
  2465. archivedSessionIds: [...state.archivedSessionIds],
  2466. }))
  2467. }
  2468. return
  2469. }
  2470. if (change.table !== 'workspaces') return
  2471. if (change.operation === 'deleted') {
  2472. if (!committedWorkspaceIds.delete(change.key)) return
  2473. queue.push(frame({
  2474. type: 'host/workspace-removed',
  2475. workspaceId: change.key as WorkspaceId,
  2476. }))
  2477. return
  2478. }
  2479. if (!committedWorkspaceIds.has(change.key)) return
  2480. // Existing-entity table writes are complete attach/touch commits.
  2481. // A new entity's first put waits for the global registry write above.
  2482. queue.push(frame({
  2483. type: 'host/workspace-changed',
  2484. workspace: changedWorkspaceView(change.key, change.value),
  2485. }))
  2486. }),
  2487. ctx.on('commands/change', () => {
  2488. queue.push(frame({ type: 'host/commands-changed' }))
  2489. }),
  2490. ctx.on('settings/document-updated', (ns) => {
  2491. // The RAW-section event, not the resolved one: a field going from
  2492. // inherited to overridden leaves the resolved value equal, and a
  2493. // configuration client still has to re-read (its held revision is
  2494. // stale, and the field's meaning changed).
  2495. const name = String(ns)
  2496. queue.push(frame({ type: 'host/settings-changed', ns: name }))
  2497. // A provider's own settings carry its model catalog and endpoint,
  2498. // so a change there invalidates the model list even when the route
  2499. // set is untouched — `llm/adapters-updated` alone misses it.
  2500. if (modelProviderNamespaces().has(name)) queue.push(frame({ type: 'host/models-changed' }))
  2501. }),
  2502. ctx.on('credentials/updated', (ref) => {
  2503. queue.push(frame({ type: 'host/credentials-changed', ref: String(ref) }))
  2504. }),
  2505. ctx.on('llm/adapters-updated', () => {
  2506. queue.push(frame({ type: 'host/models-changed' }))
  2507. }),
  2508. ]
  2509. return queue.iterate(signal, () => { for (const dispose of disposers) dispose() })
  2510. },
  2511. },
  2512. respond(message: ClientResponse): Promise<RpcReceipt> {
  2513. // Route by the echoed rpcId (the wire correlation): approvals first,
  2514. // then questions — the two registries share one id space of UUIDs.
  2515. const approval = pendingApprovals.get(message.rpcId)
  2516. if (approval !== undefined) {
  2517. if (!message.result.ok) return Promise.resolve({ accepted: false, reason: 'bad-response' })
  2518. const parsed = approvalResponsePayloadSchema.safeParse(message.result.value)
  2519. // The payload's audit correlation must match the entry the rpcId routed
  2520. // to — a mismatched answer is malformed, not merely late.
  2521. if (!parsed.success || parsed.data.approvalId !== approval.approvalId || parsed.data.sessionId !== approval.sessionId) {
  2522. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  2523. }
  2524. approval.resolve(parsed.data.outcome)
  2525. return Promise.resolve({ accepted: true })
  2526. }
  2527. const pending = pendingQuestions.get(message.rpcId)
  2528. if (pending === undefined) return Promise.resolve({ accepted: false, reason: 'not-pending' })
  2529. if (!message.result.ok) {
  2530. if (message.result.error.code !== 'cancelled') {
  2531. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  2532. }
  2533. claimQuestion(pending, 'cancelled')
  2534. pending.reject(new UserInteractionError(
  2535. 'the user cancelled ask_user_question', 'ASK_CANCELLED'))
  2536. return Promise.resolve({ accepted: true })
  2537. }
  2538. const parsed = questionResponsePayloadSchema.safeParse(message.result.value)
  2539. if (!parsed.success) {
  2540. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  2541. }
  2542. const payload: QuestionResponsePayload = {
  2543. sessionId: parsed.data.sessionId,
  2544. answer: {
  2545. answers: parsed.data.answer.answers.map(answer => ({
  2546. id: answer.id,
  2547. selected: answer.selected,
  2548. ...(answer.custom === undefined ? {} : { custom: answer.custom }),
  2549. })),
  2550. },
  2551. }
  2552. if (!matchesQuestions(payload, pending)) {
  2553. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  2554. }
  2555. claimQuestion(pending, 'answered')
  2556. pending.resolve(payload.answer)
  2557. return Promise.resolve({ accepted: true })
  2558. },
  2559. }
  2560. }