Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ repository = "https://github.com/cppalliance/runvil-workshop"
# Workshop links in. All three name one commit, because two commits would
# be two copies of every type the crates share. `version` beside `git`
# keeps cargo-deny's wildcard check quiet.
runvil = { version = "0.3.0", git = "https://github.com/cppalliance/runvil-harness", rev = "ee89d0882ec8cecfcd0159c7f61c6741fceef612" }
harness-gateway-client = { version = "0.3.0", git = "https://github.com/cppalliance/runvil-harness", rev = "ee89d0882ec8cecfcd0159c7f61c6741fceef612" }
plugin-mcp = { version = "0.3.0", git = "https://github.com/cppalliance/runvil-harness", rev = "ee89d0882ec8cecfcd0159c7f61c6741fceef612" }
runvil = { version = "0.3.0", git = "https://github.com/cppalliance/runvil-harness", rev = "5d9c7bf86539401382aa5187c1b1873ceac38fb6" }
harness-gateway-client = { version = "0.3.0", git = "https://github.com/cppalliance/runvil-harness", rev = "5d9c7bf86539401382aa5187c1b1873ceac38fb6" }
plugin-mcp = { version = "0.3.0", git = "https://github.com/cppalliance/runvil-harness", rev = "5d9c7bf86539401382aa5187c1b1873ceac38fb6" }
# The safe layer over the C Plugin contract, version 0.6, from its own
# repository, pinned by commit. Only the library Plugin crates under
# `crates/workshop/` name it, for `export_plugin!`. The commit is the one
Expand Down
56 changes: 42 additions & 14 deletions crates/workshop/server/src/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,17 @@
//! search. Each launch opens a conversation in `workshop-agents` and builds
//! that conversation's one run its own [`RunSetup`]: the conversation's
//! recorder tee on a handle of the run log's [`TursoRecorder`] that names
//! the launched agent, a per-run broker over the server's inference broker
//! ([`broker`]), the stock tokio timer of the Gateway client, and a user,
//! the conversation's operator, so the run holds
//! the launched agent, the server's inference broker ([`broker`]), the
//! stock tokio timer of the Gateway client, a user, the conversation's
//! operator, so the run holds
//! `runvil/user`; the operator's messages reach the run's main chain
//! through the conversation. The run makes its own instance of each Pack
//! through the conversation, and a streaming callback that publishes each
//! live piece of a section's own round into the conversation under the
//! round's id. The run makes its own instance of each Pack
//! it holds and drops them when it ends. The run's model rounds reach the
//! gateway only through its per-run broker, which follows the live gateway
//! binding and sends each round to the dropdown's current pick. Each
//! gateway only through the server's inference broker, which follows the
//! live gateway binding and sends each round to the dropdown's current
//! pick. Each
//! run's filesystem is an in-memory root, with a read-only mount beside it
//! for each of two demos whose switch is on: the language guide, and the
//! machine's C drive (`language_guide`). Both switches are committed as
Expand Down Expand Up @@ -65,20 +68,22 @@ use std::sync::Arc;
use harness_gateway_client::{
GatewayEndpoint, SecretString, TokioTimer, provide_gateway_resources,
};
use runvil::effect::Round;
use runvil::harness::{HostResources, RunId, insert_plugin_dir};
use runvil::plugin::PackRegistry;
use runvil::{Error, ErrorCode, ErrorFact, Host, PromptFinder, RunSetup};
use serde_json::Value;
use workshop_agents::{
Conversation, ConversationId, Conversations, LaunchError, discover_agents, load_agent,
Conversation, ConversationId, Conversations, DeltaKind, LaunchError, discover_agents,
load_agent,
};
use workshop_gateway::GatewayHandles;
use workshop_registry::Registry;
use workshop_run_log::TursoRecorder;
use workshop_support::{Config, ReconnectBackoff};

