// HTTP client for the somora server. Keeps fetch-shaped code out of // components — they just await these. // // Uses loopbackFetch (undici dispatcher with no headers/body timeout) // because the TUI client polls and posts into the same somora server // over loopback, and several routes (`/chat/send-sync`, `/chat/history` // when long, `send` during a long turn) can legitimately keep the // connection idle for many minutes. With plain fetch undici would kill // these at 5 minutes once HTTPS is the transport. import { loopbackFetch } from '../../server/loopback-fetch.ts'; /** A failed response's message: the server's `{ error }` when it sent * one, else the body as it came. */ async function errorText(res: Response): Promise { const body = await res.text(); try { const parsed = JSON.parse(body) as { error?: unknown }; if (typeof parsed.error === 'string') return parsed.error; } catch { /* not JSON */ } return body || `HTTP ${res.status}`; } import type { FromSystemKind, TurnOrigin } from './types.ts'; import type { AgentInfo, ModelInfo, ProjectEntityInfo, ProjectInfo, ResetResult, SamplingPatch, SessionModelInfo, SessionProjectInfo, SessionQuestion, SessionSamplingInfo, SessionSummary, SessionWork, SessionThinkingInfo, ThinkingLevel, TuiConfig, } from './types.ts'; export class Api { constructor(private readonly base: string) {} async fetchAgents(): Promise { const res = await loopbackFetch(`${this.base}/agents`); return (await res.json()) as AgentInfo[]; } async fetchTuiConfig(): Promise { const res = await loopbackFetch(`${this.base}/tui-config`); if (!res.ok) throw new Error(`tui-config ${res.status}`); return (await res.json()) as TuiConfig; } async fetchSystemPrompt(agent: string): Promise { const res = await loopbackFetch(`${this.base}/agents/${encodeURIComponent(agent)}/system-prompt`); if (!res.ok) return null; const data = (await res.json()) as { systemPrompt?: string }; return typeof data.systemPrompt === 'string' ? data.systemPrompt : null; } async fetchLoopState(): Promise<{ active: boolean; agent?: string; dreamId?: string } | null> { try { const res = await loopbackFetch(`${this.base}/dream/loop-state`); if (!res.ok) return null; const data = (await res.json()) as { active?: boolean; agent?: string; dreamId?: string; }; return data && typeof data.active === 'boolean' ? { active: data.active, ...(data.agent ? { agent: data.agent } : {}), ...(data.dreamId ? { dreamId: data.dreamId } : {}), } : null; } catch { return null; } } async fetchSessions(agent: string, opts: { includeArchived?: boolean } = {}): Promise { const query = opts.includeArchived ? '?include_archived=true' : ''; const res = await loopbackFetch(`${this.base}/agents/${encodeURIComponent(agent)}/sessions${query}`); if (!res.ok) return []; return (await res.json()) as SessionSummary[]; } /** Compact the session by hand. Resolves with the server's outcome; * a running turn answers 409 with `busy: true`. */ async compactSession( agent: string, session: string, instructions?: string, ): Promise<{ status: string; engine?: string; note?: string; tokensBefore?: number; tokensAfter?: number; error?: string; busy?: boolean }> { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/compact`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(instructions ? { instructions } : {}) }, ); const body = (await res.json().catch(() => ({}))) as Record; if (!res.ok && typeof body.error === 'string') return { status: 'error', error: body.error, ...(body.busy === true ? { busy: true } : {}) }; return body as { status: string }; } /** Bring an archived session back. Returns the name it is listed * under now (a reset archive comes back as `-archive`). */ async unarchiveSession(agent: string, session: string): Promise<{ session: string; slug: string }> { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/unarchive`, { method: 'POST' }, ); const body = (await res.json().catch(() => ({}))) as { session?: string; slug?: string; error?: string }; if (!res.ok || !body.session) throw new Error(body.error ?? `unarchive failed (HTTP ${res.status})`); return { session: body.session, slug: body.slug ?? body.session }; } async createSession(agent: string, slug: string): Promise { const res = await loopbackFetch(`${this.base}/agents/${encodeURIComponent(agent)}/sessions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ slug }), }); if (res.status === 409) { const taken = (await res.json().catch(() => ({}))) as { id?: string }; if (taken.id) return taken.id; } if (!res.ok) throw new Error(await errorText(res)); const data = (await res.json()) as { id: string }; return data.id; } async resetSession(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/reset`, { method: 'POST' }, ); if (!res.ok) throw new Error(await errorText(res)); return (await res.json()) as ResetResult; } /** The server's view of config.yaml; `invalid` is set while the file * does not validate and the last valid version keeps running. */ async fetchConfigProblem(): Promise<{ since: string; message: string } | null> { try { const res = await loopbackFetch(`${this.base}/config/status`); if (!res.ok) return null; const body = (await res.json()) as { invalid?: { since: string; message: string } | null }; return body.invalid ?? null; } catch { return null; } } async fetchModels(): Promise { const res = await loopbackFetch(`${this.base}/models`); if (!res.ok) return []; return (await res.json()) as ModelInfo[]; } async fetchSessionModel(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/model`, ); if (!res.ok) return null; return (await res.json()) as SessionModelInfo; } async setSessionModel(agent: string, session: string, ref: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/model`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: ref }), }, ); if (!res.ok) throw new Error(await errorText(res)); } async clearSessionModel(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/model`, { method: 'DELETE' }, ); if (!res.ok) throw new Error(await errorText(res)); } async fetchSessionThinking(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/thinking`, ); if (!res.ok) return null; return (await res.json()) as SessionThinkingInfo; } async setSessionThinking(agent: string, session: string, level: ThinkingLevel): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/thinking`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ level }), }, ); if (!res.ok) throw new Error(await errorText(res)); } async clearSessionThinking(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/thinking`, { method: 'DELETE' }, ); if (!res.ok) throw new Error(await errorText(res)); } async fetchSessionSampling(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/sampling`, ); if (!res.ok) return null; return (await res.json()) as SessionSamplingInfo; } /** PUT merges into the existing override; a key set to null removes it. */ async setSessionSampling(agent: string, session: string, patch: SamplingPatch): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/sampling`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch), }, ); if (!res.ok) throw new Error(await errorText(res)); } /** DELETE clears the whole session override. */ async clearSessionSampling(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/sampling`, { method: 'DELETE' }, ); if (!res.ok) throw new Error(await errorText(res)); } async reloadConfig(): Promise<{ ok: boolean; changed?: string[]; restartRequired?: string[]; error?: string }> { const res = await loopbackFetch(`${this.base}/config/reload`, { method: 'POST' }); const body = (await res.json().catch(() => ({}))) as { ok?: boolean; changed?: string[]; restartRequired?: string[]; error?: string }; if (!res.ok) return { ok: false, error: body.error ?? `reload ${res.status}` }; return { ok: true, changed: body.changed ?? [], restartRequired: body.restartRequired ?? [] }; } async restartServer(): Promise<{ ok: boolean; error?: string; expectedDowntimeSeconds?: number }> { const res = await loopbackFetch(`${this.base}/server/restart`, { method: 'POST' }); const body = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string; expectedDowntimeSeconds?: number }; if (!res.ok) return { ok: false, error: body.error ?? `restart ${res.status}` }; return { ok: true, expectedDowntimeSeconds: body.expectedDowntimeSeconds }; } async send(agent: string, session: string, text: string): Promise<{ turnId: string }> { const res = await loopbackFetch(`${this.base}/chat/send`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ agent, session, text }), }); if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); // turnId is echoed by the server so the TUI can pair the // pending-queued entry it just created with later SSE events // (turn_queued, user_message). Older servers don't return it — // empty string means no queue indicator possible (but the turn // still runs fine). const body = (await res.json().catch(() => ({}))) as { turnId?: string }; return { turnId: typeof body.turnId === 'string' ? body.turnId : '' }; } /** What the session is doing, what waits behind it, what is about to * arrive and what it started elsewhere. Null when the server does * not have the route (older server) or the session is unknown. */ async fetchWork(agent: string, session: string): Promise { try { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/work`, ); if (!res.ok) return null; const data = (await res.json()) as Partial; if (!data || typeof data !== 'object') return null; return { asOf: typeof data.asOf === 'number' ? data.asOf : Date.now(), agent: data.agent ?? agent, session: data.session ?? session, busy: Boolean(data.busy), active: data.active ?? null, queued: Array.isArray(data.queued) ? data.queued : [], pendingWakes: Array.isArray(data.pendingWakes) ? data.pendingWakes : [], children: Array.isArray(data.children) ? data.children : [], }; } catch { return null; } } /** Take a waiting entry out of the queue before it starts. The id is * the work id (a human turn's turnId, an agent_ask call id, a spawn * task id). A human entry hands its text back. */ async dequeue(id: string): Promise { const res = await loopbackFetch(`${this.base}/chat/queue/${encodeURIComponent(id)}`, { method: 'DELETE', }); const body = (await res.json().catch(() => ({}))) as { ok?: boolean; kind?: string; text?: string; reason?: string; error?: string; }; if (res.ok) { return { status: 'removed', id, kind: typeof body.kind === 'string' ? body.kind : 'human', ...(typeof body.text === 'string' ? { text: body.text } : {}), }; } if (res.status === 409) return { status: 'already_started', id }; if (res.status === 404) return { status: 'unknown', id }; return { status: 'error', id, error: body.error ?? `dequeue ${res.status}` }; } /** Stop a sub-agent task this session started (POST /spawn-cancel, * no requesting_agent = the person). Cascades to its children. */ async cancelSpawn(taskId: string): Promise<{ ok: true } | { ok: false; error: string }> { const res = await loopbackFetch(`${this.base}/spawn-cancel`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ task_id: taskId }), }); if (res.ok) return { ok: true }; const body = (await res.json().catch(() => ({}))) as { error?: string }; return { ok: false, error: body.error ?? `spawn-cancel ${res.status}` }; } streamUrl(agent: string, session: string): string { return `${this.base}/chat/stream?agent=${encodeURIComponent(agent)}&session=${encodeURIComponent(session)}`; } activityStreamUrl(): string { return `${this.base}/activity/stream`; } /** Mark a session "seen" — the user is looking at this (agent, * session) right now. Server clamps to max(currentSeenAt, ts) and * broadcasts to sibling clients so their unread badges clear too. */ async markSeen(agent: string, session: string): Promise { try { await loopbackFetch( `${this.base}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(session)}/seen`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}), }, ); } catch { /* network blip — next focus will retry */ } } /** * Pull historical events for a session — used to repopulate the * scrollback when the TUI opens or switches to a session that * already has history. Returns the raw NormalizedEvent shape from * the JSONL; the TUI side filters + maps to its own Turn type. */ async fetchHistory( agent: string, session: string, ): Promise<{ events: HistoryEvent[] }> { const res = await loopbackFetch( `${this.base}/chat/history?agent=${encodeURIComponent(agent)}&session=${encodeURIComponent(session)}`, ); if (!res.ok) return { events: [] }; return (await res.json()) as { agent: string; session: string; events: HistoryEvent[] }; } /** * Tell the server to abort the in-flight chat turn for this * (agent, session). No-op if no turn is running. */ async abortTurn(agent: string, session: string): Promise { await loopbackFetch( `${this.base}/chat/abort?agent=${encodeURIComponent(agent)}&session=${encodeURIComponent(session)}`, { method: 'POST' }, ).catch(() => { /* best-effort — UI shouldn't error on abort */ }); } /** Feature-flag probe for the projects feature. Always 200; clients * use this at boot to decide whether to register the /projekt slash * commands and render the project chip. */ async fetchProjectsEnabled(): Promise { try { const res = await loopbackFetch(`${this.base}/projects/feature`); if (!res.ok) return false; const data = (await res.json()) as { enabled?: boolean }; return Boolean(data.enabled); } catch { return false; } } /** Phase Projects v1 — read controlled-vocab entity list. Returns [] * when projects.enabled is false (server returns 503 → treat as * feature-off, no error). */ async fetchProjectEntities(): Promise { const res = await loopbackFetch(`${this.base}/projects/entities`); if (!res.ok) return []; const data = (await res.json()) as { entities?: ProjectEntityInfo[] }; return data.entities ?? []; } /** List all (non-archived by default) projects. Empty when projects * feature is off. */ async fetchProjects(includeArchived = false): Promise { const url = includeArchived ? `${this.base}/projects?includeArchived=true` : `${this.base}/projects`; const res = await loopbackFetch(url); if (!res.ok) return []; const data = (await res.json()) as { projects?: ProjectInfo[] }; return data.projects ?? []; } /** Fetch current project focus for a session. Returns slug=null when * nothing is pinned OR when the feature is disabled. */ async fetchSessionProject(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/project`, ); if (!res.ok) return { slug: null, project: null }; const data = (await res.json()) as { slug?: string | null; project?: ProjectInfo | null; }; return { slug: data.slug ?? null, project: data.project ?? null, }; } /** The session's open question, or null (also on an older server). */ async fetchSessionQuestion(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/question`, ); if (!res.ok) return null; return ((await res.json()) as { question?: SessionQuestion | null }).question ?? null; } /** Answer the session's open question with an option label. */ async answerSessionQuestion(agent: string, session: string, questionId: string, labels: string[]): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/questions/${encodeURIComponent(questionId)}/answer`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ answers: labels }) }, ); if (!res.ok) { const body = (await res.json().catch(() => ({}))) as { error?: string }; throw new Error(body.error ?? `HTTP ${res.status}`); } } /** Pin a project to a session. */ async setSessionProject(agent: string, session: string, slug: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/project`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ slug }), }, ); if (!res.ok) throw new Error(await errorText(res)); } /** Clear the pinned project for a session. */ async clearSessionProject(agent: string, session: string): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/project`, { method: 'DELETE' }, ); if (!res.ok) throw new Error(await errorText(res)); } /** * Fetch a session export as text. Server picks the renderer based on * `format` and sends back the full document body (markdown or * JSONL). The TUI persists this to a local file — there's no * progress reporting; sessions are small (single-digit MBs at * extreme), the HTTP response arrives in one go. */ async exportSession( agent: string, session: string, format: 'json' | 'markdown', ): Promise { const res = await loopbackFetch( `${this.base}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/export?format=${format}`, ); if (!res.ok) throw new Error(`export failed: ${res.status} ${await res.text()}`); return await res.text(); } } export type DequeueResult = | { status: 'removed'; id: string; kind: string; text?: string } | { status: 'already_started'; id: string } | { status: 'unknown'; id: string } | { status: 'error'; id: string; error: string }; /** * Subset of the NormalizedEvent shape the history endpoint serves. * We don't import the server's full type — that pulls in too much * server-side dep tree into the CLI bundle. Just declare what the * TUI actually reads from history. */ export interface HistoryEvent { kind: string; ts: number; text?: string; from_agent?: string; from_session?: string; from_system?: FromSystemKind; origin?: TurnOrigin; agent_ask_call_id?: string; // tool_call / tool_result callId?: string; tool?: string; input?: unknown; output?: unknown; error?: string; // engine_meta engine?: string; itemType?: string; payload?: unknown; /** `kind: 'model_fallback'` rows. */ requested?: string; actual?: string; reason?: string; hops?: Array<{ model: string; reason: string }>; // thinking_message truncated?: boolean; }