diff --git a/Cargo.lock b/Cargo.lock index f7f0595..1f1cb03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1141,7 +1141,7 @@ dependencies = [ [[package]] name = "model-connector" version = "0.1.0" -source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=c1802d85bee3ae04b0c5737563c8343c1fef515d#c1802d85bee3ae04b0c5737563c8343c1fef515d" +source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5" dependencies = [ "aes-gcm", "base64", diff --git a/crates/mind-body/Cargo.toml b/crates/mind-body/Cargo.toml index 52e8780..5a77bdf 100644 --- a/crates/mind-body/Cargo.toml +++ b/crates/mind-body/Cargo.toml @@ -41,7 +41,7 @@ eureka-pipeline = { path = "../eureka-pipeline" } eureka-state = { path = "../eureka-state", default-features = false } ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" } huginn-mind = { path = "../huginn-mind" } -model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" } +model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector" } rmp-serde = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -73,7 +73,7 @@ syn = { version = "2", features = ["full"] } tempfile = "3" # A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it. # Same revision as the dependency; the `daemon` feature is test-only. -model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector", features = ["daemon"] } +model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector", features = ["daemon"] } [lib] name = "mind_body" diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 7aec9c5..b4ebd67 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -46,7 +46,7 @@ use crate::chat_client::{Chat, ChatPending, Form, ReplyLink}; use crate::heartbeat::HeartbeatView; pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain}; -pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key}; +pub use narrate::{Answer, Failed, KitModel, Model, Spent, StepRequest, Stepped, ToolCall, connector_key}; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; pub(crate) use commit::apply as apply_commit; diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 52b50c5..126a058 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -1,5 +1,5 @@ -//! The Projector's narration, the Persona stage's continuation, and the judge that measures them: one tool-less -//! connector call each. +//! The Projector's narration, the Persona stage's turn, and the judge that measures them: one tool-less +//! connector call each; and `KitModel::step`, the one call that hands back tool calls (the agent's, `agent`). //! //! `KitModel` is the stream organ's `KitProjector`, copied here when the stream was parked //! (`persona-only-divergence-parked`), so the Projector has one caller on the connector. @@ -12,8 +12,8 @@ use std::time::Duration; use anyhow::{Result, anyhow, bail}; use chrono::Utc; use ghostlight_persona_projection::{PersonaPrompt, build_persona_prompt}; -use model_connector::{ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, Refusal, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome}; -use serde::Serialize; +use model_connector::{CacheRetention, ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, Refusal, StopReason, ToolDefinition, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome}; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use super::select::{Forms, Packet, TurnKind, capitalized, named_pronouns, voiced}; @@ -89,7 +89,7 @@ pub struct Answer { } /// One turn's tokens, by the model that ran it, as the connector's receipt reports them. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Spent { pub model: String, pub input_tokens: u64, @@ -117,13 +117,48 @@ pub fn connector_key(credentials: &Path) -> Result { Ok(key.trim().to_owned()) } -/// One tool-less connector turn by `caller` (her instance). Loopback only, as the kit is. Each call is its own -/// conversation: nothing is carried from one to the next. The model is the tuning's, named per call. +/// One connector call by `caller` (her instance). Loopback only, as the kit is. Each call is its own request: the +/// conversation it carries is the caller's, and nothing is held here between calls. `ask` is its tool-less turn; `step` +/// is the one call that hands back tool calls, the agent's (`agent`). pub struct KitModel { client: ConnectorClient, caller: String, } +/// One tool call the model asked for, as the connector's transcript names it. `arguments` is the model's JSON text, +/// unread here: the executor that owns the tool parses it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ToolCall { + pub call_id: String, + pub name: String, + pub arguments: String, +} + +/// One request of `KitModel::step`. `input` is the whole conversation, ending on user text or on a tool result; `tools` +/// may be empty, which makes the turn tool-less. `retention` asks the provider to cache the input's prefix. +pub struct StepRequest<'a> { + pub request_id: &'a str, + pub conversation_id: &'a str, + pub model: &'a str, + pub instructions: &'a str, + pub tools: &'a [ToolDefinition], + pub input: Vec, + pub retention: Option, + /// A JSON Schema object: a schema turn, answered with the structured output alone. + pub schema: Option<&'a str>, +} + +/// What one call handed back: the items it adds to the conversation, verbatim and in order (text, tool calls and the +/// reasoning states, replayed as they came), the text and the tool calls on their own, why it stopped, and what it cost. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Stepped { + pub items: Vec, + pub text: String, + pub calls: Vec, + pub stop: StopReason, + pub usage: Spent, +} + impl KitModel { /// `endpoint` is the kit's loopback address; `connection_key` is the caller's key, read by the binary and never printed. pub fn open(endpoint: SocketAddr, connection_key: String, caller: &str, timeout: Duration) -> Result { @@ -136,38 +171,59 @@ impl KitModel { } impl KitModel { - /// One connector turn of `model` over `input`: its text. - fn run(&self, request_id: &str, model: &str, input: Vec, schema: Option<&str>) -> std::result::Result { - let mut request = ProviderRequest::new(request_id, request_id, model, INSTRUCTIONS, MAX_OUTPUT_TOKENS); - let native: Vec = input.iter().flat_map(|item| match item { - InputItem::UserText { text } | InputItem::AssistantText { text } => text.as_bytes().to_vec(), - _ => Vec::new(), - }).collect(); - request.input = input; + /// One connector call, whatever the model stopped on: a stop other than `EndTurn` is an answer here, with its `stop`, + /// for the caller to read. Tool choice is `auto`: `required` is refused on the models she runs. A refusal, a fault + /// before the provider and a provider failure are `Failed`, with the usage the connector reported. + pub fn step(&self, request: StepRequest<'_>) -> std::result::Result { + let model = request.model; + let native: Vec = request + .input + .iter() + .flat_map(|item| match item { + InputItem::UserText { text } | InputItem::AssistantText { text } => text.as_bytes().to_vec(), + InputItem::ToolCall { arguments, .. } => arguments.as_bytes().to_vec(), + InputItem::ToolResult { output, .. } => output.as_bytes().to_vec(), + InputItem::ReasoningState { .. } => Vec::new(), + }) + .collect(); + let mut provider = ProviderRequest::new(request.request_id, request.conversation_id, model, request.instructions, MAX_OUTPUT_TOKENS); + provider.input = request.input; + provider.tools = request.tools.to_vec(); + provider.cache_retention = request.retention; // The claude connector passes it as `--json-schema` and returns the structured output alone; a schema turn // hands out no resume handle, which no schema stage here needs. - request.output_schema_json = schema.map(str::to_owned); - request.reasoning_effort = Some(ReasoningEffort::Low); + provider.output_schema_json = request.schema.map(str::to_owned); + provider.reasoning_effort = Some(ReasoningEffort::Low); let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS; - let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(&native).into(), request).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?; + let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(&native).into(), provider).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?; let result = self.client.execute(&invocation).map_err(|fault| Failed { reason: format!("the connector did not answer: {fault}"), outage: client_outage(&fault), usage: None })?; - match result.disposition { - TransportDisposition::Refused(reason) => Err(Failed { reason: format!("the connector refused the call: {reason:?}"), outage: refusal_outage(&reason), usage: None }), - TransportDisposition::Transported { events, receipt } => match receipt.outcome { - TransportOutcome::Completed { stop_reason: StopReason::EndTurn, usage, .. } => { - let mut text = String::new(); + match &result.disposition { + TransportDisposition::Refused(reason) => Err(Failed { reason: format!("the connector refused the call: {reason:?}"), outage: refusal_outage(reason), usage: None }), + TransportDisposition::Transported { events, receipt } => match &receipt.outcome { + TransportOutcome::Completed { stop_reason, usage, .. } => { + let (mut text, mut calls) = (String::new(), Vec::new()); for event in events { - if let TransportEventPayload::TextDelta { text: delta } = event.payload { - text.push_str(&delta); + match &event.payload { + TransportEventPayload::TextDelta { text: delta } => text.push_str(delta), + TransportEventPayload::ToolCall { call_id, name, arguments } => calls.push(ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone() }), + TransportEventPayload::ReasoningState { .. } => {} } } - Ok(Answer { text, usage: Some(spent(model, &usage)) }) + Ok(Stepped { items: result.transcript_items(), text, calls, stop: *stop_reason, usage: spent(model, usage) }) } - TransportOutcome::Completed { stop_reason, usage, .. } => Err(Failed { reason: format!("the model's turn ended early: {stop_reason:?}"), outage: false, usage: Some(spent(model, &usage)) }), - TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), outage: failure_outage(&kind), usage: usage.as_ref().map(|usage| spent(model, usage)) }), + TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), outage: failure_outage(kind), usage: usage.as_ref().map(|usage| spent(model, usage)) }), }, } } + + /// A tool-less turn that must end: `step` with no tools, and any other stop is a failure that keeps its usage. + fn run(&self, request_id: &str, model: &str, input: Vec, schema: Option<&str>) -> std::result::Result { + let stepped = self.step(StepRequest { request_id, conversation_id: request_id, model, instructions: INSTRUCTIONS, tools: &[], input, retention: None, schema })?; + if stepped.stop != StopReason::EndTurn || !stepped.calls.is_empty() { + return Err(Failed { reason: format!("the model's turn ended early: {:?}", stepped.stop), outage: false, usage: Some(stepped.usage) }); + } + Ok(Answer { text: stepped.text, usage: Some(stepped.usage) }) + } } impl Model for KitModel { diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index c807875..71a4b13 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1025,6 +1025,58 @@ fn kit(backend: Arc, allowed: &str) -> (KitModel, tempfile::TempDir) { (KitModel::open(endpoint, KIT_KEY.into(), INSTANCE, Duration::from_secs(5)).unwrap(), root) } +/// The agent's call over a real kit: the request carries the tools, the cache retention and `auto` choice, and a model that +/// asks for a tool comes back as its calls, its stop and the items to replay, where `ask` would call it a failure. +#[test] +fn a_kit_step_hands_back_tool_calls_and_the_items_to_replay() { + struct Calling { + seen: Mutex>, + } + impl ProviderBackend for Calling { + fn ready(&self) -> Result<(), &'static str> { + Ok(()) + } + fn provider(&self) -> &str { + "anthropic-messages" + } + fn execute(&self, call: &ProviderCall) -> TransportResult { + self.seen.lock().unwrap().push(call.request().clone()); + let usage = Usage { input_tokens: 3, cache_read_tokens: 2, cache_write_tokens: 1, output_tokens: 4, reasoning_tokens: None }; + let events = vec![ + TransportEvent { sequence: 0, payload: TransportEventPayload::TextDelta { text: "Let me say it.".into() } }, + TransportEvent { sequence: 1, payload: TransportEventPayload::ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() } }, + ]; + call.transported(events, TransportOutcome::Completed { provider_response_id: Some("msg-1".into()), stop_reason: StopReason::ToolUse, usage }) + } + } + let backend = Arc::new(Calling { seen: Mutex::default() }); + let root = tempfile::tempdir().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = listener.local_addr().unwrap(); + let admission = CallerAdmission::new(INSTANCE, KIT_KEY, 1, [KIT_MODEL.to_owned()], 2, 64 * 1024, 4096).unwrap(); + let limits = ServeLimits { max_frame_bytes: 512 * 1024, max_connections: 8, socket_timeout_ms: 5000, max_expiry_skew_ms: 300_000 }; + let store = root.path().join("replay.cc"); + let served = Arc::clone(&backend); + std::thread::spawn(move || serve_kit(listener, limits, vec![admission], &store, served)); + let model = KitModel::open(endpoint, KIT_KEY.into(), INSTANCE, Duration::from_secs(5)).unwrap(); + + let tools = [model_connector::ToolDefinition { name: "say".into(), description: "Say a line.".into(), parameters_json: "{\"type\":\"object\"}".into() }]; + let input = vec![InputItem::UserText { text: "She means to answer.".into() }]; + let stepped = model.step(StepRequest { request_id: "agent-1", conversation_id: "agent-c", model: KIT_MODEL, instructions: "You act for her.", tools: &tools, input: input.clone(), retention: Some(model_connector::CacheRetention::Long), schema: None }).unwrap(); + assert_eq!((stepped.stop, stepped.text.as_str()), (StopReason::ToolUse, "Let me say it.")); + assert_eq!(stepped.calls, [ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() }]); + assert_eq!(stepped.items, [InputItem::AssistantText { text: "Let me say it.".into() }, InputItem::ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() }]); + assert_eq!(stepped.usage, Spent { model: KIT_MODEL.into(), input_tokens: 3, output_tokens: 4, cache_read_tokens: 2, cache_write_tokens: 1, reasoning_tokens: None }); + { + let seen = backend.seen.lock().unwrap(); + assert_eq!((seen[0].tools.clone(), seen[0].tool_choice, seen[0].cache_retention, seen[0].conversation_id.as_str()), (tools.to_vec(), model_connector::ToolChoice::Auto, Some(model_connector::CacheRetention::Long), "agent-c")); + assert_eq!(seen[0].input, input); + } + // The tool-less turns have no use for a tool call: the same answer is a named failure there, with its usage. + let failed = model.ask("id-ask", KIT_MODEL, "p", None).unwrap_err(); + assert!(failed.reason.contains("ended early") && failed.usage.is_some(), "{failed:?}"); +} + #[test] fn a_kit_refusal_or_a_cut_short_turn_is_a_fault() { let backend = Scripted::ending(StopReason::EndTurn, &["Never said."]); diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index a37b265..3ae17cd 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -259,7 +259,7 @@ mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < C mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; } mind_body::projection: pub trait PersonaStore : PersonaSource { fn put (& self , state : & Value , expected_updated_at : Option < & str > , session : & str) -> Result < Put > ; } mind_body::projection: pub use domain :: { DomainFacts , DomainSource , HttpForge , MindDomain } ; -mind_body::projection: pub use narrate :: { Answer , Failed , KitModel , Model , Spent , connector_key } ; +mind_body::projection: pub use narrate :: { Answer , Failed , KitModel , Model , Spent , StepRequest , Stepped , ToolCall , connector_key } ; mind_body::projection: pub use read :: { LiveReads , ReadFailure , ReadFixture , ReadRequest , ReadSource } ; mind_body::projection: pub use select :: TurnKind ; mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ; @@ -298,13 +298,17 @@ mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Resul mind_body::projection::narrate: impl Failed mind_body::projection::narrate: impl KitModel mind_body::projection::narrate: impl KitModel: fn open (endpoint : SocketAddr , connection_key : String , caller : & str , timeout : Duration) -> Result < Self > +mind_body::projection::narrate: impl KitModel: fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed > mind_body::projection::narrate: impl Model for KitModel mind_body::projection::narrate: impl std :: fmt :: Display for Failed mind_body::projection::narrate: pub trait Model { fn ask (& self , request_id : & str , model : & str , prompt : & str , schema : Option < & str >) -> std :: result :: Result < Answer , Failed > ; } mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[text: String, usage: Option < Spent >] mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, outage: bool, usage: Option < Spent >] mind_body::projection::narrate: struct KitModel pub-fields[] -mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >] +mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >] +mind_body::projection::narrate: struct StepRequest< 'a > pub-fields[request_id: & 'a str, conversation_id: & 'a str, model: & 'a str, instructions: & 'a str, tools: & 'a [ToolDefinition], input: Vec < InputItem >, retention: Option < CacheRetention >, schema: Option < & 'a str >] +mind_body::projection::narrate: struct Stepped # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[items: Vec < InputItem >, text: String, calls: Vec < ToolCall >, stop: StopReason, usage: Spent] +mind_body::projection::narrate: struct ToolCall # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[call_id: String, name: String, arguments: String] mind_body::projection::outcome: impl Outcome mind_body::projection::outcome: impl Part mind_body::projection::outcome: impl Refusal