import m, {MithrilComponent} from '@garage44/mithril' import {Button, Card, FieldSelect, FieldSwitch, FieldText} from '@garage44/mithril/components' import {Accounts} from '@/components/accounts' import {AdminPasskey} from '@/components/admin' import {act} from '@/lib/actions' import {api} from '@/lib/api' import type {AgentEntry, BotOverview, Device, DeviceCode,DiscussOverview, DiscussSettings} from '@/lib/api' import {talk} from '@/lib/discuss' import {checkNtfy, notify, ntfy, saveNtfy, setNotify} from '@/lib/notify' import {age} from '@/lib/format' import {bind, local} from '@/lib/reactive' import {$s} from '@/lib/store' /** A choice of the ones offered, with the one set kept among them even when the account no longer lists it. */ const choices = (offered: string[], current: string) => [...new Set([current, ...offered])].filter(Boolean).map((v) => ({value: v, label: v})) /** The page's parts, for its headings and the row that jumps to them: the first anyone's, the rest an admin's. */ const SECTIONS = [ {id: 'device', title: 'This device', lead: 'This browser on this device, for whoever is logged in here.'}, {id: 'people', title: 'People', lead: 'Who logs in to this page, and what each may do.'}, {id: 'admin', title: 'Admin', lead: "Root on the hub's machine: only in a window you allow with your passkey."}, {id: 'voice', title: 'Voice', lead: 'Talking sessions over by voice: Discuss, in the header.'}, {id: 'agents', title: 'Agents', lead: 'What a session runs: Claude Code, or another agent you add here.'}, {id: 'bots', title: 'Bots', lead: 'Cartopolis accounts an AI agent speaks for.'}, ] /** A part of the page under its heading. */ const section = (id: string, ...body: m.Children[]) => { const it = SECTIONS.find((x) => x.id === id)! return (

{it.title}

{it.lead}

{body}
) } /** Jumps down the page; links would change the address, which says the page. */ const jump = () => ( ) /** The switch's model: reading says whether this browser is subscribed, writing subscribes or unsubscribes it. */ const notifyModel = { get value() { return notify.on }, set value(on: boolean) { void setNotify(on) }, } /** The apps paired to the hub (device.rs): a phone whose tools the sessions call, and the code that pairs one. */ class Devices extends MithrilComponent { s = local({list: [] as Device[], code: null as DeviceCode | null, error: ''}) timer = 0 oninit() { void this.load() // Online or not changes as the app opens and closes. this.timer = window.setInterval(() => void this.load(), 10000) } onremove() { window.clearInterval(this.timer) } async load() { try { this.s.list = (await api.devices()).devices this.s.error = '' } catch (e) { this.s.error = (e as Error).message } } view() { const {list, code} = this.s return ( act('pairing code made', async () => (this.s.code = await api.deviceCode()), {quiet: true})}> Pair a device , ]} > {this.s.error ?

{this.s.error}

: null} {code ? (
{/* The app does not open `code.link` yet: typing the code is the way in. */}

In the app, open Developer tools ▸ Midas and type {code.code}. Good once, for ten minutes.

) : null} {!list.length ? (

None yet.

) : ( )}
) } } /** Notify this device when something needs its person: a person's, so only once logged in. */ const device = () => !$s.account ? (

Log in to have this device notified.

) : ( [ m(Devices), {notify.supported ? ( ) : (

This browser cannot be notified; on an iPhone, add the page to the Home Screen first.

)}
, act('a test sent to ntfy', () => api.testPushNtfy())}> Send a test , , ]} > , ] ) /** * The hub's settings an admin sets here: who logs in to the page * (accounts.tsx), talking sessions over by voice (discuss.rs): the OpenAI key, which the page can replace or remove but * never read back, and the realtime model, its voice and the languages. */ export class Settings extends MithrilComponent { s = local({ overview: null as DiscussOverview | null, draft: null as DiscussSettings | null, models: {voice: [] as string[], backend: [] as string[]}, key: '', error: '', }) oninit() { void this.load() checkNtfy().catch(() => undefined) } async load() { try { this.show((await api.settings()).discuss) } catch (e) { this.s.error = (e as Error).message } } /** What the hub says now; and, with a key, the models it may use. */ show(o: DiscussOverview) { this.s.overview = o this.s.draft = {...o.settings} // The Discuss button follows the key. talk.available = o.key.set if (o.key.set) { api.settingsModels() .then((r) => (this.s.models = {voice: r.voice, backend: r.backend ?? []})) .catch(() => (this.s.models = {voice: [], backend: []})) } } view() { // Only this device, for anyone not an admin. if ($s.role !== 'admin') return
{section('device', device())}
const {overview: o, draft: d} = this.s if (!o || !d) return this.s.error ?

{this.s.error}

:

Loading…

const changed = JSON.stringify(d) !== JSON.stringify(o.settings) const languages = o.languages.map((l) => ({value: l.code, label: l.name})) return (
{jump()} {section('device', device())} {section('people', )} {section('admin', )} {section( 'voice', act('OpenAI key removed', async () => this.show((await api.setOpenaiKey('')).discuss))}> Remove it ) : null, , ]} >

For talking sessions over by voice, on OpenAI's realtime model. The hub keeps it beside its state, readable by its own user only, and only signs calls with it: it never reaches a browser.

A restricted key needs: List models on Read, and under Model capabilities, Realtime on Write; Voices on Read only for a custom voice. The rest can stay at None.

, (this.s.draft = {...o.settings})}> Undo , , ]} > {d.model.startsWith('gpt-live') ? ( ) : null} , )} {section('agents', )} {section('bots', )}
) } } /** * The agents a session may run (agents.rs): Claude Code always, and each one * added here, a name and the command the sessions runner starts for it. The * new-session form offers them in its model choice. */ class Agents extends MithrilComponent { s = local({ agents: null as AgentEntry[] | null, drafts: {} as Record, adding: {id: '', name: '', command: ''}, error: '', }) oninit() { api.settingsAgents() .then((list) => this.show(list)) .catch((e: Error) => (this.s.error = e.message)) } show(list: AgentEntry[]) { this.s.agents = list this.s.drafts = Object.fromEntries(list.map((a) => [a.id, {name: a.name, command: a.command ?? ''}])) } agent(a: AgentEntry) { const d = this.s.drafts[a.id] if (!d) return null const changed = d.name !== a.name || d.command !== (a.command ?? '') return ( act(`${a.name} removed`, async () => this.show(await api.removeAgent(a.id)))}> Remove , , ]} > ) } view() { const {agents, adding} = this.s if (!agents) return this.s.error ?

{this.s.error}

: null const id = adding.id.trim() const ready = /^[a-z0-9-]{1,32}$/.test(id) && id !== 'claude' && !agents.some((a) => a.id === id) && adding.name.trim() && adding.command.trim() return [

Claude Code is always there, with midas's hooks and skills; the others get the session's brief only if they take a system prompt.

, ...agents.filter((a) => a.id !== 'claude').map((a) => this.agent(a)), act(`${adding.name.trim()} added`, async () => { this.show(await api.setAgent(id, adding.name, adding.command)) this.s.adding = {id: '', name: '', command: ''} }) } > Add , ]} >

