| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738 |
- /**
- * Host-side ApiProxy implementation. Signature discipline: unary takes the
- * narrow RpcRequest<P> and echoes request.rpcId on the RpcResponse<T>.
- */
- import { randomUUID } from 'node:crypto'
- import { mkdir, stat } from 'node:fs/promises'
- import { join } from 'node:path'
- import type { Context } from 'cordis'
- import { installAgentLlmTarget } from '@deepseek-ai/dsh-agent'
- import type {
- Agent, AgentLlmTarget, AgentLlmTargetRef, AgentStatus, InboxItem, InboxItemId,
- } from '@deepseek-ai/dsh-agent'
- import { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
- import { errorChain } from '@deepseek-ai/dsh-llm'
- import type { MessageSource } from '@deepseek-ai/dsh-llm'
- import { isAppendSurfaceEvent, lastActivityTime } from '@deepseek-ai/dsh-session'
- import type { Session, SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session'
- import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
- import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace'
- import {
- workspaceDomainState, workspaceRecord, WorkspaceId as brandWorkspaceId,
- WorkspaceMoveInvalidError, WorkspaceNameConflictError,
- } from '@deepseek-ai/dsh-workspace'
- // Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters).
- import type {} from '@deepseek-ai/dsh-tools'
- import type {
- ApiProxy, GoalRef, HistoryEntry, HostFrame, ModelCatalogFailure, ModelProviderGroup, ModelReasoning,
- MuxFrame, QuestionResponsePayload, SessionProjectionsBlock, SessionSummary, ToolEventView,
- WorkspaceId, WorkspaceView,
- } from './api/index.ts'
- // Type-only: resolves `ctx.get('sessionProjections')` to the projection registry.
- import type {} from '@deepseek-ai/dsh-session-projection'
- // Type-only: resolves `ctx.get('sessionProjectionCache')` (the cold listing column).
- import type {} from '@deepseek-ai/dsh-session-projection-cache'
- // GoalError narrows domain rejections to their stable codes at the wire boundary.
- import { GoalError } from '@deepseek-ai/dsh-goal'
- import type { GoalRef as CoreGoalRef } from '@deepseek-ai/dsh-goal'
- // Type-only edges: resolve `ctx.get('commands')`, the `commands/change` event, and `ctx.get('skills')`.
- import type {} from '@deepseek-ai/dsh-commands'
- import type {} from '@deepseek-ai/dsh-skill'
- // Value edge: the rename impl narrows the title service's validation failure; the import also resolves `ctx.get('sessionTitle')`.
- import { SessionTitleInvalidError } from '@deepseek-ai/dsh-session-title'
- import type { CallId } from '@deepseek-ai/dsh-llm/brand'
- import type { ApprovalOutcome, ApprovalRequestId } from '@deepseek-ai/dsh-user-approval'
- // Side-effect type import: resolves the `approval/request` waterfall and
- // `ctx.get('approval')` without a value dependency on the seam (optional composition).
- import type {} from '@deepseek-ai/dsh-user-approval'
- import { approvalResponsePayloadSchema } from './api/approvals.schema.ts'
- import { questionResponsePayloadSchema } from './api/questions.schema.ts'
- import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts'
- import { RpcId } from './api/rpc.ts'
- import type {
- AskUserQuestionAnswer, AskUserQuestionItem, AskUserQuestionRequest,
- } from '@deepseek-ai/dsh-user-interaction'
- import { UserInteractionError } from '@deepseek-ai/dsh-user-interaction'
- import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
- import { openNativePath } from './native-path-opener.ts'
- /** Page size when history is called without maxMessages. */
- const DEFAULT_MAX_MESSAGES = 50
- /** Conversation message event types (the pagination counting unit). */
- const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message'])
- /**
- * Message-boundary pagination: count maxMessages append-origin messages
- * backwards from the window tail. Replacement copies never entered the
- * conversation a reader sees — they restate a shadowed range for the model
- * alone — so they consume no quota; the page stays one contiguous raw range,
- * which keeps a compaction's log-only provenance on the same page as its
- * replacement. The cut is the starting seq of the oldest message group (chunks
- * group via sourceEventSeqs — never cut mid-message). The tail page naturally
- * includes the in-progress partial.
- */
- function paginate(
- events: readonly SessionEvent[],
- beforeSeq: number | undefined,
- maxMessages: number,
- ): { events: SessionEvent[]; hasMore: boolean } {
- const window = beforeSeq === undefined ? [...events] : events.filter(event => event.seq < beforeSeq)
- let count = 0
- let cut = 0
- for (let i = window.length - 1; i >= 0; i--) {
- const event = window[i] as SessionEvent
- if (!MESSAGE_TYPES.has(event.type) || !isAppendSurfaceEvent(event)) continue
- count++
- const sources = (event as { sourceEventSeqs?: number[] }).sourceEventSeqs
- const groupStart = sources !== undefined && sources.length > 0 ? Math.min(event.seq, ...sources) : event.seq
- if (count >= maxMessages) {
- cut = groupStart
- break
- }
- }
- const page = window.filter(event => event.seq >= cut)
- return { events: page, hasMore: cut > 0 }
- }
- /** Wrap an ok result echoing the request's rpcId. */
- function ok<T>(request: RpcRequest<unknown>, value: T): RpcResponse<T> {
- return { rpcId: request.rpcId, result: { ok: true, value } }
- }
- /** Wrap an error result echoing the request's rpcId. */
- function err<T>(request: RpcRequest<unknown>, error: RpcError): RpcResponse<T> {
- return { rpcId: request.rpcId, result: { ok: false, error } }
- }
- /** Simple async queue: core callbacks push, the AsyncIterable pulls; abort/return cleans up. */
- class FrameQueue<F> {
- private buffer: F[] = []
- private waiter: (() => void) | undefined
- private done = false
- push(item: F): void {
- if (this.done) return
- this.buffer.push(item)
- this.waiter?.()
- }
- end(): void {
- this.done = true
- this.waiter?.()
- }
- async *iterate(signal: AbortSignal, cleanup: () => void): AsyncGenerator<F> {
- const onAbort = (): void => { this.end() }
- signal.addEventListener('abort', onAbort, { once: true })
- try {
- while (true) {
- while (this.buffer.length > 0) yield this.buffer.shift() as F
- if (this.done || signal.aborted) return
- await new Promise<void>((resolve) => { this.waiter = resolve })
- this.waiter = undefined
- }
- } finally {
- signal.removeEventListener('abort', onAbort)
- cleanup()
- }
- }
- }
- /**
- * Server-side frame mint: pure pushes get a fresh rpcId per frame (answerable
- * frames — approval/question requested — mint their stable id in their
- * pending registries instead).
- */
- function frame<F>(payload: F): RpcRequest<F> {
- return { rpcId: RpcId(randomUUID()), payload }
- }
- /** Queue the subscription baseline frame. */
- function subscribeSession(queue: FrameQueue<RpcRequest<MuxFrame>>, session: Session): void {
- queue.push(frame({ type: 'session/subscribed', sessionId: session.id, lastSeq: session.seq - 1 }))
- }
- /**
- * Whether the session's conversation has started: no turn has run yet (a
- * turn is one model-loop execution). Standalone plugin events — command
- * lifecycle records, plan/mode, titles, goals — never open a turn, so
- * running `/plan` or `/goal` on a fresh session keeps it blank
- * (list-hidden, reusable).
- */
- function sessionBlank(session: Session): boolean {
- return !session.events.some(event => event.type === 'turn/start')
- }
- /** SessionSummary projection for attached (in-memory) sessions. */
- function summarize(session: Session, running: boolean): SessionSummary {
- return {
- sessionId: session.id,
- // Excludes end-seed: a resumed-but-untouched session
- // must not sort as freshly worked in.
- updatedAt: lastActivityTime(session.events) ?? session.header.createdAt,
- running,
- blank: sessionBlank(session),
- ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession },
- ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd },
- }
- }
- /**
- * SessionSummary projection for cold (persisted, unattached) sessions.
- * updatedAt is the log file's mtime; backends without a per-session file
- * (locate() undefined) fall back to the header's createdAt.
- */
- async function summarizeCold(persistence: SessionPersistence, meta: SessionHeader): Promise<SessionSummary> {
- let updatedAt = meta.createdAt
- const location = persistence.locate(meta)
- if (location !== undefined) {
- try {
- updatedAt = (await stat(location.path)).mtimeMs
- } catch {
- // The log vanished between list() and stat() (concurrent cleanup); createdAt stands in.
- }
- }
- return {
- sessionId: meta.id,
- updatedAt,
- running: false,
- // Lazy persistence keeps never-appended sessions out of list(); reading
- // a cold log to check for turns would defeat the index read, so a listed
- // cold session is served as not-blank (its log holds its conversation).
- blank: false,
- ...meta.parentSession === undefined ? {} : { parentSessionId: meta.parentSession },
- /* v8 ignore next -- the empty arm needs a cwd-less meta, but list()
- filters those out (legacy logs are not served); the conditional mirrors
- summarize() shape. */
- ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
- }
- }
- /** Map a browse-primitive failure onto the wire error vocabulary (unknown throws stay internal). */
- function directoryError(error: unknown): RpcError {
- if (error instanceof DirectoryPickerError) {
- return { code: error.code, message: error.message, details: { path: error.path } }
- }
- return { code: 'internal', message: error instanceof Error ? error.message : String(error), details: {} }
- }
- /** Resolved Host routing and project-directory defaults consumed by the API implementation. */
- export interface ApiProxyDefaults {
- provider: string
- model: string
- /** Default project directory for new sessions whose create request carries no cwd. */
- cwd: string
- /** Parent directory for name-created workspaces. */
- workspaceRoot: string
- /** Native open-with-default-application; injectable for carrier tests. */
- openPath?: (path: string, signal: AbortSignal) => Promise<void>
- }
- /** The tool/call payload fields the presenter path reads. */
- interface ToolCallData { callId: string; name: string; arguments: string }
- /**
- * One outstanding approval question: the stable server-request id, the frame
- * material replayed to late mux subscribers, and the resolver that settles the
- * answerer's promise back into `ctx.approval`.
- */
- interface PendingApproval {
- rpcId: RpcId
- sessionId: SessionId
- approvalId: ApprovalRequestId
- toolName: string
- callId?: CallId
- reason?: string
- resolve(outcome: ApprovalOutcome): void
- }
- /** Project a pending entry into its answerable mux frame (initial push and mux-open replay share it). */
- function requestedFrame(pending: PendingApproval): RpcRequest<MuxFrame> {
- return {
- rpcId: pending.rpcId,
- payload: {
- type: 'approval/requested',
- sessionId: pending.sessionId,
- approvalId: pending.approvalId,
- toolName: pending.toolName,
- ...pending.callId === undefined ? {} : { callId: pending.callId },
- ...pending.reason === undefined ? {} : { reason: pending.reason },
- },
- }
- }
- /** One host-owned question wait, addressed by the stable server-request id. */
- interface PendingQuestion {
- rpcId: RpcId
- sessionId: SessionId
- questions: AskUserQuestionItem[]
- resolve: (answer: AskUserQuestionAnswer) => void
- reject: (error: UserInteractionError) => void
- signal?: AbortSignal
- onAbort?: () => void
- }
- /** Validate one answer batch against the exact question request it resolves. */
- function matchesQuestions(payload: QuestionResponsePayload, pending: PendingQuestion): boolean {
- if (payload.sessionId !== pending.sessionId) return false
- const answers = payload.answer.answers
- if (answers.length !== pending.questions.length) return false
- return answers.every((answer, index) => {
- const question = pending.questions[index] as AskUserQuestionItem
- if (answer.id !== question.id) return false
- if (new Set(answer.selected).size !== answer.selected.length) return false
- const custom = answer.custom?.trim()
- if (custom !== undefined && custom === '') return false
- if (custom !== undefined && answer.selected.length > 0) return false
- if (question.multiSelect !== true && answer.selected.length > 1) return false
- const labels = new Set(question.options?.map(option => option.label) ?? [])
- return answer.selected.every(label => labels.has(label))
- })
- }
- /**
- * Compute the render intent for a tool/call or tool/result event through the
- * presenters registered at this moment; every other event type gets none. A
- * result's presenter needs its call's parsed args — `argsFor` supplies them
- * (live: the per-session call table; history: an in-page backscan), returning
- * undefined when the pairing is unavailable (e.g. the call fell off the page),
- * which soft-falls to no view. Presenter or JSON.parse throws also soft-fall:
- * the client's documented default (generic JSON card) covers every miss.
- */
- function viewFor(ctx: Context, event: SessionEvent, argsFor: (callId: string) => unknown): ToolEventView | undefined {
- try {
- if (event.type === 'tool/call') {
- const { name, arguments: raw } = event.data as ToolCallData
- const view = ctx.tools.get(name)?.presentCall?.(JSON.parse(raw))
- return view === undefined ? undefined : { for: 'call', view }
- }
- if (event.type === 'tool/result') {
- const { message, meta } = event.data
- const [result] = message.content
- const callId = message.source.callId
- const call = argsFor(callId) as { name: string; args: unknown } | undefined
- if (call === undefined) return undefined
- const view = ctx.tools.get(call.name)?.presentResult?.(call.args, {
- content: result.content,
- isError: result.isError === true,
- ...meta === undefined ? {} : { meta },
- })
- return view === undefined ? undefined : { for: 'result', view }
- }
- } catch (error: unknown) {
- // A throwing presenter (or unparseable arguments) must not break delivery;
- // the event still ships, just without a view.
- console.error(`api-proxy: presenter failed for ${event.type}, falling back to generic: ${String(error)}`)
- }
- return undefined
- }
- /**
- * Resolve a tool/result's call pairing by scanning a window of events backwards
- * for the matching tool/call. Used by the history path (the page is the
- * window — a cross-page pairing soft-falls to no view) and by live-path table
- * misses after a reconnect-eviction.
- */
- function backscanArgs(events: readonly SessionEvent[], callId: string): { name: string; args: unknown } | undefined {
- for (let i = events.length - 1; i >= 0; i--) {
- const event = events[i] as SessionEvent
- if (event.type !== 'tool/call') continue
- const data = event.data as ToolCallData
- if (data.callId !== callId) continue
- try {
- return { name: data.name, args: JSON.parse(data.arguments) }
- } catch {
- // Unparseable stored arguments: same soft-fall as a live parse failure.
- return undefined
- }
- }
- return undefined
- }
- /**
- * The projection baseline for one history tail page: the registry's
- * watermark-cache snapshot — one fully synchronous read (no await between the
- * page slice and this), so all values and `asOfSeq` form a single consistent
- * cut and `asOfSeq` equals the window tail event seq. The carrier holds zero
- * domain knowledge (each value passed its unit's own schema inside the
- * registry). An absent registry means the deployment has no projection seam:
- * the whole block is absent and clients treat every key as capability-absent.
- */
- function projectionsFor(ctx: Context, agent: Agent): SessionProjectionsBlock | undefined {
- const registry = ctx.get('sessionProjections')
- if (registry === undefined) return undefined
- return registry.snapshot(agent.session)
- }
- /**
- * The projection baseline of one session.list row, fail-soft: attached
- * sessions cut the registry's live watermark cache; cold sessions view the
- * persisted projection cache's identity-checked stored rows (zero log loads
- * either way — the listing use case the cache exists for). The block shape
- * (values + asOfSeq) matches the history tail's, so a client seeds its
- * value store under the same higher-seq-wins rule. Any failure — and an
- * empty value set — yields an absent block: a listing without projections
- * is degraded, never broken.
- */
- function listProjectionsFor(ctx: Context, meta: SessionHeader, session: Session | undefined): SessionProjectionsBlock | undefined {
- try {
- const block = session !== undefined
- ? ctx.get('sessionProjections')?.snapshot(session)
- : ctx.get('sessionProjectionCache')?.cachedSnapshot(meta)
- return block !== undefined && Object.keys(block.values).length > 0 ? block : undefined
- } catch (error) {
- ctx.logger.warn(`session.list: projection column for "${meta.id}" failed (serving the row without it): ${String(error)}`)
- return undefined
- }
- }
- /**
- * Thrown by the cold-resume path when the id names no servable session
- * (absent from the store, or a pre-project legacy log without a cwd).
- */
- class SessionNotFound extends Error {}
- /** Requested identity already belongs to a session with another project cwd. */
- class SessionCwdConflict extends Error {
- constructor(
- readonly sessionId: SessionId,
- readonly requestedCwd: string,
- readonly existingCwd: string | undefined,
- ) {
- super(
- `session "${sessionId}" already exists with cwd ${JSON.stringify(existingCwd)}; `
- + `requested ${JSON.stringify(requestedCwd)}`,
- )
- }
- }
- /** Host failed before the registry could adopt a name-created directory. */
- class WorkspaceDirectoryCreationError extends Error {}
- /** Shared workspace-not-found error response of the workspace.* mutation rows. */
- function workspaceNotFound<T>(request: RpcRequest<unknown>, workspaceId: string): RpcResponse<T> {
- return err(request, {
- code: 'workspace-not-found',
- message: `workspace "${workspaceId}" not found`,
- details: { workspaceId },
- })
- }
- /** Wire projection of one workspace entity (the workspace.* value row). */
- function workspaceView(workspace: Workspace): WorkspaceView {
- return {
- workspaceId: workspace.id,
- path: workspace.path,
- title: workspace.title,
- sessionIds: [...workspace.sessionIds],
- createdAt: workspace.createdAt,
- updatedAt: workspace.updatedAt,
- }
- }
- /** Wire projection of the durable record carried by `domain/changed`. */
- function changedWorkspaceView(workspaceId: string, value: unknown): WorkspaceView {
- const record: WorkspaceRecord = workspaceRecord.parse(value)
- return {
- workspaceId: workspaceId as WorkspaceId,
- path: record.path,
- title: record.title,
- sessionIds: [...record.sessionIds],
- createdAt: record.createdAt,
- updatedAt: record.updatedAt,
- }
- }
- /**
- * Implement ApiProxy over a composed host context.
- * @param ctx - a context with the Host spine and Workspace registry mounted.
- * @param defaults - host routing and project-directory defaults.
- * @returns the ApiProxy implementation.
- */
- export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiProxy {
- const agentOptions = { provider: defaults.provider, model: defaults.model }
- type WebLlmTargetRef = AgentLlmTargetRef & { current: AgentLlmTarget }
- const targets = new WeakMap<Agent, WebLlmTargetRef>()
- /** Implicit resume of cold sessions, deduplicating concurrent calls (follows the jsonrpc sessionCreations precedent). */
- const resumes = new Map<SessionId, Promise<Agent>>()
- /** Client-chosen identity creation/resume, deduplicated across concurrent retries. */
- const sessionCreations = new Map<SessionId, Promise<Agent>>()
- /** Serializes path ownership checks with record creation across spellings. */
- let workspaceCreationChain = Promise.resolve()
- const pendingQuestions = new Map<RpcId, PendingQuestion>()
- const pendingApprovals = new Map<RpcId, PendingApproval>()
- const muxQueues = new Set<FrameQueue<RpcRequest<MuxFrame>>>()
- /**
- * Install or return the session-local target that prompt assembly snapshots.
- * Seed order: latest logged request/header, else the host default routing.
- * There is no create-time per-session override tier on this wire — if one
- * returns (a create-options contribution), it must fold in between the two.
- */
- function targetFor(agent: Agent): WebLlmTargetRef {
- const installed = targets.get(agent)
- if (installed !== undefined) return installed
- const logged = agent.session.requestHeader()?.config
- const target: WebLlmTargetRef = {
- current: logged === undefined
- ? { provider: defaults.provider, model: defaults.model }
- : {
- provider: logged.provider,
- model: logged.model,
- ...logged.reasoningEffort === undefined
- ? {}
- : { reasoningEffort: logged.reasoningEffort },
- },
- assembled: undefined,
- }
- installAgentLlmTarget(agent.ctx, target)
- targets.set(agent, target)
- return target
- }
- /** Pre-publication setup used by both fresh and resumed Web agents. */
- function installTarget(agentCtx: Context): void {
- const agent = agentCtx.agent
- if (agent === undefined) throw new Error('api-proxy: agent setup has no scoped agent')
- targetFor(agent)
- }
- /** Send one transient frame to every connected mux consumer. */
- function broadcast(payload: MuxFrame): void {
- const envelope = frame(payload)
- for (const queue of muxQueues) queue.push(envelope)
- }
- // Projection change feed → session/projection push frames. The carrier
- // mints the wire frame (the seam package holds no wire vocabulary); the
- // child activates only when a projection registry is composed, and the
- // subscription unwinds with this gateway's fiber.
- ctx.inject(['sessionProjections'], (projectionCtx) => {
- projectionCtx.sessionProjections.onChanged((session, key, value, seq) => {
- broadcast({ type: 'session/projection', sessionId: session.id, key, value, seq })
- })
- })
- /**
- * Per-session queued-occurrence mirror serving the mux-open queue snapshot
- * (the same refresh-recovery baseline as pending questions). Each terminal
- * queue event retires one matching occurrence, so repeated sends of the same
- * identified message remain visible until every occurrence is claimed.
- */
- const queuedMirror = new Map<SessionId, InboxItem[]>()
- type UnseenQueueEvent =
- | { readonly kind: 'update'; readonly item: InboxItem }
- | { readonly kind: 'terminal' }
- const unseenQueueEvents = new Map<SessionId, Map<InboxItemId, UnseenQueueEvent>>()
- const rememberUnseen = (sessionId: SessionId, itemId: InboxItemId, event: UnseenQueueEvent): void => {
- let events = unseenQueueEvents.get(sessionId)
- if (events === undefined) {
- events = new Map()
- unseenQueueEvents.set(sessionId, events)
- }
- events.set(itemId, event)
- // Only synchronous re-entrancy may deliver a mutation before its outer
- // enqueue observer. Drop unmatched protocol-invalid observations instead
- // of retaining process-local ids indefinitely.
- queueMicrotask(() => {
- const current = unseenQueueEvents.get(sessionId)
- if (current?.get(itemId) !== event) return
- current.delete(itemId)
- if (current.size === 0) unseenQueueEvents.delete(sessionId)
- })
- }
- const takeUnseen = (sessionId: SessionId, itemId: InboxItemId): UnseenQueueEvent | undefined => {
- const events = unseenQueueEvents.get(sessionId)
- const event = events?.get(itemId)
- if (event === undefined) return undefined
- events?.delete(itemId)
- if (events?.size === 0) unseenQueueEvents.delete(sessionId)
- return event
- }
- const publishQueue = (sessionId: SessionId): void => {
- const items = queuedMirror.get(sessionId) ?? []
- broadcast({
- type: 'session/queue',
- sessionId,
- items: items.map(item => ({
- id: item.id,
- message: item.message,
- })),
- })
- }
- ctx.effect(() => {
- const retire = (agent: Agent, item: InboxItem): boolean => {
- const entries = queuedMirror.get(agent.id)
- if (entries === undefined) {
- rememberUnseen(agent.id, item.id, { kind: 'terminal' })
- return false
- }
- const index = entries.findIndex(entry => entry.id === item.id)
- if (index === -1) {
- rememberUnseen(agent.id, item.id, { kind: 'terminal' })
- return false
- }
- entries.splice(index, 1)
- if (entries.length === 0) queuedMirror.delete(agent.id)
- return true
- }
- const disposers = [
- ctx.on('agent/inbox/enqueue', (agent: Agent, item: InboxItem) => {
- if (item.placement !== 'queued') return
- const unseen = takeUnseen(agent.id, item.id)
- if (unseen?.kind === 'terminal') return
- let entries = queuedMirror.get(agent.id)
- if (entries === undefined) {
- entries = []
- queuedMirror.set(agent.id, entries)
- }
- entries.push(unseen?.kind === 'update' ? unseen.item : item)
- publishQueue(agent.id)
- }),
- ctx.on('agent/inbox/update', (agent: Agent, item: InboxItem) => {
- const entries = queuedMirror.get(agent.id)
- if (entries === undefined) {
- rememberUnseen(agent.id, item.id, { kind: 'update', item })
- return
- }
- const index = entries.findIndex(entry => entry.id === item.id)
- if (index === -1) {
- rememberUnseen(agent.id, item.id, { kind: 'update', item })
- return
- }
- entries.splice(index, 1, item)
- publishQueue(agent.id)
- }),
- ctx.on('agent/inbox/dequeue', (agent: Agent, item: InboxItem) => {
- if (retire(agent, item)) publishQueue(agent.id)
- }),
- ctx.on('agent/inbox/discard', (agent: Agent, items: InboxItem[]) => {
- let changed = false
- for (const item of items) changed = retire(agent, item) || changed
- if (changed) publishQueue(agent.id)
- }),
- ctx.on('session/disposed', (session: Session) => {
- queuedMirror.delete(session.id)
- unseenQueueEvents.delete(session.id)
- }),
- ]
- return () => { for (const dispose of disposers) dispose() }
- }, 'api-proxy: queued mirror')
- /** Remove a wait before settling it: synchronous deletion makes the first claimant win. */
- function claimQuestion(pending: PendingQuestion, outcome: 'answered' | 'cancelled'): void {
- pendingQuestions.delete(pending.rpcId)
- if (pending.signal !== undefined && pending.onAbort !== undefined) {
- pending.signal.removeEventListener('abort', pending.onAbort)
- }
- broadcast({
- type: 'question/resolved', sessionId: pending.sessionId,
- questionRpcId: pending.rpcId, outcome,
- })
- }
- const disposeProvider = ctx.userInteraction.registerProvider({
- ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> {
- const sessionId = request.agent?.id
- if (sessionId === undefined) {
- return Promise.reject(new UserInteractionError(
- 'web user interaction requires an agent-owned session', 'ASK_MISSING_AGENT'))
- }
- return new Promise<AskUserQuestionAnswer>((resolve, reject) => {
- const rpcId = RpcId(randomUUID())
- const pending: PendingQuestion = {
- rpcId, sessionId, questions: request.questions, resolve, reject,
- ...(request.signal === undefined ? {} : { signal: request.signal }),
- }
- const onAbort = (): void => {
- claimQuestion(pending, 'cancelled')
- reject(new UserInteractionError(
- 'ask_user_question was aborted before the user answered', 'ASK_ABORTED'))
- }
- pending.onAbort = onAbort
- pendingQuestions.set(rpcId, pending)
- request.signal?.addEventListener('abort', onAbort, { once: true })
- const envelope: RpcRequest<MuxFrame> = {
- rpcId,
- payload: { type: 'question/requested', sessionId, questions: request.questions },
- }
- for (const queue of muxQueues) queue.push(envelope)
- })
- },
- })
- ctx.effect(() => () => {
- disposeProvider()
- for (const pending of [...pendingQuestions.values()]) {
- claimQuestion(pending, 'cancelled')
- pending.reject(new UserInteractionError(
- 'web user-interaction provider was disposed', 'ASK_ABORTED'))
- }
- }, 'api-proxy: user-interaction provider')
- // --- Approval pending registry ------------------------------------------
- // The proxy is the approval channel for every agent this host owns: an ask
- // through `ctx.approval` becomes an answerable server-request on the mux
- // stream (stable rpcId), settled by POST /api/respond. The entry survives
- // client disconnects — mux-open replays still-pending requested frames with
- // the same rpcId (the refresh-recovery baseline) — and withdraws on the
- // ask's own abort signal (turn cancel), pushing `cancelled` to subscribers.
- if (ctx.get('approval') !== undefined) {
- // Teardown parity with the question provider above: a gateway disposed
- // while approvals are pending settles every entry as 'cancelled' (the
- // service's fail-closed vocabulary), so no ask promise dangles past the
- // proxy's lifetime and subscribers see the withdrawal.
- ctx.effect(() => () => {
- for (const pending of [...pendingApprovals.values()]) pending.resolve('cancelled')
- }, 'api-proxy: approval registry teardown')
- ctx.on('approval/request', (req, next) => {
- // Dispatch rides a microtask behind the service's own signal check: an
- // abort landing in that window would register the abort listener AFTER
- // the signal fired — never invoked, entry pending forever, zombie frame
- // on every mux replay. Settle synchronously instead of publishing.
- if (req.signal?.aborted === true) return Promise.resolve<ApprovalOutcome>('cancelled')
- // The audit pair `approval/asked` is already appended by the service
- // before dispatch, but dispatch rides a microtask: parallel tool calls
- // can append several asked events before any answerer runs. THIS
- // request's event is therefore the newest asked event that is still
- // undecided, unclaimed by another pending entry, and — when the ask
- // names a call — carries the same callId.
- const events = req.agent.session.events
- const claimed = new Set<ApprovalRequestId>()
- for (const entry of pendingApprovals.values()) claimed.add(entry.approvalId)
- const decided = new Set<ApprovalRequestId>()
- let approvalId: ApprovalRequestId | undefined
- for (let i = events.length - 1; i >= 0; i -= 1) {
- const event = events[i] as SessionEvent
- if (event.type === 'approval/decided') {
- decided.add(event.data.id)
- } else if (event.type === 'approval/asked') {
- if (decided.has(event.data.id) || claimed.has(event.data.id)) continue
- // Symmetric pairing: a callId-bearing ask only takes its own call's
- // record, and a callId-less ask only takes a callId-less record —
- // so neither shape can steal the other's audit id under parallel
- // asks. (Today every producer — the tool executor — passes callId;
- // the callId-less arm guards any future non-tool asker.)
- if ((req.callId ?? null) !== (event.data.callId ?? null)) continue
- approvalId = event.data.id
- break
- }
- }
- // No asked event means the request bypassed the service's audit path —
- // not this channel's question; delegate to the fail-closed default.
- if (approvalId === undefined) return next()
- const id = approvalId
- return new Promise<ApprovalOutcome>((resolve) => {
- const settle = (outcome: ApprovalOutcome): void => {
- /* v8 ignore next 3 -- defensive double-settle guard: respond() routes
- through the pending table (a settled id is not-pending before it can
- re-settle) and the first settle removes the abort listener, so no
- reachable path settles twice; kept against future settle callers. */
- if (!pendingApprovals.delete(pending.rpcId)) return
- req.signal?.removeEventListener('abort', onAbort)
- broadcast({ type: 'approval/resolved', sessionId: pending.sessionId, approvalId: id, outcome })
- // A cancelled ask was already settled by the service's own signal
- // race, which discards this late resolution; resolving is a no-op
- // there and keeps this promise from dangling forever.
- resolve(outcome)
- }
- const onAbort = (): void => { settle('cancelled') }
- const pending: PendingApproval = {
- rpcId: RpcId(randomUUID()),
- sessionId: req.agent.session.id,
- approvalId: id,
- toolName: req.toolName,
- ...req.callId === undefined ? {} : { callId: req.callId },
- ...req.reason === undefined ? {} : { reason: req.reason },
- resolve: settle,
- }
- pendingApprovals.set(pending.rpcId, pending)
- req.signal?.addEventListener('abort', onAbort, { once: true })
- const envelope = requestedFrame(pending)
- for (const queue of muxQueues) queue.push(envelope)
- })
- })
- }
- /**
- * Gate the cold path on the store: an id absent from it, or naming a legacy
- * log without a cwd (pre-release stance: not served, no compatibility), is
- * not-found before any resume is attempted. With the gate passed, a later
- * resume failure is genuinely internal. No persistence configured skips the
- * gate — resume itself then fails loud with its own diagnostic.
- */
- async function assertServable(sessionId: SessionId): Promise<void> {
- const persistence = ctx.get('sessionPersistence')
- if (persistence === undefined) return
- const meta = (await persistence.list()).find(m => m.id === sessionId)
- if (meta === undefined || meta.cwd === undefined) throw new SessionNotFound(`session "${sessionId}" not found`)
- }
- async function agentFor(sessionId: SessionId): Promise<{ agent: Agent } | { error: RpcError }> {
- const live = ctx.agents.get(sessionId)
- if (live !== undefined) return { agent: live }
- let resume = resumes.get(sessionId)
- if (resume === undefined) {
- resume = (async () => {
- try {
- await assertServable(sessionId)
- const handle = await ctx.agents.resume({
- resumeSessionId: sessionId,
- agentOptions,
- setup: installTarget,
- })
- return handle.agent
- } finally {
- resumes.delete(sessionId)
- }
- })()
- resumes.set(sessionId, resume)
- }
- try {
- return { agent: await resume }
- } catch (error: unknown) {
- if (error instanceof SessionNotFound) {
- return { error: { code: 'session-not-found', message: error.message, details: { sessionId } } }
- }
- // The internal details slot is contractually {}; the reason rides the message.
- return { error: { code: 'internal', message: `resume failed for session "${sessionId}": ${String(error)}`, details: {} } }
- }
- }
- /** Resolve one requested identity to a live agent, creating or resuming it once. */
- async function ensureSession(sessionId: SessionId, cwd: string, checkPersistedIdentity: boolean): Promise<Agent> {
- let creation = sessionCreations.get(sessionId)
- if (creation === undefined) {
- creation = (async () => {
- const live = ctx.agents.get(sessionId)
- if (live !== undefined) return live
- const persistence = checkPersistedIdentity ? ctx.get('sessionPersistence') : undefined
- const stored = persistence === undefined
- ? undefined
- : (await persistence.list()).find(header => header.id === sessionId)
- if (stored !== undefined) {
- if (stored.cwd !== cwd) {
- throw new SessionCwdConflict(sessionId, cwd, stored.cwd)
- }
- return (await ctx.agents.resume({
- resumeSessionId: sessionId,
- agentOptions,
- setup: installTarget,
- })).agent
- }
- try {
- await mkdir(cwd, { recursive: true })
- } catch (error: unknown) {
- throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
- }
- return (await ctx.agents.create({
- sessionId,
- agentOptions,
- meta: { cwd },
- setup: installTarget,
- })).agent
- })().catch((error: unknown) => {
- // Another Host entry path may have published the same identity while
- // this operation crossed an asynchronous persistence/filesystem step.
- const live = ctx.agents.get(sessionId)
- if (live !== undefined) return live
- throw error
- }).finally(() => {
- sessionCreations.delete(sessionId)
- })
- sessionCreations.set(sessionId, creation)
- }
- const agent = await creation
- if (agent.session.header.cwd !== cwd) {
- throw new SessionCwdConflict(sessionId, cwd, agent.session.header.cwd)
- }
- return agent
- }
- /** Resolve or create one path while holding the Host's workspace-create chain. */
- function ensureWorkspace(
- path: string,
- title: string | undefined,
- rejectExistingName = false,
- createDirectory = false,
- ): Promise<{ workspace: Workspace; created: boolean }> {
- const operation = workspaceCreationChain.then(async () => {
- if (rejectExistingName && title !== undefined
- && ctx.workspace.list().some(workspace => workspace.title === title)) {
- throw new WorkspaceNameConflictError(title)
- }
- if (createDirectory) {
- try {
- await mkdir(path, { recursive: true })
- } catch (error: unknown) {
- throw new WorkspaceDirectoryCreationError(
- `failed to create workspace directory "${path}": ${String(error)}`,
- )
- }
- }
- const existing = await ctx.workspace.resolveByPath(path)
- if (existing !== undefined) return { workspace: existing, created: false }
- return { workspace: await ctx.workspace.create(path, title), created: true }
- })
- workspaceCreationChain = operation.then(() => undefined, () => undefined)
- return operation
- }
- /** Resolve the goal service; absent = the deployment did not compose @deepseek-ai/dsh-goal. */
- function goalService(): NonNullable<ReturnType<typeof ctx.get<'goals'>>> | { error: RpcError } {
- const goals = ctx.get('goals')
- if (goals === undefined) {
- 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: {} } }
- }
- return goals
- }
- /** Map one goal-domain rejection to the wire error (stable GoalError codes ride in details). */
- function goalError(request: RpcRequest<unknown>, error: unknown): RpcResponse<never> {
- const details = error instanceof GoalError ? { goalCode: error.code } : {}
- return err(request, { code: 'internal', message: String(error), details })
- }
- /** Resolve a session's agent, apply one goal mutation, and acknowledge with the new CAS ref. */
- async function mutateGoal(
- request: RpcRequest<{ sessionId: SessionId }>,
- mutation: (goals: NonNullable<ReturnType<typeof ctx.get<'goals'>>>, agent: Agent) => CoreGoalRef,
- ): Promise<RpcResponse<{ ref: GoalRef }>> {
- const goals = goalService()
- if ('error' in goals) return err(request, goals.error)
- const found = await agentFor(request.payload.sessionId)
- if ('error' in found) return err(request, found.error)
- try {
- const ref = mutation(goals, found.agent)
- return ok(request, { ref: { id: ref.id, revision: ref.revision } })
- } catch (error: unknown) {
- return goalError(request, error)
- }
- }
- return {
- sessions: {
- // Attached sessions summarize from memory; persisted-but-unattached (cold)
- // sessions merge in from the persistence store so history survives restarts.
- // Legacy logs without a cwd (pre-project stance) are not served — every
- // session now records its project at create time.
- async list(request) {
- const items = ctx.sessions.list().map((session) => {
- const agent = ctx.agents.get(session.id)
- const projections = listProjectionsFor(ctx, session.header, session)
- return {
- ...summarize(session, agent?.status === 'running'),
- ...projections === undefined ? {} : { projections },
- }
- })
- const attached = new Set(items.map(item => item.sessionId))
- const persistence = ctx.get('sessionPersistence')
- if (persistence !== undefined) {
- const cold = (await persistence.list()).filter(meta => !attached.has(meta.id) && meta.cwd !== undefined)
- items.push(...await Promise.all(cold.map(async (meta) => {
- // Cold rows read the persisted projection cache only — never a
- // log load; a session without a cache row simply has no column.
- const projections = listProjectionsFor(ctx, meta, undefined)
- return {
- ...await summarizeCold(persistence, meta),
- ...projections === undefined ? {} : { projections },
- }
- })))
- }
- items.sort((a, b) => b.updatedAt - a.updatedAt)
- return ok(request, { items })
- },
- async create(request) {
- const sessionId = request.payload.sessionId ?? `session-${randomUUID()}` as SessionId
- let workspace: Workspace | undefined
- if (request.payload.workspaceId !== undefined) {
- workspace = ctx.workspace.get(brandWorkspaceId(request.payload.workspaceId))
- if (workspace === undefined) {
- return err(request, {
- code: 'workspace-not-found',
- message: `workspace "${request.payload.workspaceId}" not found`,
- details: { workspaceId: request.payload.workspaceId },
- })
- }
- }
- const cwd = workspace?.path ?? request.payload.cwd ?? defaults.cwd
- try {
- await ensureSession(sessionId, cwd, request.payload.sessionId !== undefined)
- } catch (error: unknown) {
- if (error instanceof SessionCwdConflict) {
- return err(request, {
- code: 'session-conflict',
- message: error.message,
- details: {
- sessionId: error.sessionId,
- requestedCwd: error.requestedCwd,
- ...error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd },
- },
- })
- }
- return err(request, {
- code: 'internal',
- message: `failed to create session "${sessionId}": ${String(error)}`,
- details: {},
- })
- }
- if (workspace !== undefined) {
- try {
- await workspace.attachSession(sessionId)
- } catch (error: unknown) {
- return err(request, {
- code: 'workspace-attach-failed',
- message: `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`,
- details: { sessionId, workspaceId: workspace.id },
- })
- }
- }
- return ok(request, { sessionId })
- },
- async history(request) {
- const { sessionId, beforeSeq, maxMessages } = request.payload
- const found = await agentFor(sessionId)
- if ('error' in found) return err(request, found.error)
- // Everything below the resume above is synchronous: the page slice,
- // the seq read, and the projection walk see one un-torn session state.
- const page = paginate(found.agent.session.events, beforeSeq, maxMessages ?? DEFAULT_MAX_MESSAGES)
- // Views are computed against the registry at pagination time; result
- // pairing scans within the page only (message-boundary pagination keeps
- // a call and its result on one page — a cross-page miss soft-falls).
- const entries: HistoryEntry[] = page.events.map((event) => {
- const view = viewFor(ctx, event, callId => backscanArgs(page.events, callId))
- return { event, ...view === undefined ? {} : { view } }
- })
- // Baseline rider: tail page only — loadOlder (beforeSeq present) is
- // the one path that never needs a fresh projection baseline.
- const projections = beforeSeq === undefined ? projectionsFor(ctx, found.agent) : undefined
- return ok(request, {
- events: entries,
- hasMore: page.hasMore,
- ...projections === undefined ? {} : { projections },
- })
- },
- async models(request) {
- const { sessionId } = request.payload
- const found = await agentFor(sessionId)
- if ('error' in found) return err(request, found.error)
- const current = targetFor(found.agent).current
- const catalog = await Promise.all(ctx.llm.listProviders().map(async (provider) => {
- try {
- const advertised = await ctx.llm.listModels(provider.id)
- const models = [...advertised]
- if (
- provider.id === current.provider
- && !models.some(model => model.id === current.model)
- ) {
- models.push({
- provider: provider.id,
- id: current.model,
- name: current.model,
- })
- }
- const entries = await Promise.all(models.map(async (model) => {
- const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id)
- const reasoning: ModelReasoning | undefined = resolved.reasoning === undefined
- ? undefined
- : {
- efforts: resolved.reasoning.efforts.map(effort => ({
- id: effort.id,
- name: effort.name,
- ...effort.description === undefined
- ? {}
- : { description: effort.description },
- })),
- ...resolved.reasoning.defaultEffort === undefined
- ? {}
- : { defaultEffort: resolved.reasoning.defaultEffort },
- }
- return {
- id: model.id,
- name: model.name,
- ...model.description === undefined ? {} : { description: model.description },
- ...provider.id === current.provider
- && model.id === current.model
- && !advertised.some(candidate => candidate.id === current.model)
- ? { unlisted: true as const }
- : {},
- ...reasoning === undefined ? {} : { reasoning },
- }
- }))
- const group: ModelProviderGroup = {
- id: provider.id,
- name: provider.name,
- models: entries,
- }
- return { kind: 'group' as const, group }
- } catch (error: unknown) {
- const failure: ModelCatalogFailure = {
- id: provider.id,
- name: provider.name,
- message: error instanceof Error ? error.message : String(error),
- }
- return { kind: 'failure' as const, failure }
- }
- }))
- const groups = catalog.flatMap(item => item.kind === 'group' ? [item.group] : [])
- const failures = catalog.flatMap(item => item.kind === 'failure' ? [item.failure] : [])
- return ok(request, {
- current: { ...current },
- groups: groups.filter(group => group.models.length > 0),
- failures,
- })
- },
- async selectModel(request) {
- const { sessionId, provider, model, reasoningEffort } = request.payload
- const found = await agentFor(sessionId)
- if ('error' in found) return err(request, found.error)
- try {
- const resolved = await ctx.llm.resolveCallConfig({
- provider,
- model,
- ...reasoningEffort === undefined
- ? {}
- : { reasoningEffort: ReasoningEffortId(reasoningEffort) },
- })
- const selected: AgentLlmTarget = {
- provider: resolved.provider,
- model: resolved.model,
- ...resolved.reasoningEffort === undefined
- ? {}
- : { reasoningEffort: resolved.reasoningEffort },
- }
- targetFor(found.agent).current = selected
- return ok(request, { selected: { ...selected } })
- } catch (error: unknown) {
- return err(request, {
- code: 'model-unavailable',
- message: error instanceof Error ? error.message : String(error),
- details: { provider, model },
- })
- }
- },
- async rename(request) {
- const { sessionId, title } = request.payload
- const found = await agentFor(sessionId)
- if ('error' in found) return err(request, found.error)
- const titles = ctx.get('sessionTitle')
- if (titles === undefined) {
- return err(request, { code: 'internal', message: 'renaming is unavailable: this deployment mounts no session-title service', details: {} })
- }
- try {
- const accepted = titles.rename(found.agent.session, title)
- return ok(request, { title: accepted.title, seq: accepted.eventSeq })
- } catch (error: unknown) {
- // Only the input's fault maps to title-invalid (the message is
- // product-user-visible in the rename dialog); liveness and disposal
- // races are deployment trouble, not a bad title.
- if (error instanceof SessionTitleInvalidError) {
- return err(request, {
- code: 'title-invalid',
- message: error.message,
- details: { sessionId },
- })
- }
- return err(request, {
- code: 'internal',
- message: `failed to rename session "${sessionId}": ${String(error)}`,
- details: {},
- })
- }
- },
- async prompt(request) {
- const { sessionId, mode, content } = request.payload
- const found = await agentFor(sessionId)
- if ('error' in found) return err(request, found.error)
- const agent = found.agent
- // The rpcId rides MessageSource into user/message (merge declaration in api/sessions.ts; provisional correlation).
- const source: MessageSource = { kind: 'user', rpcId: request.rpcId }
- try {
- const message: UserMessage = createUserMessage({ content, source })
- if (mode === 'steer') agent.steer(message)
- else agent.followup(message)
- } catch (error: unknown) {
- // A synchronous throw from steer/followup means disposed or invalid input; surface as agent-busy with the reason attached.
- return err(request, { code: 'agent-busy', message: 'prompt rejected', details: { reason: String(error) } })
- }
- return ok(request, { accepted: true as const })
- },
- updateQueue(request) {
- const { sessionId, itemId, action } = request.payload
- const agent = ctx.agents.get(sessionId)
- if (agent === undefined || agent.updateInbox(itemId, action) === 'not-found') {
- return Promise.resolve(err(request, {
- code: 'queue-item-not-found',
- message: 'queued item is no longer pending',
- details: { itemId },
- }))
- }
- return Promise.resolve(ok(request, { accepted: true as const }))
- },
- cancel(request) {
- const { sessionId } = request.payload
- const agent = ctx.agents.get(sessionId)
- if (agent === undefined) {
- return Promise.resolve(err(request, {
- code: 'session-not-found',
- message: `session "${sessionId}" not found (not attached)`,
- details: { sessionId },
- }))
- }
- agent.cancel({ kind: 'user' })
- return Promise.resolve(ok(request, { accepted: true as const }))
- },
- },
- workspace: {
- list(request) {
- return Promise.resolve(ok(request, { items: ctx.workspace.list().map(workspaceView) }))
- },
- // Exactly one of path/name arrives (schema refine). Existing-folder
- // adoption reuses its canonical path; create-by-name rejects a name
- // already present in the registry.
- async create(request) {
- const { payload } = request
- let path: string
- if (payload.name !== undefined) {
- const name = payload.name.trim()
- if (name === '' || name === '.' || name === '..' || /[/\\]/.test(name)) {
- return err(request, {
- code: 'workspace-invalid-path',
- message: `workspace name must be one non-empty path segment, got "${payload.name}"`,
- details: { path: payload.name },
- })
- }
- path = join(defaults.workspaceRoot, name)
- } else {
- path = payload.path as string
- }
- try {
- const name = payload.name?.trim()
- const { workspace, created } = await ensureWorkspace(
- path,
- name,
- name !== undefined,
- name !== undefined,
- )
- return ok(request, { workspace: workspaceView(workspace), created })
- } catch (error: unknown) {
- if (error instanceof WorkspaceNameConflictError) {
- return err(request, {
- code: 'workspace-name-conflict',
- message: error.message,
- details: { name: error.workspaceName },
- })
- }
- if (error instanceof WorkspaceDirectoryCreationError) {
- return err(request, { code: 'internal', message: error.message, details: {} })
- }
- // The registry rejects a path that does not resolve to an existing
- // directory (realpath ENOENT / not-a-directory) — the business
- // error of the typed-path flow, surfaced as a validation failure.
- return err(request, {
- code: 'workspace-invalid-path',
- message: `cannot create a workspace at "${path}": ${error instanceof Error ? error.message : String(error)}`,
- details: { path },
- })
- }
- },
- async rename(request) {
- const { payload } = request
- const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
- if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
- const title = payload.title.trim()
- // Uniqueness AND the same-title no-op both ride the create chain so
- // they observe the state left by earlier queued renames — checked
- // up front, a queued A→A could report success while an earlier A→B
- // still lands afterwards.
- const operation = workspaceCreationChain.then(async () => {
- if (title === workspace.title) return
- if (ctx.workspace.list().some(other => other.id !== workspace.id && other.title === title)) {
- throw new WorkspaceNameConflictError(title)
- }
- await workspace.setTitle(title)
- })
- workspaceCreationChain = operation.then(() => undefined, () => undefined)
- try {
- await operation
- } catch (error: unknown) {
- if (error instanceof WorkspaceNameConflictError) {
- return err(request, {
- code: 'workspace-name-conflict',
- message: error.message,
- details: { name: error.workspaceName },
- })
- }
- throw error
- }
- return ok(request, { workspace: workspaceView(workspace) })
- },
- async delete(request) {
- const { workspaceId } = request.payload
- const operation = workspaceCreationChain.then(() =>
- ctx.workspace.delete(brandWorkspaceId(workspaceId)))
- workspaceCreationChain = operation.then(() => undefined, () => undefined)
- if (!await operation) return workspaceNotFound(request, workspaceId)
- return ok(request, { deleted: true as const })
- },
- async insertSessionBefore(request) {
- const { payload } = request
- const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId))
- if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId)
- try {
- await workspace.insertSessionBefore(payload.sessionId, payload.beforeSessionId)
- } catch (error: unknown) {
- // Only the entity's unaccounted-id rejection is the business code;
- // storage/durability failures propagate as internal errors.
- if (!(error instanceof WorkspaceMoveInvalidError)) throw error
- return err(request, {
- code: 'workspace-move-invalid',
- message: error.message,
- details: {
- workspaceId: payload.workspaceId,
- sessionId: payload.sessionId,
- ...payload.beforeSessionId === undefined ? {} : { beforeSessionId: payload.beforeSessionId },
- },
- })
- }
- return ok(request, { workspace: workspaceView(workspace) })
- },
- },
- host: {
- describe(request) {
- // TODO(step2): version should read apps/cli's package.json; placeholder for now.
- return Promise.resolve(ok(request, {
- version: '0.0.1',
- // Same source as session.create's fallback: the UI's default project
- // must match where an unspecified-cwd session actually lands.
- cwd: defaults.cwd,
- provider: defaults.provider,
- model: defaults.model,
- attachedSessions: ctx.agents.list().length,
- }))
- },
- async pickDirectory(request, signal) {
- const capability = ctx.directoryPicker.capability()
- if (capability.kind !== 'native') {
- return err(request, {
- code: 'directory-picker-unavailable',
- message: `host.pickDirectory needs the native capability; the composed picker serves "${capability.kind}"`,
- details: { capability: capability.kind },
- })
- }
- try {
- const path = await capability.pick(signal)
- return ok(request, { path })
- } catch (error: unknown) {
- if (signal.aborted) {
- return err(request, {
- code: 'cancelled',
- message: 'directory picker was aborted',
- details: {},
- })
- }
- return err(request, {
- code: 'internal',
- message: `directory picker failed: ${error instanceof Error ? error.message : String(error)}`,
- details: {},
- })
- }
- },
- async listDirectory(request, signal) {
- const capability = ctx.directoryPicker.capability()
- if (capability.kind !== 'browse') {
- return err(request, {
- code: 'directory-picker-unavailable',
- message: `host.listDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
- details: { capability: capability.kind },
- })
- }
- try {
- // The carrier's signal follows the caller: a disconnect or timeout
- // stops the backend's directory scan instead of outliving it.
- return ok(request, await capability.list(request.payload.path, signal))
- } catch (error: unknown) {
- // An abort is the caller's own timeout/disconnect, not a server
- // failure — same code pickDirectory and command.execute report.
- if (signal.aborted) {
- return err(request, { code: 'cancelled', message: 'directory listing was aborted', details: {} })
- }
- return err(request, directoryError(error))
- }
- },
- async createDirectory(request) {
- const capability = ctx.directoryPicker.capability()
- if (capability.kind !== 'browse') {
- return err(request, {
- code: 'directory-picker-unavailable',
- message: `host.createDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
- details: { capability: capability.kind },
- })
- }
- try {
- return ok(request, { path: await capability.createDirectory(request.payload.path, request.payload.name) })
- } catch (error: unknown) {
- return err(request, directoryError(error))
- }
- },
- async openPath(request, signal) {
- try {
- const open = defaults.openPath
- ?? ((path: string, openSignal: AbortSignal) => openNativePath(path, openSignal))
- await open(request.payload.path, signal)
- return ok(request, { opened: true as const })
- } catch (error: unknown) {
- if (signal.aborted) {
- return err(request, {
- code: 'cancelled',
- message: 'path open was aborted',
- details: {},
- })
- }
- return err(request, {
- code: 'internal',
- message: `path open failed: ${error instanceof Error ? error.message : String(error)}`,
- details: {},
- })
- }
- },
- },
- commands: {
- // Both methods address one session's agent (agentFor keeps its
- // resume-on-miss: clients only send a sessionId for a published
- // session, and resume restores an existing entity).
- async list(request) {
- // Missing service = the deployment omitted dsh-commands from its
- // composition, not an empty catalog: fail loud instead of serving [].
- const commands = ctx.get('commands')
- if (commands === undefined) {
- 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: {} })
- }
- const found = await agentFor(request.payload.sessionId)
- if ('error' in found) return err(request, found.error)
- return ok(request, { commands: commands.list(found.agent) })
- },
- async execute(request, signal) {
- const commands = ctx.get('commands')
- if (commands === undefined) {
- 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: {} })
- }
- const { sessionId, line } = request.payload
- const found = await agentFor(sessionId)
- if ('error' in found) return err(request, found.error)
- try {
- // Pure admission: the executor's durable command/run + command/done
- // pair (broadcast on the mux stream) carries the outcome; the
- // response reports whether the line resolved to a handler, plus the
- // minted pairing id so the issuing client can correlate its request
- // with the flow node the lifecycle events produce.
- const execution = await commands.execute(found.agent, line, signal)
- return ok(request, execution === undefined
- ? { matched: false }
- : { matched: true, commandId: execution.commandId })
- } catch (error: unknown) {
- if (signal.aborted) return err(request, { code: 'cancelled', message: 'command execution was aborted', details: {} })
- return err(request, { code: 'internal', message: `command failed: ${String(error)}`, details: {} })
- }
- },
- },
- goals: {
- // Mutations only — the read side is the 'goal' session projection.
- // Every verb resolves the session's agent (agentFor: implicit cold
- // resume, the command.* precedent) and acknowledges with the new CAS
- // ref; the committed goal/change event carries the whole value to every
- // client through the projection frames.
- async create(request) {
- const { objective, maxGoalRounds } = request.payload
- return mutateGoal(request, (goals, agent) => goals.create(agent, {
- objective,
- ...(maxGoalRounds !== undefined ? { maxGoalRounds } : {}),
- }))
- },
- async edit(request) {
- const { ref, objective, maxGoalRounds } = request.payload
- return mutateGoal(request, (goals, agent) => goals.edit(agent, ref, {
- ...(objective !== undefined ? { objective } : {}),
- ...(maxGoalRounds !== undefined ? { maxGoalRounds } : {}),
- }))
- },
- async pause(request) {
- return mutateGoal(request, (goals, agent) => goals.pause(agent, request.payload.ref))
- },
- async resume(request) {
- return mutateGoal(request, (goals, agent) => goals.resume(agent, request.payload.ref))
- },
- async complete(request) {
- return mutateGoal(request, (goals, agent) => goals.complete(agent, request.payload.ref))
- },
- async clear(request) {
- const goals = goalService()
- if ('error' in goals) return err(request, goals.error)
- const found = await agentFor(request.payload.sessionId)
- if ('error' in found) return err(request, found.error)
- try {
- goals.clear(found.agent, request.payload.ref)
- return ok(request, { cleared: true as const })
- } catch (error: unknown) {
- return goalError(request, error)
- }
- },
- },
- skills: {
- // Skill lookup never touches the Agent registry: the session address
- // resolves to a canonical cwd from the host-resident session header, so
- // listing skills cannot create or resume an agent as a side effect.
- async list(request) {
- const { sessionId } = request.payload
- const session = ctx.sessions.get(sessionId)
- if (session === undefined) {
- return err(request, {
- code: 'session-not-found',
- message: `session "${sessionId}" not found (not attached)`,
- details: { sessionId },
- })
- }
- if (session.header.cwd === undefined) {
- // Every served session records its project at create time; a
- // cwd-less header is a pre-project legacy log (not served).
- return err(request, { code: 'internal', message: `session "${sessionId}" has no project cwd`, details: {} })
- }
- const cwd = session.header.cwd
- // Same stance as the commands domain: a missing service means the
- // deployment omitted dsh-skill from its composition, not an empty
- // catalog. ctx.get also keeps this handler independent of the gateway
- // plugin's inject list (an undeclared `ctx.skills` property read
- // fails the reflect proxy).
- const skillRegistry = ctx.get('skills')
- if (skillRegistry === undefined) {
- 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: {} })
- }
- try {
- const skills = (await skillRegistry.list({ cwd }))
- .filter(skill => skill.invocation.modelInvocable && skill.invocation.userInvocable)
- return ok(request, {
- skills: skills.map(skill => ({
- name: skill.name,
- description: skill.description,
- ...skill.whenToUse === undefined ? {} : { whenToUse: skill.whenToUse },
- })),
- })
- } catch (error: unknown) {
- return err(request, { code: 'internal', message: `skill listing failed: ${String(error)}`, details: {} })
- }
- },
- },
- events: {
- mux(_request, signal) {
- const queue = new FrameQueue<RpcRequest<MuxFrame>>()
- muxQueues.add(queue)
- for (const session of ctx.sessions.list()) {
- subscribeSession(queue, session)
- }
- for (const pending of pendingQuestions.values()) {
- queue.push({
- rpcId: pending.rpcId,
- payload: {
- type: 'question/requested', sessionId: pending.sessionId,
- questions: pending.questions,
- },
- })
- }
- // Refresh recovery: still-pending approval questions replay with their
- // stable rpcId so a reconnecting client can still answer them.
- for (const pending of pendingApprovals.values()) queue.push(requestedFrame(pending))
- // Queue snapshot baseline (pendingQuestions precedent): frames replayed
- // in arrival order per session; a reconnecting client rebuilds its
- // queue view from these alone.
- for (const [sessionId, items] of queuedMirror) {
- queue.push(frame({
- type: 'session/queue',
- sessionId,
- items: items.map(item => ({
- id: item.id,
- message: item.message,
- })),
- }))
- }
- // Per-session open-call table for result-view pairing. Bounded by the
- // per-turn call count: entries clear on turn/end; a table miss (stream
- // opened mid-turn) backscans the session's in-memory events instead.
- const openCalls = new Map<SessionId, Map<string, { name: string; args: unknown }>>()
- const disposers = [
- ctx.on('session/event', (session: Session, event: SessionEvent) => {
- if (event.type === 'tool/call') {
- const data = event.data as ToolCallData
- try {
- let table = openCalls.get(session.id)
- if (table === undefined) openCalls.set(session.id, table = new Map<string, { name: string; args: unknown }>())
- table.set(data.callId, { name: data.name, args: JSON.parse(data.arguments) })
- } catch {
- // Unparseable model arguments: leave the table unset; the result view soft-falls.
- }
- } else if (event.type === 'turn/end') {
- openCalls.delete(session.id)
- }
- const view = viewFor(ctx, event, callId =>
- openCalls.get(session.id)?.get(callId) ?? backscanArgs(session.events, callId))
- queue.push(frame({ type: 'session/event', sessionId: session.id, event, ...view === undefined ? {} : { view } }))
- }),
- ctx.on('session/created', (session: Session) => {
- subscribeSession(queue, session)
- }),
- ctx.on('session/disposed', (session: Session) => {
- openCalls.delete(session.id)
- }),
- ]
- return queue.iterate(signal, () => {
- muxQueues.delete(queue)
- for (const dispose of disposers) dispose()
- })
- },
- host(_request, signal) {
- const queue = new FrameQueue<RpcRequest<HostFrame>>()
- const committedWorkspaceIds = new Set(
- ctx.workspace.list().map(workspace => String(workspace.id)),
- )
- const disposers = [
- ctx.on('session/created', (session: Session) => {
- queue.push(frame({
- type: 'host/session-added',
- sessionId: session.id,
- // Derived at frame time like summarize(); a just-created session
- // has run no turn yet, so this is constantly true in practice.
- blank: sessionBlank(session),
- ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession },
- // cwd rides the frame so the client list needs no refresh to group the new session.
- ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd },
- }))
- }),
- ctx.on('session/disposed', (session: Session) => {
- queue.push(frame({ type: 'host/session-removed', sessionId: session.id }))
- }),
- ctx.on('agent/status', (agent: Agent, status: AgentStatus) => {
- queue.push(frame({ type: 'host/session-status', sessionId: agent.id, running: status === 'running' }))
- }),
- ctx.on('agent/error', (agent: Agent, _turn: number, _step: number, error: unknown) => {
- queue.push(frame({ type: 'host/agent-error', sessionId: agent.id, message: errorChain(error) }))
- }),
- ctx.on('domain/changed', (change) => {
- if (change.domain !== 'workspace') return
- if (change.table === '') {
- if (change.operation !== 'put') return
- const state = workspaceDomainState.parse(change.value)
- for (const workspaceId of state.workspaceIds) {
- if (committedWorkspaceIds.has(workspaceId)) continue
- const workspace = ctx.workspace.get(workspaceId)
- if (workspace === undefined) {
- throw new Error(`committed workspace registry references missing workspace "${workspaceId}"`)
- }
- committedWorkspaceIds.add(workspaceId)
- queue.push(frame({ type: 'host/workspace-changed', workspace: workspaceView(workspace) }))
- }
- return
- }
- if (change.table !== 'workspaces') return
- if (change.operation === 'deleted') {
- if (!committedWorkspaceIds.delete(change.key)) return
- queue.push(frame({
- type: 'host/workspace-removed',
- workspaceId: change.key as WorkspaceId,
- }))
- return
- }
- if (!committedWorkspaceIds.has(change.key)) return
- // Existing-entity table writes are complete attach/touch commits.
- // A new entity's first put waits for the global registry write above.
- queue.push(frame({
- type: 'host/workspace-changed',
- workspace: changedWorkspaceView(change.key, change.value),
- }))
- }),
- ctx.on('commands/change', () => {
- queue.push(frame({ type: 'host/commands-changed' }))
- }),
- ]
- return queue.iterate(signal, () => { for (const dispose of disposers) dispose() })
- },
- },
- respond(message: ClientResponse): Promise<RpcReceipt> {
- // Route by the echoed rpcId (the wire correlation): approvals first,
- // then questions — the two registries share one id space of UUIDs.
- const approval = pendingApprovals.get(message.rpcId)
- if (approval !== undefined) {
- if (!message.result.ok) return Promise.resolve({ accepted: false, reason: 'bad-response' })
- const parsed = approvalResponsePayloadSchema.safeParse(message.result.value)
- // The payload's audit correlation must match the entry the rpcId routed
- // to — a mismatched answer is malformed, not merely late.
- if (!parsed.success || parsed.data.approvalId !== approval.approvalId || parsed.data.sessionId !== approval.sessionId) {
- return Promise.resolve({ accepted: false, reason: 'bad-response' })
- }
- approval.resolve(parsed.data.outcome)
- return Promise.resolve({ accepted: true })
- }
- const pending = pendingQuestions.get(message.rpcId)
- if (pending === undefined) return Promise.resolve({ accepted: false, reason: 'not-pending' })
- if (!message.result.ok) {
- if (message.result.error.code !== 'cancelled') {
- return Promise.resolve({ accepted: false, reason: 'bad-response' })
- }
- claimQuestion(pending, 'cancelled')
- pending.reject(new UserInteractionError(
- 'the user cancelled ask_user_question', 'ASK_CANCELLED'))
- return Promise.resolve({ accepted: true })
- }
- const parsed = questionResponsePayloadSchema.safeParse(message.result.value)
- if (!parsed.success) {
- return Promise.resolve({ accepted: false, reason: 'bad-response' })
- }
- const payload: QuestionResponsePayload = {
- sessionId: parsed.data.sessionId,
- answer: {
- answers: parsed.data.answer.answers.map(answer => ({
- id: answer.id,
- selected: answer.selected,
- ...(answer.custom === undefined ? {} : { custom: answer.custom }),
- })),
- },
- }
- if (!matchesQuestions(payload, pending)) {
- return Promise.resolve({ accepted: false, reason: 'bad-response' })
- }
- claimQuestion(pending, 'answered')
- pending.resolve(payload.answer)
- return Promise.resolve({ accepted: true })
- },
- }
- }
|