git clone https://garage44.eu/jeroen/midas.git.. /web/src/lib/api.ts
import type {Assertion} from '@/lib/passkey'
import type {AdminState, Build, Decision, Deploys, FilesReport, WorkspaceEvent, WorkspaceState, Landing, PoolSample, Reservations, Session, SessionName, Take, Tally, Todo} from '@/lib/types'
import type {LogItem, SearchHit} from '@/lib/stream'
import type {HubNote} from '@/lib/memory'
/**
* The hub's API, from the page it serves: same origin, so no address to
* configure. Reading is open; a change carries the caller key the person
* pasted (`KEY`), and the hub records it as `<caller>:web`.
*/
const KEY = 'midas-caller-key'
export function callerKey(): string {
try {
return localStorage.getItem(KEY) ?? ''
} catch {
return ''
}
}
export function setCallerKey(key: string) {
if (key) localStorage.setItem(KEY, key)
else localStorage.removeItem(KEY)
}
/** A refusal, with the hub's status: 401 is "log in first". */
export class HttpError extends Error {
constructor(
message: string,
public status: number,
) {
super(message)
}
}
async function get<T>(path: string): Promise<T> {
const r = await fetch(path)
if (!r.ok) {
const json = await r.json().catch(() => null)
throw new HttpError(json?.error ?? `${path}: ${r.status}`, r.status)
}
return (await r.json()) as T
}
/** A change to the workspace. Throws with the hub's own words when it refuses. */
export async function post(path: string, body: Record<string, unknown>): Promise<unknown> {
const r = await fetch(path, {
method: 'POST',
// Not `Authorization`: behind midas.cartopolis.org that is the password's.
headers: {'Content-Type': 'application/json', 'X-Midas-Key': callerKey()},
body: JSON.stringify({owner: 'web', ...body}),
})
const text = await r.text()
const json = text ? JSON.parse(text) : null
if (!r.ok) throw new HttpError(json?.error ?? `${r.status}`, r.status)
return json
}
/** How a voice discussion goes (discuss.rs): the realtime model and its voice, the languages. */
export interface DiscussSettings {
model: string
/** What runs the tools for GPT-Live (a realtime model runs its own). */
backend: string
/** The woman's voice and the man's; a call takes its role's (discuss.ts `voiceOf`). */
voice: string
male_voice: string
language: string
brief_language: string
}
export interface DiscussOverview {
settings: DiscussSettings
key: {set: boolean; ends: string | null}
languages: {code: string; name: string}[]
voices: string[]
}
/** An agent a session may run (agents.rs): its command only in Settings, an admin's. */
export interface AgentEntry {
id: string
name: string
command?: string
}
/** A bot's configuration as the page sees it (botconfig.rs): never a password or a key, only whether one is set. */
export interface BotOverview {
name: string
server: string
username: string
password_set: boolean
/** The accounts it works for, comma-separated (`--mcp-allow`). */
works_for: string
private_only: boolean
/** The node it runs on: kept the same, since its chat keys live there. */
node: string
/** Its agent's instructions, a file in the repository; empty for the default. */
brief: string
voice: boolean
/** Its own OpenAI key (and that key's last four), and whether the hub has one to fall back on. */
key: {own: boolean; ends: string | null; hub: boolean}
/** Where it is between Start and Stop, as the sessions runner last said. */
run: {state: 'stopped' | 'queued' | 'starting' | 'running' | 'stopping' | 'failed'; detail: string; at: number}
/** What it still needs before it can start, in words. */
missing: string[]
}
/** A change to a bot: what is given changes; an empty password or key keeps the one there. */
export interface BotPatch {
name: string
server?: string
username?: string
password?: string
works_for?: string
private_only?: boolean
node?: string
brief?: string
voice?: boolean
openai_key?: string
clear_key?: boolean
}
/** Who this page is to the hub: a caller key's name, or a logged-in account, and its role. */
export interface Caller {
caller: string | null
account: string | null
role: string | null
}
/** An account as an admin sees it (`/v1/accounts`): never its secrets. */
export interface Account {
name: string
role: string
created_at: number
created_by: string
/** It has a password and a code secret: it can log in. */
ready: boolean
/** A setup link is out (it may have expired). */
setup_pending: boolean
locked: boolean
recovery_left: number
/** The last use of a live login session, if any. */
last_seen: number | null
}
/** What the setup page shows (`/v1/setup/<token>`). */
export interface SetupInfo {
name: string
role: string
secret: string
uri: string
qr_svg: string
}
/** A template's brief as it was at one version, who made it and why (templates.rs). */
export interface TemplateVersion {
v: number
brief: string
by: string
why: string
at: number
session?: string | null
accepted_by?: string
}
/** A session started from a template, and how it ended. */
export interface TemplateRun {
session: string
repo: string
at: number
schedule?: string | null
outcome: 'landed' | 'dropped' | 'done' | 'ended' | null
ended?: number
review?: {state: 'asked' | 'kept' | 'changed' | 'failed'; at: number; why?: string} | null
}
export interface Template {
id: string
name: string
icon: string
brief: string
/** Who may change it: only the person, midas by proposal, or midas itself. */
editors: 'me' | 'propose' | 'midas'
versions: TemplateVersion[]
runs: TemplateRun[]
proposal?: {brief: string; why: string; session: string; at: number} | null
}
export interface Schedule {
id: string
template: string
repos: string[]
extra: string
repeat: 'daily' | 'weekdays' | 'weekly'
/** Minutes after midnight, UTC. */
minute: number
/** Weekly: the day, Monday 0. */
weekday: number
mode?: string | null
model?: string | null
autopilot: boolean
on: boolean
paused?: string | null
next: number
skipped?: number
}
export interface TemplatesState {
templates: Template[]
schedules: Schedule[]
}
/** A goal at the far end of the research tree (tree.rs): the person's own sentence. */
export interface Goal {
id: string
name: string
statement: string
who: string
signs: string
never: string[]
parent: string | null
repos: string[]
by: string
at: number
}
/** A session that researched a tech: how it ended (none while it goes on), when it started and ended, what it cost in dollars once ended. */
export interface TechSession {
id: string
outcome: string | null
at?: number
ended?: number | null
cost?: number | null
}
/** Where a tech stands, worked out by the hub. */
export type TechState = 'built' | 'researching' | 'available' | 'locked' | 'fog' | 'dropped'
/** A capability someone notices, with what it needs first. */
export interface Tech {
id: string
name: string
what: string
who: string
differently: string
exists: string
/** When it is done: one to three checks a person could make, written by the scout or the person; the research brief carries it. */
done?: string | null
/** The projects its change lands in, in order, one session each (tree.rs `lands_in`); and those that have landed. */
lands_in?: string[]
landed_in?: string[]
size: 'S' | 'M' | 'L'
evidence: string[]
needs: string[]
goals: string[]
repos: string[]
moves: string[]
built: boolean
built_at?: number | null
built_by?: string | null
confirmed_by?: string | null
dropped?: {by: string; at: number; why: string} | null
/** A guess that faded: dropped with nobody's word, as nobody started it and no look found it again (tree.rs `guess_faded`). */
faded?: boolean
/** The hub's rebuilt SVG: geometry only, in currentColor. */
icon?: string | null
/** The scout's wireframe of the screen where someone uses it, rebuilt by the hub as icons are. */
mockup?: string | null
/** When the scout last photographed its mockup (a Sketch), and in which frame: `/v1/hosted/tree/mockups/<id>`. */
mockup_png?: number | null
mockup_frame?: 'phone' | 'wide' | null
/** What the scout says its photographed mockup shows, in words: what a voice talking it over is told. */
mockup_shows?: string | null
/** Pictures of it as it really works, kept by a session (`midas show --tech`): `/v1/hosted/tree/shots/<id>/<n>`. */
shots?: {n: number; caption?: string | null; session: string; at: number}[]
/** The session photographing it, started from its dialog or the queue (tree.rs `start_photograph`), and whether it is at it. */
photograph?: {session: string; by: string; at: number} | null
photographing?: boolean
/** The person's remarks on its mockup, waiting for its next drawing, which takes them away. */
remarks?: {id: string; text: string; by: string; at: number}[]
/** Fields changed on the person's word (`tech_edit`): each one's value before, by whom and when. */
edited?: Partial<Record<'name' | 'what' | 'who' | 'differently' | 'exists' | 'done' | 'size' | 'lands_in', {was: string; by: string; at: number}>>
/** The session researching it, started from the tree. */
research?: {session: string; by: string; at: number} | null
/** Every session that researched it, oldest first, and how each ended (`landed`, `dropped`, `done`, `ended`); none while it goes on. */
sessions?: TechSession[]
by: string
at: number
state: TechState
}
/** An observation that is not a tech yet, the scout's or the person's own. */
export interface Insight {
id: string
goal: string
text: string
about: string | null
evidence: string[]
move: string
by: string
at: number
faded: boolean
dropped?: {by: string; at: number; why: string} | null
}
/** One move of the scout on one goal. */
export interface Round {
id: string
goal: string
move: string
by: string
at: number
/** `skipped`: a look's move with nothing to do when its turn came; `stopped`: its look was stopped. */
state: 'queued' | 'asked' | 'done' | 'failed' | 'skipped' | 'stopped'
/** When a runner took it. */
taken_at?: number
ended?: number
summary?: string
error?: string | null
counts?: {added: number; confirmed: number; built: number; insights: number; themes?: number; mockups?: number}
/** What it changed, by id: techs added, confirmed, built or drawn, and insights. */
changed?: {added: string[]; confirmed: string[]; built: string[]; drawn: string[]; insights: string[]}
/** What the person asked it to look at, in their words. */
focus?: string | null
/** The look it is a move of (the look's first round's id), and the round it waits for. */
look?: string
after?: string | null
/** The tech a look on one tech is about. */
about?: string | null
/** Who has seen what it brought. */
seen?: string[]
/** `talk`: asked in a voice conversation. */
via?: string | null
/** The scout at work on it, as its runner says every few seconds: its last steps, newest first, and what it said last
* between them; once it is back only how much it read. */
live?: {lines: LiveLine[]; thought: string; reads: number; searches: number; at: number} | null
}
/** One step of the scout at work: a file it read, or what it searched or listed (`in` a folder), in a project. */
export interface LiveLine {
kind: 'read' | 'search' | 'list'
text: string
in?: string | null
repo: string
at: number
}
export interface TreeState {
goals: Goal[]
techs: Tech[]
insights: Insight[]
rounds: Round[]
/** The directions chosen on the tree, in the person's order: each researches the techs on the way to its `target` one after another (tree.rs `tick`). */
directions?: Direction[]
/** What every direction together may start, and what it holds now (tree.rs `budget_of`). */
budget?: TreeBudget
/** The built techs waiting to be photographed, one session after another (tree.rs `photo_step`). */
photos?: {queue: string[]; by: string; at: number} | null
/** Themes the scout's Group proposed: goals under `goal`, each with its techs, until kept or dropped. */
proposals?: Proposal[]
moves: string[]
last_goal?: string
}
/** At once, a day and at once in one project, for all directions together; what goes now, started today, and cost this week. */
export interface TreeBudget {
at_once: number
per_day: number
per_project: number
going: number
today: number
week_cost: number
}
/** Goals ▸ Map (graph.rs): every project with its place, and the lines between them, each one recorded. */
export interface ProjectGraph {
projects: {name: string; public: boolean; description?: string; sessions?: number; techs: number; built: number; col: number; row: number}[]
/** `to`'s manifest `file` names `from`'s code at `rev`, `behind` commits short of its main. */
code: {from: string; to: string; rev?: string | null; file: string; behind?: number | null}[]
/** Sessions that worked in both. */
shared: {a: string; b: string; n: number}[]
/** Techs of `to` that need a tech of `from`. */
needs: {from: string; to: string; n: number}[]
landed: {name: string; repo: string; at: number}[]
}
export interface RepoAbout {
repo: string
description?: string
public: boolean
/** Where the workspace clones it by key. */
ssh: string
head?: {sha: string; author: string; at: string; subject: string} | null
project?: {gate?: string; gate_nodes?: string; pre_land?: string; main?: string} | null
}
export interface RepoEntry {
kind: 'dir' | 'file'
path: string
commit: string
entries?: {name: string; kind: 'dir' | 'file'; size?: number | null}[]
text?: string | null
size?: number
binary?: boolean
}
export interface Direction {
id: string
target: string
name: string
by: string
at: number
at_once: number
per_day: number
/** Whether it sends the scout by itself when the way runs out, and after how many landings since its last look (0: only when it runs out). */
scout?: boolean
scout_every?: number
/** When it sent the scout, and the last time why (`out`: nothing left to start; `every`: enough landed). */
scouts?: number[]
scouted?: {at: number; why: 'out' | 'every'; look: string} | null
/** Why it stopped starting researches, until resumed. */
paused: string | null
reached: number | null
cleared?: {by: string; at: number} | null
runs: {tech: string; session: string; repo?: string; at: number; outcome: string | null; ended?: number; cost?: number | null}[]
/** What it starts next, and why not yet (tree.rs `next_of`). */
next?: DirectionNext | null
}
/**
* Why the next tech on the way has not started: `soon` at the hub's next look, `after` a tech it needs
* (or the one going, for `at_once`), `per_day` today's used until `at`, `focus` the person's attention at
* its cap, `paused`, `scouting` while the scout looks along the way (nothing starts meanwhile).
*/
export interface DirectionNext {
tech: string | null
why: 'soon' | 'after' | 'at_once' | 'per_day' | 'focus' | 'paused' | 'scouting' | 'budget' | 'project'
after?: string | null
at?: number | null
/** The project it works in; for `project`, the one that has no room. */
project?: string | null
}
/** A voice conversation kept by the hub (talks.rs): what was said, the brief, what it was about. */
export interface SavedTalk {
id?: string
by: string
at: number
updated: number
about: {kind: string; id?: string; goal?: string}
persona: string
brief: string
sent_to: string
lines: {who: 'you' | 'midas' | 'note'; text: string}[]
}
/** Of a kept conversation, what the list shows. */
export interface TalkSummary {
id: string
by: string
at: number
updated: number
about: {kind: string; id?: string; goal?: string}
persona: string
sent_to: string
title: string | null
said: number
preview: string
}
export interface Proposal {
id: string
goal: string
name: string
statement: string
techs: string[]
at: number
}
/** A device paired to the hub, as it last said itself. */
/** `GET /v1/power` (power.rs): each machine's chip power, bucketed. */
export interface Power {
from: number
to: number
step: number
machines: Record<string, {now: {w: number; at: number} | null; source: string | null; points: [number, number, number][]}>
}
/** A sessions runner's stop (`runner_stopped`, runners.rs), or an absence nobody wrote down (`unexplained`). */
export interface RunnerStop {
runner: string
at: number
reason: 'build' | 'signal' | 'panic' | 'killed' | 'exit' | 'unexplained'
signal?: string | null
by_pid?: number | null
by_cmd?: string | null
by_owner?: string | null
by_parents?: string[] | null
by_note?: string | null
where?: string | null
message?: string | null
sessions?: number | null
lived_s?: number | null
version?: string | null
/** Its supervisor wrote it: the stop was sent to the supervisor, or the runner died without a word. */
supervisor?: boolean | null
seen_by?: string | null
}
/** `GET /v1/runners` (runners.rs): each sessions runner now, and its starts, stops and absences in the range. */
export interface Runners {
now: number
since: number
runners: {name: string; polled: number; away: number | null; up_since: number | null; sessions: number}[]
stops: RunnerStop[]
starts: {runner: string; at: number; by: 'build' | 'supervisor' | 'watch' | 'hand'; version?: string}[]
away: {runner: string; from: number; to: number | null; sessions: number | null}[]
panics: {runner: string; at: number; where: string; message: string; thread: string}[]
}
/** `GET /v1/watch` (watch.rs): one minute of a watched target's service, as stored. */
export interface WatchSample {
t: number
active?: string
mem?: number | null
cpu?: number | null
restarts?: number | null
probes?: {u: string; c: number; ms: number | null}[]
}
/** A deploy of a watched target, with the landings it carried. */
export interface WatchDeploy {
t: number
sha: string
by: string | null
landings: {session: string; branch: string | null; sha: string}[]
}
/** A watched target: its state now and its samples, each `[start, memory MB, CPU %, probe ms, up 0/1, restarts]`. */
export interface WatchTarget {
name: string
repo: string
unit: string | null
probes: string[]
memory_mb: number | null
restarts_per_h: number | null
state: 'ok' | 'trouble' | 'down' | 'unknown'
why: string
now: WatchSample | null
restarts_h: number | null
serves: string | null
points: [number, number | null, number | null, number | null, number, number][]
deploys: WatchDeploy[]
}
export interface Watch {
from: number
to: number
step: number
targets: WatchTarget[]
machine: {
now: {mem_total: number | null; mem_used: number | null; load: number | null; disks: {p: string; free: number; size: number}[]} | null
/** `[start, memory used MB, load]`. */
points: [number, number, number][]
}
}
export interface Device {
id: string
name: string
app: string
version: string
account: string
created: number
seen: number | null
online: boolean
tools: {name: string; description?: string}[]
build: {version?: string; commit?: string} | null
}
/** A one-time pairing code, its link and the link as a QR code (SVG). */
export interface DeviceCode {
code: string
expires: number
link: string
qr: string | null
}
export const api = {
health: () => get<{ok: boolean; version: string; recipe?: string}>('/v1/health'),
/** Who the hub sees: the pasted key's caller, or the logged-in account. */
caller: async (): Promise<Caller> => {
const r = await fetch('/v1/caller', {headers: callerKey() ? {'X-Midas-Key': callerKey()} : {}})
return r.ok ? ((await r.json()) as Caller) : {caller: null, account: null, role: null}
},
login: (name: string, password: string, code: string) => post('/v1/login', {name, password, code}),
logout: () => post('/v1/logout', {}),
setupInfo: (token: string) => get<SetupInfo>(`/v1/setup/${encodeURIComponent(token)}`),
setupComplete: (token: string, password: string, code: string) =>
post('/v1/setup', {token, password, code}) as Promise<{recovery: string[]}>,
state: () => get<WorkspaceState>('/v1/state'),
deploys: () => get<Deploys>('/v1/deploys'),
names: () => get<Record<string, SessionName>>('/v1/names'),
reservations: () => get<Reservations>('/v1/reservations'),
todos: () => get<Todo[]>('/v1/todos'),
decisions: () => get<Decision[]>('/v1/decisions'),
builds: (since: number) => get<Build[]>(`/v1/builds?since=${since}`),
history: (since: number) => get<{takes: Take[]; pool: PoolSample[]}>(`/v1/history?since=${since}`),
/** Each node's held and busy seconds over the range (at most a week). */
nodeUse: (since: number) => get<{use?: Record<string, {held_s: number; busy_s: number}>}>(`/v1/history?since=${since}&use=1`),
/** What each machine drew: per `step` seconds, `[start, average watts, watt-hours]`. */
power: (since: number, step: number) => get<Power>(`/v1/power?since=${since}&step=${step}`),
/** Each watched deploy target's service over the last `since` seconds, and the deploys in it. */
watch: (since: number) => get<Watch>(`/v1/watch?since=${since}`),
/** The sessions runners: each now, and their stops and absences over the last `since` seconds. */
runners: (since: number) => get<Runners>(`/v1/runners?since=${since}`),
sessions: (since: number) => get<Session[]>(`/v1/sessions?since=${since}`),
/** Every session's conversation in the range, counted. */
conversations: (since: number) => get<Tally[]>(`/v1/hosted/stats?since=${since}`),
landings: (since: number) => get<Landing[]>(`/v1/landings?since=${since}`),
/** The event log since `since` seconds ago, oldest first; only `kinds` when given. */
events: (since: number, kinds: string[] = []) =>
get<WorkspaceEvent[]>(`/v1/events?since=${since}${kinds.length ? `&kind=${kinds.join(',')}` : ''}`),
drain: (node: string, why: string) => post('/v1/drain', {node, why}),
undrain: (node: string) => post('/v1/drain', {node}),
release: (node: string) => post('/v1/release', {node, force: true}),
unqueue: (owner: string) => post('/v1/unqueue', {owner}),
/** A message to a session (or `@<node>`, `@waiting:<machine>`), as `midas say` leaves one. */
say: (to: string, text: string) => post('/v1/say', {to, text}) as Promise<{to: string[]}>,
deploy: (target: string) => post('/v1/deploy', {target}),
holdDeploys: (why: string) => post('/v1/deploy/hold', {why}),
pushKey: () => get<{key: string}>('/v1/push/key'),
pushNtfy: () => get<{topic: string | null}>('/v1/push/ntfy'),
setPushNtfy: (topic: string) => post('/v1/push/ntfy', {topic, page: location.origin + '/'}) as Promise<{topic: string | null}>,
testPushNtfy: () => post('/v1/push/ntfy/test', {}),
/** Paired devices (device.rs): an app on a phone whose tools the sessions call. */
devices: () => get<{devices: Device[]}>('/v1/devices'),
deviceCode: () => post('/v1/devices/code', {}) as Promise<DeviceCode>,
forgetDevice: (id: string) => post('/v1/devices/forget', {id}),
pushSubscribe: (endpoint: string) => post('/v1/push/subscribe', {endpoint}),
pushUnsubscribe: (endpoint: string) => post('/v1/push/unsubscribe', {endpoint}),
releaseDeploys: () => post('/v1/deploy/release', {}),
addTodo: (target: string, text: string) => post('/v1/todos/add', {for: target, text}),
doneTodo: (id: string) => post('/v1/todos/done', {id, note: 'done from the web page'}),
/** A session by name and brief (sessions.rs `create`): refused with 400 or 409 and why. */
createSession: (name: string, brief: string) =>
post('/v1/hosted/create', {name, brief}) as Promise<{id: string; status: string; branch: string}>,
startSession: (prompt: string, repo: string, base: string, mode: string, model: string, agent: string, images: string[] = []) =>
post('/v1/hosted/start', {prompt, repo, base, mode, model, agent, images}) as Promise<{id: string}>,
/** The agents a session may run (Settings ▸ Agents), Claude Code first: ids and names. */
agents: () => get<AgentEntry[]>('/v1/hosted/agents'),
/** The same with their commands, and changing them: an admin's. */
settingsAgents: () => get<AgentEntry[]>('/v1/settings/agents'),
setAgent: (id: string, name: string, command: string) => post('/v1/settings/agent', {id, name, command}) as Promise<AgentEntry[]>,
removeAgent: (id: string) => post('/v1/settings/agent/remove', {id}) as Promise<AgentEntry[]>,
/** The workspace's projects (hub.conf's repos), the first a session's when none is chosen. */
projects: () => get<{repo: string; name: string}[]>('/v1/hosted/projects'),
setModel: (id: string, model: string) => post(`/v1/hosted/${id}/model`, {model}),
/** A message not yet taken: `remove`, `edit` (text), `move` (to, 0 first), `clear` (all), `now` (first; the turn stops). */
queueOp: (id: string, op: 'remove' | 'edit' | 'move' | 'clear' | 'now', fields: {qid?: number; text?: string; to?: number} = {}) =>
post(`/v1/hosted/${id}/queue`, {op, ...fields}),
/** `now`: stop what it is doing and take this next, rather than queue it after the turn. */
/** A session's conversation from its start (sessions.rs `log`). */
sessionLog: (id: string) => get<{items: LogItem[]; next: number}>(`/v1/hosted/${id}/log`),
sayTo: (id: string, text: string, now = false, images: string[] = []) => post(`/v1/hosted/${id}/say`, {text, now, images}),
/** A pasted image, ahead of its message: its bytes as they are. Answers the token a message names it by. */
upload: async (blob: Blob, name: string): Promise<{token: string}> => {
const r = await fetch('/v1/uploads', {
method: 'POST',
headers: {'X-Midas-Name': encodeURIComponent(name), 'X-Midas-Key': callerKey()},
body: blob,
})
const json = await r.json().catch(() => null)
if (!r.ok) throw new HttpError(json?.error ?? `${r.status}`, r.status)
return json as {token: string}
},
setMode: (id: string, mode: string) => post(`/v1/hosted/${id}/mode`, {mode}),
/** Its autopilot on (until a time, or none; to a goal, or what the person asked) or off (autopilot.rs). */
setAutopilot: (id: string, on: boolean, until: number | null = null, goal = '') => post(`/v1/hosted/${id}/autopilot`, {on, until, goal}),
/** The autopilot on for many sessions at once (Take over): those taken, and why any were passed over. */
takeOver: (ids: string[], goal: string, until: number | null) =>
post('/v1/hosted/autopilot', {ids, on: true, goal, until}) as Promise<{taken: string[]; passed: Record<string, string>}>,
/** Templates and their schedules (templates.rs). */
templates: () => get<TemplatesState>('/v1/hosted/templates'),
/** A change to them, by op (save, revert, accept, reject, delete, schedule, schedule_on, schedule_delete, start): the whole state after. */
templateOp: (op: string, fields: Record<string, unknown>) => post('/v1/hosted/templates', {op, ...fields}) as Promise<TemplatesState & {started?: string[]}>,
/** The research tree (tree.rs). */
tree: () => get<TreeState>('/v1/hosted/tree'),
/** Goals ▸ Map: every project, which uses which, the sessions between them, and the map drawn (graph.rs). */
graph: () => get<{graph: ProjectGraph; svg: string}>('/v1/hosted/graph'),
/** A hosted project: how to get it and its landing settings (hub.rs `repo_read`). */
repoAbout: (repo: string) => get<RepoAbout>(`/v1/repos/${repo}/about`),
/** A directory's entries or a file's text at the main branch. */
repoShow: (repo: string, path: string) => get<RepoEntry>(`/v1/repos/${repo}/show?path=${encodeURIComponent(path)}`),
/** A project's description, visibility or landing, changed (hosted.rs `set`; on the page, an admin's). */
projectSet: (repo: string, fields: Record<string, unknown>) => post('/v1/projects/set', {repo, ...fields}),
/** Another name for it (hosted.rs `rename`); the old one still clones. */
projectRename: (repo: string, to: string) => post('/v1/projects/rename', {repo, to}) as Promise<{repo: string}>,
/** Deleted, by the person (hosted.rs `delete`): moved aside on the hub. */
projectDelete: (repo: string) => post('/v1/projects/delete', {repo}),
/** A change to it, by op (goal_save, goal_delete, idea, insight_drop, tech_confirm, tech_drop, tech_restore, tech_built, scout): the whole tree after. */
treeOp: (op: string, fields: Record<string, unknown>) => post('/v1/hosted/tree', {op, ...fields}) as Promise<TreeState>,
reopen: (id: string) => post(`/v1/hosted/${id}/reopen`, {}),
permit: (id: string, request: string, option: string) => post(`/v1/hosted/${id}/permit`, {request, option}),
cancelTurn: (id: string) => post(`/v1/hosted/${id}/cancel`, {}),
stopSession: (id: string) => post(`/v1/hosted/${id}/stop`, {}),
/** An editor's session, to go on here (the hub's runner); and back to its editor. */
handoff: (id: string) => post(`/v1/hosted/${id}/handoff`, {}),
/** The project of a session that names none (an editor's from an older midas). */
setProject: (id: string, repo: string) => post(`/v1/hosted/${id}/project`, {repo}),
handback: (id: string) => post(`/v1/hosted/${id}/handback`, {}),
/** The answer to an agent's question form: `accept` with the fields, or `decline` (skip). */
answer: (id: string, request: string, action: 'accept' | 'decline', content: Record<string, string | string[]>) =>
post(`/v1/hosted/${id}/answer`, {request, action, content}),
archiveSession: (id: string, on: boolean) => post(`/v1/hosted/${id}/archive`, {on}),
/** Finished on the person's word: ended and filed as done, its branch kept. */
markDone: (id: string) => post(`/v1/hosted/${id}/done`, {}),
deleteSession: (id: string) => post(`/v1/hosted/${id}/delete`, {}),
renameSession: (id: string, title: string) => post(`/v1/hosted/${id}/title`, {title}),
/** When it carries on by itself: moved to `at`, cancelled, or now. */
moveWake: (id: string, at: number) => post(`/v1/hosted/${id}/wake`, {at}),
cancelWake: (id: string) => post(`/v1/hosted/${id}/wake`, {cancel: true}),
wakeNow: (id: string) => post(`/v1/hosted/${id}/wake`, {now: true}),
/** What it waits on the person for: the secret given (to the hub, never the session), put off, or declined. */
giveAwaited: (id: string, value: string) => post(`/v1/hosted/${id}/awaits`, {value}),
snoozeAwaited: (id: string, until: number) => post(`/v1/hosted/${id}/awaits`, {snooze: until}),
declineAwaited: (id: string) => post(`/v1/hosted/${id}/awaits`, {decline: true}),
/** What a session's branch changes, as its runner last reported it. */
sessionFiles: (id: string) => get<FilesReport>(`/v1/hosted/${id}/files`),
/** Agents' memory, every set the hub keeps (memory.rs): the page's Memory. */
/** Every set of notes, and the files each note names that its repository no longer has (`set/file` → paths). */
memory: () => get<{sets: Record<string, Record<string, HubNote>>; stale?: Record<string, string[]>}>('/v1/memory'),
/** Whether the hub can open a voice conversation about a session (it has an OpenAI key; discuss.rs). */
discussAvailable: () => get<{available: boolean}>('/v1/hosted/discuss'),
/** The hub's settings the page sets (Settings): of the OpenAI key, only whether there is one. */
settings: () => get<{discuss: DiscussOverview}>('/v1/settings'),
/** The realtime models the hub's OpenAI key may use, newest first. */
settingsModels: () => get<{voice: string[]; backend?: string[]}>('/v1/settings/models'),
setDiscuss: (s: DiscussSettings) => post('/v1/settings/discuss', {...s}) as Promise<{discuss: DiscussOverview}>,
/** Replace the OpenAI key, or remove it with an empty one. */
setOpenaiKey: (key: string) => post('/v1/settings/openai_key', {key}) as Promise<{discuss: DiscussOverview}>,
/** The bots `midas bot start --name …` configures: their sign-in and voice key (Settings ▸ Bots). */
bots: () => get<{bots: BotOverview[]}>('/v1/settings/bots'),
setBot: (patch: BotPatch) => post('/v1/settings/bot', {...patch}) as Promise<{bots: BotOverview[]}>,
removeBot: (name: string) => post('/v1/settings/bot/remove', {name}) as Promise<{bots: BotOverview[]}>,
/** Start or stop a configured bot: the sessions runner does it, and says how it went. */
startBot: (name: string) => post('/v1/settings/bot/start', {name}) as Promise<{bots: BotOverview[]}>,
stopBot: (name: string) => post('/v1/settings/bot/stop', {name}) as Promise<{bots: BotOverview[]}>,
/** The people who log in to the page (accounts.rs), and an admin's changes to them. */
accounts: () => get<Account[]>('/v1/accounts'),
/** A new account: its setup link's token, good for a day. */
addAccount: (name: string, role: string) => post('/v1/accounts/add', {name, role}) as Promise<{name: string; token: string}>,
setAccountRole: (name: string, role: string) => post('/v1/accounts/role', {name, role}),
/** Start an account over (a lost phone, a leaked password): a new setup link's token. */
resetAccount: (name: string) => post('/v1/accounts/reset', {name}) as Promise<{name: string; token: string}>,
removeAccount: (name: string) => post('/v1/accounts/remove', {name}),
/** A question about the code for a runner's Claude Code (ask.rs), and its answer once there is one (a long poll). */
askCode: (question: string, repo: string, session: string) => post('/v1/hosted/discuss/ask', {question, repo, session}) as Promise<{id: string}>,
codeAnswer: (id: string) => post('/v1/hosted/discuss/answer', {id}) as Promise<{state: string; answer?: string; error?: string}>,
/** Voice conversations kept (talks.rs), newest first. */
talks: () => get<{talks: TalkSummary[]}>('/v1/hosted/talks'),
/** One kept conversation, whole. */
talk: (id: string) => get<SavedTalk>(`/v1/hosted/talks/${encodeURIComponent(id)}`),
/** A conversation saved as it goes; a new one (no id) gets one. `keepalive` lets it go out as the page is closed. */
saveTalk: async (t: Omit<SavedTalk, 'by' | 'at' | 'updated'>, keepalive = false): Promise<{id: string}> => {
if (!keepalive) return post('/v1/hosted/talks', {...t}) as Promise<{id: string}>
const body = JSON.stringify({owner: 'web', ...t})
// A browser sends at most 64 KB as a page closes: a longer one waits for the next save.
if (body.length > 60_000) return {id: t.id ?? ''}
const r = await fetch('/v1/hosted/talks', {method: 'POST', keepalive: true, headers: {'Content-Type': 'application/json', 'X-Midas-Key': callerKey()}, body})
return (await r.json()) as {id: string}
},
forgetTalk: (id: string) => post('/v1/hosted/talks/forget', {id}),
searchSessions: (q: string) => get<{results: SearchHit[]; more: boolean}>(`/v1/hosted/search?q=${encodeURIComponent(q)}`),
/** Put a card away (or back): any session's, on the board. */
archiveCard: (session: string, on: boolean) => post('/v1/archive', {session, on}),
decide: (id: string, choice: string, note?: string) => post('/v1/decisions/answer', {id, choice, note}),
/** Admin windows (admin.rs): how they stand; the grant to sign for one; the signed Allow; No; closing the open one. */
admin: () => get<AdminState>('/v1/admin'),
adminToSign: (id: string) => get<{grant: {issued_at: number}; challenge: string; rp_id: string; keys: string[]}>(`/v1/admin/sign?id=${encodeURIComponent(id)}`),
adminGrant: (id: string, issued_at: number, assertion: Assertion) => post('/v1/admin/grant', {id, issued_at, assertion}),
adminDecline: (id: string) => post('/v1/admin/decline', {id}),
adminClose: () => post('/v1/admin/close', {}),
}