- `suggest` refuses an echo as `say` and `amend` do, before the one-a-turn and private checks, whatever the note's kind. Soul's probe filed Nibu's line, refused as an echo when said, as her `idea` note. - A feedback note that passes someone's words on verbatim is refused too: Q-E is unanswered, so option A (the echo refusal applies) holds for notes as well. A note in her own words is left as before. - The K18 assertion that an echo-refused line's draft could be a feedback note is gone; a refused act still leaves its draft free (the amend case stays). Verification: the echo draft as an idea note and as a feedback note about Nibu is refused (say: echo, suggest: echo) and no note is left; a note in her own words is left. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
547 lines
31 KiB
Rust
547 lines
31 KiB
Rust
//! The Interpreter's speech (map section 4, cut C3b; map 16.19 K1d): what she says aloud this turn, decided from her
|
|
//! prose by one tool-less schema turn of a model, and taken by code from the drafts she set down.
|
|
//!
|
|
//! The Persona writes her thought, and when she writes words she would type she sets them between `<typed>` and
|
|
//! `</typed>` (`narrate::persona_speech_form`, code's form). Each such pair is a draft (`drafts`), numbered in order.
|
|
//! The Interpreter decides whether she sends a draft now, where and to whom: it answers with zero or more drafts by
|
|
//! number, each with the people she addresses (Matrix mentions and a reply target, as structured fields), and the gaps.
|
|
//! Code checks only that a number names a draft and that a draft goes one place; the line is the draft's text, whole,
|
|
//! exactly as she set it down. So a line can never be part of what she wrote, nor words the model wrote (I16.6). No code
|
|
//! here reads a quotation mark or a sentence: whose words a draft carries and whether she means it now are the
|
|
//! Interpreter's judgement, as privacy is. What this gives up: speech she does not set down is never said (an
|
|
//! `unwritten` gap records it), and she cannot say half a draft.
|
|
//!
|
|
//! Code keeps a line only when it names a draft not already used; drops an echo (at least `ECHO_MIN_WORDS` words, and
|
|
//! at least `ECHO_OVERLAP` of its word trigrams in the bodies of the lines she was shown, or at least that share of one
|
|
//! such line's trigrams in it: `echo`); keeps at most `MAX_LINES` lines;
|
|
//! and keeps a mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in
|
|
//! the turn's room. Whether a draft tells what she knows privately is a reading of its meaning, so it is the
|
|
//! Interpreter's judgement over the private items the packet lists to it (`Packet::private`), never a word match here.
|
|
//! Every refusal and drop is reported. Every gap is typed (`GapKind`) and shown to her later (K9) only as what it is: a
|
|
//! draft by number, or a located passage of her thought (`gap`). The prompt tells the Interpreter what she can do this
|
|
//! turn (`select::turn_words`), so a reach past it is a `missing_affordance` gap. Nothing here posts: the commit (C3c)
|
|
//! will.
|
|
//!
|
|
//! The same answer may add a draft after a line of hers listed as one she may add to (`amend`, map 16.17; the actuator
|
|
//! composes the edit), and leave Self one note (`suggest`, map 16.18; recorded in the turn's record, never a write to her
|
|
//! Mind). One draft goes one place across all three.
|
|
|
|
use ghostlight_persona_projection::SourceSpan;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Value, json};
|
|
|
|
use super::narrate::{Model, heard_overlap, lived_stream, words};
|
|
use super::select::{Forms, Packet, capitalized, spoken, turn_words, voiced};
|
|
use super::tuning::Tuning;
|
|
|
|
/// The most lines she says in one turn.
|
|
pub(crate) const MAX_LINES: usize = 2;
|
|
/// A line of at least this many words whose word trigrams are at least this share of what she heard is an echo, not
|
|
/// her speech.
|
|
const ECHO_MIN_WORDS: usize = 8;
|
|
const ECHO_OVERLAP: f64 = 0.8;
|
|
/// The fewest words a passage of her thought shown back to her may be: a shorter quote ("tell") says nothing of what
|
|
/// she meant, and is kept as unlocated.
|
|
const GAP_QUOTE_MIN_WORDS: usize = 4;
|
|
|
|
/// The marks of a draft: two literal tokens no natural prose holds (map 16.19.1).
|
|
pub(crate) const DRAFT_OPEN: &str = "<typed>";
|
|
pub(crate) const DRAFT_CLOSE: &str = "</typed>";
|
|
|
|
/// How every speech prompt begins, whoever she is: the test doubles route on it.
|
|
pub(crate) const SPEECH_OPENING: &str = "You decide what one person says aloud in a chat room this turn";
|
|
|
|
/// The speech contract, sent as the schema turn's output schema (`--json-schema`): the drafts she sends now by number,
|
|
/// and the gaps. The model writes no words of hers.
|
|
pub(crate) const SPEECH_SCHEMA: &str = r#"{"type":"object","additionalProperties":false,"required":["say","gaps","amend","suggest"],"properties":{"suggest":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","about","private"],"properties":{"kind":{"type":"string","enum":["feedback","idea"]},"draft":{"type":"integer","minimum":1},"about":{"type":["string","null"]},"private":{"type":"boolean"}}}},"amend":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["target","draft"],"properties":{"target":{"type":"string"},"draft":{"type":"integer","minimum":1}}}},"say":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["draft","mentions","reply_to"],"properties":{"draft":{"type":"integer","minimum":1},"mentions":{"type":"array","items":{"type":"string"}},"reply_to":{"type":["string","null"]}}}},"gaps":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["kind","draft","quote","detail"],"properties":{"kind":{"type":"string","enum":["conditional","addressee","elsewhere","missing_affordance","unwritten"]},"draft":{"type":["integer","null"]},"quote":{"type":["string","null"]},"detail":{"type":"string"}}}}}}"#;
|
|
|
|
/// The speech frame before the guidance: what to decide, from what, and the attribution rule. Code, not tuning (map
|
|
/// 16.7), in her own pronouns (16.19.7). The tuning's `interpreter.guidance` (what counts as her choosing to send it
|
|
/// now) is set after it, so it reads as part of the decision and every rule after it still binds.
|
|
fn speech_frame_head(her: Forms) -> String {
|
|
let Forms { subj, obj, poss, be, s, .. } = her;
|
|
format!(
|
|
"{SPEECH_OPENING}, from {poss} own prose. You never write {poss} words: you choose among {poss} drafts.
|
|
|
|
Below are who {subj} {be}, what {subj} can do here, the room and who is in it, what reached {obj}, {poss} lived moment, {poss} prose, and {poss} drafts. When {subj} write{s} words {subj} would type, {subj} set{s} them between {DRAFT_OPEN} and {DRAFT_CLOSE}: each is a draft, numbered below. Decide which of {poss} drafts {subj} choose{s} to send now, in this room. Only {poss} drafts can be said. Someone else's words in {poss} thought are never {poss} speech. A draft that carries someone else's words is said only when {poss} thought shows {subj} mean{s} to pass them on, and then as {poss} to pass on."
|
|
)
|
|
}
|
|
|
|
/// The speech frame after the guidance: the room and the private rules, the contract and the gap kinds.
|
|
fn speech_frame_tail(her: Forms) -> String {
|
|
let Forms { subj, cap_subj, obj, poss, has, s, .. } = her;
|
|
format!(
|
|
"{cap_subj} speak{s} only in this room. What {subj} know{s} privately is listed below as private: {subj} say{s} none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a draft fits who is listening is yours to judge.
|
|
|
|
Answer with the speech contract's object. `say` lists the drafts {subj} send{s} now, each by its number, with the Matrix ids of anyone listed whom {subj} address{es} directly (`mentions`) and the Matrix id of the person whose message {subj} answer{s} (`reply_to`, or null). `gaps` records what {subj} meant and did not send. `amend` adds to one of {poss} own lines listed below, at most one a turn, only when {poss} thought shows {obj} choosing to correct or add to that line: name the line by its id, and the draft that is {poss} addition. The line stays as it was and the draft is added after it; {subj} never take{s} a word back. `suggest` leaves Self one note, at most one a turn, only when {poss} thought shows {obj} choosing to: name the draft that is the note, its kind (feedback when {subj} pass{es} on what someone listed said, with that person's Matrix id in `about`; idea when it is {poss} own, `about` null), and set `private` when it carries anything listed as private or gives it away; such a note is not left.
|
|
|
|
A draft is said whole or not at all, and only once. At most two drafts a turn. Record a gap instead of guessing: conditional when {subj} {has} drafted something {subj} might say but {has} not chosen to, addressee when {subj} mean{s} to send a draft but whom to is unclear, elsewhere when {subj} mean{s} a draft for another room or another time; for these three, name the draft by number. missing_affordance when {subj} mean{s} to do something, now or later, that {poss} body cannot do (what {subj} can do here is listed below), whether {subj} said so in a draft or only thought it; name the draft when there is one. unwritten when {subj} mean{s} to say something and wrote no draft of it. Every intent of {poss} that is not carried out has a kind: an intent to act is missing_affordance, an intent to say with no draft is unwritten. When a gap names no draft, quote the words of {poss} thought that show it, at least four words, copied exactly.",
|
|
es = if s.is_empty() { "" } else { "es" },
|
|
)
|
|
}
|
|
|
|
/// One draft she set down: its number, from 1 in her prose's order, and its words, trimmed, with where they lie in her
|
|
/// prose (`prose[start..end] == text`).
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub(crate) struct Draft {
|
|
pub n: usize,
|
|
pub start: usize,
|
|
pub end: usize,
|
|
pub text: String,
|
|
}
|
|
|
|
/// Her drafts, and what of her prose is not her thought: every tagged span, marks included (an empty one too), and an
|
|
/// opener left unclosed, from it to the end. `unfinished` is the byte where that opener starts.
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
pub(crate) struct Drafts {
|
|
pub drafts: Vec<Draft>,
|
|
pub unfinished: Option<usize>,
|
|
regions: Vec<(usize, usize)>,
|
|
}
|
|
|
|
impl Drafts {
|
|
fn numbered(&self, n: i64) -> Option<&Draft> {
|
|
usize::try_from(n).ok().and_then(|n| self.drafts.iter().find(|draft| draft.n == n))
|
|
}
|
|
|
|
/// Her prose outside every draft: her thought, as byte ranges.
|
|
fn thought(&self, prose: &str) -> Vec<(usize, usize)> {
|
|
let mut at = 0;
|
|
let mut out = Vec::new();
|
|
for &(start, end) in &self.regions {
|
|
if at < start {
|
|
out.push((at, start));
|
|
}
|
|
at = end;
|
|
}
|
|
if at < prose.len() {
|
|
out.push((at, prose.len()));
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
/// Her drafts: each `<typed>` to the next `</typed>`, in order. The inside, trimmed, is the draft; an empty one is no
|
|
/// draft. A second opener before a closer ends nothing and is text of the first. An opener with no closer (the word
|
|
/// budget cut her off) is `unfinished`, never a draft. Two literal tokens, and nothing about language.
|
|
pub(crate) fn drafts(prose: &str) -> Drafts {
|
|
let mut found = Drafts::default();
|
|
let mut from = 0;
|
|
while let Some(open) = prose[from..].find(DRAFT_OPEN).map(|at| from + at) {
|
|
let inside = open + DRAFT_OPEN.len();
|
|
let Some(close) = prose[inside..].find(DRAFT_CLOSE).map(|at| inside + at) else {
|
|
found.unfinished = Some(open);
|
|
found.regions.push((open, prose.len()));
|
|
break;
|
|
};
|
|
let raw = &prose[inside..close];
|
|
let text = raw.trim();
|
|
if !text.is_empty() {
|
|
let start = inside + (raw.len() - raw.trim_start().len());
|
|
found.drafts.push(Draft { n: found.drafts.len() + 1, start, end: start + text.len(), text: text.to_owned() });
|
|
}
|
|
from = close + DRAFT_CLOSE.len();
|
|
found.regions.push((open, from));
|
|
}
|
|
found
|
|
}
|
|
|
|
/// Why code held back a draft she had cited, typed: what she is told next turn (`outcome`) is keyed by it, never by text
|
|
/// (map 16.16). `why` is its words for the report.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub(crate) enum Refusal {
|
|
/// The turn has no room, so nothing is said in one.
|
|
NoRoom,
|
|
/// The number names no draft she set down: the Interpreter's error, nothing of hers.
|
|
NoDraft,
|
|
/// The draft already went somewhere this turn.
|
|
Used,
|
|
/// The same words already went out this turn, from another draft: said once (map 16.20.7).
|
|
Duplicate,
|
|
/// Mostly the words she had just heard.
|
|
Echo,
|
|
/// Past the lines one turn may say.
|
|
OverLines,
|
|
/// An amendment whose target is no line of hers listed as one she may add to (map 16.17).
|
|
NotAmendable,
|
|
/// A second amendment in one turn.
|
|
SecondAmend,
|
|
/// A second note to Self in one turn.
|
|
SecondNote,
|
|
/// A note to Self the Interpreter judged to carry something private.
|
|
Private,
|
|
}
|
|
|
|
impl Refusal {
|
|
fn why(self) -> &'static str {
|
|
match self {
|
|
Self::NoRoom => "the turn has no room to speak in",
|
|
Self::NoDraft => "it names no draft she set down",
|
|
Self::Used => "one draft goes one place: it already went somewhere this turn",
|
|
Self::Duplicate => "the same words already went out this turn",
|
|
Self::Echo => "mostly words she heard: an echo, not her speech",
|
|
Self::OverLines => "past the lines one turn may say",
|
|
Self::NotAmendable => "it names no line of hers she may add to here",
|
|
Self::SecondAmend => "one amendment a turn",
|
|
Self::SecondNote => "one note to Self a turn",
|
|
Self::Private => "it carries something she may not pass on",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What she does with a draft: says it, adds it to a line of hers, or leaves it for Self.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
enum Act {
|
|
Say,
|
|
Amend,
|
|
Suggest,
|
|
}
|
|
|
|
/// What a note to Self is (map 16.18): feedback someone gave her, or her own idea.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub(crate) enum NoteKind {
|
|
Feedback,
|
|
Idea,
|
|
}
|
|
|
|
/// A refused act in the report: what it was, the draft, its words when it names one, and the typed reason with its words.
|
|
fn refused(act: Act, draft: Option<&Draft>, cited: Option<i64>, reason: Refusal) -> Value {
|
|
json!({ "act": act, "draft": draft.map_or_else(|| json!(cited), |draft| json!(draft.n)), "text": draft.map(|draft| draft.text.as_str()), "reason": reason, "why": reason.why() })
|
|
}
|
|
|
|
/// What a gap is (map 16.16, 16.19): words she meant and did not send now, and why. Typed by code from the model's
|
|
/// `kind`; a kind the contract does not name is kept as `Unresolved` and reported, never dropped.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub(crate) enum GapKind {
|
|
/// She drafted something she might say, and has not chosen to.
|
|
Conditional,
|
|
/// She means to send a draft, and whom to is unclear.
|
|
Addressee,
|
|
/// She means a draft for another room or another time.
|
|
Elsewhere,
|
|
/// She means to do something, now or later, that no affordance of hers does (map 16.20.6): a reach in her thought, or a
|
|
/// promise in a draft, said or not. A tool request in waiting (section 4.2).
|
|
MissingAffordance,
|
|
/// She means to say something and wrote no draft of it, so nothing went out.
|
|
Unwritten,
|
|
Unresolved,
|
|
}
|
|
|
|
impl GapKind {
|
|
fn of(kind: &str) -> Self {
|
|
match kind.trim() {
|
|
"conditional" => Self::Conditional,
|
|
"addressee" => Self::Addressee,
|
|
"elsewhere" => Self::Elsewhere,
|
|
"missing_affordance" => Self::MissingAffordance,
|
|
"unwritten" => Self::Unwritten,
|
|
_ => Self::Unresolved,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One gap as the report keeps it: its typed kind (with what the model declared when that is no kind), and what of her
|
|
/// prose it shows her, by `from`:
|
|
/// - `draft`: the draft it names, by number, with that draft's words: "you wrote:" (K9);
|
|
/// - `thought`: a passage of her thought outside every draft, located by `SourceSpan::locate` and at least
|
|
/// `GAP_QUOTE_MIN_WORDS` words, with its bytes: "in your thought:" (K9). Found in her prose, not certified as her
|
|
/// intent: whether it is her reach or her report of someone else's words was the Interpreter's reading;
|
|
/// - `unlocated`: neither; the model's quote is kept for the trace and never shown to her.
|
|
///
|
|
/// - `acted`: it names, or quotes from, a draft that went somewhere this turn (said, added to a line, left for Self), so it
|
|
/// contradicts what happened and is not shown to her (`decide` sets it). One exception: a `missing_affordance` gap that
|
|
/// names a draft she said is a promise of an act she cannot do, and is kept and shown (map 16.20.6).
|
|
///
|
|
/// Every kind but `unwritten` may name a draft: an unwritten line is about words she did not set down, so it is always a
|
|
/// passage of her thought, whatever draft the model names. A reach (`missing_affordance`) names the draft that promises
|
|
/// it when there is one, said or not (map 16.20.6), and otherwise quotes her thought; a reach that names no draft and
|
|
/// quotes one (at least `GAP_QUOTE_MIN_WORDS` words, found in the draft's words) is about that draft, as if named.
|
|
///
|
|
/// The model's `detail` is kept for the trace and is never what she is told.
|
|
fn gap(prose: &str, found: &Drafts, raw: &Value) -> Value {
|
|
let kind = GapKind::of(raw.get("kind").and_then(Value::as_str).unwrap_or_default());
|
|
let mut gap = json!({ "kind": kind, "detail": raw.get("detail").cloned().unwrap_or(Value::Null) });
|
|
if kind == GapKind::Unresolved {
|
|
gap["declared"] = raw.get("kind").cloned().unwrap_or_else(|| raw.clone());
|
|
}
|
|
let names_a_draft = kind != GapKind::Unwritten;
|
|
let quote = raw.get("quote").and_then(Value::as_str).unwrap_or_default().trim();
|
|
// A reach that quotes a draft by its words, with no number, is about that draft: a promise in it (map 16.20.6).
|
|
let quoted_draft = || (kind == GapKind::MissingAffordance && words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.drafts.iter().find(|draft| draft.text.contains(quote))).flatten();
|
|
if let Some(draft) = raw.get("draft").and_then(Value::as_i64).and_then(|n| found.numbered(n)).filter(|_| names_a_draft).or_else(quoted_draft) {
|
|
gap["from"] = json!("draft");
|
|
gap["draft"] = json!(draft.n);
|
|
gap["words"] = json!(draft.text);
|
|
return gap;
|
|
}
|
|
let located = (words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| SourceSpan::locate(&prose[start..end], quote).map(|span| (start + span.start_byte(), start + span.end_byte())))).flatten();
|
|
match located {
|
|
Some((start, end)) => {
|
|
gap["from"] = json!("thought");
|
|
gap["words"] = json!(&prose[start..end]);
|
|
gap["start_byte"] = json!(start);
|
|
gap["end_byte"] = json!(end);
|
|
}
|
|
None => {
|
|
gap["from"] = json!("unlocated");
|
|
gap["quote"] = json!(quote);
|
|
}
|
|
}
|
|
gap
|
|
}
|
|
|
|
/// The answer's shape, decoded whole from the schema turn's structured output. `say` and `gaps` are required: an answer
|
|
/// without them is not the contract, a failure and never a silence. `amend` and `suggest` read as none when
|
|
/// left out: an answer without them proposes no such act.
|
|
#[derive(Debug, Deserialize)]
|
|
struct Answer {
|
|
say: Vec<Proposed>,
|
|
gaps: Vec<Value>,
|
|
#[serde(default)]
|
|
amend: Vec<ProposedAmend>,
|
|
#[serde(default)]
|
|
suggest: Vec<ProposedNote>,
|
|
}
|
|
|
|
/// A note to Self as the model proposes it: its kind, the draft that is the note, whose feedback it passes on (a Matrix
|
|
/// id from the people listed, or none for her own idea), and whether it carries something private.
|
|
#[derive(Debug, Deserialize)]
|
|
struct ProposedNote {
|
|
kind: NoteKind,
|
|
#[serde(default)]
|
|
draft: Option<i64>,
|
|
#[serde(default)]
|
|
about: Option<String>,
|
|
/// Absent is not "not private": a note whose answer does not say is refused as private (fails closed, map 16.20.7).
|
|
#[serde(default)]
|
|
private: Option<bool>,
|
|
}
|
|
|
|
/// An amendment as the model proposes it: the id of a line she may add to, and the draft that is her addition.
|
|
#[derive(Debug, Deserialize)]
|
|
struct ProposedAmend {
|
|
#[serde(default)]
|
|
target: Option<String>,
|
|
#[serde(default)]
|
|
draft: Option<i64>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct Proposed {
|
|
#[serde(default)]
|
|
draft: Option<i64>,
|
|
#[serde(default)]
|
|
mentions: Vec<String>,
|
|
#[serde(default)]
|
|
reply_to: Option<String>,
|
|
}
|
|
|
|
pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> String {
|
|
let her = packet.forms;
|
|
let mut people = String::new();
|
|
for (label, id) in &packet.people {
|
|
people.push_str(&format!("- {label} \u{2014} {id}\n"));
|
|
}
|
|
if people.is_empty() {
|
|
people.push_str("- no one else has spoken here lately\n");
|
|
}
|
|
let mut private: String = packet.private.iter().map(|words| format!("- private: {words}\n")).collect();
|
|
if private.is_empty() {
|
|
private.push_str("- none\n");
|
|
}
|
|
let mut amendable: String = packet.amendable.iter().map(|line| format!("- {} \u{2014} {}\n", line.id, spoken(&line.text))).collect();
|
|
if amendable.is_empty() {
|
|
amendable.push_str("- none\n");
|
|
}
|
|
let found = drafts(prose);
|
|
let mut numbered: String = found.drafts.iter().map(|draft| format!("{}. {}\n", draft.n, draft.text)).collect();
|
|
if numbered.is_empty() {
|
|
numbered.push_str("- none\n");
|
|
}
|
|
if found.unfinished.is_some() {
|
|
numbered.push_str(&format!("- {} began one more and was cut off before finishing it: it is no draft and cannot be said\n", her.subj));
|
|
}
|
|
// The conversation's speech cues, beside the room, where whether she speaks is decided (map 16.20.2).
|
|
let conversation = if packet.speaking.is_empty() { String::new() } else { format!("The conversation: {}\n", packet.speaking) };
|
|
// The tuning's guidance, as a paragraph of its own; an empty one leaves no gap in the frame.
|
|
let guidance = voiced(tuning.interpreter.guidance.trim(), her);
|
|
let guidance = if guidance.is_empty() { String::new() } else { format!("{guidance}\n\n") };
|
|
format!(
|
|
"{}\n\n{guidance}{}\n\nWho {} {}:\n{}\n\nWhat {} can do here:\n{}.\n\nThe room: {} ({}).\n{conversation}Who is in it, as label \u{2014} Matrix id:\n{people}\nWhat {} know{} privately, none of it to be said here:\n{private}\n{poss} own lines in this room that {} may add to, as id \u{2014} line:\n{amendable}\nWhat reached {}:\n{}\n\n{poss} lived moment:\n{}\n\n{poss} prose:\n{prose}\n\n{poss} drafts, by number:\n{numbered}",
|
|
speech_frame_head(her),
|
|
speech_frame_tail(her),
|
|
her.subj,
|
|
her.be,
|
|
packet.name,
|
|
her.subj,
|
|
capitalized(&turn_words(&packet.affordances, her)),
|
|
packet.room.as_deref().unwrap_or("none"),
|
|
packet.room_kind.words(),
|
|
her.subj,
|
|
her.s,
|
|
her.subj,
|
|
her.obj,
|
|
packet.stimulus,
|
|
lived_stream(narration, &packet.heard),
|
|
poss = capitalized(her.poss),
|
|
)
|
|
}
|
|
|
|
/// Whether a line carries someone else's words (Q-E unanswered, so option A: the echo refusal applies): long enough to
|
|
/// judge, and either nearly all a run of what she heard, or carrying nearly all of one line she heard that is itself
|
|
/// long enough to judge, by word trigrams against the bodies of the lines she was shown (`Packet::bodies`, the earlier
|
|
/// lines too; `heard_overlap`). The second catches a line said verbatim behind a lead-in or with words of her own after
|
|
/// it. Short answers such as "ok" or "Hi" are never echoes, a short line she heard is never one, and a line that answers
|
|
/// a claim by naming it is not one.
|
|
fn echo(line: &str, bodies: &[String]) -> bool {
|
|
let long = |text: &str| text.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).count() >= ECHO_MIN_WORDS;
|
|
long(line) && (heard_overlap(line, &bodies.join("\n")) >= ECHO_OVERLAP || bodies.iter().any(|body| long(body) && heard_overlap(body, line) >= ECHO_OVERLAP))
|
|
}
|
|
|
|
/// One speech decision: the Interpreter's schema turn, then code's hold on each line. The report carries the lines said,
|
|
/// the lines refused with why, the mentions dropped, the gaps, an unfinished draft, and the call's usage. A failed call
|
|
/// or an answer that is not the contract is a failure, never a silence.
|
|
pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> Value {
|
|
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose, tuning), Some(SPEECH_SCHEMA)) {
|
|
Ok(answer) => answer,
|
|
Err(failed) => return json!({ "failed": failed.reason, "usage": failed.usage }),
|
|
};
|
|
let Ok(parsed) = serde_json::from_str::<Answer>(&answer.text) else {
|
|
return json!({ "failed": "the answer is not the speech contract", "raw": answer.text, "usage": answer.usage });
|
|
};
|
|
let found = drafts(prose);
|
|
let gaps: Vec<Value> = parsed.gaps.iter().map(|raw| gap(prose, &found, raw)).collect();
|
|
// What she was shown this turn rides in the record, so what she is told of it next turn quotes none of it (`outcome`).
|
|
let mut decision = json!({ "said": [], "refused": [], "gaps": gaps, "heard": packet.bodies, "usage": answer.usage });
|
|
if let Some(open) = found.unfinished {
|
|
decision["unfinished"] = json!(prose[open + DRAFT_OPEN.len()..].trim());
|
|
}
|
|
// Only speech needs a room: a note to Self does not.
|
|
let room = packet.room.clone();
|
|
let shown = |id: &str| packet.people.iter().any(|(_, person)| person == id);
|
|
let mut said: Vec<Value> = Vec::new();
|
|
let mut refusals = Vec::new();
|
|
// A draft is its number (map 16.20.7): one draft goes one place, and a draft is used only when its act succeeds, so a
|
|
// refused act leaves it free. The same words go out once: a said draft whose words already went out is `Duplicate`,
|
|
// and only speech is held to that, so two identical drafts may still be a line and a note. `went` holds the drafts
|
|
// that went somewhere; `said_drafts` the ones said.
|
|
let mut used: Vec<usize> = Vec::new();
|
|
let mut went: Vec<&Draft> = Vec::new();
|
|
let mut said_drafts: Vec<usize> = Vec::new();
|
|
for line in parsed.say {
|
|
let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else {
|
|
refusals.push(refused(Act::Say, None, line.draft, Refusal::NoDraft));
|
|
continue;
|
|
};
|
|
let reason = if room.is_none() {
|
|
Some(Refusal::NoRoom)
|
|
} else if used.contains(&draft.n) {
|
|
Some(Refusal::Used)
|
|
} else if said.iter().any(|line| line["text"] == draft.text.as_str()) {
|
|
Some(Refusal::Duplicate)
|
|
} else if echo(&draft.text, &packet.bodies) {
|
|
Some(Refusal::Echo)
|
|
} else if said.len() >= MAX_LINES {
|
|
Some(Refusal::OverLines)
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(reason) = reason {
|
|
refusals.push(refused(Act::Say, Some(draft), None, reason));
|
|
continue;
|
|
}
|
|
let (mentions, unknown): (Vec<String>, Vec<String>) = line.mentions.into_iter().partition(|id| shown(id));
|
|
let (reply_to, unknown_reply) = match line.reply_to.filter(|id| !id.trim().is_empty()) {
|
|
Some(id) if shown(&id) => (Some(id), None),
|
|
Some(id) => (None, Some(id)),
|
|
None => (None, None),
|
|
};
|
|
used.push(draft.n);
|
|
said_drafts.push(draft.n);
|
|
went.push(draft);
|
|
said.push(json!({ "room": room, "text": draft.text, "mentions": mentions, "reply_to": reply_to, "rests_on": { "draft": draft.n, "start_byte": draft.start, "end_byte": draft.end }, "dropped": { "mentions": unknown, "reply_to": unknown_reply } }));
|
|
}
|
|
// An amendment adds a whole draft after a line of hers listed as one she may add to; the actuator composes it, so
|
|
// nothing here can rewrite the line (map 16.17).
|
|
let mut amended: Vec<Value> = Vec::new();
|
|
for proposed in parsed.amend {
|
|
let Some(draft) = proposed.draft.and_then(|n| found.numbered(n)) else {
|
|
refusals.push(refused(Act::Amend, None, proposed.draft, Refusal::NoDraft));
|
|
continue;
|
|
};
|
|
let target = proposed.target.as_deref().and_then(|id| packet.amendable.iter().find(|line| line.id == id.trim()));
|
|
let reason = if used.contains(&draft.n) {
|
|
Some(Refusal::Used)
|
|
} else if echo(&draft.text, &packet.bodies) {
|
|
Some(Refusal::Echo)
|
|
} else if !amended.is_empty() {
|
|
Some(Refusal::SecondAmend)
|
|
} else {
|
|
None
|
|
};
|
|
match (reason, target) {
|
|
(None, Some(line)) => {
|
|
used.push(draft.n);
|
|
went.push(draft);
|
|
amended.push(json!({ "target": line.id, "event": line.event, "room": line.room, "original": line.text, "added": draft.text, "draft": draft.n }));
|
|
}
|
|
(reason, _) => refusals.push(refused(Act::Amend, Some(draft), None, reason.unwrap_or(Refusal::NotAmendable))),
|
|
}
|
|
}
|
|
// A note to Self (map 16.18): one whole draft, at most one a turn, refused as an echo as a line is, and when the
|
|
// Interpreter judges it carries something private. It is recorded in the turn's record and nowhere else; nothing here writes her Mind.
|
|
let mut suggestions: Vec<Value> = Vec::new();
|
|
for proposed in parsed.suggest {
|
|
let Some(draft) = proposed.draft.and_then(|n| found.numbered(n)) else {
|
|
refusals.push(refused(Act::Suggest, None, proposed.draft, Refusal::NoDraft));
|
|
continue;
|
|
};
|
|
let reason = if used.contains(&draft.n) {
|
|
Some(Refusal::Used)
|
|
} else if echo(&draft.text, &packet.bodies) {
|
|
Some(Refusal::Echo)
|
|
} else if !suggestions.is_empty() {
|
|
Some(Refusal::SecondNote)
|
|
} else if proposed.private != Some(false) {
|
|
Some(Refusal::Private)
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(reason) = reason {
|
|
refusals.push(refused(Act::Suggest, Some(draft), None, reason));
|
|
continue;
|
|
}
|
|
let (about, dropped) = match proposed.about.filter(|id| !id.trim().is_empty()) {
|
|
Some(id) if shown(&id) => (Some(id), None),
|
|
Some(id) => (None, Some(id)),
|
|
None => (None, None),
|
|
};
|
|
used.push(draft.n);
|
|
went.push(draft);
|
|
suggestions.push(json!({ "kind": proposed.kind, "about": about, "room": room, "text": draft.text, "draft": draft.n, "dropped": { "about": dropped } }));
|
|
}
|
|
// A gap about a draft that went somewhere, or quoting from one, contradicts what happened: it is kept for the trace as
|
|
// `acted` and never shown to her. A reach naming a draft she said is a promise she cannot keep, and is kept (16.20.6).
|
|
for gap in decision["gaps"].as_array_mut().into_iter().flatten() {
|
|
let promise = gap["kind"] == json!(GapKind::MissingAffordance) && gap["from"] == "draft" && gap["draft"].as_u64().is_some_and(|n| said_drafts.iter().any(|said| *said as u64 == n));
|
|
let named = !promise && gap["draft"].as_u64().is_some_and(|n| went.iter().any(|draft| draft.n as u64 == n)) && gap["from"] == "draft";
|
|
let quoted = gap["from"] == "unlocated" && gap["quote"].as_str().is_some_and(|quote| !quote.is_empty() && went.iter().any(|draft| draft.text.contains(quote)));
|
|
if named || quoted {
|
|
gap["from"] = json!("acted");
|
|
}
|
|
}
|
|
decision["amended"] = json!(amended);
|
|
decision["suggestions"] = json!(suggestions);
|
|
decision["room"] = json!(room);
|
|
decision["room_kind"] = json!(packet.room_kind);
|
|
decision["said"] = json!(said);
|
|
decision["refused"] = json!(refusals);
|
|
decision
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) mod tests;
|