use bindings::with_host_state;
use broker::{RunBroker, WorkshopBroker};
use broker::WorkshopBroker;
use gateway::{UsableGateway, usable_gateway};
use socket::Receivers;
pub(crate) use state::{SessionsState, register};
Expand Down Expand Up @@ -341,7 +346,7 @@ struct Inner {
/// The run log every run is recorded in, through a handle naming its
/// agent behind each run's tee.
recorder: Arc<TursoRecorder>,
/// The inference broker behind each run's broker.
/// The inference broker every run's setup holds.
broker: WorkshopBroker,
/// What every run shares: the installed Packs each run makes its
/// instances of, the built-ins among them, and the finder that reads
Expand Down Expand Up @@ -462,15 +467,19 @@ impl AgentSessions {
}

/// The setup of `conversation`'s run before the Host state is read:
/// its recorder tee over a run-log handle naming its agent, its broker,
/// the stock tokio timer, its filesystem, and a user, since every
/// conversation has an operator.
/// its recorder tee over a run-log handle naming its agent, the
/// server's inference broker, the stock tokio timer, its filesystem, a
/// user, since every conversation has an operator, and the streaming
/// callback that publishes each live piece into the conversation.
fn setup_for(&self, conversation: &Conversation) -> RunSetup {
let recorder = conversation.recorder(self.inner.recorder.for_agent(conversation.agent()));
let broker = RunBroker::new(self.inner.broker.clone(), conversation.clone());
RunSetup::new(recorder, broker, TokioTimer)
// The broker is a handle, and the setup owns one. The callback is
// `'static`, and the caller still needs the conversation to run
// the run, so the callback takes a handle to it.
RunSetup::new(recorder, self.inner.broker.clone(), TokioTimer)
.vfs(language_guide::run_vfs())
.has_user(true)
.streaming(live_pieces(conversation.clone()))
}

/// The running conversation with this id, when one exists: how a
Expand All @@ -496,6 +505,25 @@ impl AgentSessions {
}
}

/// The run's streaming callback: publishes each live piece of a section's
/// own round into `conversation`, under the round's id. It sends on the
/// conversation's own broadcast and returns, and it calls nothing of the
/// Harness.
fn live_pieces(
conversation: Conversation,
) -> impl Fn(Round, runvil::harness::Delta) + Send + Sync + 'static {
move |round, piece| {
let (kind, content) = match piece {
runvil::harness::Delta::Text(text) => (DeltaKind::Text, text),
runvil::harness::Delta::Reasoning(text) => (DeltaKind::Reasoning, text),
// The enum is non-exhaustive across the crate seam; any other
// piece has no delta kind and stays unshown.
_ => return,
};
conversation.publish_delta(round.id, kind, content);
}
}

