git clone https://garage44.eu/jeroen/midas.git.. /web/src/lib/discuss.ts
import {answerTo} from '@/lib/answers'
import {api} from '@/lib/api'
import type {SavedTalk, TreeState} from '@/lib/api'
import {LiveCall} from '@/lib/live'
import {local} from '@/lib/reactive'
import {go} from '@/lib/route'
import {cards, hosted, links, nodes, todos} from '@/lib/stream'
import {roundNews, techText, treeText} from '@/lib/treetalk'
import type {Hosted, LogItem} from '@/lib/stream'
/**
* Talking things over out loud (OpenAI's realtime voice, `live.ts`), started from the page's
* header about what the person picks: a new session or a session's next step,
* designed with the coach, who keeps the design as a brief beside the
* conversation; a session, to hear how it stands; the board, to see how the
* work goes together and what to do first; or nothing in particular.
*
* A conversation runs until the person ends it, by the button or by saying so:
* not when a session starts, not on a silence, not when they go to another
* page; a dropped call is called again. What goes to a session is still theirs
* to send.
*/
/** A picture the person added: its upload's token, to send it with the brief, and a local address to show it by. */
export interface Picture {
token: string
url: string
name: string
}
/** What a conversation is about. */
export type About = {kind: 'new'} | {kind: 'session'; id: string} | {kind: 'board'} | {kind: 'free'} | {kind: 'tree'; goal?: string}
/**
* With whom. Midas answers about the work; every other role designs (a new
* session, a session's next step) and keeps the brief: the operator who gets
* it started (`coach`), a design coach, a CTO/CEO, and a customer who would use it.
*/
export type Persona = 'coach' | 'midas' | 'designer' | 'executive' | 'user'
/** Whether a role designs: it keeps the brief, and its conversation has the design's page. */
export const designs = (p: Persona) => p !== 'midas'
/** The roles that design, and their names on the page. */
export const DESIGNERS: {value: Persona; label: string}[] = [
{value: 'coach', label: 'Operator'},
{value: 'designer', label: 'Design coach'},
{value: 'executive', label: 'CTO / CEO'},
{value: 'user', label: 'Customer'},
]
/** Whose voice a role speaks in: the hub's woman's or man's (Settings). */
export type Voice = 'female' | 'male'
const VOICES_KEY = 'midas-discuss-voices'
/** Each role's voice, as last picked on this device; the woman's when never picked. */
export function voiceOf(p: Persona): Voice {
try {
return (JSON.parse(localStorage.getItem(VOICES_KEY) ?? '{}') as Record<string, Voice>)[p] === 'male' ? 'male' : 'female'
} catch {
return 'female'
}
}
export function setVoiceOf(p: Persona, v: Voice) {
try {
const all = JSON.parse(localStorage.getItem(VOICES_KEY) ?? '{}') as Record<string, Voice>
localStorage.setItem(VOICES_KEY, JSON.stringify({...all, [p]: v}))
} catch {
// No storage (a private window): it is the woman's voice again next time.
}
}
export interface Line {
who: 'you' | 'midas' | 'note'
text: string
}
/** What the voice is up to in a silence: what the person sees, the phone put down or not. */
export type Activity = 'listening' | 'thinking' | 'working' | 'speaking'
export const talk = local({
about: null as About | null,
persona: 'midas' as Persona,
state: 'off' as 'off' | 'joining' | 'on' | 'reconnecting',
activity: 'listening' as Activity,
/** While working: what on, in a few words. */
doing: '',
muted: false,
lines: [] as Line[],
/** The design as it stands (the coach's): what the session is started with, or sent. */
brief: '',
/** Where the brief went, once it did: the session's id. */
sentTo: '',
/** The hub's id for it (talks.rs), once first saved: it is saved as it goes. */
id: '',
/** Pictures the person added (a sketch, a photo, a screenshot): the voice saw them, and they go with the brief. */
pictures: [] as Picture[],
/** The sessions it follows: what they report comes into the conversation by itself. */
following: [] as string[],
/** Whether the hub can open one (it has an OpenAI key); unknown until asked. */
available: null as boolean | null,
})
/** What the page lends the conversation: starting a session is the composer's (its project, model, mode). */
export const hooks = {
startSession: async (_brief: string, _images: string[]): Promise<string> => {
throw new Error('no composer on this page')
},
/** What is in a composer now: a design starts from it. */
draft: (_about: About): string => '',
/** The research page, when it is open: the goal it shows, and to be read again after a change. */
treeGoal: (): string => '',
treeChanged: (_tree: TreeState) => {},
/** The research page shows this goal or theme: the one the conversation reads or changes. */
treeShow: (_goal: string) => {},
/** The research page opens this tech's dialog: the one the conversation talks over. */
treeOpen: (_tech: string) => {},
}
let call: LiveCall | null = null
let ending = false
/** Recent drops, to stop calling again when it cannot hold. */
let drops: number[] = []
/** Asked once a page: the button shows only where the hub has a key. */
export function checkAvailable() {
if (talk.available !== null) return
talk.available = false
api.discussAvailable()
.then((r) => (talk.available = r.available))
.catch(() => (talk.available = false))
}
export const talking = () => talk.state !== 'off'
/** Lines kept of a conversation: all of a long one (talks.rs keeps as many). */
const LINES_KEPT = 1000
function say(who: Line['who'], text: string) {
talk.lines = [...talk.lines, {who, text}].slice(-LINES_KEPT)
keep()
}
/**
* Saving it as it goes (talks.rs): a second after the last change, at once
* when it ends, and as the page is closed. Until 2026-11-17 it lived only in
* the page, and a phone that closed the page in the background took a whole
* design with it. The one open is remembered on this device, and shown again
* when the page comes back (`restoreTalk`).
*/
const OPEN_KEY = 'midas-discuss-open'
let keepTimer: ReturnType<typeof setTimeout> | undefined
let saving: Promise<unknown> = Promise.resolve()
/** Each conversation's id, by what it is about (a new object each conversation). */
const ids = new WeakMap<About, string>()
/** Worth keeping: something was said, or a brief written. */
const worthKeeping = () => talk.lines.some((l) => l.who !== 'note') || !!talk.brief.trim()
function keep(now = false) {
clearTimeout(keepTimer)
if (now) void saveTalk()
else keepTimer = setTimeout(() => void saveTalk(), 1000)
}
function saveTalk(closing = false): Promise<unknown> {
clearTimeout(keepTimer)
const about = talk.about
if (!about || !worthKeeping()) return saving
// As it is now: by the time an earlier save is done, another conversation may have started.
const body = {about, persona: talk.persona, brief: talk.brief, sent_to: talk.sentTo, lines: talk.lines}
if (talk.id) ids.set(about, talk.id)
// One save at a time, in order: a new conversation's first save gives it its id, which the next one names.
saving = saving.then(async () => {
try {
const {id} = await api.saveTalk({...body, id: ids.get(about) || undefined}, closing)
if (!id) return
ids.set(about, id)
if (talk.about === about) {
talk.id = id
remember(id)
}
} catch {
// Saved again at the next change.
}
})
return saving
}
function remember(id: string) {
try {
if (id) localStorage.setItem(OPEN_KEY, id)
else localStorage.removeItem(OPEN_KEY)
} catch {
// No storage: it is still on the hub, in the list.
}
}
if (typeof window !== 'undefined') window.addEventListener('pagehide', () => talk.about && void saveTalk(true))
/** The conversation open on this device when the page went: shown again, ended, to carry on or close. */
export async function restoreTalk() {
let id = ''
try {
id = localStorage.getItem(OPEN_KEY) ?? ''
} catch {
return
}
if (!id || talk.about) return
const t = await api.talk(id).catch(() => null)
if (!t || talk.about) return remember(t ? id : '')
loadTalk(t)
}
function loadTalk(t: SavedTalk) {
talk.id = t.id ?? ''
talk.about = {...t.about} as About
if (talk.id) ids.set(talk.about, talk.id)
talk.persona = (t.persona || 'midas') as Persona
talk.brief = t.brief ?? ''
talk.sentTo = t.sent_to ?? ''
talk.lines = t.lines ?? []
talk.state = 'off'
clearPictures()
}
/** A kept conversation, opened again (ended: Carry on calls). */
export async function openTalk(id: string) {
const t = await api.talk(id)
if (talk.state !== 'off') endTalk()
loadTalk(t)
remember(talk.id)
}
/** Talk on in the conversation shown: called again with what was said so far. */
export async function carryOn() {
const about = talk.about
if (!about || talk.state !== 'off') return
ending = false
drops = []
talk.muted = false
talk.state = 'joining'
say('note', 'carried on')
void holdScreen()
if (about.kind === 'session') watch(about.id)
if (talk.sentTo) watch(talk.sentTo)
await connect('resume')
}
/** The person, or the voice: what it is up to now. */
let thinkTimer: ReturnType<typeof setTimeout> | undefined
function setActivity(a: Activity, doing = '') {
clearTimeout(thinkTimer)
talk.activity = a
talk.doing = doing
// A pause after they spoke that nothing answers: it is listening again, not stuck thinking.
if (a === 'thinking') thinkTimer = setTimeout(() => talk.activity === 'thinking' && setActivity('listening'), 8000)
}
/** What looks at the workspace: every conversation has it, so the coach sees the work a design could collide with. */
const READ = ['read_board', 'read_session', 'find_sessions', 'ask_code', 'read_tree']
/** What acts on sessions and the workspace, as their pages do; each only on the person's word (discuss.rs `TOOL_RULE`). */
const MANAGE = [
'create_session',
'send_to_session',
'answer_permission',
'answer_question',
'decide',
'interrupt_session',
'stop_session',
'reopen_session',
'archive_session',
'rename_session',
'set_session_mode',
'set_session_model',
'land_session',
'deploy',
'drain_node',
'undrain_node',
'release_node',
'add_open_end',
'close_open_end',
'open_tech',
'change_tree',
'scout_tree',
]
/**
* What the coach builds with, once a design went out: it follows the session
* it started and steers it on the person's word, its questions and "Shall it
* land?" too. Not the workspace's: no deploys, nodes, or other sessions' ends.
*/
const BUILD = ['send_to_session', 'answer_permission', 'answer_question', 'interrupt_session', 'land_session']
/** The tools each conversation gets, of the hub's (discuss.rs): the coach designs and builds along, Midas manages. */
export function toolsFor(_about: About, persona: Persona): string[] {
if (designs(persona)) return ['write_brief', ...READ, 'start_session', ...BUILD, 'end_discussion']
return [...READ, ...MANAGE, 'end_discussion']
}
const PERSONAS: Record<Persona, string> = {
midas: "You are Midas, the workspace's assistant: you know how its agent sessions stand. Answer in one or two short sentences, the fact first; say more only when they ask. Say when you do not know, and look it up rather than guess. The page follows you: it shows the board, the session or the workspace you look at or act on, so do not read out what they can see.",
coach: "You are Midas as the operator who gets work started: you turn what the person wants into a session for a coding agent and drive it on their word. Take the task as they put it. A question (what is there, how something works, how work stands) is not yet a task: answer it first, with ask_code, the board or a session, and write no brief until they say what to change. Before you write anything about the code, ask_code what already does it or part of it, and say what it found in a sentence: what exists makes the task smaller, and a task built on not knowing it is wasted. Say plainly when what they ask cannot be checked from the workshop (a phone's frame rate, a person's taste) rather than writing it into the brief as a goal. Do not interrogate them, add scope, or invent criteria, measurements, levels or reports they did not ask for.",
designer:
"You are a design coach, helping the person think through what they want before a coding agent builds it. Walk through it as the person who will use it meets it, step by step, and ask about the step that is unclear, one question at a time: asking is your work here, so a question may end a turn. When you see a simpler way, propose it once, with why, and let them choose. Before you speak about the code, ask_code what already does it. You help them decide; you add no scope of your own, and no criteria, levels or reports they did not ask for.",
executive:
"You are a CTO and CEO in one, hearing this proposal. Ask what a busy leader asks: why this matters now, who it is for, what it costs in time and attention, what it puts off, what could go wrong, and what the smallest version worth doing is. Be blunt, and say \"not now\" when you think so, with the reason. Ask one thing at a time; a question may end a turn. Before you speak about the code, ask_code what already exists. You challenge; they decide.",
user:
"You play a customer: someone who would use what they want to build, not a developer, and you know nothing of the code. React to it as you would meet it: what you would want from it, what confuses you, what you would not use and why, in plain words and from your own situation. Stay in the role; when they ask what kind of user you are, choose one that fits what they build and keep to it. You also keep the brief for them: what they settle after hearing you, in their words, not your wishes.",
}
const RULES = `Be brief: one or two short sentences a turn, one thing at a time, then hand the turn back. No preamble and no summary of what they just said. If they start talking while you speak, stop and listen.
No compliments, no praise ("good question", "great idea"), no thanking them for asking, and no agreeing to please them: when they are wrong or a plan is weak, say so and why. Ask a question only when you cannot go on without the answer, one at a time; never end a turn by offering more ("shall I…?", "want me to…?", "anything else?").
Before you use a tool to look something up or do something, first say in a few words what you are doing ("let me look at the board"), so a silence is never a mystery.
The conversation runs until they say to stop or end it: only then end it (end_discussion), after a word of goodbye. Never end it on your own: not after a session starts, not when they are quiet. A silence means they are thinking or busy: wait.
Anything that changes something is theirs to decide: creating a session or sending to one, answering a session's request or question, a decision on the board, stopping, landing, deploying, a node. Do it only when they say to, with their words and choices; before stopping a session, landing, deploying or changing a node, say back in one sentence what you will do and wait for their yes.`
const BRIEF_RULES = `Keep the design current with write_brief: the whole brief each time, once a point is settled, without announcing every write. It shows beside this conversation, where they read and edit it, and you hear when they do. It is what the agent starts from: a first line "# " and a name in a few words (the session's title), then what to build and why, in their words, and what ask_code found already exists. Only what they said: no sections to fill, no acceptance criteria, measurements or decision rules unless they named them. A change someone can see or use, not a study, unless they asked for a study. The agent is Claude Code, in a worktree and branch of its own: it reads the code itself and decides how.
End the brief with a short "Decided" list: each point settled in this conversation, one line each, so nothing agreed is lost between turns.
They check the brief before it goes: when they say to start or send it, do it (start_session), then say in a few words that it went, and carry on if they want to.
Pictures come into the conversation: a sketch, a photo or a screenshot the person adds, and what a session shows. Look at them: say what you see that matters, what you would change, and put what it settles in the brief. Pictures they added go with the brief when it is sent.`
/**
* How the operator talks: it does what was asked in as few turns as it takes.
* It was a design coach until 2026-10-29, handing every turn back with a
* question and offering ideas of its own; its briefs grew criteria, levels and
* reports nobody asked for, and a session spent an afternoon on a study of a
* pipeline the code already had.
*/
const COACH_RULES = `Work as an operator: do what they ask in as few turns as it takes. Ask only when you cannot go on without the answer, one question at a time. Object only when what they ask will not work or already exists, with the one reason, and then do what they decide.`
/** How a role that is not the operator opens a new design, in its own manner. */
const OPENINGS: Partial<Record<Persona, string>> = {
designer: 'Greet them in a few words as their design coach, and ask what they want to make.',
executive: 'Greet them in a few words, as a busy CTO and CEO would, and ask what they are proposing.',
user: 'Introduce yourself in one sentence as someone who might use what they make, and ask what it is.',
}
/** How a followed session's news is taken, for both: told, not acted on. */
const FOLLOW_RULES = `You follow the sessions this conversation is about and those you started, sent to or acted on: their news comes to you by itself, marked as news from a session, not the person's words (a turn ended with its last words, a question or request waiting, a picture it showed, an error). Tell them in a sentence or two at a natural moment, the point first, not while they are mid-thought; then say what you would do next. Its questions and requests are theirs to answer: put them, and answer only with what they choose. Building together: when it finished a step, look at what it did, and propose the next step for them to agree before you send it.`
/** What the voice is told: who it is, what about, how to talk, and what is on the page. */
export function instructions(about: About, persona: Persona, context: string, brief: string, recent: string[]): string {
const sessions = recent.length ? `\n\nSessions in this workspace, newest first:\n${recent.map((r) => `- ${r}`).join('\n')}` : ''
const design = designs(persona) ? `\n\n${persona === 'coach' ? `${COACH_RULES}\n\n` : ''}${BRIEF_RULES}\n\nThe brief now:\n${brief.trim() || '(empty: nothing settled yet)'}` : ''
return `${PERSONAS[persona]}\n\n${RULES}\n\n${FOLLOW_RULES}\n\n${context}${design}${sessions}`
}
/** Of a session: what it is, and its last answer or more, for the voice. */
const sessionLine = (h: Hosted) => `${h.id}: "${h.title}" (${h.status}${h.doing ? `, ${h.doing}` : ''}${h.branch ? `, on ${h.branch}` : ''})`
export function recent(except = ''): string[] {
return hosted()
.filter((h) => !h.archived && !h.imported && h.id !== except)
.slice(0, 12)
.map(sessionLine)
}
/** A session's conversation, as text: its latest turns, clipped from the start. */
export function conversation(items: LogItem[], max = 9000): string {
const out: string[] = []
for (const i of items) {
if (i.kind === 'user' && i.text) out.push(`\n[the person] ${i.text.trim()}`)
else if (i.kind === 'agent' && i.text) {
// Its answers come in pieces: one paragraph.
const last = out.length - 1
if (last >= 0 && out[last]!.startsWith('[agent] ')) out[last] += i.text
else out.push(`[agent] ${i.text}`)
} else if (i.kind === 'tool' && i.title) out.push(`[ran] ${i.title}`)
else if (i.kind === 'error' && i.text) out.push(`[error] ${i.text}`)
}
const text = out.join('\n').trim()
return text.length > max ? `…${text.slice(-max)}` : text
}
async function readSession(id: string): Promise<string> {
const h = hosted().find((x) => x.id === id)
if (!h) return `There is no session ${id}.`
const {items} = await api.sessionLog(id)
const queued = h.queue?.length ? `\nWaiting in its queue: ${h.queue.map((q) => `"${q.text}"`).join('; ')}` : ''
const card = cards().find((c) => c.session === h.owner)
const stage = card ? `\nOn the board: ${stageOf(card.stage)}${card.node ? ` (node ${card.node})` : ''}.` : ''
const asks = openAsks(items)
const waiting = asks.length ? `\n\nIt waits for the person on:\n${asks.join('\n')}` : ''
return `Session ${sessionLine(h)}${h.archived ? ', archived' : ''}.${stage}${queued}${settingsOf(items)}${waiting}\n\nIts conversation, latest last:\n${conversation(items) || '(nothing yet)'}`
}
/** A session's permission requests and questions not answered yet, with the ids and options to answer them by. */
export function openAsks(items: LogItem[]): string[] {
const open = items.filter((it) => (it.kind === 'permission' || it.kind === 'question') && it.request && !answerTo(items, it))
return open.map((it) => {
if (it.kind === 'permission') {
const what = typeof it.input?.description === 'string' ? it.input.description : (it.title ?? 'something')
const options = (it.options ?? []).map((o) => `"${o.name}" (option ${o.optionId})`).join(', ')
return `- Permission request ${it.request}: may it ${what}? Options: ${options}.`
}
const fields = Object.entries(it.schema?.properties ?? {}).map(([k, f]) => {
const options = f.oneOf ?? f.items?.anyOf
const kind = options ? `${f.type === 'array' ? 'one or more of' : 'one of'} ${options.map((o) => `"${o.const}"${o.title && o.title !== o.const ? ` (${o.title})` : ''}`).join(', ')}` : 'free text'
return ` - field ${k}${f.title ? ` "${f.title}"` : ''}: ${kind}`
})
return `- Question ${it.request}: ${it.message ?? ''}\n${fields.join('\n')}`
})
}
/** The mode and model it is on, and the ones it offers, from its log. */
function settingsOf(items: LogItem[]): string {
let modes: {id: string; name: string}[] = []
let models: {id: string; name: string}[] = []
let mode = ''
let model = ''
for (const it of items) {
if (it.kind === 'modes') modes = it.available ?? []
if (it.kind === 'mode') mode = it.current ?? mode
if (it.kind === 'models') models = it.available ?? []
if (it.kind === 'model') model = it.current ?? model
}
const list = (xs: {id: string; name: string}[]) => xs.map((x) => `${x.name} (${x.id})`).join(', ')
return [modes.length ? `\nMode: ${mode || '?'}; it offers ${list(modes)}.` : '', models.length ? `\nModel: ${model || '?'}; it offers ${list(models)}.` : ''].join('')
}
const stageOf = (s: string) => s.replaceAll('_', ' ')
/** The board, in words: every session at work, what ties them, what waits on the person. */
export async function readBoard(): Promise<string> {
const named = (owner: string) => hosted().find((h) => h.owner === owner)?.id ?? owner
const work = cards()
.filter((c) => c.stage !== 'landed')
.map((c) => {
const h = hosted().find((x) => x.owner === c.session)
const what = h ? sessionLine(h) : `${c.label ?? c.session}`
const waits = [c.node ? `on node ${c.node}` : '', c.node_wait ? `number ${c.node_wait.position} in line for ${c.node_wait.wants}` : '', c.intent ? `intends: ${c.intent}` : '', c.badges.overlaps ? `shares files with ${c.badges.overlaps} other` : ''].filter(Boolean)
return `- ${stageOf(c.stage)}: ${what}${waits.length ? `; ${waits.join('; ')}` : ''}`
})
const landed = cards()
.filter((c) => c.stage === 'landed')
.map((c) => `- ${hosted().find((x) => x.owner === c.session)?.title ?? c.label ?? c.session}`)
const ties = links()
.filter((l) => l.files.length || l.notes || l.decisions.length)
.map((l) => `- ${named(l.a)} and ${named(l.b)}: ${[l.files.length ? `both change ${l.files.slice(0, 4).join(', ')}` : '', l.notes ? `${l.notes} notes between them` : ''].filter(Boolean).join('; ')}`)
const ends = todos().map((t) => `- ${t.id}: ${t.text} (for ${t.for}${t.claimed_by ? `, taken by ${t.claimed_by}` : ''})`)
const questions = await api
.decisions()
.then((ds) => ds.filter((d) => !d.answer).map((d) => `- ${d.id}: ${d.question} (options: ${d.options.map((o) => `"${o}"`).join(' / ')}; asked by ${d.by})`))
.catch(() => [] as string[])
// Sessions waiting on a permission or a question: what, so it can be answered from here.
const asking = await Promise.all(
hosted()
.filter((h) => !h.archived && h.status === 'needs_permission')
.map((h) =>
api
.sessionLog(h.id)
.then(({items}) => openAsks(items).map((a) => `${h.id} ${a.slice(2)}`))
.catch(() => [] as string[]),
),
).then((xs) => xs.flat().map((a) => `- ${a}`))
const deploys = await api
.deploys()
.then((d) => {
const ship = new Map((d.ships ?? []).flatMap((s) => s.targets).map((t) => [t.target, t]))
return d.targets.map((t) => `- ${t.target} of ${t.repo} (on ${t.machine}): ${ship.get(t.target)?.words ?? ship.get(t.target)?.state ?? 'no deploy yet'}`)
})
.catch(() => [] as string[])
const machines = nodes().map((n) => {
const holder = n.holder ? `held by ${named(n.holder)}` : 'free'
const state = !n.online ? 'offline' : n.drained ? `out of the pool (${n.drained.why})` : holder
return `- node ${n.id} on ${n.machine}${n.renderer ? `, ${n.renderer}` : ''}: ${state}`
})
const part = (title: string, rows: string[]) => (rows.length ? `${title}:\n${rows.join('\n')}` : `${title}: none.`)
return [
part('At work', work),
part('Waiting for the person to decide', questions),
part("Sessions' requests and questions waiting for an answer", asking),
part('What ties sessions together', ties),
part('Open ends left for later', ends),
part('Landed in the last day', landed),
part('Deploy targets (each publishes the tip of main)', deploys),
part('Build nodes', machines),
].join('\n\n')
}
/** What the conversation is told about its subject, when it starts. */
async function contextOf(about: About, persona: Persona): Promise<string> {
if (about.kind === 'new') return 'They are designing a new session: it starts from main, on a branch of its own, with the brief as its first message. Read the board early (read_board) and say when the design would collide with work in progress or repeat what a session already does.'
if (about.kind === 'session') {
const now = await readSession(about.id).catch((e) => `(could not read it: ${(e as Error).message})`)
return designs(persona)
? `They are designing the next step for session ${about.id}: the brief is the next message it gets (after its current turn, if it is at work). Ground the design in what it did and found.\n\n${now}`
: `They want to talk about session ${about.id}: what it does, how far it is, what it found, what is in its way, what it should do next. Answer from what is below; read it again for what is newer. When they want to tell it something, agree the words, and send it only when they say so.\n\n${now}`
}
if (about.kind === 'board') {
const now = await readBoard().catch((e) => `(could not read it: ${(e as Error).message})`)
return `They want to talk about the board: how the sessions progress, how they relate (files they both change, notes, questions waiting for the person, the lines for build nodes and for landing), and what to steer or do first. When asked for an overview, go most important first: what waits on them, what is stuck, what collides; not a list read out. Help prioritise: say what you would do first and why. To steer a session, agree the message, and send it only when they say so. Read the board again when they ask what changed.\n\nThe board now:\n${now}`
}
if (about.kind === 'tree') {
const now = await api
.tree()
.then((d) => treeText(d, about.goal || hooks.treeGoal()))
.catch((e) => `(could not read it: ${(e as Error).message})`)
return `${TREE_RULES}\n\nThe tree now:\n${now}`
}
return 'A conversation about nothing in particular: they think out loud, ask something, or explore an idea. Be a sparring partner. If it turns into a task for an agent, say they can design it with the coach as a new session (Discuss in the header).'
}
/**
* Talking the research tree over (tree.rs, the Goals page): designing it, and
* choosing and changing where the research heads, with the scout to read the
* code for it. The goals are the person's: it proposes, they decide.
*/
const TREE_RULES = `They want to talk about the research tree (the Goals page), as in Civilization: their goals at the far end, the techs on the way (capabilities someone notices, each with what it needs first and a size), what is built, and the direction the tree heads in, which researches the techs on the way one after another by itself. Together you design it: sharpen a goal (who notices, signs of progress, what it must never lead to), and choose or change the direction.
The goals are theirs: write one only in their words, and say back a goal, a direction or a research session before you save or start it, then wait for their yes. Ideas they have along the way go on the tree as insights (change_tree idea), in their words, once they agree.
The scout reads the code for the tree: when they want to know what is built, what is missing, what earlier sessions left open, how the techs group, or what a tech would look like, send it out (scout_tree) with what they want it to look at, in their words. Say that it goes, and talk on: its result comes to you by itself in a minute or a few. Then tell them in short what it found. Its guesses need no verdict: one they start is kept, one nobody starts fades in a month; only when they say one is wrong, drop it (tech_drop) with their reason, so the scout does not bring it back.
A theme is a goal under the top one; read_tree with its id to talk about one theme. When they ask what is left for a goal or theme, or what can be built now, answer from read_tree's numbered way, which the page shows with the same numbers: what is being built now, what can start now, and what comes later and after which step; then offer to start one (change_tree research), or to build it all by itself (direction_set), and wait for their yes. When nothing is left, offer to send the scout to look for more.
To talk one tech over, open it (open_tech): it opens on their screen, and you get all of it, with what its mockup shows in words, since you cannot see the picture. When they change what it is, who notices it, what they do differently, what exists, its name or its size, say the new words back in one sentence and change it on their yes (change_tree tech_edit, only the fields that change). What they want different in the mockup is a remark (change_tree remark, in their words, with where on the screen when they said it); when they want it drawn again, send the scout to draw that tech (scout_tree, move sketch, its id), which takes the description as it is and the remarks with it. There is no button for that while you talk: it is yours to do on their word.
The page follows you to the tree. Read it again (read_tree) when they ask what changed.`
/** What the conversation is called on the page. */
export function aboutLabel(about: About | null, persona: Persona = talk.persona): string {
if (!about) return ''
// The operator is the default, so unnamed; another role is named, as the dialog calls it.
const role = persona === 'coach' || persona === 'midas' ? '' : ` with the ${{designer: 'design coach', executive: 'CTO / CEO', user: 'customer'}[persona]}`
if (about.kind === 'new') return `Designing a new session${role}`
if (about.kind === 'session') return designs(persona) ? `Designing ${about.id}'s next step${role}` : `About ${about.id}`
if (about.kind === 'tree') return 'About the research tree'
return about.kind === 'board' ? 'About the board' : 'Free conversation'
}
const text = (v: unknown) => String(v ?? '').trim()
/** What may be said back to a session's question: its fields' values, as the page's form sends them. */
function answers(v: unknown): Record<string, string | string[]> {
const out: Record<string, string | string[]> = {}
if (!v || typeof v !== 'object') return out
for (const [k, x] of Object.entries(v as Record<string, unknown>)) out[k] = Array.isArray(x) ? x.map(String) : String(x)
return out
}
/**
* The tools that act, as the pages' buttons do (the same calls, under the
* person's steer role): each says what it did, for the page's notes and the
* voice. The hub refuses what the role does not allow.
*/
const ACTS: Record<string, (a: Record<string, unknown>, id: string) => Promise<string>> = {
answer_permission: async (a, id) => {
await api.permit(id, text(a.request), text(a.option))
return `answered ${id}'s request`
},
answer_question: async (a, id) => {
const skip = a.skip === true
await api.answer(id, text(a.request), skip ? 'decline' : 'accept', skip ? {} : answers(a.answers))
return skip ? `skipped ${id}'s question` : `answered ${id}'s question`
},
decide: async (a) => {
await api.decide(text(a.decision), text(a.choice), text(a.note) || undefined)
return `decided ${text(a.decision)}: ${text(a.choice)}`
},
interrupt_session: async (_, id) => {
await api.cancelTurn(id)
return `interrupted ${id}`
},
stop_session: async (_, id) => {
await api.stopSession(id)
return `ended ${id}`
},
reopen_session: async (_, id) => {
await api.reopen(id)
return `reopened ${id}`
},
archive_session: async (a, id) => {
await api.archiveSession(id, a.archived !== false)
return a.archived !== false ? `archived ${id}` : `brought ${id} back`
},
rename_session: async (a, id) => {
if (!text(a.title)) throw new Error('an empty title')
await api.renameSession(id, text(a.title))
return `renamed ${id}: ${text(a.title)}`
},
set_session_mode: async (a, id) => {
await api.setMode(id, text(a.mode))
return `${id} in mode ${text(a.mode)}`
},
set_session_model: async (a, id) => {
await api.setModel(id, text(a.model))
return `${id} on ${text(a.model)}`
},
// As the person's own answer to "Shall it land?": the session's finish-branch skill lands it.
land_session: async (a, id) => {
await api.sayTo(id, a.finish === false ? 'Land it, keep working.' : 'Land it and finish.', false)
return `told ${id} to land`
},
deploy: async (a) => {
if (!text(a.target)) throw new Error('no target')
await api.deploy(text(a.target))
return `deploy of ${text(a.target)} queued`
},
add_open_end: async (a) => {
if (!text(a.text)) throw new Error('an empty open end')
await api.addTodo(text(a.for) || 'any', text(a.text))
return `open end left for ${text(a.for) || 'any'}`
},
close_open_end: async (a) => {
await api.doneTodo(text(a.id))
return `open end ${text(a.id)} done`
},
create_session: async (a) => {
const made = await api.createSession(text(a.name), text(a.brief))
created = made.id
return `created ${made.id} (${made.status}): ${text(a.name)}`
},
drain_node: async (a) => {
await api.drain(node(a), text(a.why) || 'from a conversation with Midas')
return `took ${node(a)} out of the pool`
},
undrain_node: async (a) => {
await api.undrain(node(a))
return `put ${node(a)} back in the pool`
},
release_node: async (a) => {
await api.release(node(a))
return `took ${node(a)} back`
},
}
/** The node a tool names, if the workspace has it. */
function node(a: Record<string, unknown>): string {
const id = text(a.node)
if (!nodes().some((n) => n.id === id)) throw new Error(`no node ${id || '(none named)'}`)
return id
}
/** The session the last `create_session` made: where the page goes after it. */
let created = ''
/**
* Where the page goes when Midas looks at or acts on something, so the person
* sees it: the board (Home, `''`) for the board, the session for a session, the workspace
* for a node or a deploy. The coach keeps its design page.
*/
export function placeOf(name: string, a: Record<string, unknown>, made = ''): string | null {
const id = text(a.session)
if (name === 'create_session') return made ? `sessions/${made}` : null
if (name === 'read_board' || name === 'decide' || name === 'add_open_end' || name === 'close_open_end') return ''
if (name === 'deploy' || name === 'drain_node' || name === 'undrain_node' || name === 'release_node') return 'workspace'
if (name === 'read_tree' || name === 'open_tech' || name === 'change_tree' || name === 'scout_tree') return 'research'
if (/^s\d+$/.test(id)) return `sessions/${id}`
return null
}
function follow(name: string, a: Record<string, unknown>) {
if (talk.persona !== 'midas' || typeof location === 'undefined') return
const to = placeOf(name, a, created)
if (to !== null) go(to)
// A goal or theme it names is the one the page shows.
if (to === 'research' && /^g\d+$/.test(text(a.goal))) hooks.treeShow(text(a.goal))
}
/**
* A code question's answer (ask_code), waited for while the conversation goes
* on, then given to the voice to say; and on the page, to read back.
*/
async function codeAnswer(id: string) {
for (;;) {
let r: {state: string; answer?: string; error?: string}
try {
r = await api.codeAnswer(id)
} catch (e) {
r = {state: 'failed', error: (e as Error).message}
}
if (talk.state === 'off') return
if (r.state === 'answered') {
say('note', `from the code: ${r.answer}`)
call?.tell(`The coding agent's answer to your ask_code question, from the code: ${r.answer}\nTell them in short, in your own words.`)
return
}
if (r.state === 'failed') {
say('note', `no answer from the code: ${r.error}`)
call?.tell(`Your ask_code question got no answer: ${r.error}. Tell them in a few words.`)
return
}
}
}
/** The tree's changes to one tech that its open dialog shows. */
const TECH_OPS = ['tech_edit', 'remark', 'remark_drop']
/** The goal a tree conversation is about: the one it named, or the one the research page shows. */
function treeGoalOf(about: About): string {
return (about.kind === 'tree' && about.goal) || hooks.treeGoal()
}
/** What a change to the tree did, in words, for the page's notes and the voice. */
export function treeDone(op: string, a: Record<string, unknown>, d: TreeState): string {
const name = (id: string) => d.goals.find((g) => g.id === id)?.name ?? d.techs.find((t) => t.id === id)?.name ?? id
const id = text(a.id)
switch (op) {
case 'goal_save':
return id ? `goal ${id} changed: ${name(id)}` : `goal ${d.last_goal ?? ''} made: ${text(a.name)}`
case 'goal_delete':
return `goal ${id} deleted`
case 'idea':
return `idea kept on ${name(text(a.goal))}`
case 'tech_confirm':
return `kept ${name(id)}`
case 'tech_drop':
return `not this: ${name(id)}`
case 'tech_edit':
return `${name(id)} changed: ${['name', 'what', 'who', 'differently', 'exists', 'done', 'size', 'lands_in'].filter((k) => k in a).join(', ')}`
case 'remark':
return `remark on the mockup of ${name(id)}`
case 'remark_drop':
return `remark on ${name(id)} taken back`
case 'direction_set':
return `heading to ${name(text(a.target))}`
case 'direction_pause':
return a.paused === false ? 'direction resumed' : 'direction paused'
case 'direction_clear':
return 'direction stopped'
case 'direction_limits':
return 'direction limits changed'
case 'direction_order':
return 'directions put in a new order'
case 'budget_set':
return 'budget for all directions changed'
case 'research':
return `research on ${name(id)} started${d.techs.find((t) => t.id === id)?.research ? ` in ${d.techs.find((t) => t.id === id)!.research!.session}` : ''}`
default:
return `${op.replaceAll('_', ' ')}${id ? ` ${name(id)}` : ''}`
}
}
/** How often a round the voice sent out is looked at, and for how long at most. */
const ROUND_EVERY = 8000
const ROUND_WAIT = 20 * 60_000
/**
* A scout's round sent out from the conversation, waited for while it goes on:
* what it found goes into the conversation (and is kept with it), and to the
* voice when the call is still on.
*/
async function awaitRound(id: string) {
const about = talk.about
const until = Date.now() + ROUND_WAIT
while (Date.now() < until) {
await new Promise((r) => setTimeout(r, ROUND_EVERY))
if (talk.about !== about) return
const d = await api.tree().catch(() => null)
const r = d?.rounds.find((x) => x.id === id)
if (!d || !r) continue
// A look is back when none of its moves is still to come; each that ran is news.
const look = r.look ? d.rounds.filter((x) => x.look === r.look) : [r]
if (look.some((x) => x.state === 'queued' || x.state === 'asked')) continue
hooks.treeChanged(d)
const ran = look.filter((x) => x.state === 'done' || x.state === 'failed')
if (!ran.length) return
const news = ran.map((x) => roundNews(d, x)).join('\n')
const ok = ran.filter((x) => x.state === 'done')
say('note', ok.length ? `the scout is back: ${ok.map((x) => x.summary || x.move).join(' ')}` : `the scout's round failed: ${ran[0]!.error ?? ''}`)
call?.tell(`${news}\nNews from the scout (not something the person said). Tell them in short at a natural moment, then go through what it found with them.`)
return
}
}
/**
* The sessions the conversation follows: the one it is about, and each it
* started, sent to or acted on. What they report comes into the call by itself,
* so building together needs no "how is it doing?": a turn ended (with its last
* words), a request or question waiting for the person, a picture it showed
* (which the voice sees), an error, its end. Read off their logs every few
* seconds while the call is on.
*/
const WATCH_EVERY = 4000
/** Of each followed session: the last log item already told, and its status then. */
const seen = new Map<string, {n: number; status: string}>()
let watchTimer: ReturnType<typeof setInterval> | undefined
let watching = false
/** Follow a session from now on: what it did before is not news. */
export function watch(id: string) {
if (!/^s\d+$/.test(id) || talk.following.includes(id)) return
talk.following = [...talk.following, id].slice(-6)
seen.set(id, {n: -1, status: ''})
void api
.sessionLog(id)
.then(({items}) => seen.set(id, {n: items.at(-1)?.n ?? 0, status: hosted().find((h) => h.id === id)?.status ?? ''}))
.catch(() => seen.delete(id))
watchTimer ??= setInterval(() => void poll(), WATCH_EVERY)
}
function unwatchAll() {
clearInterval(watchTimer)
watchTimer = undefined
seen.clear()
talk.following = []
}
async function poll() {
if (watching || talk.state === 'off') return
watching = true
try {
for (const id of talk.following) {
const was = seen.get(id)
const h = hosted().find((x) => x.id === id)
// Not read yet, or gone; idle with nothing new: no need to read its log.
if (!was || was.n < 0 || !h) continue
if (h.status === was.status && h.status !== 'working' && h.status !== 'starting') continue
const {items} = await api.sessionLog(id)
const fresh = items.filter((i) => i.n > was.n)
seen.set(id, {n: items.at(-1)?.n ?? was.n, status: h.status})
const news = report(id, fresh, items)
if (!news) continue
say('note', news.note)
const images = await Promise.all(news.images.map((f) => picture(`/v1/hosted/${id}/media/${encodeURIComponent(f)}`).catch(() => '')))
call?.tell(news.tell, images.filter(Boolean))
}
} catch {
// A read that failed is read again next time.
} finally {
watching = false
}
}
/**
* What a followed session's new log items are worth saying: for the page (a
* note), for the voice (what to tell them), and the pictures among them. Null
* when nothing is: it is still at work, its tools running.
*/
export function report(id: string, fresh: LogItem[], all: LogItem[]): {note: string; tell: string; images: string[]} | null {
const images = fresh.filter((i) => i.kind === 'media' && i.file && (i.mime ?? '').startsWith('image/')).map((i) => i.file!)
const captions = fresh.filter((i) => i.kind === 'media' && i.file).map((i) => `"${i.caption || i.file}"`)
const asks = openAsks(all).filter((a) => fresh.some((i) => i.request && a.includes(` ${i.request}:`)))
const ended = fresh.some((i) => i.kind === 'turn_end')
const errors = fresh.filter((i) => i.kind === 'error' && i.text).map((i) => i.text!.trim().slice(0, 300))
const finished = fresh.find((i) => i.kind === 'finished')
if (!images.length && !captions.length && !asks.length && !ended && !errors.length && !finished) return null
const parts: string[] = []
const notes: string[] = []
if (captions.length) {
parts.push(`It showed ${captions.join(', ')}${images.length ? ': the pictures follow, look at them' : ''}.`)
notes.push(`${id} showed ${captions.length === 1 ? 'something' : `${captions.length} things`}`)
}
if (asks.length) {
parts.push(`It waits for the person on:\n${asks.join('\n')}\nPut it to them in a sentence and answer it only with what they choose.`)
notes.push(`${id} asks something`)
}
if (errors.length) parts.push(`It ran into: ${errors.join('; ')}.`)
if (finished) {
parts.push(`It finished: ${finished.outcome ?? 'done'}.`)
notes.push(`${id} finished`)
} else if (ended) {
const words = conversation(fresh, 1500).split('\n').filter((l) => l.startsWith('[agent] ')).at(-1)?.slice(8)
parts.push(`Its turn ended${words ? `. Its last words: ${words}` : '.'}`)
notes.push(`${id} is done for now`)
}
const tell = `News from session ${id}, which you follow (not something the person said): ${parts.join('\n')}\nTell them in a sentence or two, the point first, at a natural moment; then, building together, what you would do next.`
return {note: notes.join('; ') || `${id}: news`, tell, images: images.slice(-3)}
}
/** The longest side of a picture the voice is shown: enough to read a screen, small enough for the call's channel. */
const PICTURE_SIDE = 768
/** A picture as the voice takes it: a JPEG data URL, scaled down. */
export async function picture(from: string | Blob): Promise<string> {
const blob = typeof from === 'string' ? await fetch(from).then((r) => (r.ok ? r.blob() : Promise.reject(new Error(`${r.status}`)))) : from
const bitmap = await createImageBitmap(blob)
const scale = Math.min(1, PICTURE_SIDE / Math.max(bitmap.width, bitmap.height))
const canvas = document.createElement('canvas')
canvas.width = Math.round(bitmap.width * scale)
canvas.height = Math.round(bitmap.height * scale)
const g = canvas.getContext('2d')!
// A transparent sketch on white, not on black.
g.fillStyle = '#fff'
g.fillRect(0, 0, canvas.width, canvas.height)
g.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
bitmap.close()
return canvas.toDataURL('image/jpeg', 0.7)
}
/**
* A picture the person adds to the conversation (a sketch, a photo, a
* screenshot): uploaded to go with the brief, and shown to the voice at once.
*/
export async function addPicture(blob: Blob, name: string, what = 'a picture') {
if (talk.pictures.length >= 5) return say('note', 'five pictures go with one brief at most')
const {token} = await api.upload(blob, name)
talk.pictures = [...talk.pictures, {token, url: URL.createObjectURL(blob), name}]
say('note', `added ${what}`)
if (talk.state === 'off') return
const shown = await picture(blob).catch(() => '')
call?.tell(`The person added ${what} to the conversation (it goes with the brief when it is sent): it follows. Look at it, say in a sentence what you see that matters for the design, and fold it into the brief.`, shown ? [shown] : [])
}
export function dropPicture(token: string) {
const p = talk.pictures.find((x) => x.token === token)
if (p) URL.revokeObjectURL(p.url)
talk.pictures = talk.pictures.filter((x) => x.token !== token)
call?.note(`The person took ${p?.name ?? 'a picture'} out: it no longer goes with the brief.`)
}
/** The tools the hub gave the voice (discuss.rs), run here. */
async function run(name: string, args: string): Promise<object> {
const about = talk.about
if (!about || talk.state === 'off') return {error: 'the conversation is over'}
let a: Record<string, unknown> = {}
try {
a = JSON.parse(args || '{}')
} catch {
return {error: 'arguments that are not JSON'}
}
if (name === 'write_brief') {
const brief = String(a.brief ?? '').trim()
if (!brief) return {error: 'an empty brief'}
talk.brief = brief
talk.sentTo = ''
keep()
return {ok: true}
}
if (name === 'find_sessions') {
const {results} = await api.searchSessions(String(a.query ?? ''))
return {sessions: results.slice(0, 8).map((h) => ({id: h.id, title: h.title, line: h.snippet}))}
}
if (name === 'ask_code') {
const question = text(a.question)
if (!question) return {error: 'an empty question'}
const {id} = await api.askCode(question, text(a.project), text(a.session) || (about.kind === 'session' ? about.id : ''))
void codeAnswer(id)
return {asked: true, note: 'Its answer comes as a message in half a minute or so: carry on meanwhile.'}
}
if (name === 'read_session') {
const id = String(a.session ?? (about.kind === 'session' ? about.id : ''))
if (hosted().some((h) => h.id === id)) follow(name, {session: id})
return {session: await readSession(id)}
}
if (name === 'read_board') {
follow(name, a)
return {board: await readBoard()}
}
if (name === 'send_to_session') {
const id = String(a.session ?? '')
const text = String(a.message ?? '').trim()
if (!hosted().some((h) => h.id === id)) return {error: `no session ${id}`}
if (!text) return {error: 'an empty message'}
// Cutting into its turn is for when they said to stop what it does and do this first.
const now = a.now === true
const images = a.pictures === true ? talk.pictures.map((p) => p.token) : []
await api.sayTo(id, text, now, images)
if (images.length) talk.pictures = []
say('note', `sent to ${id}${now ? ', cutting in' : ''}${images.length ? `, with ${images.length} picture${images.length > 1 ? 's' : ''}` : ''}`)
follow(name, a)
watch(id)
return {ok: true}
}
if (name === 'read_tree') {
const d = await api.tree()
follow(name, a)
return {tree: treeText(d, text(a.goal) || treeGoalOf(about))}
}
if (name === 'open_tech') {
const d = await api.tree()
const id = text(a.id)
if (!d.techs.some((t) => t.id === id)) return {error: `no tech ${id}`}
follow(name, a)
hooks.treeOpen(id)
say('note', `opened ${d.techs.find((t) => t.id === id)!.name}`)
return {tech: techText(d, id)}
}
if (name === 'change_tree') {
const {op, ...fields} = a
const opName = text(op)
if (opName === 'scout') return {error: 'send the scout with scout_tree'}
try {
const d = await api.treeOp(opName, fields)
hooks.treeChanged(d)
follow(name, a)
// A tech's words or its mockup's remarks change where they can be seen: in its dialog.
if (TECH_OPS.includes(opName)) hooks.treeOpen(text(a.id))
const done = treeDone(opName, a, d)
say('note', done)
// A research session it started, it follows: what it reports comes in.
if (opName === 'research') {
const s = d.techs.find((t) => t.id === text(a.id))?.research?.session
if (s) watch(s)
}
return {ok: true, done}
} catch (e) {
return {error: (e as Error).message}
}
}
if (name === 'scout_tree') {
const goal = text(a.goal) || treeGoalOf(about)
try {
// A look (the page's Research further) is every move that fits, one after another; its last one ends it.
const move = text(a.move) || 'look'
const before = await api.tree().catch(() => null)
const busy = !!before?.rounds.some((x) => x.goal === goal && (x.state === 'queued' || x.state === 'asked'))
const d = move === 'look'
? await api.treeOp('look', {goal, focus: text(a.focus), tech: text(a.tech), via: 'talk'})
: await api.treeOp('scout', {goal, move, focus: text(a.focus), tech: text(a.tech)})
hooks.treeChanged(d)
follow(name, a)
const r = d.rounds.filter((x) => x.goal === goal && (x.state === 'queued' || x.state === 'asked')).at(-1)
if (r) awaitRound(r.id)
// In words, as the bar says it: never the move's or the goal's id.
const where = d.goals.find((x) => x.id === goal)?.name ?? 'the goal'
const about = text(a.tech) ? d.techs.find((t) => t.id === text(a.tech))?.name : ''
say('note', `${busy ? 'question for the scout, after the look going now' : 'the scout went to look'} at “${about || where}”${text(a.focus) ? `: ${text(a.focus)}` : ''}`)
return {
ok: true,
round: r?.id,
note: busy
? 'The scout was already looking at this goal: this question waits for that look and starts by itself after it. Say so. Its result comes to you as a message: talk on meanwhile.'
: 'Its result comes to you as a message in a minute or a few: talk on meanwhile. read_tree tells what it reads now.',
}
} catch (e) {
return {error: (e as Error).message}
}
}
if (name in ACTS) {
const id = String(a.session ?? '')
if ('session' in a && !hosted().some((h) => h.id === id)) return {error: `no session ${id}`}
try {
created = ''
const done = await ACTS[name]!(a, id)
say('note', done)
follow(name, a)
// What it acted on, it follows from now on: the session it made or steered.
watch(created || id)
return {ok: true, done}
} catch (e) {
return {error: (e as Error).message}
}
}
if (name === 'start_session') return sendBrief()
if (name === 'end_discussion') {
// After its goodbye: it says it, then hangs up.
setTimeout(endTalk, 2500)
return {ok: true}
}
return {error: `no tool ${name}`}
}
/** The brief to its session: a new one started with it, or the session's next message. Also the page's button. */
export async function sendBrief(): Promise<object> {
const about = talk.about
const brief = talk.brief.trim()
if (!about) return {error: 'the conversation is over'}
if (!brief) return {error: 'the brief is empty: write it first'}
if (talk.sentTo) return {error: `already sent to ${talk.sentTo}`}
const images = talk.pictures.map((p) => p.token)
try {
if (about.kind === 'session') {
await api.sayTo(about.id, brief, false, images)
talk.sentTo = about.id
say('note', `sent to ${about.id}`)
} else {
const id = await hooks.startSession(brief, images)
talk.sentTo = id
say('note', `${id} started`)
// It goes on about the session it started: its next step, should they want one.
talk.about = {kind: 'session', id}
call?.note(`Session ${id} has started with the brief. You follow it now: what it reports comes to you by itself. If they go on, it is about ${id}'s next step: the brief you write next is its next message.`)
}
} catch (e) {
return {error: (e as Error).message}
}
// An upload's token is spent once its message names it.
talk.pictures = []
keep()
watch(talk.sentTo)
return {ok: true, session: talk.sentTo}
}
/**
* The screen stays on while a conversation runs: the phone is put down to talk,
* and a screen that sleeps can take the page, and the call, with it. The
* browser drops the lock whenever the page is hidden, so it is asked again each
* time the page comes back while the conversation is still on.
*/
let wake: WakeLockSentinel | null = null
let wakeWanted = false
/** Said once a conversation: the screen may sleep, and why. */
let wakeNoted = false
async function holdScreen() {
wakeWanted = true
if (wake || document.visibilityState !== 'visible') return
if (!('wakeLock' in navigator)) {
if (!wakeNoted) say('note', 'this browser cannot keep the screen on: it may sleep during the conversation')
wakeNoted = true
return
}
try {
const lock = await navigator.wakeLock.request('screen')
// Ended while it was being asked for.
if (!wakeWanted) return void lock.release().catch(() => {})
wake = lock
lock.addEventListener('release', () => wake === lock && (wake = null))
} catch (e) {
if (!wakeNoted) say('note', `the screen may sleep: ${(e as Error).message}`)
wakeNoted = true
}
}
function releaseScreen() {
wakeWanted = false
wakeNoted = false
const lock = wake
wake = null
lock?.release().catch(() => {})
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'visible' || talk.state === 'off') return
if (wakeWanted) void holdScreen()
// A call that dropped while the page was away is called again now it is back.
if (talk.state === 'reconnecting' && !call) void connect('again')
})
}
/** Start talking it over: about what, with whom. */
export async function startTalk(about: About, persona: Persona) {
if (talk.state !== 'off') endTalk()
ending = false
drops = []
talk.about = about
talk.persona = persona
talk.lines = []
talk.brief = designs(persona) ? hooks.draft(about).trim() : ''
talk.sentTo = ''
// A new conversation: the one before stays kept on the hub, under its own id.
talk.id = ''
remember('')
clearPictures()
talk.muted = false
talk.state = 'joining'
void holdScreen()
if (about.kind === 'session') watch(about.id)
await connect('start')
}
function clearPictures() {
for (const p of talk.pictures) URL.revokeObjectURL(p.url)
talk.pictures = []
}
/** What the hub takes for instructions (discuss.rs `INSTRUCTIONS_MAX`), with room: a big board is clipped. */
const CONTEXT_MAX = 20_000
let connecting = false
/**
* Open the call: at the start, again after it dropped, or to resume a kept conversation
* (`carryOn`); the last two with what was said so far.
*/
type How = 'start' | 'again' | 'resume'
async function connect(how: How) {
const about = talk.about
if (!about || ending || connecting || call) return
connecting = true
try {
await open(about, how)
} finally {
connecting = false
}
}
async function open(about: About, how: How) {
const again = how === 'again'
let mic: MediaStream
try {
// No noise suppression here: OpenAI's (far_field) does it, and two in a row eat the starts of
// words (Podium found it first; "Hoi" was heard as "Hoy").
mic = await navigator.mediaDevices.getUserMedia({audio: {echoCancellation: true, noiseSuppression: false, autoGainControl: true}})
} catch (e) {
if (again) {
// Most often: the page is in the background. It is called again when it comes back.
say('note', `waiting to call again: ${(e as Error).message}`)
return
}
say('note', `no microphone: ${(e as Error).message}`)
return endTalk()
}
if (ending) return mic.getTracks().forEach((t) => t.stop())
const c: LiveCall = new LiveCall({
onYou: (text) => {
say('you', text)
if (talk.activity !== 'speaking' && talk.activity !== 'working') setActivity('thinking')
},
onHearing: () => talk.activity !== 'working' && setActivity('listening'),
onVoice: (text) => say('midas', text),
onSpeaking: (on) => {
if (call !== c) return
if (on) setActivity('speaking')
else if (talk.activity === 'speaking') setActivity('listening')
},
onToolCall: async (name, args, id) => {
setActivity('working', DOING[name] ?? name)
const out = await run(name, args).catch((e) => ({error: String(e)}))
if (talk.activity === 'working') setActivity('thinking')
c.toolResult(id, out, name !== 'end_discussion')
},
onClosed: (reason) => {
if (call !== c) return
call = null
dropped(reason)
},
})
call = c
const full = await contextOf(about, talk.persona)
const context = full.length > CONTEXT_MAX ? `${full.slice(0, CONTEXT_MAX)}\n…(clipped: read it again for the rest)` : full
const said = talk.lines.filter((l) => l.who !== 'note').slice(-24)
const recap = how !== 'start' && said.length ? `\n\n${again ? 'The call dropped and is connected again' : 'The person comes back to this conversation, ended earlier, to carry on'}. The conversation so far, latest last; carry on from it, without greeting again:\n${said.map((l) => `${l.who === 'you' ? 'They' : 'You'}: ${l.text}`).join('\n')}` : ''
const opening = again
? 'Say in a few words that you are back, and carry on where you were.'
: how === 'resume'
? 'Say in one short sentence where you left off, then wait.'
: designs(talk.persona)
? about.kind === 'new'
? talk.brief
? 'Say in a few words that you have read the start of their brief, and ask the first thing that matters about it.'
: OPENINGS[talk.persona] ?? 'Greet them in a few words and ask what they want to work on.'
: 'Say in a few words that you know where the session is, and ask what its next step should be.'
: about.kind === 'session'
? 'Say in one short sentence where the session stands, then wait.'
: about.kind === 'board'
? 'Say in one short sentence what waits on them first, then wait.'
: about.kind === 'tree'
? 'Say in one short sentence where the tree stands (what it heads for, what is next), then ask where they want to take it.'
: 'Say hello in two or three words, then wait.'
try {
await c.start(mic.getAudioTracks()[0]!, instructions(about, talk.persona, context, talk.brief, recent(about.kind === 'session' ? about.id : '')) + recap, opening, toolsFor(about, talk.persona), voiceOf(talk.persona))
if (call === c) {
talk.state = 'on'
setActivity('listening')
}
if (talk.muted) c.mute(true)
} catch (e) {
mic.getTracks().forEach((x) => x.stop())
if (call === c) {
call = null
c.close()
if (again) dropped((e as Error).message)
else {
say('note', `could not start: ${(e as Error).message}`)
endTalk()
}
}
}
}
/** What it is busy with, said on the page while a tool runs. */
const DOING: Record<string, string> = {
write_brief: 'writing the brief',
find_sessions: 'looking up sessions',
ask_code: 'asking about the code',
read_session: 'reading the session',
read_board: 'reading the board',
send_to_session: 'sending it',
start_session: 'starting the session',
answer_permission: 'answering its request',
answer_question: 'answering its question',
decide: 'deciding',
interrupt_session: 'interrupting it',
stop_session: 'ending the session',
reopen_session: 'reopening it',
archive_session: 'filing it',
rename_session: 'renaming it',
set_session_mode: 'changing its mode',
set_session_model: 'changing its model',
land_session: 'telling it to land',
deploy: 'deploying',
create_session: 'creating the session',
drain_node: 'taking the node out of the pool',
undrain_node: 'putting the node back',
release_node: 'taking the node back',
add_open_end: 'leaving an open end',
close_open_end: 'closing the open end',
read_tree: 'reading the tree',
change_tree: 'changing the tree',
scout_tree: 'sending the scout',
end_discussion: 'hanging up',
}
/** The call ended without the person ending it: call again, unless it keeps dropping. */
function dropped(reason: string) {
if (ending || talk.state === 'off') return
const now = Date.now()
drops = [...drops.filter((t) => now - t < 120_000), now]
if (drops.length > 3) {
say('note', `the call keeps dropping (${reason}): ended`)
return endTalk()
}
say('note', `the call dropped (${reason}): calling again`)
talk.state = 'reconnecting'
setActivity('listening')
// Hidden: the microphone is not given to a page in the background; it is called when it is back.
if (document.visibilityState === 'visible') setTimeout(() => void connect('again'), 1000 * drops.length)
}
export function endTalk() {
ending = true
call?.close()
call = null
clearTimeout(editTimer)
clearTimeout(thinkTimer)
unwatchAll()
releaseScreen()
talk.state = 'off'
talk.activity = 'listening'
talk.doing = ''
keep(true)
}
/** Done with it: the conversation and the brief leave the page, kept on the hub (Earlier conversations). */
export function closeTalk() {
if (talk.state !== 'off') endTalk()
else keep(true)
remember('')
talk.id = ''
talk.lines = []
talk.brief = ''
talk.sentTo = ''
clearPictures()
talk.about = null
}
export function muteTalk(on: boolean) {
talk.muted = on
call?.mute(on)
}
let editTimer: ReturnType<typeof setTimeout> | undefined
/** The person edited the brief by hand: the voice hears the new text once they pause. */
export function editBrief(text: string) {
talk.brief = text
talk.sentTo = ''
keep()
if (talk.state === 'off') return
clearTimeout(editTimer)
editTimer = setTimeout(() => call?.note(`The person edited the brief by hand. It now reads:\n${text.trim() || '(empty)'}`), 2000)
}