git clone https://garage44.eu/jeroen/midas.git.. /src/discuss.rs
//! Talking things over, out loud: a voice conversation on OpenAI's realtime
//! model (gpt-realtime-2.1, the one Podium's presenter speaks with), started
//! from the page's header about what the person picks: a new session or an
//! open one's next step (with the coach, who keeps the design as a brief beside
//! the conversation), a session, the board, or nothing in particular. What a
//! session is sent is still the person's to send: the conversation shapes the
//! text.
//!
//! The page opens the call itself over WebRTC; the hub only signs it, so the
//! OpenAI key never reaches a browser. `POST /v1/hosted/discuss` takes the
//! page's SDP offer, the conversation's instructions (the page knows what is
//! on it: the session, its last answer, the board, the brief so far) and which
//! of the hub's tools it wants, and answers OpenAI's SDP. The tools are the
//! hub's, so a page cannot hand the call anything else to do; the voice model
//! calls them itself, and its calls come to the page, which runs them
//! (`web/src/lib/discuss.ts`).
//!
//! Its settings are the hub's, set on the page's Settings (an admin's): the
//! realtime model and its voice, the language spoken and the brief's, in
//! `discuss.json` beside the registry; and the OpenAI key, in `openai.key`
//! beside the state directory (`/srv/midas/openai.key`, the hub's user only),
//! which the page can replace or remove but never read back. Not in
//! `/etc/midas/hub.conf`: the hub cannot write there. Without a key, the page
//! offers no Discuss button. No trace of a call is kept at OpenAI
//! (`tracing: null`).
//!
//! Two engines, by the model Settings names. GPT-Live (gpt-live-1, as
//! Podium's feedback coach talks) is full duplex and sounds the most like a
//! person; it talks, and a backend model (`backend`) reasons and runs the
//! tools for it (`/v1/live/sessions`, delegation "responses"). The realtime
//! model (gpt-realtime-2.1) calls the tools itself (`/v1/realtime/calls`). It
//! ran on GPT-Live until 2026-10-24, on the realtime model until 2026-11-05,
//! when the person found GPT-Live the better voice and it came back as the
//! default.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::store;
/// What a page may brief the conversation with: a session's last answer and a
/// brief, with room.
const INSTRUCTIONS_MAX: usize = 32 * 1024;
/// The model a call talks on when the settings name none it can use.
const DEFAULT_MODEL: &str = "gpt-live-1";
/// What reasons and runs the tools for GPT-Live, unless the settings name another (Podium's too).
const DEFAULT_BACKEND: &str = "gpt-6-luna";
/// What hears the person, for the transcript on the page: the best of the
/// account's transcribers that a realtime session takes.
const TRANSCRIBER: &str = "gpt-live-transcribe";
/// The languages it can be told to speak and write in; "" is theirs: English
/// and the widely spoken ones it handles in practice.
pub const LANGUAGES: [(&str, &str); 16] = [
("", "Auto"), ("en", "English"), ("nl", "Dutch"), ("de", "German"), ("fr", "French"), ("es", "Spanish"),
("it", "Italian"), ("pt", "Portuguese"), ("pl", "Polish"), ("sv", "Swedish"), ("da", "Danish"),
("tr", "Turkish"), ("hi", "Hindi"), ("ja", "Japanese"), ("ko", "Korean"), ("zh", "Chinese"),
];
/// The realtime model's built-in voices. A custom voice goes by its id (`voice_…`).
pub const VOICES: [&str; 10] = ["alloy", "ash", "ballad", "cedar", "coral", "echo", "marin", "sage", "shimmer", "verse"];
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(default)]
pub struct Settings {
/// The model it talks on: GPT-Live's or a realtime model.
pub model: String,
/// What reasons and runs the tools for GPT-Live; a realtime model runs its own.
pub backend: String,
/// The woman's voice, and the man's: a call asks for one (its role's, picked on the page).
pub voice: String,
pub male_voice: String,
/// What it speaks, and what it writes the brief in: a code of [`LANGUAGES`], "" for theirs.
pub language: String,
pub brief_language: String,
}
impl Default for Settings {
fn default() -> Self {
Settings {
model: DEFAULT_MODEL.into(),
backend: DEFAULT_BACKEND.into(),
voice: "marin".into(),
male_voice: "cedar".into(),
language: String::new(),
brief_language: String::new(),
}
}
}
fn settings_path() -> PathBuf {
crate::registry::root().join("discuss.json")
}
fn key_path() -> PathBuf {
let root = crate::registry::root();
root.parent().map(|p| p.join("openai.key")).unwrap_or_else(|| root.join("openai.key"))
}
/// The settings, with a model a call can talk on, and a backend.
pub fn settings() -> Settings {
let mut s: Settings = store::read(&settings_path()).unwrap_or_default();
if !voice_model(&s.model) {
s.model = DEFAULT_MODEL.into();
}
if !backend_model(&s.backend) {
s.backend = DEFAULT_BACKEND.into();
}
s
}
/// A model a call can talk on: GPT-Live's, or a realtime one.
fn voice_model(m: &str) -> bool {
live_model(m) || realtime_model(m)
}
/// GPT-Live: gpt-live-1, -1.1 and so on. Not its transcriber.
fn live_model(m: &str) -> bool {
m.strip_prefix("gpt-live-")
.is_some_and(|v| !v.is_empty() && v.len() <= 8 && v.bytes().all(|b| b.is_ascii_digit() || b == b'.') && v.parse::<f64>().is_ok())
}
/// A text model that can run the tools for GPT-Live: `gpt-<version>-<name>`
/// of 5.6 and up (luna, sol, terra…), which carry tools well.
fn backend_model(m: &str) -> bool {
backend_version(m).is_some_and(|v| v >= 5.6)
}
fn backend_version(m: &str) -> Option<f64> {
let (v, name) = m.strip_prefix("gpt-")?.split_once('-')?;
(!name.is_empty() && name.len() <= 16 && name.bytes().all(|b| b.is_ascii_lowercase())).then_some(())?;
(v.len() <= 6 && v.bytes().all(|b| b.is_ascii_digit() || b == b'.')).then_some(())?;
v.parse().ok()
}
/// A realtime model this call can drive: gpt-realtime, -1.5, -2.1, their minis.
/// Not translate or whisper, which take no conversation, and nothing a request
/// could be bent with.
fn realtime_model(m: &str) -> bool {
let Some(rest) = m.strip_prefix("gpt-realtime") else { return false };
let rest = rest.strip_suffix("-mini").unwrap_or(rest);
match rest.strip_prefix('-') {
None => rest.is_empty(),
Some(v) => !v.is_empty() && v.len() <= 8 && v.bytes().all(|b| b.is_ascii_digit() || b == b'.') && v.parse::<f64>().is_ok(),
}
}
fn language_name(code: &str) -> Option<&'static str> {
LANGUAGES.iter().find(|(c, _)| *c == code).map(|(_, n)| *n)
}
pub fn set_settings(new: &Settings, by: &str) -> Result<()> {
if !voice_model(&new.model) {
bail!("not a model to talk on (GPT-Live or realtime): {}", new.model);
}
if !backend_model(&new.backend) {
bail!("not a backend model (gpt-<5.6 or newer>-<name>): {}", new.backend);
}
for v in [&new.voice, &new.male_voice] {
let custom = v.strip_prefix("voice_").is_some_and(|id| !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric()));
if !VOICES.contains(&v.as_str()) && !custom {
bail!("not a voice: {v} (one of {}, or a custom voice's voice_… id)", VOICES.join(", "));
}
}
for l in [&new.language, &new.brief_language] {
if language_name(l).is_none() {
bail!("not a language here: {l}");
}
}
store::write_json(&settings_path(), new, store::PUBLIC)?;
crate::events::emit("settings_changed", json!({"actor": by, "what": "discuss", "settings": new}));
Ok(())
}
pub(crate) fn key() -> Option<String> {
std::fs::read_to_string(key_path()).ok().map(|k| k.trim().to_string()).filter(|k| !k.is_empty())
}
/// Whether the page may offer a conversation: the hub has a key.
pub fn available() -> bool {
key().is_some()
}
/// The key, replaced; or removed, when empty. Never said back, nor logged.
pub fn set_key(new: &str, by: &str) -> Result<()> {
let new = new.trim();
if new.is_empty() {
match std::fs::remove_file(key_path()) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
}
} else {
if !new.starts_with("sk-") || new.len() < 20 || new.len() > 400 || !new.bytes().all(|b| b.is_ascii_graphic()) {
bail!("that does not look like an OpenAI API key (sk-…)");
}
store::write_atomic(&key_path(), format!("{new}\n").as_bytes(), store::PRIVATE)?;
}
crate::events::emit("settings_changed", json!({"actor": by, "what": "openai key", "set": !new.is_empty()}));
Ok(())
}
/// What the Settings page shows: the settings, what they can be, and of the key
/// only whether there is one and its last four characters.
pub fn overview() -> Value {
let tail = key().map(|k| k.chars().rev().take(4).collect::<Vec<_>>().into_iter().rev().collect::<String>());
json!({
"settings": settings(),
"key": {"set": tail.is_some(), "ends": tail},
"languages": LANGUAGES.iter().map(|(c, n)| json!({"code": c, "name": n})).collect::<Vec<_>>(),
"voices": VOICES,
})
}
/// The account's realtime models to choose from, newest first.
pub fn models() -> Result<Value> {
let Some(key) = key() else { bail!("no OpenAI key yet") };
let (code, body) = request("GET", "https://api.openai.com/v1/models", &key, Body::None)?;
let v: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
if !(200..300).contains(&code) {
bail!("OpenAI: {}", v["error"]["message"].as_str().unwrap_or(&format!("{code}")));
}
let ids: Vec<String> = v["data"].as_array().into_iter().flatten().filter_map(|m| m["id"].as_str().map(str::to_string)).collect();
let mut live: Vec<String> = ids.iter().filter(|id| live_model(id)).cloned().collect();
live.sort_by(|a, b| b.cmp(a));
let voice = [live, voice_models(&ids)].concat();
Ok(json!({"voice": voice, "backend": backend_models(&ids)}))
}
/// The backends of the account, newest first.
fn backend_models(ids: &[String]) -> Vec<String> {
let mut found: Vec<(f64, String)> = ids.iter().filter(|id| backend_model(id)).filter_map(|id| Some((backend_version(id)?, id.clone()))).collect();
found.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
found.into_iter().map(|(_, id)| id).collect()
}
/// By version, the full model before its mini; the first gpt-realtime counts as 1.
fn voice_models(ids: &[String]) -> Vec<String> {
let version = |id: &str| -> f64 {
let rest = id.trim_start_matches("gpt-realtime").trim_end_matches("-mini");
rest.strip_prefix('-').and_then(|v| v.parse().ok()).unwrap_or(1.0)
};
let mut found: Vec<String> = ids.iter().filter(|id| realtime_model(id)).cloned().collect();
found.sort_by(|a, b| version(b).total_cmp(&version(a)).then(a.ends_with("-mini").cmp(&b.ends_with("-mini"))).then(a.cmp(b)));
found
}
/// Where a language's speakers are from, for its accent, where one place is meant.
fn native_of(code: &str) -> Option<&'static str> {
Some(match code {
"nl" => "the Netherlands (Netherlands Dutch, not Flemish)",
"de" => "Germany",
"fr" => "France",
"es" => "Spain",
"pt" => "Portugal",
"it" => "Italy",
"en" => "England (British English)",
_ => return None,
})
}
/// What it speaks and writes in, as the settings say: added by the hub, so a page cannot say otherwise.
fn language_rule(s: &Settings) -> String {
let speak = match language_name(&s.language) {
// Everything else it is given is English (these instructions, the sessions, the code), so without a firm rule it drifts into English.
// The voices are American: without a word on the accent they speak another language with one.
Some(n) if !s.language.is_empty() => format!(
"Always speak {n} with them, from your first word to your last, even though these instructions, the sessions and the code are in English. \
Speak it as a native speaker {}: their accent, intonation and rhythm, never an American or English accent.",
native_of(&s.language).map_or_else(|| format!("of {n}"), |w| format!("from {w}"))),
_ => "Speak the language they speak.".into(),
};
let write = match language_name(&s.brief_language) {
Some(n) if !s.brief_language.is_empty() => format!("Write the brief in {n}, whatever language you speak together."),
_ => "Write the brief in the language they speak with you, unless they ask for another.".into(),
};
format!("{speak} {write}")
}
/// How the tools are used, whatever a page says: the hub's, so a page cannot loosen it.
const TOOL_RULE: &str = "Use your tools when you need them: write_brief always with the whole brief; read_session and read_board to know how things stand rather than guess; find_sessions to look up earlier work; read_tree to know the research tree as it stands; ask_code for every question about the code, which you cannot read yourself: never answer one from memory or guess. ask_code answers in half a minute or so: say you are asking, carry on talking meanwhile, and give them the answer in short when it comes. Every other tool changes something: use it only when the person said to, with their words and choices, never on your own. Before stopping a session, landing, deploying or changing a node, say back what you will do (which session, target or node) in one short sentence and wait for their yes.";
/// The tools a page gets when it names none: the brief and its sending, as before contexts.
const DEFAULT_TOOLS: [&str; 4] = ["write_brief", "find_sessions", "start_session", "end_discussion"];
/// What the voice may do, each run by the page.
fn tools() -> Value {
let mut all = json!([
{
"type": "function",
"name": "write_brief",
"description": "Write the brief: the whole design as it stands, which the session will be given, shown beside the conversation, where the person reads and edits it. Call it whenever the picture changed enough to matter, and when the person asks to see or change it.",
"parameters": {
"type": "object",
"properties": {
"brief": {"type": "string", "description": "The full brief in Markdown, its first line a `# ` heading that names the session in a few words (it becomes the session's title): then the goal and why, what to do, what done looks like, what to leave out, open questions for the agent. Short, concrete, in the person's words where they gave some."}
},
"required": ["brief"]
}
},
{
"type": "function",
"name": "find_sessions",
"description": "Search the workspace's past and running agent sessions (their conversations) for a word or phrase: to find earlier work on the same thing, or what was decided. Returns sessions with a matching line each.",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "A word or a short phrase, as it would appear in a conversation."}},
"required": ["query"]
}
},
{
"type": "function",
"name": "ask_code",
"description": "Ask a coding agent that reads the code (it can read, not change) a question about it: how something works, where it is, whether it does something, why it behaves as it does, what a session's branch changed. It reads the project's main as it is now, or a session's own worktree when you name the session. Its answer comes as a message to you in half a minute or so; carry on talking meanwhile.",
"parameters": {
"type": "object",
"properties": {
"question": {"type": "string", "description": "The question, whole and on its own: the agent hears nothing of this conversation, so give it the context it needs, in English."},
"project": {"type": "string", "description": "The project it is about, by name: one of the workspace's projects your instructions list. Leave it out only for the session's own, or the first."},
"session": {"type": "string", "description": "A session's id, such as s12, to read its branch's code rather than main's."}
},
"required": ["question"]
}
},
{
"type": "function",
"name": "start_session",
"description": "Send the brief as it stands now: it starts the new session, or goes to the session as its next message. Only when the person says to (start it, send it, go); never on your own.",
"parameters": {"type": "object", "properties": {}}
},
{
"type": "function",
"name": "create_session",
"description": "Create a new agent session with a name and a brief: it gets a branch of its own off main, and the brief is its first message. Only when the person said to create it, with the name and brief agreed with them; never on your own.",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The session's title: a few words, one line."},
"brief": {"type": "string", "description": "What it is to do and why, what done looks like, what to leave out: short, in the person's words where they gave some."}
},
"required": ["name", "brief"]
}
},
{
"type": "function",
"name": "read_session",
"description": "Read a session as it is now: its status, what it is doing, and the latest of its conversation (what it was asked, what it said, what it ran). Use it before answering about a session, and again when the person asks what changed.",
"parameters": {
"type": "object",
"properties": {"session": {"type": "string", "description": "The session's id, such as s12."}},
"required": ["session"]
}
},
{
"type": "function",
"name": "read_board",
"description": "Read the board as it is now: every session at work, its stage (working, waiting for or on a build node, landing, landed), what it waits on, the files sessions share, the open questions for the person, and the open ends left for later.",
"parameters": {"type": "object", "properties": {}}
},
{
"type": "function",
"name": "send_to_session",
"description": "Send a message to a session, as the person would from its page: it goes in the session's queue for after its current turn, or cuts into it. Only when the person said to send it, and with the words they agreed to; never on your own. You follow the session from then on.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"message": {"type": "string", "description": "The message, as agreed with the person."},
"now": {"type": "boolean", "description": "true: stop what it is doing and take this first; only when the person said to cut in. Left out: after its current turn."},
"pictures": {"type": "boolean", "description": "true: the pictures the person added in this conversation go with it."}
},
"required": ["session", "message"]
}
},
{
"type": "function",
"name": "answer_permission",
"description": "Answer a session's permission request (\"May it?\"), as the person would on its page, with one of the options read_session lists for it. Only with the option the person chose.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"request": {"type": "string", "description": "The request's id, as read_session gives it."},
"option": {"type": "string", "description": "The option's id, as read_session gives it."}
},
"required": ["session", "request", "option"]
}
},
{
"type": "function",
"name": "answer_question",
"description": "Answer a question a session asked (a form of fields, each a choice or free text, as read_session lists it), or skip it. This is also how a session's \"Shall it land?\" is answered. Only with the answers the person gave.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"request": {"type": "string", "description": "The question's id, as read_session gives it."},
"answers": {"type": "object", "description": "Each field's id to its answer: an option's value, a list of them for a field that takes several, or text.", "additionalProperties": true},
"skip": {"type": "boolean", "description": "Skip the question instead of answering it."}
},
"required": ["session", "request"]
}
},
{
"type": "function",
"name": "decide",
"description": "Answer a question waiting for the person on the board (read_board lists them with their ids and options). Only with the choice the person made.",
"parameters": {
"type": "object",
"properties": {
"decision": {"type": "string", "description": "The question's id, as read_board gives it."},
"choice": {"type": "string", "description": "One of its options, as written."},
"note": {"type": "string", "description": "What the person added, if anything."}
},
"required": ["decision", "choice"]
}
},
{
"type": "function",
"name": "interrupt_session",
"description": "Stop what a session is doing now (its current turn); it stays open and takes its next message. Only when the person says to.",
"parameters": {
"type": "object",
"properties": {"session": {"type": "string", "description": "The session's id, such as s12."}},
"required": ["session"]
}
},
{
"type": "function",
"name": "stop_session",
"description": "End a session: its agent stops; its branch is kept and it can be reopened. Only when the person says to, after saying back which session.",
"parameters": {
"type": "object",
"properties": {"session": {"type": "string", "description": "The session's id, such as s12."}},
"required": ["session"]
}
},
{
"type": "function",
"name": "reopen_session",
"description": "Reopen an ended session, to go on with it. Only when the person says to.",
"parameters": {
"type": "object",
"properties": {"session": {"type": "string", "description": "The session's id, such as s12."}},
"required": ["session"]
}
},
{
"type": "function",
"name": "archive_session",
"description": "File a session away out of the list, or bring it back. Only when the person says to.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"archived": {"type": "boolean", "description": "true to archive it, false to bring it back."}
},
"required": ["session", "archived"]
}
},
{
"type": "function",
"name": "rename_session",
"description": "Give a session a new title. Only when the person says to.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"title": {"type": "string", "description": "The new title, a few words."}
},
"required": ["session", "title"]
}
},
{
"type": "function",
"name": "set_session_mode",
"description": "Change how much a session may do without asking (its mode: read_session lists the ones it offers, such as Manual, Accept edits, Plan, Auto, Trusted). Only when the person says to.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"mode": {"type": "string", "description": "The mode's id, as read_session gives it."}
},
"required": ["session", "mode"]
}
},
{
"type": "function",
"name": "set_session_model",
"description": "Change the model a session thinks with (read_session lists the ones it offers). Only when the person says to.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"model": {"type": "string", "description": "The model's id, as read_session gives it."}
},
"required": ["session", "model"]
}
},
{
"type": "function",
"name": "land_session",
"description": "Tell a session to land its branch on main: it checks the work, gates it on a build node and fast-forwards main, as when the person answers its \"Shall it land?\". If it is asking that now, answer the question instead. Only when the person says to land it, after saying back which session.",
"parameters": {
"type": "object",
"properties": {
"session": {"type": "string", "description": "The session's id, such as s12."},
"finish": {"type": "boolean", "description": "true: land it and finish the session once it is live; false: land it and keep the session open."}
},
"required": ["session", "finish"]
}
},
{
"type": "function",
"name": "deploy",
"description": "Publish the tip of main to a deploy target (read_board lists the targets and how each stands). Only when the person says to, after saying back which target.",
"parameters": {
"type": "object",
"properties": {"target": {"type": "string", "description": "The target's name, as read_board gives it."}},
"required": ["target"]
}
},
{
"type": "function",
"name": "drain_node",
"description": "Take a build node out of the pool (read_board lists the nodes): nobody is given it until it is put back; whoever holds it now keeps it. Only when the person says to, after saying back which node.",
"parameters": {
"type": "object",
"properties": {
"node": {"type": "string", "description": "The node's id, as read_board gives it."},
"why": {"type": "string", "description": "Why, in the person's words."}
},
"required": ["node", "why"]
}
},
{
"type": "function",
"name": "undrain_node",
"description": "Put a node taken out of the pool back in it. Only when the person says to.",
"parameters": {
"type": "object",
"properties": {"node": {"type": "string", "description": "The node's id, as read_board gives it."}},
"required": ["node"]
}
},
{
"type": "function",
"name": "release_node",
"description": "Take a node back from the session holding it, for the next in line: that session's builds there are cut off. Only when the person says to, after saying back which node and whose it is.",
"parameters": {
"type": "object",
"properties": {"node": {"type": "string", "description": "The node's id, as read_board gives it."}},
"required": ["node"]
}
},
{
"type": "function",
"name": "add_open_end",
"description": "Leave an open end: something to do later, which the next session of that machine takes first. Only when the person says to.",
"parameters": {
"type": "object",
"properties": {
"for": {"type": "string", "description": "Whose: a machine's caller (workstation, agent), or any."},
"text": {"type": "string", "description": "What is to be done, as agreed with the person."}
},
"required": ["for", "text"]
}
},
{
"type": "function",
"name": "close_open_end",
"description": "Mark an open end done (read_board lists them with their ids). Only when the person says to.",
"parameters": {
"type": "object",
"properties": {"id": {"type": "string", "description": "The open end's id, as read_board gives it."}},
"required": ["id"]
}
}
]);
// The tree's own, in a json! of their own: one macro of them all is past its recursion limit.
let list = all.as_array_mut().expect("an array");
list.extend(tree_tools());
list.push(json!({
"type": "function",
"name": "end_discussion",
"description": "End this conversation: hang up. Only when the person says to stop or end it (stop the discussion, we're done, hang up); never on your own, not after a session started, not after a silence.",
"parameters": {"type": "object", "properties": {}}
}));
all
}
/// Talking the research tree over (tree.rs): reading it, changing it as its page does, and sending the scout out.
fn tree_tools() -> Vec<Value> {
let v = json!([
{
"type": "function",
"name": "read_tree",
"description": "Read the research tree as it is now: the goals (with who notices, signs of progress, what they must never lead to, their projects), the techs on the way to the one named (built, available, locked, in the fog, dropped, each with what it needs, its size and what it is), the insights, the direction the tree heads in and what it starts next, and the scout's latest rounds. Read it before talking about the tree, and again when they ask what changed.",
"parameters": {
"type": "object",
"properties": {"goal": {"type": "string", "description": "The goal's id, such as g3; left out, the one the page shows."}}
}
},
{
"type": "function",
"name": "open_tech",
"description": "Open one tech on the person's screen, as tapping it does, to talk it over: answers with all of it — its description, what it needs and leads to, the notes on it, what its mockup shows (you cannot see the picture: tell them from this) and the remarks waiting for its next drawing. Open it whenever they name a tech to talk about; read it again after a change.",
"parameters": {
"type": "object",
"properties": {"id": {"type": "string", "description": "The tech's id, such as k12."}},
"required": ["id"]
}
},
{
"type": "function",
"name": "change_tree",
"description": "Change the research tree, as its page's buttons do. Only on the person's word, with their words: a goal is theirs, so before saving or deleting one, or setting, pausing or stopping the direction, or starting a research session, say back in one sentence what you will do and wait for their yes. Answers with the tree's new state in short.",
"parameters": {
"type": "object",
"properties": {
"op": {"type": "string", "enum": ["goal_save", "goal_delete", "idea", "insight_drop", "tech_confirm", "tech_drop", "tech_restore", "tech_built", "tech_edit", "remark", "remark_drop", "proposal_accept", "proposal_drop", "research", "direction_set", "direction_limits", "direction_pause", "direction_clear", "direction_order", "budget_set"],
"description": "goal_save: a new goal (no id) or a changed one (its id), name and statement required; goal_delete: a goal (id); idea: the person's idea as an insight on a goal (goal, text, about: a tech's id when it is about one); insight_drop: an insight (id, why); tech_confirm: Keep it, a tech out of the fog (id); tech_drop: Not this (id, why); tech_restore: a dropped tech back (id); tech_built: built or not after all (id, built); tech_edit: a tech's description changed (id, and only the fields that change: name, what, who, differently, exists, done, size, lands_in), said back first; remark: a remark on a tech's mockup for its next drawing, in their words (id, text); remark_drop: one taken back (id, remark); proposal_accept: a theme the scout proposed made a goal (id, name to rename it); proposal_drop: (id); research: start a session researching a tech (id); direction_set: head this way, to a goal, a theme or a far tech (target, and at_once, per_day, scout, scout_every when they said them); it goes beside the directions going, or changes the one already heading there; direction_limits: a direction's limits (id, at_once, per_day, scout, scout_every); direction_pause: pause (paused true) or resume (paused false) a direction (id); direction_clear: stop a direction (id); direction_order: the directions in the order they come first when the budget is short (ids); budget_set: what every direction together may start (at_once, per_day, per_project)."},
"id": {"type": "string", "description": "The goal, tech, insight, proposal or direction it acts on, by id (g3, k12, i4, p2, d5)."},
"ids": {"type": "array", "items": {"type": "string"}, "description": "For direction_order: the directions' ids, the first first."},
"at_once": {"type": "integer", "description": "For direction_set and direction_limits: research sessions at once (1-3). For budget_set: for all directions together (1-6)."},
"per_day": {"type": "integer", "description": "For direction_set and direction_limits: started a day (1-12). For budget_set: for all together (1-30)."},
"per_project": {"type": "integer", "description": "For budget_set: at once in one project (1-3)."},
"scout": {"type": "boolean", "description": "For direction_set and direction_limits: send the scout when the way runs out."},
"scout_every": {"type": "integer", "description": "For direction_set and direction_limits: and after this many landings (0: only when it runs out)."},
"done": {"type": "string", "description": "For tech_edit: when it is done, one to three checks someone could make."},
"lands_in": {"type": "array", "items": {"type": "string"}, "description": "For tech_edit: the projects its change lands in, the one the others depend on first (owner/name); empty for one."},
"goal": {"type": "string", "description": "For idea: the goal it is about."},
"target": {"type": "string", "description": "For direction_set: a goal's or tech's id."},
"text": {"type": "string", "description": "For idea: the idea, in a sentence or two, in the person's words. For remark: what the next drawing must change, and where on the screen when they said where."},
"remark": {"type": "string", "description": "For remark_drop: the remark's id (m3)."},
"what": {"type": "string", "description": "For tech_edit: what the tech is, one sentence."},
"differently": {"type": "string", "description": "For tech_edit: what they do differently once it exists."},
"exists": {"type": "string", "description": "For tech_edit: what already exists toward it."},
"size": {"type": "string", "enum": ["S", "M", "L"], "description": "For tech_edit: its size."},
"about": {"type": "string", "description": "For idea: the tech it is about, if one."},
"why": {"type": "string", "description": "For tech_drop and insight_drop: why not, in their words (it keeps the scout from bringing it back)."},
"name": {"type": "string", "description": "For goal_save: the goal's name, a few words. For proposal_accept: a new name, if they gave one. For tech_edit: the tech's new name."},
"statement": {"type": "string", "description": "For goal_save: what the goal means, in their words."},
"who": {"type": "string", "description": "For goal_save: who notices when it is reached. For tech_edit: who notices the tech."},
"signs": {"type": "string", "description": "For goal_save: what would visibly be different."},
"never": {"type": "array", "items": {"type": "string"}, "description": "For goal_save: what it must never lead to."},
"parent": {"type": "string", "description": "For goal_save: the goal it stands under, if any."},
"repos": {"type": "array", "items": {"type": "string"}, "description": "For goal_save: the projects it is about, as owner/name (the projects your instructions list)."},
"built": {"type": "boolean", "description": "For tech_built: true built, false not after all."},
"paused": {"type": "boolean", "description": "For direction_pause: true pause, false resume."}
},
"required": ["op"]
}
},
{
"type": "function",
"name": "scout_tree",
"description": "Send the scout out on one goal or theme, reading the goal's projects' code as a coding agent (read-only). look (the usual one, what the page's Research further does): every move that fits, one after another — what is built and comes next, what finished sessions left open, themes when there are none, sketches of what has none. Or one move alone: map: what on the way is built and what it clearly needs next; harvest: what finished sessions left open; group: sort the techs into themes, proposed as goals; sketch: draw the mockups of techs still to build (or of one tech). Give it what the person wants it to look at, in their words. Only when they ask for it. A move takes a minute to a few; the result comes to you as a message by itself: carry on meanwhile.",
"parameters": {
"type": "object",
"properties": {
"goal": {"type": "string", "description": "The goal's id, such as g3."},
"move": {"type": "string", "enum": ["look", "map", "harvest", "group", "sketch"]},
"focus": {"type": "string", "description": "What to look at this round, as the person put it, in a sentence or two (a direction, a kind of user, a part of the product, a question): whole and on its own, as the scout hears nothing of this conversation."},
"tech": {"type": "string", "description": "For look: one tech's id, to look at that tech alone; for sketch: one tech's id, to draw its mockup again."}
},
"required": ["goal"]
}
},
]);
v.as_array().cloned().unwrap_or_default()
}
/// The hub's tools a page asked for, in the hub's order; unknown names are refused.
fn chosen_tools(names: &[String]) -> Result<Value> {
let all = tools();
let names: Vec<&str> = if names.is_empty() { DEFAULT_TOOLS.to_vec() } else { names.iter().map(String::as_str).collect() };
for n in &names {
if !all.as_array().unwrap().iter().any(|t| t["name"] == *n) {
bail!("no tool {n}");
}
}
Ok(Value::Array(all.as_array().unwrap().iter().filter(|t| names.iter().any(|n| t["name"] == *n)).cloned().collect()))
}
/// The workspace's projects, each with a line on what it is: what ask_code is
/// pointed at. Without it the voice left the project out, and a question about
/// a talk's slides went to the first project (cartopolis), which has none.
fn projects_rule(projects: &[(String, String)]) -> String {
if projects.is_empty() {
return String::new();
}
let list: Vec<String> = projects.iter()
.map(|(n, line)| if line.is_empty() { format!("- {n}") } else { format!("- {n}: {line}") })
.collect();
format!("\n\nThe workspace's projects, the first the default:\n{}\nName the project in ask_code whenever a question is about \
one: work on a talk or a deck is in its own project, not in the code it talks about. When an answer says the thing \
is not there, think which other project would hold it and ask there before you tell them it does not exist.",
list.join("\n"))
}
/// The hub's projects, by name, each with its first README paragraph, read
/// from the hub's mirror on the project's main.
fn workspace_projects() -> Vec<(String, String)> {
let conf = crate::conf::hub();
conf.repos.iter().filter_map(|r| crate::mirror::repo_name(r).ok()).map(|repo| {
let name = repo.trim_end_matches(".git");
let main = conf.project(name).and_then(|p| p["main"].as_str().map(str::to_string)).unwrap_or_else(|| "main".into());
let readme = Command::new("git").arg("--git-dir").arg(crate::mirror::mirror_path(&repo))
.args(["show", &format!("{main}:README.md")]).stdin(Stdio::null()).stderr(Stdio::null()).output().ok()
.filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
(name.rsplit('/').next().unwrap_or(name).to_string(), readme_line(&readme))
}).collect()
}
/// A README's first paragraph of prose, on one line, at most 200 characters.
fn readme_line(readme: &str) -> String {
let mut words = Vec::new();
for line in readme.lines().map(str::trim) {
if line.is_empty() {
if words.is_empty() { continue } else { break }
}
if words.is_empty() && (line.starts_with('#') || line.starts_with('!') || line.starts_with('[') || line.starts_with('<')) {
continue;
}
words.extend(line.split_whitespace().map(|w| w.replace("**", "").replace('`', "")));
}
let text = words.join(" ");
if text.chars().count() <= 200 {
return text;
}
format!("{}…", text.chars().take(200).collect::<String>().trim_end())
}
/// The realtime session a call opens with, in the man's voice when `male`.
fn session(s: &Settings, instructions: &str, projects: &str, tools: Value, male: bool) -> Value {
let v = if male { &s.male_voice } else { &s.voice };
let voice = if v.starts_with("voice_") { json!({"id": v}) } else { json!(v) };
let mut transcription = json!({"model": TRANSCRIBER});
if !s.language.is_empty() {
transcription["language"] = json!(s.language);
}
json!({
"type": "realtime",
"model": s.model,
// No trace in the OpenAI dashboard, where others in the project could read it.
"tracing": null,
"instructions": format!("{instructions}\n\n{TOOL_RULE}{projects}\n\n{}", language_rule(s)),
"tools": tools,
"tool_choice": "auto",
"audio": {
"input": {
// A phone put down on the table to talk, as often as held.
"noise_reduction": {"type": "far_field"},
"transcription": transcription,
// It answers when they finished a thought, not at every pause, and stops when cut into.
// Eager: the default (medium) waited up to seconds after a finished sentence, which was
// most of its slowness (2026-10-29: the model's first audio comes ~1 s after it is asked,
// whatever the instructions' size). Cutting in early costs little: they talk on, it stops.
"turn_detection": {"type": "semantic_vad", "eagerness": "high", "create_response": true, "interrupt_response": true},
},
"output": {"voice": voice},
},
})
}
/// What the backend is told: it acts for the voice, which says what it found.
const BACKEND_RULE: &str = "You act for the voice of Midas, who is talking with a person about the agent sessions of their coding \
workspace. You run the tools; the voice says what you report. Report briefly what you did or found, with the facts the voice needs \
to answer, in English; the voice speaks their language.";
/// A GPT-Live session a call opens with: the voice talks, the backend runs the tools.
fn live_session(s: &Settings, instructions: &str, projects: &str, tools: Value, male: bool, sdp: &str) -> Value {
let v = if male { &s.male_voice } else { &s.voice };
let voice = if v.starts_with("voice_") { json!({"id": v}) } else { json!(v) };
json!({
"session": {
"model": s.model,
"instructions": format!("{instructions}{projects}\n\n{}", language_rule(s)),
"audio": {"output": {"voice": voice}},
// No trace at OpenAI, as `tracing: null` for the realtime model.
"store": false,
"delegation": {
"type": "responses",
"responses": {
"model": s.backend,
"instructions": format!("{BACKEND_RULE}\n\n{TOOL_RULE}{projects}"),
"tools": tools,
"tool_choice": "auto",
}
}
},
"transport": {"type": "webrtc", "sdp": sdp},
})
}
/// A call for the page: its SDP offer in, OpenAI's answer out, and which
/// engine it talks on (`live` or `realtime`), whose events differ. `voice`:
/// `male` or `female` (the default), whose voice the settings name.
pub fn open(sdp: &str, instructions: &str, tools: &[String], voice: &str) -> Result<(String, &'static str)> {
let male = match voice {
"male" => true,
"female" | "" => false,
v => bail!("a voice is male or female, not {v}"),
};
let Some(key) = key() else { bail!("no OpenAI key on the hub: an admin sets one on the page's Settings") };
if sdp.trim().is_empty() {
bail!("no SDP offer");
}
if instructions.len() > INSTRUCTIONS_MAX {
bail!("instructions of at most {} KB", INSTRUCTIONS_MAX / 1024);
}
let s = settings();
let (projects, tools) = (projects_rule(&workspace_projects()), chosen_tools(tools)?);
if live_model(&s.model) {
let body = live_session(&s, instructions, &projects, tools, male, sdp).to_string();
let (code, body) = request("POST", "https://api.openai.com/v1/live/sessions", &key, Body::Json(&body))?;
let v: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
return match v["transport"]["sdp"].as_str() {
Some(answer) if (200..300).contains(&code) => Ok((answer.to_string(), "live")),
_ => bail!("GPT-Live: {}", v["error"]["message"].as_str().unwrap_or(&format!("{code}"))),
};
}
let session = session(&s, instructions, &projects, tools, male);
let (code, body) = request("POST", "https://api.openai.com/v1/realtime/calls", &key, Body::Form(&[("sdp", sdp), ("session", &session.to_string())]))?;
if (200..300).contains(&code) && body.starts_with("v=") {
return Ok((body, "realtime"));
}
let v: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
bail!("OpenAI: {}", v["error"]["message"].as_str().unwrap_or(&format!("{code}")))
}
/// What a request carries: nothing, a multipart form's fields, or JSON.
enum Body<'a> {
None,
Form(&'a [(&'a str, &'a str)]),
Json(&'a str),
}
/// A call to OpenAI through curl, the key and any body in its config on stdin
/// (never on its command line), as the hub's other calls out are made. A
/// form's fields are sent exactly as they are.
fn request(method: &str, url: &str, key: &str, body: Body) -> Result<(u16, String)> {
let q = crate::util::curl_quote;
let mut cfg = format!(
"silent\nshow-error\nrequest = {}\nurl = {}\nheader = {}\nwrite-out = \"\\n%{{http_code}}\"\n",
q(method), q(url), q(&format!("Authorization: Bearer {key}")));
match body {
Body::None => {}
Body::Form(form) => {
for (name, value) in form {
// form-string: no `@file` or `<file` reading, and no `;type=` parsing, whatever the value holds.
cfg.push_str(&format!("form-string = {}\n", q(&format!("{name}={value}"))));
}
}
// Compact JSON has no raw line break, so it stays one config line (curl_quote escapes the rest).
Body::Json(json) => cfg.push_str(&format!("header = \"Content-Type: application/json\"\ndata-binary = {}\n", q(json))),
}
let mut child = Command::new("curl").args(["-K", "-", "--max-time", "30"])
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.spawn().context("starting curl")?;
child.stdin.take().unwrap().write_all(cfg.as_bytes())?;
let out = child.wait_with_output()?;
let text = String::from_utf8_lossy(&out.stdout).to_string();
let (body, code) = text.rsplit_once('\n').unwrap_or(("", text.as_str()));
match code.trim().parse::<u16>() {
Ok(c) if c > 0 => Ok((c, body.to_string())),
_ => bail!("curl failed: {}", String::from_utf8_lossy(&out.stderr).trim()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_tools_are_the_hubs_and_named_as_the_page_runs_them() {
let names: Vec<String> = tools().as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect();
assert_eq!(
names,
[
"write_brief", "find_sessions", "ask_code", "start_session", "create_session", "read_session", "read_board", "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", "read_tree", "open_tech", "change_tree", "scout_tree",
"end_discussion",
]
);
// OpenAI refuses a session whose tool is not a plain function with an object of parameters.
assert!(tools().as_array().unwrap().iter().all(|t| t["type"] == "function" && t["parameters"]["type"] == "object"));
}
#[test]
fn a_page_picks_among_the_hubs_tools_and_no_others() {
let names = |v: Value| v.as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
assert_eq!(names(chosen_tools(&["read_board".into(), "end_discussion".into()]).unwrap()), ["read_board", "end_discussion"]);
assert_eq!(names(chosen_tools(&[]).unwrap()), DEFAULT_TOOLS);
assert!(chosen_tools(&["run_shell".into()]).is_err());
}
#[test]
fn a_language_chosen_is_held_to() {
let s = Settings { language: "nl".into(), ..Settings::default() };
assert!(language_rule(&s).contains("Always speak Dutch"));
assert!(language_rule(&s).contains("native speaker from the Netherlands") && language_rule(&s).contains("never an American"));
let ja = Settings { language: "ja".into(), ..Settings::default() };
assert!(language_rule(&ja).contains("native speaker of Japanese"));
assert!(!language_rule(&Settings::default()).contains("accent"), "no accent for a language it is not told");
assert!(LANGUAGES.iter().all(|(c, _)| c.is_empty() || c.len() == 2));
assert_eq!(session(&s, "", "", json!([]), false)["audio"]["input"]["transcription"]["language"], "nl");
}
#[test]
fn a_call_speaks_in_the_voice_its_role_asked_for() {
let s = Settings::default();
assert_eq!(session(&s, "", "", json!([]), false)["audio"]["output"]["voice"], "marin");
assert_eq!(session(&s, "", "", json!([]), true)["audio"]["output"]["voice"], "cedar");
let custom = Settings { male_voice: "voice_abc123".into(), ..Settings::default() };
assert_eq!(session(&custom, "", "", json!([]), true)["audio"]["output"]["voice"], json!({"id": "voice_abc123"}));
let old: Settings = serde_json::from_str(r#"{"model": "gpt-realtime-2.1", "voice": "marin", "language": "", "brief_language": ""}"#).unwrap();
assert_eq!(old.male_voice, "cedar", "settings saved before there were two voices");
assert!(set_settings(&Settings { male_voice: "bob".into(), ..Settings::default() }, "t").is_err());
}
#[test]
fn the_voice_knows_every_project_and_what_it_is() {
let rule = projects_rule(&[
("cartopolis".into(), "Open-source social twin-world".into()),
("about-cartopolis".into(), String::new()),
]);
assert!(rule.contains("- cartopolis: Open-source social twin-world"));
assert!(rule.contains("- about-cartopolis\n") || rule.ends_with("- about-cartopolis"));
assert!(rule.contains("Name the project in ask_code"));
assert_eq!(projects_rule(&[]), "", "no list for a workspace without projects");
let session = session(&Settings::default(), "Hi.", &rule, json!([]), false);
assert!(session["instructions"].as_str().unwrap().contains("- cartopolis: "));
}
#[test]
fn a_readme_gives_its_first_paragraph() {
let readme = "# Podium\n\nRehearse a talk out loud to an AI listener that answers with spoken\nfeedback, built on the **Realtime API**.\n\n## Run\n";
assert_eq!(readme_line(readme), "Rehearse a talk out loud to an AI listener that answers with spoken feedback, built on the Realtime API.");
assert_eq!(readme_line("# Only a title\n"), "");
assert!(readme_line(&format!("# T\n\n{}", "word ".repeat(100))).chars().count() <= 201);
}
#[test]
fn only_realtime_models_that_hold_a_conversation() {
for ok in ["gpt-realtime", "gpt-realtime-mini", "gpt-realtime-1.5", "gpt-realtime-2.1", "gpt-realtime-2.1-mini"] {
assert!(realtime_model(ok), "{ok}");
}
for no in ["gpt-live-1", "gpt-realtime-translate", "gpt-realtime-whisper", "gpt-realtime-2025-08-28", "gpt-realtime-", "gpt-realtime-2.1\"", "gpt-6-luna"] {
assert!(!realtime_model(no), "{no}");
}
let ids: Vec<String> = ["gpt-realtime", "gpt-realtime-2.1-mini", "gpt-live-1", "gpt-realtime-1.5", "gpt-realtime-2.1", "gpt-realtime-mini"].map(String::from).to_vec();
assert_eq!(voice_models(&ids), ["gpt-realtime-2.1", "gpt-realtime-2.1-mini", "gpt-realtime-1.5", "gpt-realtime", "gpt-realtime-mini"]);
}
#[test]
fn gpt_live_and_its_backend_are_models_to_talk_on() {
let old: Settings = serde_json::from_str(r#"{"model": "gpt-live-1", "voice": "ballad", "backend": "gpt-6-luna", "language": "nl", "brief_language": ""}"#).unwrap();
assert_eq!(old.voice, "ballad");
assert!(live_model(&old.model) && voice_model(&old.model) && !realtime_model(&old.model));
for ok in ["gpt-live-1", "gpt-live-1.1"] {
assert!(live_model(ok), "{ok}");
}
for no in ["gpt-live-transcribe", "gpt-live-", "gpt-live-1\"", "gpt-live"] {
assert!(!live_model(no), "{no}");
}
for ok in ["gpt-6-luna", "gpt-5.6-sol"] {
assert!(backend_model(ok), "{ok}");
}
for no in ["gpt-5-mini", "gpt-5.5-luna", "gpt-6-Luna", "gpt-realtime-2.1", "gpt-6-luna\""] {
assert!(!backend_model(no), "{no}");
}
let ids: Vec<String> = ["gpt-5.6-sol", "gpt-6-luna", "gpt-5-mini", "gpt-6-astra"].map(String::from).to_vec();
assert_eq!(backend_models(&ids), ["gpt-6-astra", "gpt-6-luna", "gpt-5.6-sol"]);
assert_eq!(Settings::default().model, "gpt-live-1", "GPT-Live is the default since 2026-11-05");
}
#[test]
fn a_gpt_live_call_hands_the_tools_to_its_backend() {
let s = Settings { language: "nl".into(), ..Settings::default() };
let tools = chosen_tools(&["ask_code".into(), "end_discussion".into()]).unwrap();
let v = live_session(&s, "Hi.", "\n\nThe workspace's projects:\n- cartopolis", tools, true, "v=0\r\n");
assert_eq!(v["session"]["model"], "gpt-live-1");
assert_eq!(v["session"]["store"], false);
assert_eq!(v["session"]["audio"]["output"]["voice"], "cedar");
assert_eq!(v["transport"], json!({"type": "webrtc", "sdp": "v=0\r\n"}));
let voice = v["session"]["instructions"].as_str().unwrap();
assert!(voice.starts_with("Hi.") && voice.contains("- cartopolis") && voice.contains("Always speak Dutch"));
let backend = &v["session"]["delegation"]["responses"];
assert_eq!(backend["model"], "gpt-6-luna");
assert_eq!(backend["tools"].as_array().unwrap().len(), 2);
let rule = backend["instructions"].as_str().unwrap();
assert!(rule.contains("You run the tools") && rule.contains("ask_code for every question") && rule.contains("- cartopolis"));
}
#[test]
fn a_body_with_lines_and_quotes_stays_one_curl_config_line() {
// curl reads its config line by line: compact JSON has no raw newline.
let body = json!({"instructions": "one\ntwo \"three\" \\four"}).to_string();
let quoted = crate::util::curl_quote(&body);
assert!(!quoted.contains('\n'));
// An SDP offer does, and keeps them.
let sdp = crate::util::curl_quote("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n");
assert!(!sdp.contains('\n') && !sdp.contains('\r'));
assert!(sdp.ends_with("\\r\\n\""));
}
}