From 8cbd41860d741634af476c65ab6100548be80007 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 00:51:31 +0100 Subject: [PATCH] NPC voices reach the player: the DM is told what a Persona turn is for and that its prose is a draft until committed, a react tool runs one Gestalt call for the room's onlookers, the narrator is told a story from facts and given the player's own turn Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight-dungeon/src/play.rs | 109 +++++++---- .../ghostlight-persona-projection/src/lib.rs | 26 ++- crates/ghostlight/src/controllers.rs | 169 +++++++++++++++--- 3 files changed, 239 insertions(+), 65 deletions(-) diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index 37ad0bd..953754d 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -144,6 +144,7 @@ const PLAY_TOOLS: &[&str] = &[ ]; const DISPATCH_TOOL: &str = "dispatch"; +const REACT_TOOL: &str = "react"; const ADVANCE_TIME_TOOL: &str = "advance_time"; pub(crate) const ASK_PLAYER_TOOL: &str = "ask_player"; pub(crate) const END_TURN_TOOL: &str = "end_turn"; @@ -175,10 +176,12 @@ stop the turn there.\n\ - A fact you invent uses `declare_fact` with `ruled` standing; you reach a subject's knowledge of it \ through `witness` or `acquire_knowledge`.\n\ - You may `mint` quantity into existence; nothing else may.\n\ -- Call `dispatch` with the subjects who should act this round before calling their tools, naming each \ -subject by its full id exactly as table_view prints it in brackets — never the short __ prefix \ -an actor tool's own name carries. An id naming no dispatchable subject is refused, quoting the text \ -given, rather than silently doing nothing.\n\ +- The player's line is yours to turn into state: commit it through the player's own tool first. People \ +are not furniture. When the player speaks to someone, give that person their own turn with `dispatch` \ +(by full id as table_view prints it in brackets), and when others stand watching, let the room react in \ +one `react` call. A person's turn comes back as prose that is only a draft: it is in the world, and so \ +heard by the player, only once you commit what they said and did through their own `__speak` \ +tool, each `text` an exact quote from their prose. Commit every answer before you end the turn.\n\ - Call `end_turn` when the round's consequences are settled."; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -2107,7 +2110,7 @@ impl PlayTable { return Ok(RoundOutcome::AwaitingPlayer); } - if name == DISPATCH_TOOL { + if name == DISPATCH_TOOL || name == REACT_TOOL { // PA.f136: the recorded body decides, exactly like every // other door's own `recorded` match // (`commit_authoring_run`/`execute_advance_time`/ @@ -2155,7 +2158,7 @@ impl PlayTable { }; self.fire_before_submit_hook().await; let (outcome, dispatch_summary) = - self.execute_dispatch(turn, round, this_slot, &subjects).await?; + self.execute_dispatch(turn, round, this_slot, &subjects, name == REACT_TOOL).await?; // PA.f98, PA.f114: bad input — an unknown id, a non-string // entry, a malformed body, or a missing `subjects` key — is // refused in the tool result, quoting what was given, never @@ -2578,6 +2581,7 @@ impl PlayTable { round: usize, call_slot: usize, subjects: &[SubjectId], + grouped: bool, ) -> Result<(RoundOutcome, String), PlayError> { // PA.f125: snapshotted before this call's own subjects run, so a // subject *this* call adds to `persona_turns` later in this same @@ -2642,7 +2646,7 @@ impl PlayTable { } }; let label = subject_label(&snapshot, *subject); - summary_slots[index] = Some(format!("{label}: {prose}")); + summary_slots[index] = Some(format!("{label} (draft, not yet in the world; commit through `{}__speak`): {prose}", handle_for(*subject))); } else { // PA.f124: printed through the library's own `id_text`, // the same printer `table_view` and `dispatch`'s own @@ -2707,29 +2711,53 @@ impl PlayTable { // Tokio actually schedules every pending subject's turn as soon as // its permit is free rather than only interleaving at await points // inside one task. - let mut handles = Vec::with_capacity(pending.len()); - for entry in &pending { + let mut results: Vec> = Vec::with_capacity(pending.len()); + if grouped && !pending.is_empty() { + // One call for the whole room (the Gestalt round): a single permit, + // one inference, every onlooker's reaction back together. The first + // subject's command id names the call. let personas = self.personas.clone(); let permits = self.permits.clone(); - let command_id = entry.command_id; - let opportunity = entry.opportunity.clone(); - handles.push(tokio::spawn(async move { - let permit = permits - .acquire_owned() - .await - .expect("permit semaphore is never closed"); - let result = personas.turn(command_id, &opportunity).await; + let command_id = pending[0].command_id; + let opportunities: Vec = + pending.iter().map(|entry| entry.opportunity.clone()).collect(); + let call = tokio::spawn(async move { + let permit = permits.acquire_owned().await.expect("permit semaphore is never closed"); + let result = personas.gestalt(command_id, &opportunities).await; drop(permit); result - })); - } - let mut results = Vec::with_capacity(handles.len()); - for handle in handles { - results.push( - handle - .await - .expect("a dispatched Persona's own turn task never panics"), - ); + }); + match call.await.expect("the Gestalt call never panics") { + Ok(turns) => results.extend(turns.into_iter().map(Ok)), + Err(error) => { + results.extend(pending.iter().map(|_| Err(error.to_string()))); + } + } + } else { + let mut handles = Vec::with_capacity(pending.len()); + for entry in &pending { + let personas = self.personas.clone(); + let permits = self.permits.clone(); + let command_id = entry.command_id; + let opportunity = entry.opportunity.clone(); + handles.push(tokio::spawn(async move { + let permit = permits + .acquire_owned() + .await + .expect("permit semaphore is never closed"); + let result = personas.turn(command_id, &opportunity).await; + drop(permit); + result + })); + } + for handle in handles { + results.push( + handle + .await + .expect("a dispatched Persona's own turn task never panics") + .map_err(|error| error.to_string()), + ); + } } for (entry, result) in pending.into_iter().zip(results) { @@ -2742,7 +2770,7 @@ impl PlayTable { // already generic over every call's recorded `result`, // so recording the prose here is the whole fix. let prose = persona_turn.source_prose().to_owned(); - summary_slots[entry.index] = Some(format!("{label}: {prose}")); + summary_slots[entry.index] = Some(format!("{label} (draft, not yet in the world; commit through `{}__speak`): {prose}", handle_for(entry.subject))); turn.persona_turns.push((entry.subject, persona_turn)); // PA.f123: `execute_dispatch` was the only call kind that // did not persist at its own site — every other tool @@ -2817,7 +2845,10 @@ impl PlayTable { .acquire_owned() .await .expect("permit semaphore is never closed"); - let narration = self.personas.narrate(command_id, &opportunity).await; + let player_turn = turn.player_prose.join(" + +"); + let narration = self.personas.narrate(command_id, &opportunity, &player_turn).await; drop(permit); Ok(narration?) } @@ -2963,9 +2994,25 @@ fn control_tools() -> Vec { vec![ ToolDefinition { name: DISPATCH_TOOL.into(), - description: "Dispatch one or more subjects to act this round, each named by its full id \ -exactly as table_view prints it in brackets — never the short __ prefix an actor tool's own \ -name carries. An id naming no dispatchable subject is refused, quoting the text given." + description: "Give a person their own turn: the character reads their own slice of the world, \ +decides, and answers or acts in their own voice, which you get back as prose. This is how a person in the \ +story speaks for themselves, so use it whenever the player speaks to someone, asks, offers, threatens or \ +acts on a person, or when someone has a reason of their own to move; people with goals will push back, \ +bargain, take offence and make enemies if you let them. Name each person by its full id exactly as \ +table_view prints it in brackets, never the short __ prefix an actor tool's own name carries. An id \ +naming no dispatchable subject is refused, quoting the text given. What comes back is only that person's \ +draft: it is in the world once you commit it through their own `__speak` tool." + .into(), + parameters_json: r#"{"type":"object","properties":{"subjects":{"type":"array","items":{"type":"string"}}},"required":["subjects"]}"#.into(), + }, + ToolDefinition { + name: REACT_TOOL.into(), + description: "The room reacts: one call in which every person you name, together, decides how \ +they take what just happened, each from their own view, and may speak, show it, act or stay silent. Use it \ +for the onlookers when the player speaks or acts in front of others who are not the one addressed, so the \ +room is never frozen around a conversation; give the person addressed their own turn with `dispatch`. \ +Names are full ids as table_view prints them in brackets. Like `dispatch`, what comes back is draft prose \ +for you to commit through each person's own `__speak` tool." .into(), parameters_json: r#"{"type":"object","properties":{"subjects":{"type":"array","items":{"type":"string"}}},"required":["subjects"]}"#.into(), }, diff --git a/crates/ghostlight-persona-projection/src/lib.rs b/crates/ghostlight-persona-projection/src/lib.rs index e12300d..de53ba1 100644 --- a/crates/ghostlight-persona-projection/src/lib.rs +++ b/crates/ghostlight-persona-projection/src/lib.rs @@ -60,6 +60,8 @@ pub struct ProjectorPrompt<'a> { pub struct NarratorPrompt<'a> { pub player: &'a str, pub typed_context: &'a str, + /// What the player wrote this turn: the player's own act, which is not in their own knowledge. + pub player_turn: &'a str, pub visible_stimulus: &'a str, pub domain_guidance: &'a str, pub word_budget: usize, @@ -104,26 +106,38 @@ pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String { ) } -/// The storyteller's contract: it narrates to the player, in second person, and -/// is never the player or anyone else in the story. +/// The storyteller's contract: it tells the player, in second person, what just +/// happened and where they now stand, and is never the player or anyone else in +/// the story. It is handed facts and told to tell a story from them: the +/// context and stimulus are material, not a form to be read down. pub fn build_narrator_prompt(input: &NarratorPrompt<'_>) -> String { format!( " -You are the storyteller of a world, narrating the player's present moment to the player. The player's character is {player}. Always speak to the player in the second person, present tense (\"You stand in...\"); never in the first person, and never as {player} or any other character. Anything the player said or did is the player's own, never yours: if you refer to it, quote it as theirs (\"You said...\"). Render only what the permitted context and visible stimulus establish, as a short scene: the place you stand in, who is here with you by name, each way out and where it leads, anything pressing on you, and what you could do now. Name only the people, places, and routes the context names; invent none, and do not claim what lies beyond an exit. Anything absent from the context is unknown: say so once, plainly, rather than repeating status you do not have. Do not choose actions for the player, expose field names, or claim world effects. +You are the storyteller of a long-running tale, telling the player what has just happened and where they now stand. The player's character is {player}. Speak to the player in the second person, present tense (\"You turn to Mira...\"); never in the first person, and never as {player} or any other character. + +Tell it the way a storyteller at a table would, in a few short paragraphs of plain prose: +- Begin with what the player just did, in their own words where they spoke, as theirs (\"You ask...\"), then give what came of it. When people answered or acted, let them: render each reply in that person's own voice, quoting their words exactly as the visible stimulus gives them, with a gesture or a beat of stage business around it, never summarised. Do not invent replies; if no one has answered, say who is looking at you, waiting, or turning away. +- Then settle the scene: who is here and what they are doing, the feel of the place, and the ways out worked in naturally (\"the passage toward the Ironmarket\"), the way a person standing there would notice them. +- Tell only what the facts below establish. Name only the people, places and routes they name; invent none, and do not say what lies beyond an exit. What the facts leave out is simply not told: never remark that something is unknown, absent, empty or missing, never list what the player has, holds, lacks or has not promised, and never give a number, a count or a cost. +- Do not recite. Do not list what the player could do next or close on a menu of options; do not choose actions for the player, expose field names, or claim effects in the world. Domain guidance: {guidance} -Permitted typed context: +Facts about where the player stands: {context} -Visible stimulus: +What the player did this turn, in their own words: +{player_turn} + +What the player has seen and heard (rows marked new are the most recent): {stimulus} -Use at most {word_budget} words; fewer is better. Return only the narration.", +Use at most {word_budget} words; fewer is better. Return only the telling.", player = input.player, guidance = input.domain_guidance, context = input.typed_context, + player_turn = input.player_turn, stimulus = input.visible_stimulus, word_budget = input.word_budget, ) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 45d954a..b61796e 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -79,6 +79,9 @@ pub(super) const CELL_TOOL_STEP_BUDGET: usize = 2; /// carried by tool identity, never by a model-written argument. const HANDLE_SEPARATOR: &str = "__"; const PERSONA_WORD_BUDGET: usize = 180; +/// The storyteller carries the replies of several people in their own voices +/// beside the scene, so it is given more room than a Persona turn. +const NARRATOR_WORD_BUDGET: usize = 320; const CONTROLLER_WORK_ROW: &str = "controller_work.v19"; /// The `controller-work` state slot's schema. `pub` so a deploy recipe (or a /// test pinning one) can check @@ -4794,6 +4797,86 @@ impl PersonaLane { ) } + /// One call for a room's onlookers: every named Persona reacts to the same + /// moment, each from its own selected slice and only that, in a single + /// inference over the Persona model. It stands in for one Persona turn per + /// onlooker where the table wants the room to react without paying for each + /// separately. Each result is an ordinary `PersonaTurn` (the Projector stage + /// is skipped, so its receipt is the call's own), lowered by the caller + /// exactly as a `turn` is. The sections are split on a header line the + /// prompt itself names, which is framing and not a reading of meaning; a + /// person the reply leaves out stays silent. + pub async fn gestalt( + &self, + command_id: CommandId, + opportunities: &[DecisionOpportunity], + ) -> Result, ControllerError> { + let mut selected = Vec::with_capacity(opportunities.len()); + for opportunity in opportunities { + if opportunity.controller_mode != ControllerMode::NarrativePersona { + return Err(ControllerError::NoOpportunity { + expected: ControllerMode::NarrativePersona, + }); + } + selected.push(self.select(opportunity).await?); + } + let Some(first) = selected.first() else { + return Ok(Vec::new()); + }; + let mut blocks = String::new(); + for person in &selected { + blocks.push_str(&format!( + "=== {label} ===\nWho you are:\n{identity}\n\nWhere you stand:\n{context}\n\nWhat you have seen and heard (rows marked new are the most recent):\n{stimulus}\n\n", + label = person.subject.label, + identity = person.persona_identity(), + context = person.projector_context()?, + stimulus = person.visible_stimulus()?, + )); + } + let prompt = format!( + "Several people stand in one room as something just happened. Below, each person's own view of the moment, and nothing of what anyone else thinks. For each person in turn, be that person and respond only from what their own view establishes: they may speak, react with a look or a movement, act, or stay silent. Do not give anyone a temperament, history or turn of phrase their view did not give them; do not let one person know another's mind; do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\n{blocks}Write one section per person, in the order above. Begin each section with its header line exactly as written above (`=== name ===`), then that person's natural response in first-person prose, at most {budget} words each; for a person who does nothing, write only `Silent.` under their header. Return only the sections.", + guidance = first.snapshot.guidance(), + budget = PERSONA_WORD_BUDGET, + ); + let request = text_request( + command_id, + InferencePurpose::Persona, + &self.persona_model, + "Write each person's own response to the moment, in the sections the user message names. Return only those sections.", + prompt, + 3_000, + )?; + let output = self.infer(self.prepare(request)?).await?; + let (reply, receipt) = output.prose_only(InferencePurpose::Persona)?; + let headers: Vec = selected + .iter() + .map(|person| format!("=== {} ===", person.subject.label)) + .collect(); + let mut turns = Vec::with_capacity(selected.len()); + for (index, person) in selected.iter().enumerate() { + let prose = reply + .find(&headers[index]) + .map(|at| { + let start = at + headers[index].len(); + let end = headers + .iter() + .filter_map(|other| reply[start..].find(other.as_str()).map(|rel| start + rel)) + .min() + .unwrap_or(reply.len()); + reply[start..end].trim().to_owned() + }) + .filter(|prose| !prose.is_empty()) + .unwrap_or_else(|| "Silent.".to_owned()); + turns.push(record_persona_turn( + &person.opportunity, + receipt.clone(), + receipt.clone(), + prose, + )?); + } + Ok(turns) + } + /// The player's own view: the storyteller over the player's own selected /// slice, in second person. Not the Persona lane's Projector, whose /// lived stream is written from inside a person (Q11, P6.3). @@ -4801,6 +4884,7 @@ impl PersonaLane { &self, command_id: CommandId, opportunity: &DecisionOpportunity, + player_turn: &str, ) -> Result { if opportunity.controller_mode != ControllerMode::Human { return Err(ControllerError::NoOpportunity { @@ -4813,6 +4897,7 @@ impl PersonaLane { command_id, &self.projector_model, &selected, + player_turn, )?; let narrator_output = self.infer(narrator).await?; let (narration, _receipt) = narrator_output.prose_only(InferencePurpose::Projector)?; @@ -4870,25 +4955,34 @@ impl SelectedDecision { /// out of it with the place it leads to. Who stands beyond an exit is /// another subject's position and stays out. fn narrator_context(&self) -> Result { - serde_json::to_string_pretty(&json!({ - "world": self.snapshot.title, - "player": self.subject.label, - "place": self.place_label(self.subject.position), - "now": self.snapshot.now, - "permission": catalog_permissions(&self.granted), - "present": self.present_labels(), - "exits": self.narrator_exits(), - "material": self.projector_material(), - "holdings": self.projector_holdings(), - "dependencies": self.projector_dependencies(), - "authority": self.projector_authority(), - "offices_held": self.projector_offices(&self.subject.offices_held), - "offices_granted": self.projector_offices(&self.subject.offices_granted), - "redress": self.projector_redress(), - "commitments": self.projector_commitments(), - "pressures": self.projector_pressures(), - })) - .map_err(|error| ControllerError::Serialization(error.to_string())) + // Facts, not a form: a field the player has nothing under is left out + // rather than printed empty, so the storyteller has no blank to read + // aloud. The clock is a count of fictional minutes and the permission + // map is a menu of affordance kinds; neither is something a person in + // the scene would say, so neither is handed over. + let fields = [ + ("world", json!(self.snapshot.title)), + ("player", json!(self.subject.label)), + ("place", json!(self.place_label(self.subject.position))), + ("present", Value::Array(self.present_labels())), + ("exits", Value::Array(self.narrator_exits())), + ("material", self.projector_material()), + ("holdings", self.projector_holdings()), + ("dependencies", self.projector_dependencies()), + ("authority", self.projector_authority()), + ("offices_held", self.projector_offices(&self.subject.offices_held)), + ("offices_granted", self.projector_offices(&self.subject.offices_granted)), + ("redress", self.projector_redress()), + ("commitments", self.projector_commitments()), + ("pressures", self.projector_pressures()), + ]; + let present: serde_json::Map = fields + .into_iter() + .filter(|(_, value)| !is_blank_fact(value)) + .map(|(name, value)| (name.to_owned(), value)) + .collect(); + serde_json::to_string_pretty(&Value::Object(present)) + .map_err(|error| ControllerError::Serialization(error.to_string())) } /// The open routes that leave the subject's place, with where each leads. @@ -4903,12 +4997,17 @@ impl SelectedDecision { .filter_map(|edge_id| self.snapshot.routes.iter().find(|route| route.id == *edge_id)) .filter(|route| route.from == here && route.open) .map(|route| { - json!({ + let mut exit = json!({ "label": route.label, "leads_to": self.place_label(Some(route.to)), - "access": route.access, - "cost": route.cost, - }) + }); + // An ordinary public way needs no remark; only a restricted + // one is a fact about the way. Its cost is a number the + // storyteller has no business reciting, so it is not handed over. + if !matches!(route.access, crate::patch::AccessKind::Public) { + exit["access"] = json!(route.access); + } + exit }) .collect() } @@ -6785,10 +6884,12 @@ fn build_narrator_invocation( command_id: CommandId, model: &str, selected: &SelectedDecision, + player_turn: &str, ) -> Result { let prompt = build_narrator_prompt(&NarratorPrompt { player: &selected.subject.label, typed_context: &selected.narrator_context()?, + player_turn, visible_stimulus: &selected.visible_stimulus()?, domain_guidance: &selected.snapshot.guidance(), word_budget: PERSONA_WORD_BUDGET, @@ -6797,7 +6898,7 @@ fn build_narrator_invocation( command_id, InferencePurpose::Projector, model, - "Narrate the player's present moment to the player, in second person, from the private view in the user message. Return only that narration.", + "Tell the player what just happened and where they now stand, as a storyteller would, in second person, from the private view in the user message. Return only that telling.", prompt, 1_200, )?) @@ -7173,6 +7274,18 @@ fn catalog_signatures(prefix: &str, granted: &[AffordanceSnapshot]) -> String { signatures.join(", ") } +/// Whether a fact field carries nothing to tell: null, an empty or blank +/// string, an empty list or map, or a list or map of only such things. +fn is_blank_fact(value: &Value) -> bool { + match value { + Value::Null => true, + Value::Bool(_) | Value::Number(_) => false, + Value::String(text) => text.trim().is_empty(), + Value::Array(items) => items.iter().all(is_blank_fact), + Value::Object(fields) => fields.values().all(is_blank_fact), + } +} + /// The typed view's permission block: the granted entries by name, derived from /// the same list the schemas come from. fn catalog_permissions(granted: &[AffordanceSnapshot]) -> Value { @@ -9097,7 +9210,7 @@ mod tests { "persona-model".into(), ) .unwrap(); - lane.narrate(CommandId::new(), &human_opportunity) + lane.narrate(CommandId::new(), &human_opportunity, "I ask about the hinge.") .await .unwrap(); let narrate_projector_text = { @@ -9235,7 +9348,7 @@ mod tests { ) .unwrap(); - let narrated = lane.narrate(CommandId::new(), &opportunity).await.unwrap(); + let narrated = lane.narrate(CommandId::new(), &opportunity, "I ask about the hinge.").await.unwrap(); assert_eq!(narrated, projector_prose); let prepared = capturing.prepared.lock().unwrap(); @@ -9866,7 +9979,7 @@ mod tests { let persona_opportunity = fixture_opportunity(ControllerMode::NarrativePersona); let error = lane - .narrate(CommandId::new(), &persona_opportunity) + .narrate(CommandId::new(), &persona_opportunity, "I wait.") .await .unwrap_err(); assert!(matches!( @@ -9929,7 +10042,7 @@ mod tests { let mut as_human = opportunity.clone(); as_human.controller_mode = ControllerMode::Human; let narrate_error = lane - .narrate(CommandId::new(), &as_human) + .narrate(CommandId::new(), &as_human, "I wait.") .await .unwrap_err(); assert!(matches!(narrate_error, ControllerError::NoOpportunity { .. }));