/// A refused agent launch, relayed to the client as an error frame.
#[derive(Debug, thiserror::Error)]
enum LaunchRefusal {
Expand Down
85 changes: 21 additions & 64 deletions crates/workshop/server/src/agents/broker-tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
//! with no URL or key in the message, after a replacement binding is
//! published the next round and the next model list reach the
//! replacement, a model list waits while the menu's catalog holds no
//! chat-capable model, a streaming round hands its pieces to its callback
//! and answers whole, a run's broker streams only its section's own
//! rounds into the conversation, and the window comparison flags a pick
//! whose context window is smaller than the round's binding's.
//! chat-capable model, the broker says it streams, a round hands its
//! pieces to its callback and answers whole, and the window comparison
//! flags a pick whose context window is smaller than the round's
//! binding's.

use std::num::NonZeroU32;
use std::sync::{Arc, Mutex, PoisonError};
Expand All @@ -16,22 +16,20 @@ use axum::Router;
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use harness_gateway_client::StreamDelta;
use runvil::effect::Round;
use runvil::event::ReplyOrigin;
use runvil::harness::InferenceBroker;
use runvil::harness::{Delta, InferenceBroker, PieceSink};
use runvil::ids::RoundId;
use runvil::model::{
CompletionOptions, CompletionResult, Message, ModelBinding, ModelId, ModelInvocation, phrase,
};
use runvil::{Error, ErrorCode};
use serde_json::json;
use workshop_agents::{Conversations, DeltaKind};
use workshop_gateway::{GatewayBinding, GatewayHandles, GatewayHealth};
use workshop_menu::{CatalogBus, MenuBus};
use workshop_registry::{Registration, Registry};

use super::{RunBroker, WorkshopBroker, narrower_pick_window};
use super::{WorkshopBroker, narrower_pick_window};
use crate::app::test_helpers::spawn_gateway;

/// A registry holding gateway handles bound to `base_url` under `key`,
Expand Down Expand Up @@ -121,6 +119,7 @@ async fn round(broker: &WorkshopBroker) -> Result<String, Error> {
Vec::new(),
CompletionOptions::new("m"),
Round::new(RoundId::new(0), ReplyOrigin::Infer),
None,
)
.await?;
match completion.result() {
Expand All @@ -131,20 +130,24 @@ async fn round(broker: &WorkshopBroker) -> Result<String, Error> {

/// Runs one streaming round on `broker` and returns its reply text beside
/// every piece its callback was handed.
async fn streamed_round(broker: &WorkshopBroker) -> (Result<String, Error>, Vec<StreamDelta>) {
let kept: Arc<Mutex<Vec<StreamDelta>>> = Arc::default();
async fn streamed_round(broker: &WorkshopBroker) -> (Result<String, Error>, Vec<Delta>) {
let kept: Arc<Mutex<Vec<Delta>>> = Arc::default();
// The callback moves into the round, so the helper keeps this second
// handle to read what the callback was handed.
let sink = Arc::clone(&kept);
let on_piece: PieceSink = Arc::new(move |piece| {
sink.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(piece);
});
let completion = broker
.chat_streaming(
.chat(
binding(),
vec![Message::user("hi")],
Vec::new(),
CompletionOptions::new("m"),
Arc::new(move |piece| {
sink.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(piece);
}),
Round::new(RoundId::new(0), ReplyOrigin::Chat),
Some(on_piece),
)
.await;
let reply = completion.map(|completion| match completion.result() {
Expand Down Expand Up @@ -196,6 +199,7 @@ async fn a_streaming_round_hands_its_pieces_to_the_callback_and_answers_whole()
let gateway = spawn_gateway(keyed_gateway("first-model", "first-key")).await;
let (registry, _binding, _guard) = registry_with_gateway(&gateway, "first-key");
let broker = WorkshopBroker::new(registry);
assert!(broker.supports_streaming(), "the Workshop broker streams");

let (reply, pieces) = streamed_round(&broker).await;
assert_eq!(
Expand All @@ -205,7 +209,7 @@ async fn a_streaming_round_hands_its_pieces_to_the_callback_and_answers_whole()
);
assert_eq!(
pieces,
[StreamDelta::Text("from first-model".to_owned())],
[Delta::Text("from first-model".to_owned())],
"the reply's one content chunk reaches the callback as it arrives"
);
}
Expand Down Expand Up @@ -285,53 +289,6 @@ async fn a_model_list_waits_until_the_catalog_holds_a_chat_capable_model() {
assert_eq!(models, ["first-model"], "the list is the gateway's own");
}

/// Runs one round of `origin` numbered `id` on a conversation's run
/// broker and returns its reply text.
async fn run_round(broker: &RunBroker, id: u64, origin: ReplyOrigin) -> String {
let completion = broker
.chat(
binding(),
vec![Message::user("hi")],
Vec::new(),
CompletionOptions::new("m"),
Round::new(RoundId::new(id), origin),
)
.await
.expect("the gateway answers");
match completion.result() {
CompletionResult::Text(text) => text.clone(),
other => panic!("the round replies with text: {other:?}"),
}
}

#[tokio::test]
async fn a_sections_round_streams_into_its_conversation_under_the_round_id_and_an_infer_round_does_not()
{
let gateway = spawn_gateway(keyed_gateway("first-model", "first-key")).await;
let (registry, _binding, _guard) = registry_with_gateway(&gateway, "first-key");
let conversation = Conversations::new().open("chat");
let mut deltas = conversation.subscribe_deltas();
let broker = RunBroker::new(WorkshopBroker::new(registry), conversation);

assert_eq!(
run_round(&broker, 4, ReplyOrigin::Infer).await,
"from first-model"
);
assert!(
deltas.try_recv().is_err(),
"a nested infer round streams nothing"
);

assert_eq!(
run_round(&broker, 3, ReplyOrigin::Chat).await,
"from first-model"
);
let delta = deltas.try_recv().expect("the section's round streamed");
assert_eq!(delta.kind, DeltaKind::Text);
assert_eq!(delta.content, "from first-model");
assert_eq!(delta.reply, 3, "the piece carries its round's id");
}

#[test]
fn the_window_comparison_flags_a_pick_smaller_than_the_binding_and_not_an_equal_or_larger_one() {
let models = [
Expand Down
Loading
Loading