api-proxy.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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, AgentMessage, AgentMessageId, AgentStatus,
  12. } from '@deepseek-ai/dsh-agent'
  13. import { ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  14. import { errorChain } from '@deepseek-ai/dsh-llm'
  15. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  16. import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId, TodoItem } from '@deepseek-ai/dsh-session'
  17. import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
  18. import { foldSessionTitle } from '@deepseek-ai/dsh-session-title'
  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, HistoryEntry, HostFrame, ModelCatalogFailure, ModelProviderGroup, ModelReasoning,
  28. MuxFrame, QuestionResponsePayload, SessionSummary, ToolEventView,
  29. WorkspaceId, WorkspaceView,
  30. } from './api/index.ts'
  31. // Type-only edges: resolve `ctx.get('commands')`, the `commands/change` event, and `ctx.get('skills')`.
  32. import type {} from '@deepseek-ai/dsh-commands'
  33. import type {} from '@deepseek-ai/dsh-skill'
  34. import { questionResponsePayloadSchema } from './api/questions.schema.ts'
  35. import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts'
  36. import { RpcId } from './api/rpc.ts'
  37. import type {
  38. AskUserQuestionAnswer, AskUserQuestionItem, AskUserQuestionRequest,
  39. } from '@deepseek-ai/dsh-user-interaction'
  40. import { UserInteractionError } from '@deepseek-ai/dsh-user-interaction'
  41. import { pickNativeDirectory } from './native-directory-picker.ts'
  42. /** Page size when history is called without maxMessages. */
  43. const DEFAULT_MAX_MESSAGES = 50
  44. /** Surface message event types (the pagination counting unit). */
  45. const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message'])
  46. /**
  47. * Message-boundary pagination: count maxMessages surface messages backwards from
  48. * the window tail; the cut is the starting seq of the oldest message group
  49. * (chunks group via sourceEventSeqs — never cut mid-message). The tail page
  50. * naturally includes the in-progress partial.
  51. */
  52. function paginate(
  53. events: readonly SessionEvent[],
  54. beforeSeq: number | undefined,
  55. maxMessages: number,
  56. ): { events: SessionEvent[]; hasMore: boolean } {
  57. const window = beforeSeq === undefined ? [...events] : events.filter(event => event.seq < beforeSeq)
  58. let count = 0
  59. let cut = 0
  60. for (let i = window.length - 1; i >= 0; i--) {
  61. const event = window[i] as SessionEvent
  62. if (!MESSAGE_TYPES.has(event.type)) continue
  63. count++
  64. const sources = (event as { sourceEventSeqs?: number[] }).sourceEventSeqs
  65. const groupStart = sources !== undefined && sources.length > 0 ? Math.min(event.seq, ...sources) : event.seq
  66. if (count >= maxMessages) {
  67. cut = groupStart
  68. break
  69. }
  70. }
  71. const page = window.filter(event => event.seq >= cut)
  72. return { events: page, hasMore: cut > 0 }
  73. }
  74. /** Wrap an ok result echoing the request's rpcId. */
  75. function ok<T>(request: RpcRequest<unknown>, value: T): RpcResponse<T> {
  76. return { rpcId: request.rpcId, result: { ok: true, value } }
  77. }
  78. /** Wrap an error result echoing the request's rpcId. */
  79. function err<T>(request: RpcRequest<unknown>, error: RpcError): RpcResponse<T> {
  80. return { rpcId: request.rpcId, result: { ok: false, error } }
  81. }
  82. /** Simple async queue: core callbacks push, the AsyncIterable pulls; abort/return cleans up. */
  83. class FrameQueue<F> {
  84. private buffer: F[] = []
  85. private waiter: (() => void) | undefined
  86. private done = false
  87. push(item: F): void {
  88. if (this.done) return
  89. this.buffer.push(item)
  90. this.waiter?.()
  91. }
  92. end(): void {
  93. this.done = true
  94. this.waiter?.()
  95. }
  96. async *iterate(signal: AbortSignal, cleanup: () => void): AsyncGenerator<F> {
  97. const onAbort = (): void => { this.end() }
  98. signal.addEventListener('abort', onAbort, { once: true })
  99. try {
  100. while (true) {
  101. while (this.buffer.length > 0) yield this.buffer.shift() as F
  102. if (this.done || signal.aborted) return
  103. await new Promise<void>((resolve) => { this.waiter = resolve })
  104. this.waiter = undefined
  105. }
  106. } finally {
  107. signal.removeEventListener('abort', onAbort)
  108. cleanup()
  109. }
  110. }
  111. }
  112. /**
  113. * Server-side frame mint: pure pushes get a fresh rpcId per frame (stable ids
  114. * for answerable frames belong to the approval/question registry, absent in
  115. * this minimal version).
  116. */
  117. function frame<F>(payload: F): RpcRequest<F> {
  118. return { rpcId: RpcId(randomUUID()), payload }
  119. }
  120. type SessionTitleFrame = Extract<MuxFrame, { type: 'session/title' }>
  121. /** Project the latest durable title without exposing title-generation policy. */
  122. function titleFrame(session: Session): SessionTitleFrame | undefined {
  123. const title = foldSessionTitle(session.events)
  124. if (title === undefined) return undefined
  125. return {
  126. type: 'session/title',
  127. sessionId: session.id,
  128. title: title.title,
  129. eventSeq: title.eventSeq,
  130. updatedAt: title.updatedAt,
  131. }
  132. }
  133. /** Queue the subscription baseline followed by its optional title snapshot. */
  134. function subscribeSession(queue: FrameQueue<RpcRequest<MuxFrame>>, session: Session): void {
  135. queue.push(frame({ type: 'session/subscribed', sessionId: session.id, lastSeq: session.seq - 1 }))
  136. const title = titleFrame(session)
  137. if (title !== undefined) queue.push(frame(title))
  138. }
  139. /** SessionSummary projection for attached (in-memory) sessions. */
  140. function summarize(session: Session, running: boolean): SessionSummary {
  141. return {
  142. sessionId: session.id,
  143. updatedAt: session.events.at(-1)?.time ?? session.header.createdAt,
  144. running,
  145. blank: session.events.length === 0,
  146. ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession },
  147. ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd },
  148. }
  149. }
  150. /**
  151. * SessionSummary projection for cold (persisted, unattached) sessions.
  152. * updatedAt is the log file's mtime; backends without a per-session file
  153. * (locate() undefined) fall back to the header's createdAt.
  154. */
  155. async function summarizeCold(persistence: SessionPersistence, meta: SessionHeader): Promise<SessionSummary> {
  156. let updatedAt = meta.createdAt
  157. const location = persistence.locate(meta)
  158. if (location !== undefined) {
  159. try {
  160. updatedAt = (await stat(location.path)).mtimeMs
  161. } catch {
  162. // The log vanished between list() and stat() (concurrent cleanup); createdAt stands in.
  163. }
  164. }
  165. return {
  166. sessionId: meta.id,
  167. updatedAt,
  168. running: false,
  169. // Lazy persistence keeps never-appended sessions out of list(): a cold
  170. // session necessarily has events, so blank is constantly false here.
  171. blank: false,
  172. ...meta.parentSession === undefined ? {} : { parentSessionId: meta.parentSession },
  173. /* v8 ignore next -- the empty arm needs a cwd-less meta, but list()
  174. filters those out (legacy logs are not served); the conditional mirrors
  175. summarize() shape. */
  176. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  177. }
  178. }
  179. /** Resolved Host routing and project-directory defaults consumed by the API implementation. */
  180. export interface ApiProxyDefaults {
  181. provider: string
  182. model: string
  183. /** Default project directory for new sessions whose create request carries no cwd. */
  184. cwd: string
  185. /** Parent directory for name-created workspaces. */
  186. workspaceRoot: string
  187. /** Native single-directory picker; injectable for carrier tests. */
  188. pickDirectory?: (signal: AbortSignal) => Promise<string | null>
  189. }
  190. /** The tool/call payload fields the presenter path reads. */
  191. interface ToolCallData { callId: string; name: string; arguments: string }
  192. /** The tool/result payload fields the presenter path reads. */
  193. interface ToolResultData { callId: string; content: ContentBlock[]; isError: boolean; meta?: JsonValue }
  194. /** One host-owned question wait, addressed by the stable server-request id. */
  195. interface PendingQuestion {
  196. rpcId: RpcId
  197. sessionId: SessionId
  198. questions: AskUserQuestionItem[]
  199. resolve: (answer: AskUserQuestionAnswer) => void
  200. reject: (error: UserInteractionError) => void
  201. signal?: AbortSignal
  202. onAbort?: () => void
  203. }
  204. /** Validate one answer batch against the exact question request it resolves. */
  205. function matchesQuestions(payload: QuestionResponsePayload, pending: PendingQuestion): boolean {
  206. if (payload.sessionId !== pending.sessionId) return false
  207. const answers = payload.answer.answers
  208. if (answers.length !== pending.questions.length) return false
  209. return answers.every((answer, index) => {
  210. const question = pending.questions[index] as AskUserQuestionItem
  211. if (answer.id !== question.id) return false
  212. if (new Set(answer.selected).size !== answer.selected.length) return false
  213. const custom = answer.custom?.trim()
  214. if (custom !== undefined && custom === '') return false
  215. if (custom !== undefined && answer.selected.length > 0) return false
  216. if (question.multiSelect !== true && answer.selected.length > 1) return false
  217. const labels = new Set(question.options?.map(option => option.label) ?? [])
  218. return answer.selected.every(label => labels.has(label))
  219. })
  220. }
  221. /**
  222. * Compute the render intent for a tool/call or tool/result event through the
  223. * presenters registered at this moment; every other event type gets none. A
  224. * result's presenter needs its call's parsed args — `argsFor` supplies them
  225. * (live: the per-session call table; history: an in-page backscan), returning
  226. * undefined when the pairing is unavailable (e.g. the call fell off the page),
  227. * which soft-falls to no view. Presenter or JSON.parse throws also soft-fall:
  228. * the client's documented default (generic JSON card) covers every miss.
  229. */
  230. function viewFor(ctx: Context, event: SessionEvent, argsFor: (callId: string) => unknown): ToolEventView | undefined {
  231. try {
  232. if (event.type === 'tool/call') {
  233. const { name, arguments: raw } = event.data as ToolCallData
  234. const view = ctx.tools.get(name)?.presentCall?.(JSON.parse(raw))
  235. return view === undefined ? undefined : { for: 'call', view }
  236. }
  237. if (event.type === 'tool/result') {
  238. const { callId, content, isError, meta } = event.data as ToolResultData
  239. const call = argsFor(callId) as { name: string; args: unknown } | undefined
  240. if (call === undefined) return undefined
  241. const view = ctx.tools.get(call.name)?.presentResult?.(call.args, { content, isError, ...meta === undefined ? {} : { meta } })
  242. return view === undefined ? undefined : { for: 'result', view }
  243. }
  244. } catch (error: unknown) {
  245. // A throwing presenter (or unparseable arguments) must not break delivery;
  246. // the event still ships, just without a view.
  247. console.error(`api-proxy: presenter failed for ${event.type}, falling back to generic: ${String(error)}`)
  248. }
  249. return undefined
  250. }
  251. /**
  252. * Resolve a tool/result's call pairing by scanning a window of events backwards
  253. * for the matching tool/call. Used by the history path (the page is the
  254. * window — a cross-page pairing soft-falls to no view) and by live-path table
  255. * misses after a reconnect-eviction.
  256. */
  257. function backscanArgs(events: readonly SessionEvent[], callId: string): { name: string; args: unknown } | undefined {
  258. for (let i = events.length - 1; i >= 0; i--) {
  259. const event = events[i] as SessionEvent
  260. if (event.type !== 'tool/call') continue
  261. const data = event.data as ToolCallData
  262. if (data.callId !== callId) continue
  263. try {
  264. return { name: data.name, args: JSON.parse(data.arguments) }
  265. } catch {
  266. // Unparseable stored arguments: same soft-fall as a live parse failure.
  267. return undefined
  268. }
  269. }
  270. return undefined
  271. }
  272. /** Current todo projection: the latest `todo/write` over the full log (whole-list replace ⇒ last write wins); undefined when none. */
  273. function backscanTodos(events: readonly SessionEvent[]): TodoItem[] | undefined {
  274. for (let i = events.length - 1; i >= 0; i--) {
  275. const event = events[i]
  276. if (event !== undefined && event.type === 'todo/write') return event.data.todos
  277. }
  278. return undefined
  279. }
  280. /**
  281. * Thrown by the cold-resume path when the id names no servable session
  282. * (absent from the store, or a pre-project legacy log without a cwd).
  283. */
  284. class SessionNotFound extends Error {}
  285. /** Requested identity already belongs to a session with another project cwd. */
  286. class SessionCwdConflict extends Error {
  287. constructor(
  288. readonly sessionId: SessionId,
  289. readonly requestedCwd: string,
  290. readonly existingCwd: string | undefined,
  291. ) {
  292. super(
  293. `session "${sessionId}" already exists with cwd ${JSON.stringify(existingCwd)}; `
  294. + `requested ${JSON.stringify(requestedCwd)}`,
  295. )
  296. }
  297. }
  298. /** Host failed before the registry could adopt a name-created directory. */
  299. class WorkspaceDirectoryCreationError extends Error {}
  300. /** Shared workspace-not-found error response of the workspace.* mutation rows. */
  301. function workspaceNotFound<T>(request: RpcRequest<unknown>, workspaceId: string): RpcResponse<T> {
  302. return err(request, {
  303. code: 'workspace-not-found',
  304. message: `workspace "${workspaceId}" not found`,
  305. details: { workspaceId },
  306. })
  307. }
  308. /** Wire projection of one workspace entity (the workspace.* value row). */
  309. function workspaceView(workspace: Workspace): WorkspaceView {
  310. return {
  311. workspaceId: workspace.id,
  312. path: workspace.path,
  313. title: workspace.title,
  314. sessionIds: [...workspace.sessionIds],
  315. createdAt: workspace.createdAt,
  316. updatedAt: workspace.updatedAt,
  317. }
  318. }
  319. /** Wire projection of the durable record carried by `domain/changed`. */
  320. function changedWorkspaceView(workspaceId: string, value: unknown): WorkspaceView {
  321. const record: WorkspaceRecord = workspaceRecord.parse(value)
  322. return {
  323. workspaceId: workspaceId as WorkspaceId,
  324. path: record.path,
  325. title: record.title,
  326. sessionIds: [...record.sessionIds],
  327. createdAt: record.createdAt,
  328. updatedAt: record.updatedAt,
  329. }
  330. }
  331. /**
  332. * Implement ApiProxy over a composed host context.
  333. * @param ctx - a context with the Host spine and Workspace registry mounted.
  334. * @param defaults - host routing and project-directory defaults.
  335. * @returns the ApiProxy implementation.
  336. */
  337. export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiProxy {
  338. const agentOptions = { provider: defaults.provider, model: defaults.model }
  339. type WebLlmTargetRef = AgentLlmTargetRef & { current: AgentLlmTarget }
  340. const targets = new WeakMap<Agent, WebLlmTargetRef>()
  341. /** Implicit resume of cold sessions, deduplicating concurrent calls (follows the jsonrpc sessionCreations precedent). */
  342. const resumes = new Map<SessionId, Promise<Agent>>()
  343. /** Client-chosen identity creation/resume, deduplicated across concurrent retries. */
  344. const sessionCreations = new Map<SessionId, Promise<Agent>>()
  345. /** Serializes path ownership checks with record creation across spellings. */
  346. let workspaceCreationChain = Promise.resolve()
  347. const pendingQuestions = new Map<RpcId, PendingQuestion>()
  348. const muxQueues = new Set<FrameQueue<RpcRequest<MuxFrame>>>()
  349. /**
  350. * Install or return the session-local target that prompt assembly snapshots.
  351. * Seed order: latest logged request/header, else the host default routing.
  352. * There is no create-time per-session override tier on this wire — if one
  353. * returns (a create-options contribution), it must fold in between the two.
  354. */
  355. function targetFor(agent: Agent): WebLlmTargetRef {
  356. const installed = targets.get(agent)
  357. if (installed !== undefined) return installed
  358. const logged = agent.session.requestHeader()?.config
  359. const target: WebLlmTargetRef = {
  360. current: logged === undefined
  361. ? { provider: defaults.provider, model: defaults.model }
  362. : {
  363. provider: logged.provider,
  364. model: logged.model,
  365. ...logged.reasoningEffort === undefined
  366. ? {}
  367. : { reasoningEffort: logged.reasoningEffort },
  368. },
  369. assembled: undefined,
  370. }
  371. installAgentLlmTarget(agent.ctx, target)
  372. targets.set(agent, target)
  373. return target
  374. }
  375. /** Pre-publication setup used by both fresh and resumed Web agents. */
  376. function installTarget(agentCtx: Context): void {
  377. const agent = agentCtx.agent
  378. if (agent === undefined) throw new Error('api-proxy: agent setup has no scoped agent')
  379. targetFor(agent)
  380. }
  381. /** Send one transient frame to every connected mux consumer. */
  382. function broadcast(payload: MuxFrame): void {
  383. const envelope = frame(payload)
  384. for (const queue of muxQueues) queue.push(envelope)
  385. }
  386. /**
  387. * Per-session inbox mirror serving the mux-open queue snapshot (the same
  388. * refresh-recovery baseline as pending questions). Keyed by the stable
  389. * AgentMessageId: every enqueued id receives exactly one terminal
  390. * `agent/inbox/dequeue` OR `agent/inbox/discard` (the inbox contract), so
  391. * the mirror needs no consumption heuristics or sweeps beyond disposal.
  392. */
  393. const queuedMirror = new Map<SessionId, Map<AgentMessageId, { message: AgentMessage; steering: boolean }>>()
  394. ctx.effect(() => {
  395. const retire = (agent: Agent, id: AgentMessageId): void => {
  396. const entries = queuedMirror.get(agent.id)
  397. if (entries === undefined) return
  398. entries.delete(id)
  399. if (entries.size === 0) queuedMirror.delete(agent.id)
  400. }
  401. const disposers = [
  402. ctx.on('agent/inbox/enqueue', (agent: Agent, message: AgentMessage, placement) => {
  403. let entries = queuedMirror.get(agent.id)
  404. if (entries === undefined) {
  405. entries = new Map<AgentMessageId, { message: AgentMessage; steering: boolean }>()
  406. queuedMirror.set(agent.id, entries)
  407. }
  408. const steering = placement === 'steering'
  409. entries.set(message.id, { message, steering })
  410. broadcast({
  411. type: 'session/queued',
  412. sessionId: agent.id,
  413. content: message.content,
  414. source: message.source,
  415. steering,
  416. })
  417. }),
  418. ctx.on('agent/inbox/dequeue', (agent: Agent, message: AgentMessage) => {
  419. retire(agent, message.id)
  420. }),
  421. ctx.on('agent/inbox/discard', (agent: Agent, messages: AgentMessage[]) => {
  422. for (const message of messages) retire(agent, message.id)
  423. }),
  424. ctx.on('session/disposed', (session: Session) => {
  425. queuedMirror.delete(session.id)
  426. }),
  427. ]
  428. return () => { for (const dispose of disposers) dispose() }
  429. }, 'api-proxy: queued mirror')
  430. /** Remove a wait before settling it: synchronous deletion makes the first claimant win. */
  431. function claimQuestion(pending: PendingQuestion, outcome: 'answered' | 'cancelled'): void {
  432. pendingQuestions.delete(pending.rpcId)
  433. if (pending.signal !== undefined && pending.onAbort !== undefined) {
  434. pending.signal.removeEventListener('abort', pending.onAbort)
  435. }
  436. broadcast({
  437. type: 'question/resolved', sessionId: pending.sessionId,
  438. questionRpcId: pending.rpcId, outcome,
  439. })
  440. }
  441. const disposeProvider = ctx.userInteraction.registerProvider({
  442. ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> {
  443. const sessionId = request.agent?.id
  444. if (sessionId === undefined) {
  445. return Promise.reject(new UserInteractionError(
  446. 'web user interaction requires an agent-owned session', 'ASK_MISSING_AGENT'))
  447. }
  448. return new Promise<AskUserQuestionAnswer>((resolve, reject) => {
  449. const rpcId = RpcId(randomUUID())
  450. const pending: PendingQuestion = {
  451. rpcId, sessionId, questions: request.questions, resolve, reject,
  452. ...(request.signal === undefined ? {} : { signal: request.signal }),
  453. }
  454. const onAbort = (): void => {
  455. claimQuestion(pending, 'cancelled')
  456. reject(new UserInteractionError(
  457. 'ask_user_question was aborted before the user answered', 'ASK_ABORTED'))
  458. }
  459. pending.onAbort = onAbort
  460. pendingQuestions.set(rpcId, pending)
  461. request.signal?.addEventListener('abort', onAbort, { once: true })
  462. const envelope: RpcRequest<MuxFrame> = {
  463. rpcId,
  464. payload: { type: 'question/requested', sessionId, questions: request.questions },
  465. }
  466. for (const queue of muxQueues) queue.push(envelope)
  467. })
  468. },
  469. })
  470. ctx.effect(() => () => {
  471. disposeProvider()
  472. for (const pending of [...pendingQuestions.values()]) {
  473. claimQuestion(pending, 'cancelled')
  474. pending.reject(new UserInteractionError(
  475. 'web user-interaction provider was disposed', 'ASK_ABORTED'))
  476. }
  477. }, 'api-proxy: user-interaction provider')
  478. /**
  479. * Gate the cold path on the store: an id absent from it, or naming a legacy
  480. * log without a cwd (pre-release stance: not served, no compatibility), is
  481. * not-found before any resume is attempted. With the gate passed, a later
  482. * resume failure is genuinely internal. No persistence configured skips the
  483. * gate — resume itself then fails loud with its own diagnostic.
  484. */
  485. async function assertServable(sessionId: SessionId): Promise<void> {
  486. const persistence = ctx.get('sessionPersistence')
  487. if (persistence === undefined) return
  488. const meta = (await persistence.list()).find(m => m.id === sessionId)
  489. if (meta === undefined || meta.cwd === undefined) throw new SessionNotFound(`session "${sessionId}" not found`)
  490. }
  491. async function agentFor(sessionId: SessionId): Promise<{ agent: Agent } | { error: RpcError }> {
  492. const live = ctx.agents.get(sessionId)
  493. if (live !== undefined) return { agent: live }
  494. let resume = resumes.get(sessionId)
  495. if (resume === undefined) {
  496. resume = (async () => {
  497. try {
  498. await assertServable(sessionId)
  499. const handle = await ctx.agents.resume({
  500. resumeSessionId: sessionId,
  501. agentOptions,
  502. setup: installTarget,
  503. })
  504. return handle.agent
  505. } finally {
  506. resumes.delete(sessionId)
  507. }
  508. })()
  509. resumes.set(sessionId, resume)
  510. }
  511. try {
  512. return { agent: await resume }
  513. } catch (error: unknown) {
  514. if (error instanceof SessionNotFound) {
  515. return { error: { code: 'session-not-found', message: error.message, details: { sessionId } } }
  516. }
  517. // The internal details slot is contractually {}; the reason rides the message.
  518. return { error: { code: 'internal', message: `resume failed for session "${sessionId}": ${String(error)}`, details: {} } }
  519. }
  520. }
  521. /** Resolve one requested identity to a live agent, creating or resuming it once. */
  522. async function ensureSession(sessionId: SessionId, cwd: string, checkPersistedIdentity: boolean): Promise<Agent> {
  523. let creation = sessionCreations.get(sessionId)
  524. if (creation === undefined) {
  525. creation = (async () => {
  526. const live = ctx.agents.get(sessionId)
  527. if (live !== undefined) return live
  528. const persistence = checkPersistedIdentity ? ctx.get('sessionPersistence') : undefined
  529. const stored = persistence === undefined
  530. ? undefined
  531. : (await persistence.list()).find(header => header.id === sessionId)
  532. if (stored !== undefined) {
  533. if (stored.cwd !== cwd) {
  534. throw new SessionCwdConflict(sessionId, cwd, stored.cwd)
  535. }
  536. return (await ctx.agents.resume({
  537. resumeSessionId: sessionId,
  538. agentOptions,
  539. setup: installTarget,
  540. })).agent
  541. }
  542. try {
  543. await mkdir(cwd, { recursive: true })
  544. } catch (error: unknown) {
  545. throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
  546. }
  547. return (await ctx.agents.create({
  548. sessionId,
  549. agentOptions,
  550. meta: { cwd },
  551. setup: installTarget,
  552. })).agent
  553. })().catch((error: unknown) => {
  554. // Another Host entry path may have published the same identity while
  555. // this operation crossed an asynchronous persistence/filesystem step.
  556. const live = ctx.agents.get(sessionId)
  557. if (live !== undefined) return live
  558. throw error
  559. }).finally(() => {
  560. sessionCreations.delete(sessionId)
  561. })
  562. sessionCreations.set(sessionId, creation)
  563. }
  564. const agent = await creation
  565. if (agent.session.header.cwd !== cwd) {
  566. throw new SessionCwdConflict(sessionId, cwd, agent.session.header.cwd)
  567. }
  568. return agent
  569. }
  570. /** Resolve or create one path while holding the Host's workspace-create chain. */
  571. function ensureWorkspace(
  572. path: string,
  573. title: string | undefined,
  574. rejectExistingName = false,
  575. createDirectory = false,
  576. ): Promise<{ workspace: Workspace; created: boolean }> {
  577. const operation = workspaceCreationChain.then(async () => {
  578. if (rejectExistingName && title !== undefined
  579. && ctx.workspace.list().some(workspace => workspace.title === title)) {
  580. throw new WorkspaceNameConflictError(title)
  581. }
  582. if (createDirectory) {
  583. try {
  584. await mkdir(path, { recursive: true })
  585. } catch (error: unknown) {
  586. throw new WorkspaceDirectoryCreationError(
  587. `failed to create workspace directory "${path}": ${String(error)}`,
  588. )
  589. }
  590. }
  591. const existing = await ctx.workspace.resolveByPath(path)
  592. if (existing !== undefined) return { workspace: existing, created: false }
  593. return { workspace: await ctx.workspace.create(path, title), created: true }
  594. })
  595. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  596. return operation
  597. }
  598. return {
  599. sessions: {
  600. // Attached sessions summarize from memory; persisted-but-unattached (cold)
  601. // sessions merge in from the persistence store so history survives restarts.
  602. // Legacy logs without a cwd (pre-project stance) are not served — every
  603. // session now records its project at create time.
  604. async list(request) {
  605. const items = ctx.sessions.list().map((session) => {
  606. const agent = ctx.agents.get(session.id)
  607. return summarize(session, agent?.status === 'running')
  608. })
  609. const attached = new Set(items.map(item => item.sessionId))
  610. const persistence = ctx.get('sessionPersistence')
  611. if (persistence !== undefined) {
  612. const cold = (await persistence.list()).filter(meta => !attached.has(meta.id) && meta.cwd !== undefined)
  613. items.push(...await Promise.all(cold.map(meta => summarizeCold(persistence, meta))))
  614. }
  615. items.sort((a, b) => b.updatedAt - a.updatedAt)
  616. return ok(request, { items })
  617. },
  618. async create(request) {
  619. const sessionId = request.payload.sessionId ?? `session-${randomUUID()}` as SessionId
  620. let workspace: Workspace | undefined
  621. if (request.payload.workspaceId !== undefined) {
  622. workspace = ctx.workspace.get(brandWorkspaceId(request.payload.workspaceId))
  623. if (workspace === undefined) {
  624. return err(request, {
  625. code: 'workspace-not-found',
  626. message: `workspace "${request.payload.workspaceId}" not found`,
  627. details: { workspaceId: request.payload.workspaceId },
  628. })
  629. }
  630. }
  631. const cwd = workspace?.path ?? request.payload.cwd ?? defaults.cwd
  632. try {
  633. await ensureSession(sessionId, cwd, request.payload.sessionId !== undefined)
  634. } catch (error: unknown) {
  635. if (error instanceof SessionCwdConflict) {
  636. return err(request, {
  637. code: 'session-conflict',
  638. message: error.message,
  639. details: {
  640. sessionId: error.sessionId,
  641. requestedCwd: error.requestedCwd,
  642. ...error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd },
  643. },
  644. })
  645. }
  646. return err(request, {
  647. code: 'internal',
  648. message: `failed to create session "${sessionId}": ${String(error)}`,
  649. details: {},
  650. })
  651. }
  652. if (workspace !== undefined) {
  653. try {
  654. await workspace.attachSession(sessionId)
  655. } catch (error: unknown) {
  656. return err(request, {
  657. code: 'workspace-attach-failed',
  658. message: `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`,
  659. details: { sessionId, workspaceId: workspace.id },
  660. })
  661. }
  662. }
  663. return ok(request, { sessionId })
  664. },
  665. async history(request) {
  666. const { sessionId, beforeSeq, maxMessages } = request.payload
  667. const found = await agentFor(sessionId)
  668. if ('error' in found) return err(request, found.error)
  669. const page = paginate(found.agent.session.events, beforeSeq, maxMessages ?? DEFAULT_MAX_MESSAGES)
  670. // Views are computed against the registry at pagination time; result
  671. // pairing scans within the page only (message-boundary pagination keeps
  672. // a call and its result on one page — a cross-page miss soft-falls).
  673. const entries: HistoryEntry[] = page.events.map((event) => {
  674. const view = viewFor(ctx, event, callId => backscanArgs(page.events, callId))
  675. return { event, ...view === undefined ? {} : { view } }
  676. })
  677. // Tail page carries the session-level todo projection over the FULL
  678. // log (the page window may not contain the last todo/write; a paged
  679. // client cannot reconstruct session-level state from it).
  680. const todos = beforeSeq === undefined ? backscanTodos(found.agent.session.events) : undefined
  681. return ok(request, { events: entries, hasMore: page.hasMore, ...todos === undefined ? {} : { todos } })
  682. },
  683. async models(request) {
  684. const { sessionId } = request.payload
  685. const found = await agentFor(sessionId)
  686. if ('error' in found) return err(request, found.error)
  687. const current = targetFor(found.agent).current
  688. const catalog = await Promise.all(ctx.llm.listProviders().map(async (provider) => {
  689. try {
  690. const advertised = await ctx.llm.listModels(provider.id)
  691. const models = [...advertised]
  692. if (
  693. provider.id === current.provider
  694. && !models.some(model => model.id === current.model)
  695. ) {
  696. models.push({
  697. provider: provider.id,
  698. id: current.model,
  699. name: current.model,
  700. })
  701. }
  702. const entries = await Promise.all(models.map(async (model) => {
  703. const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id)
  704. const reasoning: ModelReasoning | undefined = resolved.reasoning === undefined
  705. ? undefined
  706. : {
  707. efforts: resolved.reasoning.efforts.map(effort => ({
  708. id: effort.id,
  709. name: effort.name,
  710. ...effort.description === undefined
  711. ? {}
  712. : { description: effort.description },
  713. })),
  714. ...resolved.reasoning.defaultEffort === undefined
  715. ? {}
  716. : { defaultEffort: resolved.reasoning.defaultEffort },
  717. }
  718. return {
  719. id: model.id,
  720. name: model.name,
  721. ...model.description === undefined ? {} : { description: model.description },
  722. ...provider.id === current.provider
  723. && model.id === current.model
  724. && !advertised.some(candidate => candidate.id === current.model)
  725. ? { unlisted: true as const }
  726. : {},
  727. ...reasoning === undefined ? {} : { reasoning },
  728. }
  729. }))
  730. const group: ModelProviderGroup = {
  731. id: provider.id,
  732. name: provider.name,
  733. models: entries,
  734. }
  735. return { kind: 'group' as const, group }
  736. } catch (error: unknown) {
  737. const failure: ModelCatalogFailure = {
  738. id: provider.id,
  739. name: provider.name,
  740. message: error instanceof Error ? error.message : String(error),
  741. }
  742. return { kind: 'failure' as const, failure }
  743. }
  744. }))
  745. const groups = catalog.flatMap(item => item.kind === 'group' ? [item.group] : [])
  746. const failures = catalog.flatMap(item => item.kind === 'failure' ? [item.failure] : [])
  747. return ok(request, {
  748. current: { ...current },
  749. groups: groups.filter(group => group.models.length > 0),
  750. failures,
  751. })
  752. },
  753. async selectModel(request) {
  754. const { sessionId, provider, model, reasoningEffort } = request.payload
  755. const found = await agentFor(sessionId)
  756. if ('error' in found) return err(request, found.error)
  757. try {
  758. const resolved = await ctx.llm.resolveCallConfig({
  759. provider,
  760. model,
  761. ...reasoningEffort === undefined
  762. ? {}
  763. : { reasoningEffort: ReasoningEffortId(reasoningEffort) },
  764. })
  765. const selected: AgentLlmTarget = {
  766. provider: resolved.provider,
  767. model: resolved.model,
  768. ...resolved.reasoningEffort === undefined
  769. ? {}
  770. : { reasoningEffort: resolved.reasoningEffort },
  771. }
  772. targetFor(found.agent).current = selected
  773. return ok(request, { selected: { ...selected } })
  774. } catch (error: unknown) {
  775. return err(request, {
  776. code: 'model-unavailable',
  777. message: error instanceof Error ? error.message : String(error),
  778. details: { provider, model },
  779. })
  780. }
  781. },
  782. async prompt(request) {
  783. const { sessionId, mode, content } = request.payload
  784. const found = await agentFor(sessionId)
  785. if ('error' in found) return err(request, found.error)
  786. const agent = found.agent
  787. // The rpcId rides MessageSource into user/message (merge declaration in api/sessions.ts; provisional correlation).
  788. const source: MessageSource = { kind: 'user', rpcId: request.rpcId }
  789. try {
  790. if (mode === 'steer') agent.steer({ content, source })
  791. else agent.followup({ content, source })
  792. } catch (error: unknown) {
  793. // A synchronous throw from steer/followup means disposed or invalid input; surface as agent-busy with the reason attached.
  794. return err(request, { code: 'agent-busy', message: 'prompt rejected', details: { reason: String(error) } })
  795. }
  796. return ok(request, { accepted: true as const })
  797. },
  798. cancel(request) {
  799. const { sessionId } = request.payload
  800. const agent = ctx.agents.get(sessionId)
  801. if (agent === undefined) {
  802. return Promise.resolve(err(request, {
  803. code: 'session-not-found',
  804. message: `session "${sessionId}" not found (not attached)`,
  805. details: { sessionId },
  806. }))
  807. }
  808. agent.cancel({ kind: 'user' })
  809. return Promise.resolve(ok(request, { accepted: true as const }))
  810. },
  811. },
  812. workspace: {
  813. list(request) {
  814. return Promise.resolve(ok(request, { items: ctx.workspace.list().map(workspaceView) }))
  815. },
  816. // Exactly one of path/name arrives (schema refine). Existing-folder
  817. // adoption reuses its canonical path; create-by-name rejects a name
  818. // already present in the registry.
  819. async create(request) {
  820. const { payload } = request
  821. let path: string
  822. if (payload.name !== undefined) {
  823. const name = payload.name.trim()
  824. if (name === '' || name === '.' || name === '..' || /[/\\]/.test(name)) {
  825. return err(request, {
  826. code: 'workspace-invalid-path',
  827. message: `workspace name must be one non-empty path segment, got "${payload.name}"`,
  828. details: { path: payload.name },
  829. })
  830. }
  831. path = join(defaults.workspaceRoot, name)
  832. } else {
  833. path = payload.path as string
  834. }
  835. try {
  836. const name = payload.name?.trim()
  837. const { workspace, created } = await ensureWorkspace(
  838. path,
  839. name,
  840. name !== undefined,
  841. name !== undefined,
  842. )
  843. return ok(request, { workspace: workspaceView(workspace), created })
  844. } catch (error: unknown) {
  845. if (error instanceof WorkspaceNameConflictError) {
  846. return err(request, {
  847. code: 'workspace-name-conflict',
  848. message: error.message,
  849. details: { name: error.workspaceName },
  850. })
  851. }
  852. if (error instanceof WorkspaceDirectoryCreationError) {
  853. return err(request, { code: 'internal', message: error.message, details: {} })
  854. }
  855. // The registry rejects a path that does not resolve to an existing
  856. // directory (realpath ENOENT / not-a-directory) — the business
  857. // error of the typed-path flow, surfaced as a validation failure.
  858. return err(request, {
  859. code: 'workspace-invalid-path',
  860. message: `cannot create a workspace at "${path}": ${error instanceof Error ? error.message : String(error)}`,
  861. details: { path },
  862. })
  863. }
  864. },
  865. async rename(request) {
  866. const { payload } = request
  867. const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
  868. if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
  869. const title = payload.title.trim()
  870. // Uniqueness AND the same-title no-op both ride the create chain so
  871. // they observe the state left by earlier queued renames — checked
  872. // up front, a queued A→A could report success while an earlier A→B
  873. // still lands afterwards.
  874. const operation = workspaceCreationChain.then(async () => {
  875. if (title === workspace.title) return
  876. if (ctx.workspace.list().some(other => other.id !== workspace.id && other.title === title)) {
  877. throw new WorkspaceNameConflictError(title)
  878. }
  879. await workspace.setTitle(title)
  880. })
  881. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  882. try {
  883. await operation
  884. } catch (error: unknown) {
  885. if (error instanceof WorkspaceNameConflictError) {
  886. return err(request, {
  887. code: 'workspace-name-conflict',
  888. message: error.message,
  889. details: { name: error.workspaceName },
  890. })
  891. }
  892. throw error
  893. }
  894. return ok(request, { workspace: workspaceView(workspace) })
  895. },
  896. async delete(request) {
  897. const { workspaceId } = request.payload
  898. const operation = workspaceCreationChain.then(() =>
  899. ctx.workspace.delete(brandWorkspaceId(workspaceId)))
  900. workspaceCreationChain = operation.then(() => undefined, () => undefined)
  901. if (!await operation) return workspaceNotFound(request, workspaceId)
  902. return ok(request, { deleted: true as const })
  903. },
  904. async insertSessionBefore(request) {
  905. const { payload } = request
  906. const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
  907. if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
  908. try {
  909. await workspace.insertSessionBefore(payload.sessionId, payload.beforeSessionId)
  910. } catch (error: unknown) {
  911. // Only the entity's unaccounted-id rejection is the business code;
  912. // storage/durability failures propagate as internal errors.
  913. if (!(error instanceof WorkspaceMoveInvalidError)) throw error
  914. return err(request, {
  915. code: 'workspace-move-invalid',
  916. message: error.message,
  917. details: {
  918. workspaceId: payload.workspaceId,
  919. sessionId: payload.sessionId,
  920. ...payload.beforeSessionId === undefined ? {} : { beforeSessionId: payload.beforeSessionId },
  921. },
  922. })
  923. }
  924. return ok(request, { workspace: workspaceView(workspace) })
  925. },
  926. },
  927. host: {
  928. describe(request) {
  929. // TODO(step2): version should read apps/cli's package.json; placeholder for now.
  930. return Promise.resolve(ok(request, {
  931. version: '0.0.1',
  932. // Same source as session.create's fallback: the UI's default project
  933. // must match where an unspecified-cwd session actually lands.
  934. cwd: defaults.cwd,
  935. provider: defaults.provider,
  936. model: defaults.model,
  937. attachedSessions: ctx.agents.list().length,
  938. }))
  939. },
  940. async pickDirectory(request, signal) {
  941. try {
  942. const path = await (defaults.pickDirectory ?? pickNativeDirectory)(signal)
  943. return ok(request, { path })
  944. } catch (error: unknown) {
  945. if (signal.aborted) {
  946. return err(request, {
  947. code: 'cancelled',
  948. message: 'directory picker was aborted',
  949. details: {},
  950. })
  951. }
  952. return err(request, {
  953. code: 'internal',
  954. message: `directory picker failed: ${error instanceof Error ? error.message : String(error)}`,
  955. details: {},
  956. })
  957. }
  958. },
  959. },
  960. commands: {
  961. // Both methods address one session's agent (agentFor keeps its
  962. // resume-on-miss: clients only send a sessionId for a published
  963. // session, and resume restores an existing entity).
  964. async list(request) {
  965. // Missing service = the deployment omitted dsh-commands from its
  966. // composition, not an empty catalog: fail loud instead of serving [].
  967. const commands = ctx.get('commands')
  968. if (commands === undefined) {
  969. 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: {} })
  970. }
  971. const found = await agentFor(request.payload.sessionId)
  972. if ('error' in found) return err(request, found.error)
  973. return ok(request, { commands: commands.list(found.agent) })
  974. },
  975. async execute(request, signal) {
  976. const commands = ctx.get('commands')
  977. if (commands === undefined) {
  978. 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: {} })
  979. }
  980. const { sessionId, line } = request.payload
  981. const found = await agentFor(sessionId)
  982. if ('error' in found) return err(request, found.error)
  983. try {
  984. const result = await commands.execute(found.agent, line, signal)
  985. if (result === undefined) return ok(request, { matched: false })
  986. return ok(request, {
  987. matched: true,
  988. result: { kind: result.kind, ...result.text === undefined ? {} : { text: result.text } },
  989. })
  990. } catch (error: unknown) {
  991. if (signal.aborted) return err(request, { code: 'cancelled', message: 'command execution was aborted', details: {} })
  992. return err(request, { code: 'internal', message: `command failed: ${String(error)}`, details: {} })
  993. }
  994. },
  995. },
  996. skills: {
  997. // Skill lookup never touches the Agent registry: the session address
  998. // resolves to a canonical cwd from the host-resident session header, so
  999. // listing skills cannot create or resume an agent as a side effect.
  1000. async list(request) {
  1001. const { sessionId } = request.payload
  1002. const session = ctx.sessions.get(sessionId)
  1003. if (session === undefined) {
  1004. return err(request, {
  1005. code: 'session-not-found',
  1006. message: `session "${sessionId}" not found (not attached)`,
  1007. details: { sessionId },
  1008. })
  1009. }
  1010. if (session.header.cwd === undefined) {
  1011. // Every served session records its project at create time; a
  1012. // cwd-less header is a pre-project legacy log (not served).
  1013. return err(request, { code: 'internal', message: `session "${sessionId}" has no project cwd`, details: {} })
  1014. }
  1015. const cwd = session.header.cwd
  1016. // Same stance as the commands domain: a missing service means the
  1017. // deployment omitted dsh-skill from its composition, not an empty
  1018. // catalog. ctx.get also keeps this handler independent of the gateway
  1019. // plugin's inject list (an undeclared `ctx.skills` property read
  1020. // fails the reflect proxy).
  1021. const skillRegistry = ctx.get('skills')
  1022. if (skillRegistry === undefined) {
  1023. 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: {} })
  1024. }
  1025. try {
  1026. const skills = await skillRegistry.list({ cwd })
  1027. return ok(request, {
  1028. skills: skills.map(skill => ({
  1029. name: skill.name,
  1030. description: skill.description,
  1031. ...skill.whenToUse === undefined ? {} : { whenToUse: skill.whenToUse },
  1032. })),
  1033. })
  1034. } catch (error: unknown) {
  1035. return err(request, { code: 'internal', message: `skill listing failed: ${String(error)}`, details: {} })
  1036. }
  1037. },
  1038. },
  1039. events: {
  1040. mux(_request, signal) {
  1041. const queue = new FrameQueue<RpcRequest<MuxFrame>>()
  1042. muxQueues.add(queue)
  1043. for (const session of ctx.sessions.list()) {
  1044. subscribeSession(queue, session)
  1045. }
  1046. for (const pending of pendingQuestions.values()) {
  1047. queue.push({
  1048. rpcId: pending.rpcId,
  1049. payload: {
  1050. type: 'question/requested', sessionId: pending.sessionId,
  1051. questions: pending.questions,
  1052. },
  1053. })
  1054. }
  1055. // Queue snapshot baseline (pendingQuestions precedent): frames replayed
  1056. // in arrival order per session; a reconnecting client rebuilds its
  1057. // queue view from these alone.
  1058. for (const [sessionId, entries] of queuedMirror) {
  1059. for (const entry of entries.values()) {
  1060. queue.push(frame({
  1061. type: 'session/queued',
  1062. sessionId,
  1063. content: entry.message.content,
  1064. source: entry.message.source,
  1065. steering: entry.steering,
  1066. }))
  1067. }
  1068. }
  1069. // Per-session open-call table for result-view pairing. Bounded by the
  1070. // per-turn call count: entries clear on turn/end; a table miss (stream
  1071. // opened mid-turn) backscans the session's in-memory events instead.
  1072. const openCalls = new Map<SessionId, Map<string, { name: string; args: unknown }>>()
  1073. const disposers = [
  1074. ctx.on('session/event', (session: Session, event: SessionEvent) => {
  1075. if (event.type === 'tool/call') {
  1076. const data = event.data as ToolCallData
  1077. try {
  1078. let table = openCalls.get(session.id)
  1079. if (table === undefined) openCalls.set(session.id, table = new Map<string, { name: string; args: unknown }>())
  1080. table.set(data.callId, { name: data.name, args: JSON.parse(data.arguments) })
  1081. } catch {
  1082. // Unparseable model arguments: leave the table unset; the result view soft-falls.
  1083. }
  1084. } else if (event.type === 'turn/end') {
  1085. openCalls.delete(session.id)
  1086. }
  1087. const view = viewFor(ctx, event, callId =>
  1088. openCalls.get(session.id)?.get(callId) ?? backscanArgs(session.events, callId))
  1089. queue.push(frame({ type: 'session/event', sessionId: session.id, event, ...view === undefined ? {} : { view } }))
  1090. if (event.type === 'session/title') {
  1091. // The accepted raw event is already in session.events, so the fold must find it.
  1092. queue.push(frame(titleFrame(session) as SessionTitleFrame))
  1093. }
  1094. }),
  1095. ctx.on('session/created', (session: Session) => {
  1096. subscribeSession(queue, session)
  1097. }),
  1098. ctx.on('session/disposed', (session: Session) => {
  1099. openCalls.delete(session.id)
  1100. }),
  1101. ]
  1102. return queue.iterate(signal, () => {
  1103. muxQueues.delete(queue)
  1104. for (const dispose of disposers) dispose()
  1105. })
  1106. },
  1107. host(_request, signal) {
  1108. const queue = new FrameQueue<RpcRequest<HostFrame>>()
  1109. const committedWorkspaceIds = new Set(
  1110. ctx.workspace.list().map(workspace => String(workspace.id)),
  1111. )
  1112. const disposers = [
  1113. ctx.on('session/created', (session: Session) => {
  1114. queue.push(frame({
  1115. type: 'host/session-added',
  1116. sessionId: session.id,
  1117. // Derived at frame time like summarize(); a just-created session
  1118. // has no events yet, so this is constantly true in practice.
  1119. blank: session.events.length === 0,
  1120. ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession },
  1121. // cwd rides the frame so the client list needs no refresh to group the new session.
  1122. ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd },
  1123. }))
  1124. }),
  1125. ctx.on('session/disposed', (session: Session) => {
  1126. queue.push(frame({ type: 'host/session-removed', sessionId: session.id }))
  1127. }),
  1128. ctx.on('agent/status', (agent: Agent, status: AgentStatus) => {
  1129. queue.push(frame({ type: 'host/session-status', sessionId: agent.id, running: status === 'running' }))
  1130. }),
  1131. ctx.on('agent/error', (agent: Agent, _turn: number, _step: number, error: unknown) => {
  1132. queue.push(frame({ type: 'host/agent-error', sessionId: agent.id, message: errorChain(error) }))
  1133. }),
  1134. ctx.on('domain/changed', (change) => {
  1135. if (change.domain !== 'workspace') return
  1136. if (change.table === '') {
  1137. if (change.operation !== 'put') return
  1138. const state = workspaceDomainState.parse(change.value)
  1139. for (const workspaceId of state.workspaceIds) {
  1140. if (committedWorkspaceIds.has(workspaceId)) continue
  1141. const workspace = ctx.workspace.get(workspaceId)
  1142. if (workspace === undefined) {
  1143. throw new Error(`committed workspace registry references missing workspace "${workspaceId}"`)
  1144. }
  1145. committedWorkspaceIds.add(workspaceId)
  1146. queue.push(frame({ type: 'host/workspace-changed', workspace: workspaceView(workspace) }))
  1147. }
  1148. return
  1149. }
  1150. if (change.table !== 'workspaces') return
  1151. if (change.operation === 'deleted') {
  1152. if (!committedWorkspaceIds.delete(change.key)) return
  1153. queue.push(frame({
  1154. type: 'host/workspace-removed',
  1155. workspaceId: change.key as WorkspaceId,
  1156. }))
  1157. return
  1158. }
  1159. if (!committedWorkspaceIds.has(change.key)) return
  1160. // Existing-entity table writes are complete attach/touch commits.
  1161. // A new entity's first put waits for the global registry write above.
  1162. queue.push(frame({
  1163. type: 'host/workspace-changed',
  1164. workspace: changedWorkspaceView(change.key, change.value),
  1165. }))
  1166. }),
  1167. ctx.on('commands/change', () => {
  1168. queue.push(frame({ type: 'host/commands-changed' }))
  1169. }),
  1170. ]
  1171. return queue.iterate(signal, () => { for (const dispose of disposers) dispose() })
  1172. },
  1173. },
  1174. respond(message: ClientResponse): Promise<RpcReceipt> {
  1175. const pending = pendingQuestions.get(message.rpcId)
  1176. if (pending === undefined) return Promise.resolve({ accepted: false, reason: 'not-pending' })
  1177. if (!message.result.ok) {
  1178. if (message.result.error.code !== 'cancelled') {
  1179. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1180. }
  1181. claimQuestion(pending, 'cancelled')
  1182. pending.reject(new UserInteractionError(
  1183. 'the user cancelled ask_user_question', 'ASK_CANCELLED'))
  1184. return Promise.resolve({ accepted: true })
  1185. }
  1186. const parsed = questionResponsePayloadSchema.safeParse(message.result.value)
  1187. if (!parsed.success) {
  1188. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1189. }
  1190. const payload: QuestionResponsePayload = {
  1191. sessionId: parsed.data.sessionId,
  1192. answer: {
  1193. answers: parsed.data.answer.answers.map(answer => ({
  1194. id: answer.id,
  1195. selected: answer.selected,
  1196. ...(answer.custom === undefined ? {} : { custom: answer.custom }),
  1197. })),
  1198. },
  1199. }
  1200. if (!matchesQuestions(payload, pending)) {
  1201. return Promise.resolve({ accepted: false, reason: 'bad-response' })
  1202. }
  1203. claimQuestion(pending, 'answered')
  1204. pending.resolve(payload.answer)
  1205. return Promise.resolve({ accepted: true })
  1206. },
  1207. }
  1208. }