Install it on the sessions runner's machine and log it in there first: it runs with that machine's login.

, ] } } /** What a bot's form holds: the secrets start empty, and stay as they are unless typed. */ interface BotDraft { server: string username: string password: string works_for: string private_only: boolean node: string brief: string voice: boolean openai_key: string } const draftOf = (b: BotOverview): BotDraft => ({ server: b.server, username: b.username, password: '', works_for: b.works_for, private_only: b.private_only, node: b.node, brief: b.brief, voice: b.voice, openai_key: '', }) /** How a run stands, in a few words for the card's subtitle. */ const RUN_WORDS: Record = { stopped: 'not running', queued: 'waiting for the runner', starting: 'starting…', running: 'running', stopping: 'stopping…', failed: 'failed to start', } /** * The bots (botconfig.rs): for each, the Cartopolis account it signs in with, * who it works for, where it runs and whether it takes calls by voice, and a * Start and Stop that the sessions runner carries out. A password or key is * never sent back here: the form shows that one is set, and a key's last four. */ class Bots extends MithrilComponent { s = local({ bots: null as BotOverview[] | null, drafts: {} as Record, adding: '', error: '', }) timer = 0 oninit() { void this.load() // A start takes minutes (a first build); its card follows it. this.timer = window.setInterval(() => { if (this.s.bots?.some((b) => ['queued', 'starting', 'stopping'].includes(b.run.state))) void this.refresh() }, 5000) } onremove() { window.clearInterval(this.timer) } async load() { try { this.show((await api.bots()).bots) } catch (e) { this.s.error = (e as Error).message } } /** New run states, keeping whatever is being typed. */ async refresh() { const bots = (await api.bots()).bots this.s.bots = bots m.redraw() } show(bots: BotOverview[]) { this.s.bots = bots this.s.drafts = Object.fromEntries(bots.map((b) => [b.name, draftOf(b)])) } bot(b: BotOverview) { const d = this.s.drafts[b.name] if (!d) return null const changed = JSON.stringify(d) !== JSON.stringify(draftOf(b)) const busy = ['queued', 'starting', 'stopping'].includes(b.run.state) const up = b.run.state === 'running' || b.run.state === 'starting' const nodes = ($s.workspace?.nodes ?? []).map((n) => ({value: n.id, label: `${n.id} (${n.machine})`})) const keyHelp = b.key.own ? `it has its own key, ending in …${b.key.ends}; type another to replace it` : b.key.hub ? "leave empty to use the hub's OpenAI key (above); a restricted key needs Realtime on Write" : 'needed for voice: the hub has no OpenAI key to use instead' return ( act(`${b.name} removed`, async () => this.show((await api.removeBot(b.name)).bots))}> Remove , , up ? ( ) : ( ), ]} > {b.run.detail ?

{b.run.detail}

: null} {b.missing.length > 0 ?

Before it can start, it needs {b.missing.join(', ')}.

: changed ?

Save before starting.

: null}

Its Cartopolis account

Who it works for

Where it runs

Voice

{d.voice ? ( ) : null} {b.key.own ? ( ) : null}
) } view() { const {bots} = this.s if (!bots) return this.s.error ?

{this.s.error}

: null const name = this.s.adding.trim() return [ ...bots.map((b) => this.bot(b)), // Keyed like the bots' cards, since a fragment's vnodes all have keys or none // do; the space keeps it apart from any bot's name. b.name === name)} onclick={() => act(`${name} added`, async () => { this.show((await api.setBot({name})).bots) this.s.adding = '' }) } > Add , ]} >

A bot is a Cartopolis account with an agent behind it. Make the account on the Cartopolis server first (and mark it as an agent on its Admin page, so callers see the badge), then add it here, fill in its card and press Start. The sessions runner builds the client from main on the node you choose and starts its agent; Stop ends both.

, ] } }