interpreter sees what her agent did: acts section, open-intention guard
The Interpreter read only her narration and thought, so an intention her agent carried out was never dropped and a near-duplicate was added at the next wake (Eureka held seven). Its prompt now carries an ACTS section, one line per tool call of this wake from the agent's receipts (tool, status, target or words, gist), beside the intentions index it already had with ids; the frame says an act that carried out or failed an intention settles it by id and that an open intention is not added again in other words. No section when no agent ran (the simulator). The shell receipt now names the command it answers. The commit refuses an intend.add whose words equal an open intention's up to case and spacing (Why::Duplicate); rewordings stay the model's. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
09901565b1
commit
7ab8344d62
7 changed files with 115 additions and 14 deletions
|
|
@ -51,7 +51,7 @@ use crate::projection::agent::read::Read as ReadTool;
|
|||
use crate::projection::agent::request_tool::RequestTool;
|
||||
use crate::projection::agent::say::{Say, Sent};
|
||||
use crate::projection::agent::shell::Shell;
|
||||
use crate::projection::agent::{Agent, Ended, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step};
|
||||
use crate::projection::agent::{Agent, Ended, Receipt, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step};
|
||||
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Fault, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Through, TurnKind, Waked, decided, failed as record_failed, heard_of, history, interpret_and_put, is_wake, load_tuning, settle_handed, wake, own_addressee as heard_as};
|
||||
|
||||
/// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it.
|
||||
|
|
@ -529,6 +529,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
// nothing, because a retry would wake the agent again and risk saying a line twice.
|
||||
let mut fault = waked.failed.clone();
|
||||
let mut acted = Value::Null;
|
||||
let mut receipts: Vec<Receipt> = vec![];
|
||||
if fault.is_none() {
|
||||
let name = if public_name.is_empty() { instance.0.clone() } else { public_name.clone() };
|
||||
let input = agent_input(&waked, &deliveries, &held, &config.own_sender);
|
||||
|
|
@ -539,6 +540,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
match step(&agent, &AgentWake { id: &wake_id, instructions: &agent_instructions(&name), input: &input, fresh: &fresh }) {
|
||||
Ok(turn) => {
|
||||
acted = json!({ "ended": format!("{:?}", turn.ended), "model_calls": turn.model_calls, "tool_calls": turn.tool_calls, "usd": turn.usd });
|
||||
receipts = turn.receipts;
|
||||
if let Ended::Failed(failed) = turn.ended {
|
||||
fault = Some(Fault { reason: failed.reason, outage: failed.outage });
|
||||
}
|
||||
|
|
@ -546,7 +548,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
Err(bug) => return failed("her agent could not be set up", bug),
|
||||
}
|
||||
if fault.is_none() {
|
||||
interpreted(start, instance, &state, &waked, &deliveries, &held, rooms[0], &stem, began_ms, &mouth);
|
||||
interpreted(start, instance, &state, &waked, &receipts, &deliveries, &held, rooms[0], &stem, began_ms, &mouth);
|
||||
}
|
||||
}
|
||||
let record_key = format!("{stem}-w");
|
||||
|
|
@ -635,12 +637,12 @@ fn agent_input(waked: &Waked, deliveries: &[&ChatDelivery], held: &[&str], own_s
|
|||
/// change is posted with its diff to the review room through the mouth, as a code-written line. Nothing here fails the wake: her
|
||||
/// next wake hears when her state was not kept.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn interpreted<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, waked: &Waked, deliveries: &[&ChatDelivery], held: &[&str], room: &str, stem: &str, began_ms: u64, mouth: &Mouth<'_>) {
|
||||
fn interpreted<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, waked: &Waked, receipts: &[Receipt], deliveries: &[&ChatDelivery], held: &[&str], room: &str, stem: &str, began_ms: u64, mouth: &Mouth<'_>) {
|
||||
let config = &start.config;
|
||||
let (Some(narration), Some(prose)) = (waked.narration.as_deref(), waked.prose.as_deref()) else { return };
|
||||
let now = (start.clock)();
|
||||
let held_lines = deliveries.iter().filter(|delivery| held.contains(&delivery.event_id.as_str()) && delivery.sender != config.own_sender).map(|delivery| delivery.text.clone());
|
||||
let heard = heard_of(state, &waked.report["packet"], room, held_lines, &config.operators, &config.minds, config.review_room.is_some(), narration, prose);
|
||||
let heard = heard_of(state, &waked.report["packet"], room, held_lines, &config.operators, &config.minds, config.review_room.is_some(), Some(receipts), narration, prose);
|
||||
// A row takes its place in her trace when it is first written, and keeps it when it is rewritten.
|
||||
let row = |body: Value| {
|
||||
let mut row = json!({ "seq": place(&*start.trace), "at": now.to_rfc3339(), "wake": stem });
|
||||
|
|
|
|||
|
|
@ -46,10 +46,14 @@ impl Executor for Shell {
|
|||
};
|
||||
let timeout_s = args.timeout_s.unwrap_or(30).clamp(1, TIMEOUT_MAX_S);
|
||||
let request = json!({ "command": args.command, "timeout_s": timeout_s });
|
||||
match ask(&self.socket, &request, Duration::from_secs(timeout_s + ANSWER_GRACE_S)) {
|
||||
let receipt = match ask(&self.socket, &request, Duration::from_secs(timeout_s + ANSWER_GRACE_S)) {
|
||||
Ok(answer) => passed_through(&answer),
|
||||
Err(why) => Receipt::new("shell", Status::Error, json!({ "why": why })),
|
||||
}
|
||||
};
|
||||
// The receipt names the command it answers, so what her trace holds says what was run, not only what came back.
|
||||
let mut fields = receipt.fields().clone();
|
||||
fields.insert("command".to_owned(), json!(args.command));
|
||||
Receipt::new("shell", receipt.status(), Value::Object(fields))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -259,6 +259,8 @@ pub(crate) struct Heard {
|
|||
pub minds: Vec<String>,
|
||||
/// Whether an identity change would be posted where people see it (`identity-write-all-visible`): none is made when not.
|
||||
pub identity_visible: bool,
|
||||
/// One line for each tool call her agent made this wake (`interpret::acts_of`), in order; none when no agent ran (the simulator).
|
||||
pub acts: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Heard {
|
||||
|
|
@ -292,6 +294,8 @@ pub(crate) enum Why {
|
|||
BadExpiry,
|
||||
/// No room shows an identity change, so none is made.
|
||||
NoReviewRoom,
|
||||
/// An intention already open says the same words, up to case and spacing.
|
||||
Duplicate,
|
||||
}
|
||||
|
||||
/// One change of her identity, for the drain to post: the field, and its value before and after.
|
||||
|
|
@ -965,6 +969,13 @@ impl Commit<'_> {
|
|||
continue;
|
||||
}
|
||||
};
|
||||
// The one duplicate the code can tell without reading meaning: the same words as an open intention. A rewording is the model's to catch.
|
||||
let same = |text: &str| text.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>();
|
||||
let wanted = same(&summary);
|
||||
if self.list(&["candidateActions", "actions"]).iter().any(|action| is_intention(action) && action["status"] == "active" && same(action["summary"].as_str().unwrap_or_default()) == wanted) {
|
||||
self.refuse("intend", item, Why::Duplicate);
|
||||
continue;
|
||||
}
|
||||
added += 1;
|
||||
let id = self.next_id('i');
|
||||
let target = match intention.target.as_deref().map(str::trim).filter(|text| !text.is_empty()) {
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ fn state() -> Value {
|
|||
}
|
||||
|
||||
fn heard() -> Heard {
|
||||
Heard { room: Some(MINDS.into()), lines: vec![], people: vec!["operator".into(), "deru".into(), "kiko".into()], operators: vec![META.into()], minds: vec![DERU.into(), KIKO.into()], identity_visible: true }
|
||||
Heard { room: Some(MINDS.into()), lines: vec![], people: vec!["operator".into(), "deru".into(), "kiko".into()], operators: vec![META.into()], minds: vec![DERU.into(), KIKO.into()], identity_visible: true, acts: None }
|
||||
}
|
||||
|
||||
fn deltas(value: Value) -> Deltas {
|
||||
|
|
@ -349,3 +349,24 @@ fn t_p2_two_stances_are_one_change() {
|
|||
assert_eq!(after["affect"]["doctrineStances"].as_array().unwrap().len(), state()["affect"]["doctrineStances"].as_array().unwrap().len());
|
||||
assert_eq!(after["affect"]["doctrineStances"][0]["summary"], "Tobiah answers slowly.");
|
||||
}
|
||||
|
||||
/// An intention whose words equal an open one's, up to case and spacing, is not added; a rewording is the model's to catch, a
|
||||
/// dropped one may be meant again, and a drop by id retires only the intention it names.
|
||||
#[test]
|
||||
fn an_intention_open_in_the_same_words_is_not_added_again() {
|
||||
let open = |state: &Value| state["candidateActions"]["actions"].as_array().unwrap().iter().filter(|action| action["status"] == "active").count();
|
||||
let add = |text: &str| json!({ "intend": { "add": [{ "summary": text, "expires_in_hours": 24 }] } });
|
||||
let (first, _) = run(&state(), add("Tobiah means to list the directory above the Aetheria path."));
|
||||
let id = first["candidateActions"]["actions"].as_array().unwrap().last().unwrap()["id"].as_str().unwrap().to_owned();
|
||||
let (again, applied) = run(&first, add(" tobiah means to LIST the directory\tabove the aetheria path. "));
|
||||
assert_eq!((open(&again), reasons(&applied)), (open(&first), vec!["duplicate".to_owned()]));
|
||||
let (twice, applied) = run(&first, json!({ "intend": { "add": [
|
||||
{ "summary": "Tobiah means to list a different directory.", "expires_in_hours": 24 },
|
||||
{ "summary": "Tobiah means to list a different DIRECTORY.", "expires_in_hours": 24 },
|
||||
] } }));
|
||||
assert_eq!((open(&twice), reasons(&applied)), (open(&first) + 1, vec!["duplicate".to_owned()]), "one batch cannot hold the same words twice");
|
||||
let (dropped, _) = run(&first, json!({ "intend": { "drop": [id.clone()] } }));
|
||||
assert_eq!(open(&dropped), open(&first) - 1);
|
||||
let (meant_again, applied) = run(&dropped, add("Tobiah means to list the directory above the Aetheria path."));
|
||||
assert_eq!((open(&meant_again), reasons(&applied)), (open(&dropped) + 1, vec![]));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ use huginn_mind::persona::validate_document;
|
|||
use serde_json::{Value, json};
|
||||
|
||||
use super::commit::{Applied, Deltas, Heard, apply as apply_commit};
|
||||
use super::agent::Receipt;
|
||||
use super::narrate::{Failed, Model, Spent};
|
||||
use super::select::{clip, forms, text, voiced};
|
||||
use super::turn::Taken;
|
||||
|
|
@ -21,7 +22,7 @@ const ITEM_BYTES: usize = 240;
|
|||
const NAME_MIN: usize = 3;
|
||||
|
||||
/// The frame of the call. `{name}` and her pronouns are filled by code, so one text serves every Mind.
|
||||
const FRAME: &str = "You are a private Interpreter. {name} has just lived a moment. Below is what the moment was like for {obj} (the narration), what {subj} thought about it (the thought), and an index of what in {poss} state can change.
|
||||
const FRAME: &str = "You are a private Interpreter. {name} has just lived a moment. Below is what the moment was like for {obj} (the narration), what {subj} thought about it (the thought), what {poss} agent did in it when it acted (the acts), and an index of what in {poss} state can change.
|
||||
|
||||
Say which way {poss} state moved, as one JSON object of the schema. Give every section and every list the schema asks for: an empty list [] or empty object {} says nothing moved there, and all of them empty is the usual answer. Change only what the thought shows moved. You give directions, never numbers: say up or down, and the commit decides how far. Use only the ids in the index; you make no need and no pressure.
|
||||
|
||||
|
|
@ -32,7 +33,7 @@ Write every text you give in the third person, about {name}, in words of your ow
|
|||
- feeling: feelings are named feelings with a strength from 0 to 1 and what they are about; mood moves valence, arousal or dominance up or down.
|
||||
- drives: a need or pressure goes up, down, or met (need) or eased (pressure).
|
||||
- self: a stance or value changes only when the thought shows {obj} changing {poss} mind about who {subj} {be}; it is rare.
|
||||
- intend: something {subj} means to do, within a week; a short third-person sentence, when it will be due in hours, and later or ready. Name an intention from the index as ready or drop it.";
|
||||
- intend: something {subj} means to do, within a week; a short third-person sentence, when it will be due in hours, and later or ready. Name an intention from the index as ready or drop it. An act that carried out an intention, or failed at it, settles it: drop it by id. An intention already in the index is not added again in other words.";
|
||||
|
||||
/// The sections each of the Interpreter's two calls answers. The API refuses a grammar that compiles too large, which all six
|
||||
/// sections in one schema are, so the answer is two strict calls whose halves together cover every `Deltas` section.
|
||||
|
|
@ -130,6 +131,42 @@ fn index(state: &Value, heard: &Heard) -> String {
|
|||
out.trim_end().to_owned()
|
||||
}
|
||||
|
||||
/// What a line of the acts shows of one target or gist.
|
||||
const ACT_BYTES: usize = 160;
|
||||
|
||||
/// One line for each tool call her agent made this wake, in order, from its receipts: the tool, the status the executor
|
||||
/// gave, the target or words the call carried, and the gist of what came of it.
|
||||
pub(crate) fn acts_of(receipts: &[Receipt]) -> Vec<String> {
|
||||
receipts
|
||||
.iter()
|
||||
.map(|receipt| {
|
||||
let fields = receipt.fields();
|
||||
let said = |key: &str| fields.get(key).and_then(Value::as_str).map(|words| words.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|words| !words.is_empty());
|
||||
let quoted = |words: String| Value::String(clip(&words, ACT_BYTES)).to_string();
|
||||
let target: Vec<String> = ["kind", "room"].iter().filter_map(|key| said(key)).chain(["command", "target", "text", "what"].iter().find_map(|key| said(key))).map(quoted).collect();
|
||||
let gist = ["why", "failure", "refusal", "cap"].iter().find_map(|key| said(key)).or_else(|| {
|
||||
let out = ["stdout_tail", "stderr_tail"].iter().find_map(|key| said(key));
|
||||
match (fields.get("exit").and_then(Value::as_i64), out) {
|
||||
(Some(exit), Some(out)) => Some(format!("exit {exit}, {}", quoted(out))),
|
||||
(Some(exit), None) => Some(format!("exit {exit}")),
|
||||
(None, _) => fields.get("bytes").and_then(Value::as_u64).map(|bytes| format!("{bytes} bytes")),
|
||||
}
|
||||
});
|
||||
let status = receipt.json()["status"].as_str().unwrap_or_default().to_owned();
|
||||
format!("- {} {status}: {}{}", receipt.tool(), target.join(" "), gist.map_or_else(String::new, |gist| format!(" -> {}", clip(&gist, ACT_BYTES * 2))))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The prompt's ACTS section, closed by its blank line: none when no agent ran this wake.
|
||||
fn acts_section(heard: &Heard) -> String {
|
||||
match heard.acts.as_deref() {
|
||||
None => String::new(),
|
||||
Some([]) => "ACTS\nHer agent made no tool call.\n\n".to_owned(),
|
||||
Some(lines) => format!("ACTS\n{}\n\n", lines.join("\n")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt: the frame in her pronouns, the index, then the narration and what she thought, fenced as data, and last the
|
||||
/// sections this call answers (`HALVES[half]`).
|
||||
fn prompt(state: &Value, heard: &Heard, narration: &str, prose: &str, half: usize) -> String {
|
||||
|
|
@ -138,7 +175,7 @@ fn prompt(state: &Value, heard: &Heard, narration: &str, prose: &str, half: usiz
|
|||
name => name,
|
||||
};
|
||||
let frame = voiced(&FRAME.replace("{name}", name), forms(state));
|
||||
format!("{frame}\n\nINDEX\n{}\n\nNARRATION\n{narration}\n\nTHOUGHT\n{prose}\n\nThis call answers only these sections: {}.", index(state, heard), HALVES[half].join(", "))
|
||||
format!("{frame}\n\nINDEX\n{}\n\n{}NARRATION\n{narration}\n\nTHOUGHT\n{prose}\n\nThis call answers only these sections: {}.", index(state, heard), acts_section(heard), HALVES[half].join(", "))
|
||||
}
|
||||
|
||||
/// Two calls' costs as one; either may have none.
|
||||
|
|
@ -225,10 +262,11 @@ pub(crate) fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken,
|
|||
|
||||
|
||||
/// What the Interpreter hears of a wake (`Heard`): the wake's room, the bodies of the lines her packet showed and any held lines
|
||||
/// the caller adds, and the people present or named. The one derivation, the drain's and the simulator's alike.
|
||||
/// the caller adds, what her agent did this wake (none when no agent ran), and the people present or named. The one derivation, the drain's and the simulator's alike.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn heard_of(state: &Value, packet: &Value, room: &str, held: impl IntoIterator<Item = String>, operators: &[String], minds: &[String], identity_visible: bool, narration: &str, prose: &str) -> Heard {
|
||||
pub(crate) fn heard_of(state: &Value, packet: &Value, room: &str, held: impl IntoIterator<Item = String>, operators: &[String], minds: &[String], identity_visible: bool, acts: Option<&[Receipt]>, narration: &str, prose: &str) -> Heard {
|
||||
let mut heard = Heard {
|
||||
acts: acts.map(acts_of),
|
||||
room: packet["room"].as_str().or(Some(room)).map(str::to_owned),
|
||||
lines: packet["bodies"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).chain(held).collect(),
|
||||
people: vec![],
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ impl Model for Answers {
|
|||
}
|
||||
|
||||
fn heard() -> Heard {
|
||||
Heard { room: None, lines: vec![], people: vec!["operator".into()], operators: vec!["@meta:gamecult.org".into()], minds: vec![DERU.into()], identity_visible: true }
|
||||
Heard { room: None, lines: vec![], people: vec!["operator".into()], operators: vec!["@meta:gamecult.org".into()], minds: vec![DERU.into()], identity_visible: true, acts: None }
|
||||
}
|
||||
|
||||
fn state() -> Value {
|
||||
|
|
@ -215,3 +215,28 @@ fn print_half_schemas() {
|
|||
println!("HALF{half} {}", schema(half));
|
||||
}
|
||||
}
|
||||
|
||||
/// Her agent's acts reach the prompt between the index and the narration, one line per tool call, beside her open intentions with
|
||||
/// their ids; a wake with no agent (the simulator) carries no acts section, and an agent that did nothing says so.
|
||||
#[test]
|
||||
fn the_prompt_carries_this_wakes_acts_and_her_open_intentions_with_their_ids() {
|
||||
use crate::projection::agent::Status;
|
||||
let receipts = [
|
||||
Receipt::new("shell", Status::Ok, json!({ "command": "ls /opt/aetheria/..", "exit": 0, "stdout_tail": "Aetheria\nCultLib\n", "stderr_tail": "" })),
|
||||
Receipt::new("read", Status::Refused, json!({ "kind": "repo", "target": "Aetheria", "why": "nothing can be read from here" })),
|
||||
Receipt::new("say", Status::Ok, json!({ "room": "minds", "text": "Found it.", "event": "$e1" })),
|
||||
];
|
||||
let mut heard = heard();
|
||||
heard.acts = Some(acts_of(&receipts));
|
||||
let asked = prompt(&state(), &heard, "n", "p", 1);
|
||||
let acts = asked.split("\nACTS\n").nth(1).unwrap().split("NARRATION").next().unwrap();
|
||||
assert_eq!(acts.trim_end(), "- shell ok: \"ls /opt/aetheria/..\" -> exit 0, \"Aetheria CultLib\"\n- read refused: \"repo\" \"Aetheria\" -> nothing can be read from here\n- say ok: \"minds\" \"Found it.\"");
|
||||
let index = asked.split("INDEX\n").nth(1).unwrap().split("ACTS").next().unwrap();
|
||||
assert!(index.contains("intentions:\n- ca-1: Tobiah means to ask Deru about the crossword."), "{index}");
|
||||
assert!(asked.contains("An act that carried out an intention, or failed at it, settles it: drop it by id."), "{asked}");
|
||||
|
||||
heard.acts = Some(vec![]);
|
||||
assert!(prompt(&state(), &heard, "n", "p", 1).contains("\nACTS\nHer agent made no tool call.\n\nNARRATION"));
|
||||
heard.acts = None;
|
||||
assert!(!prompt(&state(), &heard, "n", "p", 1).contains("\nACTS\n"), "no agent ran, so no acts section");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -535,7 +535,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &[Member], repeat: usize) ->
|
|||
&& let (Some((model, model_name)), Some(narration), Some(prose)) = (interpreter.as_ref(), waked.narration.as_deref(), waked.prose.as_deref())
|
||||
{
|
||||
let before = held[at].0.borrow().clone();
|
||||
let heard = heard_of(&before, &waked.report["packet"], &here, [], &plan.operators, &cast, true, narration, prose);
|
||||
let heard = heard_of(&before, &waked.report["packet"], &here, [], &plan.operators, &cast, true, None, narration, prose);
|
||||
// A call id the connector has not seen: the plan's clock repeats from run to run, so the call takes the wall clock, as `wake_id` does.
|
||||
let made = interpret_and_put(*model, model_name, &format!("{key}-i{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()), &held[at], &Slug(localpart(&id).to_owned()), &before, &heard, narration, prose, &key, now, &|| now, &|_| Ok(()));
|
||||
let mut row = made.row;
|
||||
|
|
|
|||
Loading…
Reference in a new issue