Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777// The page only ever talks to its own origin: `/api` is forwarded to the// daemon with its token by `albedo web` (or by Vite in development).
import type { components } from './api.gen';import type { SessionFilter } from './session-filter';type SettingsRevisionObserver = (group: string, etag: string) => void;const settingsRevisionObservers = new Set<SettingsRevisionObserver>();
export function observeSettingsRevisions( observer: SettingsRevisionObserver,): () => void { settingsRevisionObservers.add(observer); return () => { settingsRevisionObservers.delete(observer); };}
function reportSettingsRevision(group: string, etag: string): void { if (group === 'providers' && etag !== providersRevision) { providersRevision = etag; clearCatalogCache(); } for (const observer of settingsRevisionObservers) observer(group, etag);}
export type Phase = components['schemas']['SessionStatus']['phase'];export type CompactionProgress = components['schemas']['CompactionProgress'];
export type Session = components['schemas']['SessionSummary'] & { configuration_resource?: components['schemas']['SessionConfigurationResource'];};export type PreferencePatch = components['schemas']['PreferencePatch'];export type SelectionPatch = components['schemas']['SelectionPatch'];export type CompactionResult = components['schemas']['CompactionResult'];export type CatalogCandidate = components['schemas']['CatalogCandidate'];
interface Page<T> { items: T[]; next: string | null;}
export class ApiError extends Error { constructor( readonly status: number, readonly code: string, message: string, ) { super(message); }}
async function request<T>( method: string, path: string, init: { signal?: AbortSignal; body?: unknown; headers?: Record<string, string>; } = {},): Promise<T> { const raw = init.body instanceof Blob; const response = await fetch(`/api${path}`, { method, signal: init.signal, headers: { accept: 'application/json', ...(init.body === undefined || raw ? {} : { 'content-type': method === 'PATCH' ? 'application/merge-patch+json' : 'application/json', }), ...init.headers, }, body: init.body === undefined || raw ? (init.body as Blob | undefined) : JSON.stringify(init.body), }); if (!response.ok) throw await failure(response); if ( method !== 'GET' && method !== 'HEAD' && (path.startsWith('/settings') || path.startsWith('/auth') || path.endsWith('/reload')) ) clearCatalogCache(); return response.status === 204 ? (undefined as T) : response.json();}
// The daemon answers problems as RFC 9457 bodies; `albedo web` uses {error}.async function failure(response: Response): Promise<ApiError> { const body = await response.json().catch(() => null); const problem = body?.error ?? body ?? {}; return new ApiError( response.status, problem.code ?? 'http_error', problem.detail ?? problem.title ?? response.statusText, );}
function get<T>(path: string, signal?: AbortSignal): Promise<T> { return request<T>('GET', path, { signal });}
// Older sessions may lack either time; activity falls back to creation.export function listSessions( signal?: AbortSignal, options: { filter?: SessionFilter; limit?: number; next?: string | null; } = {},): Promise<Page<Session>> { const query = new URLSearchParams({ scope: 'roots', limit: String(options.limit ?? 200), }); for (const [name, value] of Object.entries(options.filter ?? {})) if (value !== undefined) query.set(name, String(value)); if (options.next) query.set('next', options.next); return get<Page<Session>>(`/sessions?${query}`, signal).then((page) => ({ next: page.next, items: page.items.map((session) => ({ ...session, activity_at: session.activity_at ?? session.created_at, })), }));}
export type ContentPart = HistoryEntry['content'][number];
export type HistoryEntry = components['schemas']['HistoryEntry'];export type MailMetadata = components['schemas']['MailMetadata'];
export type HistoryPage = components['schemas']['HistoryPage'];
/** A page of a session's transcript, oldest first: the newest page, or the one before or after a position. */export function readHistory( sessionId: string, at: { before?: number; after?: number; limit?: number } = {}, signal?: AbortSignal,): Promise<HistoryPage> { const query = new URLSearchParams({ limit: String(at.limit ?? 100) }); if (at.before !== undefined) query.set('before', String(at.before)); if (at.after !== undefined) query.set('after', String(at.after)); return get(`/sessions/${sessionId}/history?${query}`, signal);}
export type RequestRecord = components['schemas']['ProviderRequestRecord'];
/** * A page of a session's provider requests, oldest first: every model call * with its timing and tokens. `after` is a request's sequence. */export function readRequests( sessionId: string, after = 0, limit = 200, signal?: AbortSignal, since?: number,): Promise<{ items: RequestRecord[]; next: string | null }> { const query = new URLSearchParams({ after: String(after), limit: String(limit), }); if (since !== undefined) query.set('since_ms', String(since)); return get(`/sessions/${sessionId}/requests?${query}`, signal);}
/** One session as the daemon has it now, without its history. */export function getSession( sessionId: string, signal?: AbortSignal,): Promise<components['schemas']['Session']> { return get(`/sessions/${sessionId}?tail=0`, signal);}
export type ContextWindow = components['schemas']['ContextWindow'];
/** The window the session compacts against, which the context meter measures its share by. */export function getContextWindow( sessionId: string, signal?: AbortSignal,): Promise<ContextWindow> { return get(`/sessions/${sessionId}/context-window`, signal);}
export type ContextSummary = components['schemas']['ContextSummary'];
/** The prepared request's section summary and compaction threshold, without preparing a request. */export function getContextSummary( sessionId: string, signal?: AbortSignal,): Promise<ContextSummary> { return get(`/sessions/${sessionId}/context`, signal);}
/** Compacts the session's model context now (optionally switching to `strategy` first). */type CompactionReceipt = components['schemas']['CompactionReceipt'];interface PendingCompaction { id: string; strategy?: string; observing?: Promise<CompactionResult>;}const pendingCompactions = new Map<string, PendingCompaction>();
export function readCompaction( sessionId: string, actionId: string,): Promise<CompactionReceipt> { return get(`/sessions/${sessionId}/compactions/${actionId}`);}
export async function compactSession( sessionId: string, strategy?: string,): Promise<CompactionResult> { let action = pendingCompactions.get(sessionId); if (action && action.strategy !== strategy) throw new Error( `Resolve compaction ${action.id} before changing its intent.`, ); const resumed = !!action; if (!action) { action = { id: uuidv7(), strategy }; pendingCompactions.set(sessionId, action); } if (action.observing) return action.observing; try { action.observing = observeCompaction(sessionId, action, resumed); return await action.observing; } catch (error) { if (error instanceof ApiError && error.code === 'identity_expired') throw new ApiError( error.status, error.code, `Compaction ${action.id} expired with an unknown outcome. Inspect the session before reloading this page to start a new compaction.`, ); throw error; } finally { action.observing = undefined; }}
async function observeCompaction( sessionId: string, action: PendingCompaction, resumed: boolean,): Promise<CompactionResult> { const strategy = action.strategy; const url = `/sessions/${sessionId}/compactions/${action.id}`; async function submit(): Promise<CompactionReceipt> { try { return await request<CompactionReceipt>('PUT', url, { body: strategy ? { strategy } : {}, }); } catch (error) { if (error instanceof ApiError && error.status < 500) { if (error.code !== 'identity_expired') pendingCompactions.delete(sessionId); throw error; } return readCompaction(sessionId, action.id); } } let receipt: CompactionReceipt; if (resumed) { try { receipt = await readCompaction(sessionId, action.id); } catch (error) { if (!( error instanceof ApiError && error.status === 404 && error.code === 'compaction_unknown' )) throw error; receipt = await submit(); } } else { receipt = await submit(); } function validateReceipt(value: CompactionReceipt) { if ( value.id !== action.id || value.session_id !== sessionId || !['running', 'completed', 'interrupted'].includes(value.state) || (value.state === 'completed') !== !!value.result ) throw new Error( 'Invalid compaction receipt. Retry to resolve the same action.', ); } validateReceipt(receipt); const deadline = Date.now() + 200_000; let delay = 200; while (receipt.state === 'running') { if (Date.now() >= deadline) throw new Error( `Compaction ${action.id} is still unresolved. Retry to read the same action.`, ); await new Promise((resolve) => setTimeout(resolve, delay)); delay = Math.min(2000, delay * 2); receipt = await readCompaction(sessionId, action.id); validateReceipt(receipt); } if (pendingCompactions.get(sessionId) === action) pendingCompactions.delete(sessionId); if (receipt.state === 'interrupted' || !receipt.result) throw new Error( `Compaction ${action.id} was interrupted. Inspect context before starting another action.`, ); return receipt.result;}
/** Reloads a session's active extension composition so saved selection changes take effect. */export function reloadSession( sessionId: string, target: 'session' | 'models' | 'both' = 'session',): Promise<components['schemas']['ReloadResult']> { return request<components['schemas']['ReloadResult']>( 'POST', `/sessions/${sessionId}/reload`, { body: { target }, }, );}
export type GlobalExtension = components['schemas']['GlobalExtension'];
export type WebSearchProvider = components['schemas']['WebSearchProvider'];export type WebSearchChange = components['schemas']['WebSearchProviderChangeRequest']['change'];
/** Web search providers in the order a search tries them (global, in * extensions.json). 404 means the web-search extension is off. */export async function listWebSearchProviders( signal?: AbortSignal,): Promise<WebSearchProvider[]> { const page = await get<components['schemas']['WebSearchProviderPage']>( '/extensions/web-search/providers', signal, ); return page.items.map((item) => item.value);}
/** Moves one provider a place up or down, or turns it on or off. A move past * either end leaves the order as it was. */export async function changeWebSearchProvider( name: string, change: WebSearchChange,): Promise<WebSearchProvider> { const result = await request< components['schemas']['WebSearchProviderChange'] >('POST', `/extensions/web-search/providers/${encodeURIComponent(name)}`, { body: { change }, }); return result.resource.value;}
/** Installed extensions and resolved global defaults; no session is selected or changed. */async function listGlobalExtensions( signal?: AbortSignal,): Promise<GlobalExtension[]> { const server = await get<components['schemas']['Server']>( '/server?include=extensions', signal, ); if (!Array.isArray(server.extension_inventory)) throw new Error('The daemon sent a malformed global extension inventory.'); return server.extension_inventory;}
export async function listCompactionExtensions( sessionId: string, signal?: AbortSignal,): Promise<CatalogCandidate[]> { return (await sessionCatalog(sessionId, signal)).filter((c) => c.extension?.plugins.some((plugin) => ['compaction', 'notes'].includes(plugin), ), );}
export interface ExtensionChoices { candidates: CatalogCandidate[]; sessionETag: string; globalETag: string;}
/** Whether the mcp extension is on globally; null when it is not listed. */export async function mcpExtensionEnabled( signal?: AbortSignal,): Promise<boolean | null> { const listed = (await listGlobalExtensions(signal)).find( (extension) => extension.id === 'mcp', ); return listed ? listed.enabled : null;}
/** Every extension candidate in a session's catalog. */async function sessionCatalog( sessionId: string, signal?: AbortSignal,): Promise<CatalogCandidate[]> { const candidates: CatalogCandidate[] = []; let next: string | null = null; do { const page: components['schemas']['Catalog'] = await get( `/sessions/${sessionId}/catalog?kind=extensions&limit=200${next ? `&next=${encodeURIComponent(next)}` : ''}`, signal, ); if (page.discovery_failure) throw new Error(page.discovery_failure.detail); candidates.push(...(page.discovery?.candidates ?? [])); next = page.discovery?.next ?? null; } while (next); return candidates;}
/** The installed extensions and the validators for the two choice columns. * Without a session only the global column exists (see `globalExtensionChoices`). */export async function extensionChoices( sessionId?: string, signal?: AbortSignal,): Promise<ExtensionChoices> { if (sessionId === undefined) return globalExtensionChoices(signal); const [configuration, settings] = await Promise.all([ fetch(`/api/sessions/${sessionId}/configuration`, { signal }), fetch('/api/settings/extensions', { signal }), ]); for (const response of [configuration, settings]) if (!response.ok) throw await failure(response); const candidates = await sessionCatalog(sessionId, signal); return { candidates, sessionETag: configuration.headers.get('etag') ?? '', globalETag: settings.headers.get('etag') ?? '', };}
/** Global choices with their validator, with no session selected or changed. * The rows come from the daemon's global inventory, shaped like catalog * candidates with no override. The inventory carries no shelf, summary or * tools, so those are borrowed from the first session's catalog when there is * one (read-only: the metadata describes the extension, not the session); * without a session every row sits on the builtins shelf. The validator is read * before the inventory, so a change in between makes the save stale instead of * overwriting it. */async function globalExtensionChoices( signal?: AbortSignal,): Promise<ExtensionChoices> { const settings = await fetch('/api/settings/extensions', { signal }); if (!settings.ok) throw await failure(settings); const inventory = await listGlobalExtensions(signal); const [session] = (await listSessions(signal)).items; const described = new Map<string, CatalogCandidate['extension']>(); if (session) for (const candidate of await sessionCatalog(session.id, signal).catch( () => [], )) described.set(candidate.id, candidate.extension); const candidates: CatalogCandidate[] = inventory.map((item) => ({ id: item.id, kind: 'extension', title: item.id, description: item.description, source: '', resolved_source: null, preference_key: item.id, valid: !item.quarantined, eligible: !item.quarantined, effective_enabled: item.enabled, global_preference: item.enabled, session_override: null, shadowed_by: null, dependencies: item.requires, quarantined: item.quarantined, diagnostic: item.diagnostic === null ? null : { code: 'candidate_unavailable', detail: item.diagnostic }, extension: described.get(item.id) ?? null, })); return { candidates, sessionETag: '', globalETag: settings.headers.get('etag') ?? '', };}
/** Saves against the choices on screen; stale choices are never retried. A * session is needed only for the session scope. */export function selectExtensions( sessionId: string | undefined, scope: 'global' | 'session', choices: Record<string, boolean | null>, etag: string,): Promise<unknown> { return request( 'PATCH', scope === 'global' ? '/settings/extensions' : `/sessions/${sessionId}/configuration`, { body: scope === 'global' ? { defaults: choices } : { selection: { extensions: choices } }, headers: { 'if-match': etag }, }, );}
/** The sessions a session started: its child agents, with their own status. */export function listChildren( sessionId: string, signal?: AbortSignal,): Promise<Session[]> { return get<Page<Session>>( `/sessions?parent_id=${encodeURIComponent(sessionId)}&limit=200`, signal, ).then((page) => page.items);}
/** A whole family: the root session and every agent under it, however deep, with their own status. */export function listFamily( rootId: string, signal?: AbortSignal,): Promise<Session[]> { return get<Page<Session>>( `/sessions?family_id=${encodeURIComponent(rootId)}&limit=200`, signal, ).then((page) => page.items);}
type ContentPage = components['schemas']['EntryContentPage'];
/** * Every stored field of one entry in full, for content a history page only * referenced. `url` is the reference's own, which may name another entry. */export async function readEntryContent( url: string,): Promise<Record<string, string>> { const fields: Record<string, string> = {}; let next: string | null = null; do { const query: string = next ? `?next=${encodeURIComponent(next)}` : ''; const page: ContentPage = await get(`${url}${query}`); for (const part of page.parts) fields[part.field] = (fields[part.field] ?? '') + part.text; next = page.next; } while (next); return fields;}
/** * Several entries' stored fields in full, in one walk: one request per byte * budget rather than per entry. `ids` are at most 200 entry ids. */export async function readContentBatch( sessionId: string, ids: string[], signal?: AbortSignal,): Promise<Map<string, Record<string, string>>> { const fields = new Map<string, Record<string, string>>(); let next: string | null = null; do { const query = new URLSearchParams({ entries: ids.join(',') }); if (next) query.set('next', next); const page: components['schemas']['EntryContentBatch'] = await get( `/sessions/${sessionId}/history/content?${query}`, signal, ); for (const part of page.parts) { const entry = fields.get(part.entry_id) ?? {}; entry[part.field] = (entry[part.field] ?? '') + part.text; fields.set(part.entry_id, entry); } next = page.next; } while (next); return fields;}
/** * Puts text on the clipboard. Over plain http from another device the page * is not a secure context and has no Clipboard API, so it falls back to the * older copy command. */export async function copyText(text: string): Promise<void> { if (navigator.clipboard) return navigator.clipboard.writeText(text); const field = Object.assign(document.createElement('textarea'), { value: text, }); field.style.cssText = 'position:fixed;opacity:0'; document.body.append(field); field.select(); const copied = document.execCommand('copy'); field.remove(); if (!copied) throw new Error('copying is not available here');}
/** A UUIDv7: the daemon keys inputs by one, so a retried send is the same send. */export function uuidv7(): string { const bytes = crypto.getRandomValues(new Uint8Array(16)); let time = Date.now(); for (let i = 5; i >= 0; i--) { bytes[i] = time % 256; time = Math.floor(time / 256); } bytes[6] = (bytes[6] & 0x0f) | 0x70; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = [...bytes] .map((byte) => byte.toString(16).padStart(2, '0')) .join(''); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;}
/** * Stops the session's running turn and any inputs waiting behind it, and * returns the ids of the inputs it cancelled. The run and input order are read * fresh, so a stop never reaches a later run. */export async function interruptSession(sessionId: string): Promise<string[]> { const session = await get<components['schemas']['Session']>( `/sessions/${sessionId}`, ); const stopped = await request<components['schemas']['Interruption']>( 'POST', `/sessions/${sessionId}/interrupt`, { body: { run_id: session.status.run_id, through_input_order: session.input_order, }, }, ); return stopped.cancelled_input_ids;}
/** One background job as the kernel's job book keeps it; times are wall-clock milliseconds. */export type ShellCommand = components['schemas']['ShellCommand'];
/** Runs a human-authored shell command through the daemon, with a retry-stable id. */export async function submitShellCommand( sessionId: string, id: string, command: string,): Promise<ShellCommand> { return request<{ shell_command: ShellCommand }>( 'PUT', `/sessions/${sessionId}/shell-commands/${id}`, { body: { command } }, ).then((value) => value.shell_command);}
export async function getShellCommand( sessionId: string, id: string, signal?: AbortSignal,): Promise<ShellCommand> { return get<{ shell_command: ShellCommand }>( `/sessions/${sessionId}/shell-commands/${id}`, signal, ).then((value) => value.shell_command);}
export async function stopShellCommand( sessionId: string, id: string,): Promise<ShellCommand> { return request<{ shell_command: ShellCommand }>( 'POST', `/sessions/${sessionId}/shell-commands/${id}/stop`, ).then((value) => value.shell_command);}
export async function readShellOutput( sessionId: string, id: string, offset: number, signal?: AbortSignal, limit = 65536,): Promise<{ text: string; next_offset: number | null }> { return get<components['schemas']['ShellCommandOutput']>( `/sessions/${sessionId}/shell-commands/${id}/output?offset=${offset}&limit=${limit}`, signal, );}
/** One side question exchange: a question asked beside the session's turn, with its answer when it lands. */export type SideQuestion = components['schemas']['SideQuestion'];
function sideQuestionCall( method: string, sessionId: string, questionId: string, body: unknown, suffix = '',): Promise<SideQuestion> { return request<{ side_question: SideQuestion }>( method, `/sessions/${sessionId}/side-questions/${questionId}${suffix}`, { body }, ).then((value) => value.side_question);}
/** Asks a side question with a retry-stable id; the same id and question answer the current exchange and start nothing. */export function askSideQuestion( sessionId: string, questionId: string, question: string,): Promise<SideQuestion> { return sideQuestionCall('PUT', sessionId, questionId, { question });}
export function patchSideQuestion( sessionId: string, questionId: string, dismissed: boolean,): Promise<SideQuestion> { return sideQuestionCall('PATCH', sessionId, questionId, { dismissed });}
export function cancelSideQuestion( sessionId: string, questionId: string,): Promise<SideQuestion> { return sideQuestionCall('POST', sessionId, questionId, {}, '/cancel');}
/** * Creates the session a side question continues in, under a caller-chosen * id, so a repeated press retries the same creation. A lost response is * answered from the created session only when its recorded intent matches. */export async function continueSideQuestion( sourceSessionId: string, questionId: string, newSessionId: string,): Promise<components['schemas']['Session']> { try { return await request<components['schemas']['Session']>( 'PUT', `/sessions/${newSessionId}`, { body: { kind: 'side_question', source_session_id: sourceSessionId, side_question_id: questionId, name: null, }, headers: { 'if-none-match': '*' }, }, ); } catch (error) { const existing = await getSession(newSessionId).catch(() => null); const submitted = existing?.creation?.submitted; if ( existing && submitted?.kind === 'side_question' && submitted.source_session_id === sourceSessionId && submitted.side_question_id === questionId ) return existing; throw error; }}
let sideQuestionsSupport: Promise<boolean> | undefined;
/** Whether the daemon offers side questions (`side_questions` capability); read once per page. */export function sideQuestionsSupported(): Promise<boolean> { return (sideQuestionsSupport ??= get<components['schemas']['Server']>( '/server', ).then( (server) => (server.capabilities.side_questions ?? 0) >= 2, () => { sideQuestionsSupport = undefined; return false; }, ));}
export type Job = components['schemas']['JobRecord'];
/** A page of a job's output: the bytes from `offset` to `next_offset`, cut on characters. */export type JobPage = components['schemas']['JobOutputPage'];
/** The session's jobs, newest first, finished ones too while the kernel keeps their output. */export function listJobs( sessionId: string, signal?: AbortSignal,): Promise<Job[]> { return get<components['schemas']['JobRecordCollection']>( `/extensions/run/sessions/${sessionId}/jobs/recent`, signal, ).then((page) => page.items);}
/** A page of a job's output: from `offset`, or the last page when there is none. */export function readJobOutput( sessionId: string, jobId: string, offset?: number, signal?: AbortSignal,): Promise<JobPage> { const query = new URLSearchParams({ limit: '65536' }); if (offset !== undefined) query.set('offset', String(offset)); return get( `/extensions/run/sessions/${sessionId}/jobs/${encodeURIComponent(jobId)}/output?${query}`, signal, );}
/** Stops the job's process group; the kernel answers once it is gone. */export async function stopJob(sessionId: string, jobId: string): Promise<void> { await request( 'POST', `/extensions/run/sessions/${sessionId}/jobs/${encodeURIComponent(jobId)}/stop`, );}
/** A folder sessions have worked in, most used first. */export type RecentWorkspace = components['schemas']['RecentWorkspace'];
export type Directory = components['schemas']['WorkspaceDirectory'];
export function recentWorkspaces(): Promise<RecentWorkspace[]> { return get<Page<RecentWorkspace>>('/workspaces?limit=200').then( (page) => page.items, );}
export function browse(location: string): Promise<Directory> { return get<Directory>( `/workspaces?location=${encodeURIComponent(location)}&limit=200`, );}
/** A folder's directories and files, for the diff client's tree: its pages read in turn, at most `cap` entries. */export async function browseFiles( location: string, cap = 2000, signal?: AbortSignal,): Promise<Directory> { const base = `/workspaces?location=${encodeURIComponent(location)}&include=files&limit=200`; const first = await get<Directory>(base, signal); const items = [...first.items]; for (let next = first.next; next && items.length < cap;) { const page = await get<Directory>( `${base}&next=${encodeURIComponent(next)}`, signal, ); items.push(...page.items); next = page.next; } return { ...first, items };}
/** One text file on the machine of the session's workspace. */export type FileText = components['schemas']['SessionFile'];
export function readFile( sessionId: string, path: string, signal?: AbortSignal,): Promise<FileText> { return get<FileText>( `/sessions/${sessionId}/files?path=${encodeURIComponent(path)}`, signal, );}
/** What the session's checkout changed, against HEAD (`uncommitted`) or where its branch left its upstream. */export type CheckoutBase = components['schemas']['CheckoutChanges']['base']['spec'];export type CheckoutFile = components['schemas']['ChangedFile'];export type CheckoutChanges = components['schemas']['CheckoutChanges'];
/** * The checkout's changes, or null when they are the ones `etag` names: a * window following a working session asks every few seconds, and an * unchanged answer costs no body. */export async function readChanges( sessionId: string, base: CheckoutBase, etag?: string, signal?: AbortSignal,): Promise<{ etag: string; changes: CheckoutChanges } | null> { const response = await fetch( `/api/sessions/${sessionId}/changes?base=${base}`, { signal, headers: { accept: 'application/json', ...(etag ? { 'if-none-match': etag } : {}), }, }, ); if (response.status === 304) return null; if (!response.ok) throw await failure(response); return { etag: response.headers.get('etag') ?? '', changes: await response.json(), };}
/** The ssh hosts the daemon knows of: ones sessions worked on and its ssh config's, with their cached probe state. */export function knownHosts(): Promise<components['schemas']['Host'][]> { return get<components['schemas']['HostPage']>('/hosts?limit=200').then( (page) => page.items, );}
/** A provider profile: an account and endpoint, with the model and effort a new session starts on. */export type Profile = Pick< components['schemas']['ProviderProfile'], 'extension' | 'endpoint' | 'model' | 'effort'> & { id: string };
const CATALOG_TTL_MS = 10_000;let providersRevision = '';type ProfilesResult = { fallback: string | null; profiles: Profile[] };let cachedProfiles: { value: ProfilesResult; at: number } | null = null;let inflightProfiles: Promise<ProfilesResult> | null = null;const cachedModels = new Map<string, { value: Model[]; at: number }>();const inflightModels = new Map<string, Promise<Model[]>>();
function clearCatalogCache() { cachedProfiles = null; cachedModels.clear();}
function modelCacheKey(profile: string, sessionId?: string, initial = false) { return JSON.stringify([profile, sessionId ?? '', initial]);}
/** Last read profile list when already fetched, for painting pickers without a spinner. */export function peekProfiles(): ProfilesResult | null { return cachedProfiles?.value ?? null;}
/** Last read model catalogue for `profile` when already fetched. */export function peekModels( profile: string, sessionId?: string, initial = false,): Model[] | null { return ( cachedModels.get(modelCacheKey(profile, sessionId, initial))?.value ?? null );}
export function profiles(): Promise<ProfilesResult> { if (cachedProfiles && Date.now() - cachedProfiles.at < CATALOG_TTL_MS) return Promise.resolve(cachedProfiles.value); if (inflightProfiles) return inflightProfiles; inflightProfiles = get<components['schemas']['ProviderSettings']>( '/settings/providers', ) .then((providers) => { const list = Object.entries(providers.profiles).map(([id, profile]) => ({ ...profile, id, })); const result: ProfilesResult = { fallback: providers.default_profile, profiles: list.sort((a, b) => a.id.localeCompare(b.id)), }; cachedProfiles = { value: result, at: Date.now() }; return result; }) .finally(() => { inflightProfiles = null; }); return inflightProfiles;}
export type Model = components['schemas']['Model'];
/** A profile's whole catalogue, every page of it. */export function models( profile: string, sessionId?: string, initial = false,): Promise<Model[]> { const key = modelCacheKey(profile, sessionId, initial); const cached = cachedModels.get(key); if (cached && Date.now() - cached.at < CATALOG_TTL_MS) return Promise.resolve(cached.value); const pending = inflightModels.get(key); if (pending) return pending; const load = (async () => { const items: Model[] = []; let next: string | null = null; do { const query: string = next ? `&next=${encodeURIComponent(next)}` : ''; const page: Page<Model> = await get( `/models?provider_profile=${encodeURIComponent(profile)}${sessionId ? `&session=${encodeURIComponent(sessionId)}` : ''}${initial ? '&initial=true' : ''}${query}`, ); items.push(...page.items); next = page.next; } while (next); cachedModels.set(key, { value: items, at: Date.now() }); return items; })().finally(() => { inflightModels.delete(key); }); inflightModels.set(key, load); return load;}
/** The models an extension offers before any profile uses it, as the TUI's new-profile flow lists them. */export async function providerModels( extension: string, endpoint?: string,): Promise<Model[]> { const items: Model[] = []; let next: string | null = null; do { const query = `provider=${encodeURIComponent(extension)}${endpoint ? `&endpoint=${encodeURIComponent(endpoint)}` : ''}${next ? `&next=${encodeURIComponent(next)}` : ''}`; const page: Page<Model> = await get(`/models?${query}`); items.push(...page.items); next = page.next; } while (next); return items;}
export type Choice = Pick< components['schemas']['SessionConfiguration'], 'provider_profile' | 'model' | 'effort'> & { cyber_access?: null | 'daybreak_blue' };export type SessionConfiguration = components['schemas']['SessionConfiguration'];
/** Starts a session in a folder; null choices take the defaults. */export async function createSession( workspace: string, choice: Choice, sessionId = uuidv7(),): Promise<Session> { // If-None-Match makes the PUT a create: it never replaces a session. try { return await request<Session>('PUT', `/sessions/${sessionId}`, { body: { kind: 'new', workspace, ...choice }, headers: { 'if-none-match': '*' }, }); } catch (error) { // A lost response may follow a committed creation. Never allocate another // identity or reuse an existing one without proving the submitted intent. const existing = await getSession(sessionId).catch(() => null); const submitted = existing?.creation?.submitted; if ( existing && submitted?.kind === 'new' && submitted.workspace === workspace && submitted.name === null && submitted.context_window == null && submitted.provider_profile === choice.provider_profile && submitted.model === choice.model && submitted.effort === (choice.effort ?? null) && (submitted.cyber_access ?? null) === (choice.cyber_access ?? null) ) return existing; throw error; }}
/** Conditional configuration edits preserve an observed validator and surface stale writes. */export type SessionConfigPatch = | Partial<Choice> | { preferences: PreferencePatch } | { context_window: number | null } | { selection: SelectionPatch };
export async function configureSession( sessionId: string, change: SessionConfigPatch, etag: string,) { if (!etag) throw new Error('Read the session before changing its configuration.'); const url = `/sessions/${sessionId}/configuration`; try { const result = await request< components['schemas']['SessionConfigurationChange'] >('PATCH', url, { body: change, headers: { 'if-match': etag } }); return result.resource; } catch (error) { if (error instanceof ApiError && error.status === 412) throw new ApiError( 412, error.code, 'Session configuration changed. Review the current values and choose again.', ); throw error; }}
/** Moves a session to another folder, as the terminal's /cd does: on the same daemon, its kernel on that folder's host. */export async function moveWorkspace( sessionId: string, workspace: string,): Promise<void> { const session = await getSession(sessionId); await request('POST', `/sessions/${sessionId}/workspace`, { body: { workspace, family_revision: session.family_revision }, headers: { 'if-match': session.configuration_resource.etag }, });}
export type TransferPreflight = components['schemas']['TransferPreflight'];export type TransferRunsThere = components['schemas']['TransferRunsThere'];export type Move = components['schemas']['Move'];export type SessionMoved = components['schemas']['SessionMoved'];export type MoveBinding = components['schemas']['MoveBinding'];
/** Whether the session could move to the daemon on target's host now; the daemon answers within about ten seconds. */export function preflightMove( sessionId: string, target: string, signal?: AbortSignal,): Promise<TransferPreflight> { return get( `/transfers/preflight?${new URLSearchParams({ session_id: sessionId, target })}`, signal, );}
/** Starts moving the session to target's daemon, or answers the move already under `transferId`; `profiles` names the target profile for each session preflight offered alternatives for. */export function startMove( sessionId: string, transferId: string, target: string, profiles: Record<string, string> = {},): Promise<Move> { const body = Object.keys(profiles).length ? { transfer_id: transferId, target, profiles } : { transfer_id: transferId, target }; return request('POST', `/sessions/${sessionId}/move`, { body });}
export function readMove( transferId: string, signal?: AbortSignal,): Promise<Move> { return get(`/transfers/${transferId}`, signal);}
/** Disarms every binding the move's checklist lists and finishes the move; a partial failure answers the move still in checklist, each binding with its status. */export function finishMove(transferId: string): Promise<Move> { return request('POST', `/transfers/${transferId}/finish`);}
/** An MCP server and its OAuth sign-in, as the mcp settings group reports them; tokens never reach the page. */export type McpServer = components['schemas']['MCPDefinition'] & { name: string;};export type Login = components['schemas']['Login'];
// Provider accounts (the TUI's /login): sign-ins, saved API keys, renames and// removals. Secrets go in and never come back; GET /auth is redacted.export type Auth = components['schemas']['Auth'];export type Account = components['schemas']['Account'];export type LoginProvider = components['schemas']['LoginProvider'];export type LoginTerms = components['schemas']['LoginTerms'];
export function readAuth(signal?: AbortSignal): Promise<Auth> { return get('/auth', signal);}
/** Starts a provider sign-in at a fresh id; browser and manual flows send no values. */export function startLogin( provider: string, flow: 'browser' | 'manual' | 'device' | 'form', values: Record<string, unknown> = {},): Promise<Login> { return request('PUT', `/auth/logins/${uuidv7()}`, { body: { provider, flow, values }, });}
/** Hands the daemon a pasted callback URL or code for a manual sign-in. */export async function answerLogin( id: string, response: string,): Promise<Login> { const current = await fetch(`/api/auth/logins/${id}`, { headers: { accept: 'application/json' }, }); if (!current.ok) throw await failure(current); return request('PATCH', `/auth/logins/${id}`, { body: { response }, headers: { 'if-match': current.headers.get('etag') ?? '*' }, });}
export function saveKeyAccount( provider: string, endpoint: string, apiKey: string, label: string,): Promise<Account> { return request('PUT', `/auth/keys/${uuidv7()}`, { body: { provider, endpoint, api_key: apiKey, ...(label ? { label } : {}) }, });}
export function renameAccount(id: string, label: string): Promise<Account> { return request('PATCH', `/auth/accounts/${encodeURIComponent(id)}`, { body: { label }, });}
export function removeAccount(id: string): Promise<void> { return request('DELETE', `/auth/accounts/${encodeURIComponent(id)}`);}
// Webhooks (the TUI's /webhooks), served while the webhooks extension is on;// a 404 from the list means it is off.export type Hook = components['schemas']['Hook'];export type HookConfiguration = components['schemas']['HookConfiguration'];export type HookChange = components['schemas']['HookChange'];export type HookCreate = components['schemas']['HookCreate'];export type HookPatch = components['schemas']['HookPatch'];export type Delivery = components['schemas']['Delivery'];
export async function listHooks(signal?: AbortSignal): Promise<Hook[]> { const hooks: Hook[] = []; let next: string | null = null; do { const page: components['schemas']['HookPage'] = await get( `/extensions/webhooks/hooks?limit=200${next ? `&next=${encodeURIComponent(next)}` : ''}`, signal, ); hooks.push(...page.items); next = page.next ?? null; } while (next); return hooks;}
export function createHook(hook: HookCreate): Promise<HookChange> { return request('POST', '/extensions/webhooks/hooks', { body: hook });}
export function editHook( id: string, etag: string, patch: HookPatch,): Promise<HookChange> { return request( 'PATCH', `/extensions/webhooks/hooks/${encodeURIComponent(id)}?view=configuration`, { body: patch, headers: { 'if-match': etag }, }, );}
export function rotateHookSecret( id: string, etag: string, secret?: string,): Promise<HookChange> { return request( 'POST', `/extensions/webhooks/hooks/${encodeURIComponent(id)}/secret`, { body: secret ? { secret } : {}, headers: { 'if-match': etag } }, );}
export function deleteHook(id: string, etag: string): Promise<unknown> { return request( 'DELETE', `/extensions/webhooks/hooks/${encodeURIComponent(id)}?view=configuration`, { headers: { 'if-match': etag } }, );}
export async function hookDeliveries( id: string, signal?: AbortSignal,): Promise<Delivery[]> { const page: components['schemas']['DeliveryPage'] = await get( `/extensions/webhooks/hooks/${encodeURIComponent(id)}/deliveries?limit=20`, signal, ); return page.items;}
/** Whether a session's agent may manage hooks itself, with the validator a change needs. */export async function hookPermission( session: string, signal?: AbortSignal,): Promise<{ agent_manage: boolean; etag: string }> { const response = await fetch( `/api/extensions/webhooks/permissions/${encodeURIComponent(session)}`, { signal, headers: { accept: 'application/json' } }, ); if (!response.ok) throw await failure(response); const value: components['schemas']['HookPermission'] = await response.json(); return { agent_manage: value.agent_manage, etag: response.headers.get('etag') ?? '', };}
export async function setHookPermission( session: string, etag: string, agentManage: boolean,): Promise<void> { await request( 'PATCH', `/extensions/webhooks/permissions/${encodeURIComponent(session)}`, { body: { agent_manage: agentManage }, headers: { 'if-match': etag }, }, );}
// Discord bots (the TUI's /discord), one per session, served while the// discord extension is on; a 404 from the list means it is off. Tokens go in// and never come back.export type DiscordBot = components['schemas']['DiscordBot'];export type DiscordGuild = components['schemas']['DiscordGuild'];export type DiscordChannel = components['schemas']['DiscordChannel'];export type DiscordDelivery = components['schemas']['DiscordDelivery'];export type DiscordDMs = components['schemas']['DiscordDMs'];
export async function listDiscordBots( signal?: AbortSignal,): Promise<DiscordBot[]> { return ( await get<components['schemas']['DiscordBotPage']>( '/extensions/discord/bots', signal, ) ).items;}
export function createDiscordBot( bot: components['schemas']['DiscordBotCreate'],): Promise<DiscordBot> { return request('POST', '/extensions/discord/bots', { body: bot });}
export function editDiscordBot( id: string, patch: components['schemas']['DiscordBotPatch'],): Promise<DiscordBot> { return request( 'PATCH', `/extensions/discord/bots/${encodeURIComponent(id)}`, { body: patch }, );}
export function deleteDiscordBot( id: string, revision: number,): Promise<unknown> { return request( 'DELETE', `/extensions/discord/bots/${encodeURIComponent(id)}?revision=${revision}`, );}
export async function discordGuilds( id: string, signal?: AbortSignal,): Promise<DiscordGuild[]> { return ( await get<components['schemas']['DiscordGuildList']>( `/extensions/discord/bots/${encodeURIComponent(id)}/guilds`, signal, ) ).guilds;}
export function setDiscordChannel( id: string, guild: DiscordGuild, channel: DiscordChannel, delivery: DiscordDelivery, mentionsOnly: boolean,): Promise<unknown> { return request( 'PUT', `/extensions/discord/bots/${encodeURIComponent(id)}/channels/${encodeURIComponent(channel.id)}`, { body: { delivery, mentions_only: mentionsOnly, guild_id: guild.id, guild_name: guild.name, channel_name: channel.name, }, }, );}
export function discordDMs( id: string, signal?: AbortSignal,): Promise<DiscordDMs> { return get(`/extensions/discord/bots/${encodeURIComponent(id)}/dms`, signal);}
export function allowDiscordUser( id: string, user: string, name: string | null,): Promise<unknown> { return request( 'PUT', `/extensions/discord/bots/${encodeURIComponent(id)}/dms/${encodeURIComponent(user)}`, { body: { name } }, );}
export function removeDiscordUser(id: string, user: string): Promise<unknown> { return request( 'DELETE', `/extensions/discord/bots/${encodeURIComponent(id)}/dms/${encodeURIComponent(user)}`, );}
export function dismissDiscordRequest( id: string, user: string,): Promise<unknown> { return request( 'DELETE', `/extensions/discord/bots/${encodeURIComponent(id)}/requests/${encodeURIComponent(user)}`, );}
export function readLogin(id: string, signal?: AbortSignal): Promise<Login> { return get(`/auth/logins/${id}`, signal);}
export function cancelLogin(id: string): Promise<void> { return request('DELETE', `/auth/logins/${id}`);}
export type ImageUpload = components['schemas']['ImageUpload'];export type MessageImage = components['schemas']['MessageImage'];export type Upload = components['schemas']['Upload'];export type FileUpload = components['schemas']['FileUpload'];
/** a repeat with the same bytes answers the same upload. */export function uploadMedia( sessionId: string, uploadId: string, bytes: Blob, mimeType: ImageUpload['mime_type'],): Promise<Upload> { return request('PUT', `/sessions/${sessionId}/uploads/${uploadId}`, { body: bytes, headers: { 'content-type': mimeType }, });}
/** Sends a slash command or skill as an input, with its arguments as a form. */export function sendCommand( sessionId: string, inputId: string, commandId: string, fields: Record<string, unknown>,): Promise<unknown> { return request('PUT', `/sessions/${sessionId}/inputs/${inputId}`, { body: { kind: 'command', command_id: commandId, arguments: fields }, });}
function messageBody( text: string, images: MessageImage[] = [], files: FileUpload[] = [],) { return { kind: 'message', text, ...(images.length ? { images } : {}), ...(files.length ? { files } : {}), };}
export function sendMessage( sessionId: string, inputId: string, text: string, images: MessageImage[] = [], files: FileUpload[] = [],): Promise<unknown> { return request('PUT', `/sessions/${sessionId}/inputs/${inputId}`, { body: messageBody(text, images, files), });}
export type InputHold = components['schemas']['InputHold'];export type InputEdit = components['schemas']['InputEdit'];
/** * Holds a typed message still waiting in the queue, so the agent does not * read it while it is edited. Asking again renews the lease, which runs out * after `lease_ms` unless renewed. 409 `input_not_waiting`: already read. */export function holdInput( sessionId: string, inputId: string,): Promise<InputHold> { return request('POST', `/sessions/${sessionId}/inputs/${inputId}/hold`, { body: {}, });}
/** Lets a held message be read as it was. Idempotent. */export function releaseInput( sessionId: string, inputId: string,): Promise<void> { return request('DELETE', `/sessions/${sessionId}/inputs/${inputId}/hold`);}
/** * Replaces a waiting message in place: same id and queue position, hold * released. 409 `input_not_waiting` once it was read or cancelled. */export function editInput( sessionId: string, inputId: string, text: string, images: MessageImage[] = [], files: FileUpload[] = [],): Promise<InputEdit> { return request('POST', `/sessions/${sessionId}/inputs/${inputId}/edit`, { body: messageBody(text, images, files), });}
export function sendContinue( sessionId: string, inputId: string,): Promise<unknown> { return request('PUT', `/sessions/${sessionId}/inputs/${inputId}`, { body: { kind: 'continue' }, });}
export type SkillLoad = components['schemas']['SkillLoad'];export type SkillLoadSummary = components['schemas']['SkillLoadSummary'];
/** The skills a session loaded, by its model or its person, first loaded first. */export function listSkillLoads( sessionId: string, signal?: AbortSignal,): Promise<SkillLoadSummary[]> { return get<components['schemas']['SkillLoadList']>( `/extensions/skills/loads?session_id=${encodeURIComponent(sessionId)}`, signal, ).then((page) => page.items);}
export type Artifact = components['schemas']['Artifact'];export type ArtifactDetail = components['schemas']['ArtifactDetail'];export type ArtifactVersion = components['schemas']['ArtifactVersion'];
/** Every artifact, newest change first; with `session`, only that session's. */export function listArtifacts( options: { session?: string; limit?: number; signal?: AbortSignal } = {},): Promise<Artifact[]> { const query = new URLSearchParams({ limit: String(options.limit ?? 200) }); if (options.session) query.set('session', options.session); return get<{ items: Artifact[] }>( `/extensions/artifacts/items?${query}`, options.signal, ).then((page) => page.items);}
/** One artifact with every version, newest first. */export function getArtifact( id: string, signal?: AbortSignal,): Promise<ArtifactDetail> { return get(`/extensions/artifacts/items/${id}`, signal);}
/** Deletes an artifact and all its versions, from the gallery and for good. */export function deleteArtifact(id: string): Promise<void> { return request('DELETE', `/extensions/artifacts/items/${id}`);}
/** * Where one version's page is served: `albedo web`'s sandboxed frame route, * whose key is the capability (robot-docs/artifacts.md). */export function frameUrl( artifact: Pick<Artifact, 'id' | 'key'>, version: number, entry: string,): string { const path = entry.split('/').map(encodeURIComponent).join('/'); return `/frame/${artifact.id}.${artifact.key}/${version}/${path}`;}
/** The page's address that follows the newest version, reloading as it moves. */export function latestFrameUrl(artifact: Pick<Artifact, 'id' | 'key'>): string { return `/frame/${artifact.id}.${artifact.key}/latest/`;}
/** A global settings group as read: the validator `If-Match` needs, and the value. */export type SettingsRead<T> = { etag: string; value: T };export type SettingsSaved<T> = { etag: string; value: T; warnings: string[]; /** Whether loaded sessions need a reload to apply the change. */ compositionChanged: boolean; validation: 'passed' | 'skipped' | 'not_applicable';};export type ProviderSettings = components['schemas']['ProviderSettings'];export type ProviderSettingsPatch = components['schemas']['ProviderSettingsPatch'];export type DeclaredSettings = components['schemas']['DeclaredSettings'];export type DeclaredSettingsSection = components['schemas']['DeclaredSettingsSection'];export type DeclaredSetting = components['schemas']['DeclaredSetting'];export type DeclaredSettingsPatch = components['schemas']['DeclaredSettingsPatch'];
/** One global settings group with its validator. */export async function readSettingsGroup<T>( group: string, signal?: AbortSignal,): Promise<SettingsRead<T>> { const response = await fetch(`/api/settings/${encodeURIComponent(group)}`, { signal, headers: { accept: 'application/json' }, }); if (!response.ok) throw await failure(response); const value = await response.json(); const etag = response.headers.get('etag') ?? ''; reportSettingsRevision(group, etag); return { etag, value };}
/** * Changes a group against the validator it was read with. A 412 is thrown as * an ApiError; the caller decides, and nothing is retried with a newer one. */export async function patchSettingsGroup<T>( group: string, etag: string, patch: unknown,): Promise<SettingsSaved<T>> { const change = await request<{ resource: { etag: string; value: T }; application?: { composition_changed?: boolean; validation?: 'passed' | 'skipped' | 'not_applicable'; warnings?: { code: string; detail: string }[]; }; }>('PATCH', `/settings/${encodeURIComponent(group)}`, { body: patch, headers: { 'if-match': etag }, }); const warnings = (change.application?.warnings ?? []).map( (warning) => warning.detail || warning.code, ); reportSettingsRevision(group, change.resource.etag); return { etag: change.resource.etag, value: change.resource.value, warnings, compositionChanged: change.application?.composition_changed ?? false, validation: change.application?.validation ?? 'not_applicable', };}
export type UsageDay = components['schemas']['UsageDay'];
export type UsageLine = components['schemas']['UsageLine'];
export type UsageScope = components['schemas']['UsageScope'];
export type UsageSummary = components['schemas']['UsageSummary'];
/** * What the provider calls used over `days` days of the client's own clock: * `offset` is the minutes the page's clock is ahead of UTC, which decides where * its days begin, and a scope narrows `days` and `lines` to one provider and * account. `account: ''` asks for the rows of a provider that has no account * pool, which is a different read from leaving the account out (every account * of that provider), so it is only sent beside the provider that names it. */export function getUsage( days: number, offset: number, signal?: AbortSignal, scope: { provider?: string; account?: string } = {},): Promise<UsageSummary> { const query = new URLSearchParams({ days: String(days), utc_offset_minutes: String(Math.round(offset)), }); if (scope.provider) { query.set('provider', scope.provider); if (scope.account !== undefined) query.set('account', scope.account); } return get(`/usage?${query}`, signal);}
/** One limit as the daemon last read it: the provider's own reading, not one this page took. */export type Quota = components['schemas']['QuotaObservation'];
/** * The latest reading of each limit the daemon polls, which it reports on * `/server` beside its state. They belong to the accounts themselves and are * not narrowed by any usage filter, and a daemon polling none sends none. */export async function getLimits(signal?: AbortSignal): Promise<Quota[]> { const server = await get<components['schemas']['Server']>('/server', signal); return server.quota ?? [];}
export type QueueItem = components['schemas']['QueueItem'];export type QueueCollection = components['schemas']['QueueCollection'];export function readQueue( sessionId: string, signal?: AbortSignal,): Promise<QueueCollection> { return get(`/extensions/mail/sessions/${sessionId}/queue`, signal);}export function dropQueued( sessionId: string, itemId: string,): Promise<QueueCollection> { return request( 'DELETE', `/extensions/mail/sessions/${sessionId}/queue/${encodeURIComponent(itemId)}`, { body: {} }, );}export function moveQueuedFirst( sessionId: string, itemId: string,): Promise<QueueCollection> { return request( 'POST', `/extensions/mail/sessions/${sessionId}/queue/${encodeURIComponent(itemId)}/first`, { body: {} }, );}export function arrangeQueue( sessionId: string, ids: string[],): Promise<QueueCollection> { return request('PUT', `/extensions/mail/sessions/${sessionId}/queue/order`, { body: { ids }, });}export function clearQueue(sessionId: string): Promise<QueueCollection> { return request('DELETE', `/extensions/mail/sessions/${sessionId}/queue`, { body: {}, });}