api-proxy.ts 75 KB

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