Add direct console Responses integration and namespace replay
This commit is contained in:
@@ -17,6 +17,7 @@ use crate::{
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub model: Option<String>,
|
||||
pub worker: Arc<RwLock<WorkerStatus>>,
|
||||
pub tokenizer: Option<Arc<Tokenizer>>,
|
||||
pub generation: Option<mpsc::Sender<GenerationCommand>>,
|
||||
@@ -26,6 +27,7 @@ pub struct AppState {
|
||||
impl Default for AppState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
model: None,
|
||||
worker: Arc::new(RwLock::new(WorkerStatus::default())),
|
||||
tokenizer: None,
|
||||
generation: None,
|
||||
@@ -42,6 +44,7 @@ struct HealthResponse {
|
||||
#[derive(Serialize)]
|
||||
struct StatusResponse {
|
||||
service: &'static str,
|
||||
model: Option<String>,
|
||||
version: &'static str,
|
||||
worker: WorkerState,
|
||||
ready: bool,
|
||||
@@ -72,7 +75,10 @@ async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusRespons
|
||||
} else {
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
};
|
||||
(code, Json(status_body(worker, inference_ready)))
|
||||
(
|
||||
code,
|
||||
Json(status_body(worker, inference_ready, state.model)),
|
||||
)
|
||||
}
|
||||
|
||||
async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
|
||||
@@ -80,12 +86,17 @@ async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
|
||||
let inference_ready = worker.state == WorkerState::Ready
|
||||
&& state.tokenizer.is_some()
|
||||
&& state.generation.is_some();
|
||||
Json(status_body(worker, inference_ready))
|
||||
Json(status_body(worker, inference_ready, state.model))
|
||||
}
|
||||
|
||||
fn status_body(worker: WorkerStatus, inference_ready: bool) -> StatusResponse {
|
||||
fn status_body(
|
||||
worker: WorkerStatus,
|
||||
inference_ready: bool,
|
||||
model: Option<String>,
|
||||
) -> StatusResponse {
|
||||
StatusResponse {
|
||||
service: "strata-control",
|
||||
model,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
worker: worker.state,
|
||||
ready: inference_ready,
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::worker::WorkerConfig;
|
||||
|
||||
pub struct Config {
|
||||
pub bind: SocketAddr,
|
||||
pub model: Option<String>,
|
||||
pub worker: Option<WorkerConfig>,
|
||||
pub tokenizer_dir: Option<PathBuf>,
|
||||
}
|
||||
@@ -14,6 +15,7 @@ pub struct Config {
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileConfig {
|
||||
bind: Option<String>,
|
||||
model: Option<String>,
|
||||
engine: Option<FileEngine>,
|
||||
}
|
||||
|
||||
@@ -96,8 +98,22 @@ impl Config {
|
||||
if worker.is_none() && tokenizer_dir.is_some() {
|
||||
return Err("tokenizer_dir requires an engine executable".into());
|
||||
}
|
||||
let model = optional_env("STRATA_MODEL_ID")?.or(file.model);
|
||||
if model.as_ref().is_some_and(|id| {
|
||||
id.is_empty()
|
||||
|| id.len() > 180
|
||||
|| !id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
|
||||
}) {
|
||||
return Err(
|
||||
"model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
bind,
|
||||
model,
|
||||
worker,
|
||||
tokenizer_dir,
|
||||
})
|
||||
|
||||
@@ -21,6 +21,7 @@ pub mod model;
|
||||
pub mod model_pipeline;
|
||||
pub mod prepare_preview;
|
||||
pub mod prompt;
|
||||
mod response_tools;
|
||||
pub mod responses;
|
||||
pub mod stream_parts;
|
||||
pub mod tensor_export;
|
||||
|
||||
@@ -730,7 +730,10 @@ fn print_tensor_index(path: &Path, hash: bool) -> Result<(), Box<dyn std::error:
|
||||
async fn serve() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = Config::load()?;
|
||||
let listener = tokio::net::TcpListener::bind(config.bind).await?;
|
||||
let mut state = app::AppState::default();
|
||||
let mut state = app::AppState {
|
||||
model: config.model.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(path) = config.tokenizer_dir.as_deref() {
|
||||
state.tokenizer = Some(Arc::new(tokenizer::Tokenizer::from_assets(path)?));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Reversible namespace lowering for Qwen's flat function template.
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub struct Catalog {
|
||||
pub flat: Vec<Value>,
|
||||
identities: HashMap<String, (String, Option<String>)>,
|
||||
}
|
||||
|
||||
pub fn alias(name: &str, namespace: Option<&str>) -> Result<String, &'static str> {
|
||||
fn valid(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|
||||
}
|
||||
if !valid(name) || namespace.is_some_and(|value| !valid(value)) {
|
||||
return Err(
|
||||
"tool and namespace names require 1..64 ASCII letters, digits, hyphens or underscores",
|
||||
);
|
||||
}
|
||||
Ok(match namespace {
|
||||
None => name.to_owned(),
|
||||
Some(namespace) => format!(
|
||||
"ns_{}",
|
||||
hex::encode(Sha256::digest(format!("{namespace}/{name}")))[..24].to_owned()
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
pub fn new(tools: &[Value]) -> Result<Self, &'static str> {
|
||||
let mut catalog = Self {
|
||||
flat: Vec::new(),
|
||||
identities: HashMap::new(),
|
||||
};
|
||||
let mut namespaces = std::collections::HashSet::new();
|
||||
for tool in tools {
|
||||
if tool["type"] == "namespace" {
|
||||
let namespace = tool["name"].as_str().ok_or("namespace needs a name")?;
|
||||
alias(namespace, None)?;
|
||||
if !namespaces.insert(namespace) {
|
||||
return Err("duplicate namespace");
|
||||
}
|
||||
let children = tool["tools"].as_array().ok_or("namespace needs tools")?;
|
||||
for child in children {
|
||||
catalog.add(child, Some(namespace))?;
|
||||
}
|
||||
} else {
|
||||
catalog.add(tool, None)?;
|
||||
}
|
||||
}
|
||||
Ok(catalog)
|
||||
}
|
||||
|
||||
fn add(&mut self, tool: &Value, namespace: Option<&str>) -> Result<(), &'static str> {
|
||||
if tool["type"] != "function" {
|
||||
return Err("only function tools and function namespaces are supported");
|
||||
}
|
||||
let name = tool["name"].as_str().ok_or("function needs a name")?;
|
||||
let alias = alias(name, namespace)?;
|
||||
if self
|
||||
.identities
|
||||
.insert(
|
||||
alias.clone(),
|
||||
(name.to_owned(), namespace.map(str::to_owned)),
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
return Err("duplicate tool identity or alias collision");
|
||||
}
|
||||
let mut flat = tool.clone();
|
||||
flat["name"] = Value::String(alias);
|
||||
if let Some(namespace) = namespace {
|
||||
flat["description"] = Value::String(format!(
|
||||
"{namespace}.{name}\n{}",
|
||||
tool["description"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
self.flat.push(flat);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restore(&self, item: &mut Value) -> Result<(), String> {
|
||||
let name = item["name"].as_str().ok_or("tool item needs a name")?;
|
||||
let (name, namespace) = self
|
||||
.identities
|
||||
.get(name)
|
||||
.ok_or("undeclared tool identity")?;
|
||||
item["name"] = Value::String(name.clone());
|
||||
if let Some(namespace) = namespace {
|
||||
item["namespace"] = Value::String(namespace.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+216
-17
@@ -26,6 +26,7 @@ use tokio::sync::{RwLock, mpsc, oneshot};
|
||||
use crate::{
|
||||
app::AppState,
|
||||
prompt::{self, Effort, Message, Role},
|
||||
response_tools::Catalog,
|
||||
tokenizer::Tokenizer,
|
||||
tool_output::{self, Incremental, Segment},
|
||||
wire::{Event, Finish, Generate},
|
||||
@@ -130,6 +131,10 @@ pub struct CreateRequest {
|
||||
pub truncation: Option<String>,
|
||||
pub metadata: Option<Map<String, Value>>,
|
||||
pub store: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub include: Vec<String>,
|
||||
pub prompt_cache_key: Option<String>,
|
||||
pub client_metadata: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
@@ -203,8 +208,23 @@ impl CreateRequest {
|
||||
}
|
||||
}
|
||||
reasoning_effort(self)?;
|
||||
if self
|
||||
.include
|
||||
.iter()
|
||||
.any(|field| field != "reasoning.encrypted_content")
|
||||
{
|
||||
return Err(("include", "unsupported optional response field"));
|
||||
}
|
||||
if self
|
||||
.prompt_cache_key
|
||||
.as_ref()
|
||||
.is_some_and(|key| key.len() > 512)
|
||||
{
|
||||
return Err(("prompt_cache_key", "cache key exceeds 512 bytes"));
|
||||
}
|
||||
let catalog = Catalog::new(&self.tools).map_err(|message| ("tools", message))?;
|
||||
let mut names = HashSet::new();
|
||||
for tool in &self.tools {
|
||||
for tool in &catalog.flat {
|
||||
let Some(name) = tool.get("name").and_then(Value::as_str) else {
|
||||
return Err(("tools", "only named function tools are supported"));
|
||||
};
|
||||
@@ -273,6 +293,19 @@ pub async fn create(
|
||||
message,
|
||||
);
|
||||
}
|
||||
if state
|
||||
.model
|
||||
.as_ref()
|
||||
.is_some_and(|model| model != &request.model)
|
||||
{
|
||||
return api_error(
|
||||
StatusCode::NOT_FOUND,
|
||||
"invalid_request_error",
|
||||
"model_not_found",
|
||||
Some("model"),
|
||||
"the requested model is not served by this runtime",
|
||||
);
|
||||
}
|
||||
if state.worker.read().await.state != WorkerState::Ready {
|
||||
return api_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
@@ -355,9 +388,22 @@ pub async fn create(
|
||||
);
|
||||
}
|
||||
};
|
||||
let remaining = state
|
||||
.worker
|
||||
.read()
|
||||
.await
|
||||
.max_context
|
||||
.map(|context| {
|
||||
context
|
||||
.saturating_sub(token_ids.len())
|
||||
.min(u32::MAX as usize) as u32
|
||||
})
|
||||
.unwrap_or(32768);
|
||||
let generate = Generate {
|
||||
token_ids,
|
||||
max_new: request.max_output_tokens.unwrap_or(1024),
|
||||
max_new: request
|
||||
.max_output_tokens
|
||||
.unwrap_or(32768.min(remaining).max(1)),
|
||||
temperature: request.temperature,
|
||||
top_p: request.top_p,
|
||||
};
|
||||
@@ -557,7 +603,8 @@ fn parse_output_items(
|
||||
deltas: vec![output],
|
||||
}]);
|
||||
}
|
||||
let mut items = tool_output::parse_complete(&output, &request.tools)?
|
||||
let catalog = Catalog::new(&request.tools)?;
|
||||
let mut items = tool_output::parse_complete(&output, &catalog.flat)?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, segment)| match segment {
|
||||
@@ -852,6 +899,12 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("function call needs name")?;
|
||||
let namespace = match item.get("namespace") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(value)) => Some(value.as_str()),
|
||||
_ => return Err("function namespace must be a string".into()),
|
||||
};
|
||||
let name = crate::response_tools::alias(name, namespace)?;
|
||||
if call_id.is_empty()
|
||||
|| name.is_empty()
|
||||
|| !name.bytes().all(|byte| {
|
||||
@@ -897,10 +950,22 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("tool output needs call_id")?;
|
||||
let output = item
|
||||
.get("output")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("tool output needs text")?;
|
||||
let output = match item.get("output") {
|
||||
Some(Value::String(text)) => text.clone(),
|
||||
Some(Value::Array(parts)) => parts
|
||||
.iter()
|
||||
.map(|part| {
|
||||
if part["type"] != "input_text" {
|
||||
return Err(
|
||||
"tool output supports only input_text content parts",
|
||||
);
|
||||
}
|
||||
part["text"].as_str().ok_or("tool output part needs text")
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join("\n"),
|
||||
_ => return Err("tool output needs text or input_text parts".into()),
|
||||
};
|
||||
if !calls.iter().any(|(id, _)| id == call_id)
|
||||
|| outputs.iter().any(|(id, _)| id == call_id)
|
||||
{
|
||||
@@ -939,6 +1004,10 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
|
||||
);
|
||||
}
|
||||
}
|
||||
// The pinned Qwen template only accepts leading instruction messages.
|
||||
// Keep all instruction text and its order/authority; never demote a late
|
||||
// developer instruction (including approval criteria) into user content.
|
||||
owned.sort_by_key(|(role, _, _)| !matches!(role, Role::System | Role::Developer));
|
||||
let messages = owned
|
||||
.iter()
|
||||
.map(|(role, content, reasoning)| Message {
|
||||
@@ -950,7 +1019,7 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
|
||||
prompt::render_with_tools(
|
||||
&messages,
|
||||
reasoning_effort(request).map_err(|(_, message)| message.to_owned())?,
|
||||
&request.tools,
|
||||
&Catalog::new(&request.tools)?.flat,
|
||||
)
|
||||
.map_err(str::to_owned)
|
||||
}
|
||||
@@ -1380,10 +1449,23 @@ impl ToolStream {
|
||||
self.finish_text(false).await?;
|
||||
let index = self.items.len();
|
||||
let item_id = format!("fc_{}_{}", &self.response_id[5..], index);
|
||||
self.event("response.output_item.added", json!({"response_id":self.response_id,"output_index":index,"item":{"id":item_id,"type":"function_call","status":"in_progress","call_id":call_id,"name":name,"arguments":""}})).await?;
|
||||
let catalog = Catalog::new(&request.tools)?;
|
||||
let mut pending = json!({"id":item_id,"type":"function_call","status":"in_progress","call_id":call_id,"name":name,"arguments":""});
|
||||
catalog.restore(&mut pending)?;
|
||||
self.event(
|
||||
"response.output_item.added",
|
||||
json!({"response_id":self.response_id,"output_index":index,"item":pending}),
|
||||
)
|
||||
.await?;
|
||||
self.event("response.function_call_arguments.delta", json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"delta":arguments})).await?;
|
||||
self.event("response.function_call_arguments.done", json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"arguments":arguments})).await?;
|
||||
self.event("response.output_item.done", json!({"response_id":self.response_id,"output_index":index,"item":{"id":item_id,"type":"function_call","status":"completed","call_id":call_id,"name":name,"arguments":arguments}})).await?;
|
||||
let mut completed = json!({"id":item_id,"type":"function_call","status":"completed","call_id":call_id,"name":name,"arguments":arguments});
|
||||
catalog.restore(&mut completed)?;
|
||||
self.event(
|
||||
"response.output_item.done",
|
||||
json!({"response_id":self.response_id,"output_index":index,"item":completed}),
|
||||
)
|
||||
.await?;
|
||||
self.items.push(OutputItem::FunctionCall {
|
||||
name,
|
||||
call_id,
|
||||
@@ -1443,7 +1525,8 @@ fn stream_live_tools(
|
||||
tokenizer.special_id("<|im_end|>"),
|
||||
tokenizer.special_id("<|endoftext|>"),
|
||||
];
|
||||
let mut parser = Incremental::new(&request.tools);
|
||||
let catalog = Catalog::new(&request.tools).expect("validated tools");
|
||||
let mut parser = Incremental::new(&catalog.flat);
|
||||
let mut pending_bytes = Vec::new();
|
||||
let mut text_ended = false;
|
||||
let mut done = None;
|
||||
@@ -1793,8 +1876,9 @@ impl ResponseTrace {
|
||||
let mut all_text = String::new();
|
||||
let mut has_text = false;
|
||||
let mut call_ids = HashSet::new();
|
||||
let allowed_tools: HashSet<&str> = request
|
||||
.tools
|
||||
let catalog = Catalog::new(&request.tools)?;
|
||||
let allowed_tools: HashSet<&str> = catalog
|
||||
.flat
|
||||
.iter()
|
||||
.filter_map(|tool| tool.get("name").and_then(Value::as_str))
|
||||
.collect();
|
||||
@@ -1869,7 +1953,8 @@ impl ResponseTrace {
|
||||
return Err("function call_id must be unique".to_owned());
|
||||
}
|
||||
let item_id = format!("fc_{}_{}", &id[5..], index);
|
||||
let pending = json!({"id": item_id, "type": "function_call", "status": "in_progress", "call_id": call_id, "name": name, "arguments": ""});
|
||||
let mut pending = json!({"id": item_id, "type": "function_call", "status": "in_progress", "call_id": call_id, "name": name, "arguments": ""});
|
||||
catalog.restore(&mut pending)?;
|
||||
emitter.push(
|
||||
"response.output_item.added",
|
||||
json!({"response_id": id, "output_index": index, "item": pending}),
|
||||
@@ -1884,8 +1969,8 @@ impl ResponseTrace {
|
||||
if !parsed_arguments.is_object() {
|
||||
return Err("function call arguments must be a JSON object".to_owned());
|
||||
}
|
||||
if let Some(schema) = request
|
||||
.tools
|
||||
if let Some(schema) = catalog
|
||||
.flat
|
||||
.iter()
|
||||
.find(|tool| tool.get("name").and_then(Value::as_str) == Some(name))
|
||||
.and_then(|tool| tool.get("parameters"))
|
||||
@@ -1899,7 +1984,8 @@ impl ResponseTrace {
|
||||
})?;
|
||||
}
|
||||
emitter.push("response.function_call_arguments.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "arguments": arguments}));
|
||||
let done = json!({"id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, "arguments": arguments});
|
||||
let mut done = json!({"id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, "arguments": arguments});
|
||||
catalog.restore(&mut done)?;
|
||||
emitter.push(
|
||||
"response.output_item.done",
|
||||
json!({"response_id": id, "output_index": index, "item": done}),
|
||||
@@ -2063,6 +2149,119 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn console_envelope_namespaced_calls_preserve_identity_and_replay() {
|
||||
let request = make_request(json!({
|
||||
"include":["reasoning.encrypted_content"], "client_metadata":{"session_id":"fixture"},
|
||||
"prompt_cache_key":"fixture", "store":false, "parallel_tool_calls":true,
|
||||
"tool_choice":"auto", "reasoning":{"effort":"none"},
|
||||
"tools":[{"type":"namespace","name":"files","tools":[
|
||||
{"type":"function","name":"read","parameters":{"type":"object",
|
||||
"properties":{"path":{"type":"string"}},"required":["path"],"additionalProperties":false}}
|
||||
]},{"type":"function","name":"read","parameters":{"type":"object"}}]
|
||||
}));
|
||||
request.validate().unwrap();
|
||||
let alias = crate::response_tools::alias("read", Some("files")).unwrap();
|
||||
let prompt = render_request_prompt(&request).unwrap();
|
||||
assert!(prompt.contains(&alias));
|
||||
assert!(prompt.contains("files.read"));
|
||||
let markup = format!(
|
||||
"<tool_call>\n<function={alias}>\n<parameter=path>\nanswer.txt\n</parameter>\n</function>\n</tool_call>"
|
||||
);
|
||||
let items = parse_output_items(&request, markup.clone(), "resp_console").unwrap();
|
||||
let trace = ResponseTrace::build(&request, &items, usage(), "resp_console", 1, 2).unwrap();
|
||||
let output = trace.response["output"][0].clone();
|
||||
assert_eq!(output["name"], "read");
|
||||
assert_eq!(output["namespace"], "files");
|
||||
let mut replay = request.clone();
|
||||
replay.input = json!([{"role":"user","content":"Read the file"},output,
|
||||
{"type":"function_call_output","call_id":output["call_id"],"output":[{"type":"input_text","text":"42"},{"type":"input_text","text":"verified"}]}]);
|
||||
let replayed = render_request_prompt(&replay).unwrap();
|
||||
assert!(replayed.contains(&markup));
|
||||
assert!(replayed.contains("42\nverified"));
|
||||
let (tokenizer, root) = test_tokenizer();
|
||||
let (sender, source) = mpsc::channel(4096);
|
||||
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
|
||||
for id in tokenizer.encode(&markup, false).unwrap() {
|
||||
sender.send(Ok(Event::Token(id))).await.unwrap();
|
||||
}
|
||||
// Inspect the real incremental path before DONE, where callable items escape.
|
||||
loop {
|
||||
let frame = tokio::time::timeout(std::time::Duration::from_secs(2), body.frame())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let event = parse_sse(&frame.into_data().unwrap());
|
||||
if event["type"] == "response.output_item.done" {
|
||||
assert_eq!(event["item"]["name"], "read");
|
||||
assert_eq!(event["item"]["namespace"], "files");
|
||||
assert_eq!(event["item"]["arguments"], "{\"path\":\"answer.txt\"}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
drop(body);
|
||||
sender.closed().await;
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn console_late_approval_instructions_retain_authority_and_content() {
|
||||
let request = make_request(json!({"instructions":"Initial instructions", "input":[
|
||||
{"role":"user","content":"Review the proposed read"},
|
||||
{"role":"developer","content":"Apply the approval criteria strictly"},
|
||||
{"role":"developer","content":"Return the structured decision"}
|
||||
]}));
|
||||
let rendered = render_request_prompt(&request).unwrap();
|
||||
let expected = prompt::render(
|
||||
&[
|
||||
Message {
|
||||
role: Role::System,
|
||||
content: "Initial instructions",
|
||||
reasoning: None,
|
||||
},
|
||||
Message {
|
||||
role: Role::Developer,
|
||||
content: "Apply the approval criteria strictly",
|
||||
reasoning: None,
|
||||
},
|
||||
Message {
|
||||
role: Role::Developer,
|
||||
content: "Return the structured decision",
|
||||
reasoning: None,
|
||||
},
|
||||
Message {
|
||||
role: Role::User,
|
||||
content: "Review the proposed read",
|
||||
reasoning: None,
|
||||
},
|
||||
],
|
||||
Effort::XHigh,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rendered, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn console_tool_catalog_rejects_collisions_and_unknown_features() {
|
||||
for tools in [
|
||||
json!([{"type":"namespace","name":"files","tools":[{"type":"function","name":"read"},{"type":"function","name":"read"}]}]),
|
||||
json!([{"type":"namespace","name":"files","tools":[{"type":"namespace","name":"nested","tools":[]}]}]),
|
||||
json!([{"type":"web_search"}]),
|
||||
] {
|
||||
assert!(make_request(json!({"tools":tools})).validate().is_err());
|
||||
}
|
||||
let alias = crate::response_tools::alias("read", Some("files")).unwrap();
|
||||
let collision = make_request(json!({"tools":[{"type":"function","name":alias},
|
||||
{"type":"namespace","name":"files","tools":[{"type":"function","name":"read"}]}]}));
|
||||
assert!(collision.validate().is_err());
|
||||
assert!(
|
||||
make_request(json!({"include":["unsupported"]}))
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_history_evicts_oldest_response() {
|
||||
let mut history = ResponseHistory::default();
|
||||
|
||||
@@ -121,3 +121,45 @@ summary remains empty, and raw text is never mislabeled as a summary. Explicit
|
||||
The reasoning content and event shapes follow the
|
||||
[Responses raw-reasoning extension](https://developers.openai.com/cookbook/articles/gpt-oss/handle-raw-cot).
|
||||
This local Qwen implementation does not provide OpenAI encrypted reasoning.
|
||||
|
||||
## Console request compatibility
|
||||
|
||||
The native route accepts the console's `include`, `prompt_cache_key`, and
|
||||
string-valued `client_metadata` fields. Only `reasoning.encrypted_content` is
|
||||
accepted in `include`: it is an optional inclusion hint, and this runtime still
|
||||
returns **raw reasoning content, not encrypted content**. Metadata is not added
|
||||
to the model prompt or persisted by the runtime. The cache key is a routing hint;
|
||||
it does not partition the single worker's token-verified prefix cache.
|
||||
|
||||
Function namespaces are lowered to deterministic, collision-checked aliases for
|
||||
the Qwen template. Output items retain the original function `name` and
|
||||
`namespace`, and replay uses the same alias even for historical functions no
|
||||
longer advertised. Duplicate identities, alias collisions, nested namespaces,
|
||||
custom/free-form tools, and server-side web search are rejected. Typed argument
|
||||
validation applies after namespace lowering on both JSON and SSE paths.
|
||||
`function_call_output.output` accepts text or an array of `input_text` parts;
|
||||
parts are joined with a newline. Image/file parts remain unsupported.
|
||||
|
||||
When `max_output_tokens` is omitted, generation reserves up to 32,768 tokens,
|
||||
limited by the remaining context minus the worker's eight-token margin. An
|
||||
explicit output limit is preserved. Configuring `model` (or `STRATA_MODEL_ID`)
|
||||
exposes that identity in `/status` and rejects requests for another model.
|
||||
An omitted configured identity preserves the earlier single-worker API behavior.
|
||||
|
||||
The opt-in console integration is installed with
|
||||
`python3 scripts/install-qwen-native.py`. It adds the `strata-native` backend to
|
||||
`qwen-codex-ctl` and uses a direct Responses provider in `qwen-codex`. This path
|
||||
has no Python serving bridge. The launcher itself remains a local convenience
|
||||
script. Existing selections remain unchanged, and an installation backup is
|
||||
retained. `QWEN_CODEX_PROFILE` selects a separate console profile for tests.
|
||||
|
||||
The native preview requires a loopback connection (an SSH tunnel for a remote
|
||||
GPU) because it does not yet authenticate API clients. Native discovery uses
|
||||
`/status`, requires a configured model identity and a ready 256K worker, and does
|
||||
not synthesize legacy `/props` or `/slots`. `stop` refuses to operate on this
|
||||
externally managed runtime; `logs` identifies its host-side logs.
|
||||
|
||||
Approval/review requests can append developer messages after user input. The
|
||||
native adapter stably coalesces these instruction messages into the leading
|
||||
Qwen system section, preserving their content and order. It does not demote
|
||||
approval instructions to user messages or bypass the console's review step.
|
||||
|
||||
@@ -414,3 +414,34 @@ The isolated worker and temporary uploaded CLI/tokenizer/config were removed
|
||||
after measurement; the latest CLI is retained privately on the laptop.
|
||||
Production profiles remain unchanged. Full console-harness replay and sustained
|
||||
soak still remain; hosted Actions has not run.
|
||||
|
||||
## Native console compatibility, 2026-10-04
|
||||
|
||||
- An isolated local capture of the installed Codex CLI confirmed its actual
|
||||
request fields, function namespaces and optional encrypted-reasoning include.
|
||||
Capture/configs remain private outside Git. The native route now accepts that
|
||||
envelope and preserves namespace identities through prompt, output and replay.
|
||||
- Added optional configured model identity and direct `strata-native` discovery
|
||||
in the installed qwen launcher. The installer is reproducible in
|
||||
`scripts/install-qwen-native.py`; it preserves the selected connection and
|
||||
existing MCP configuration. Native traffic bypasses `responses_bridge.py`.
|
||||
- A real IQ3_S RTX 5090 console smoke run wrote `answer.txt`, read it through the
|
||||
console shell tool and completed successfully: 370 output tokens, including
|
||||
190 reasoning tokens, across two native requests. The file contains exactly
|
||||
two bytes, `42`. The console reported 45,944 cumulative input tokens and
|
||||
23,045 reused tokens. This is a functional check, not a speed comparison.
|
||||
- The first full Three.js/MCP qualification attempt exposed an unsupported
|
||||
array-valued tool result after a successful MCP project search. The runtime
|
||||
rejected it with `tool output needs text`. Added text-part array replay and
|
||||
a regression, retaining the failed attempt privately. A fresh agent run is
|
||||
required after the fix; the failure is not counted as a successful benchmark.
|
||||
- The next attempt reached native approval review, which failed because the
|
||||
pinned prompt renderer required developer messages to be at the beginning.
|
||||
The adapter now stably coalesces instruction messages at the front without
|
||||
dropping their content or demoting their role. Approval remains enabled.
|
||||
The incomplete attempt is retained; it produced no game and is not a pass.
|
||||
- 113 Rust tests, format, and Clippy with warnings denied pass. New regressions
|
||||
cover the captured envelope shape, namespace collision rejection, live
|
||||
namespaced item identity, tool text-part replay, and late approval
|
||||
instructions. A fresh install into a temporary launcher copy matches the
|
||||
installed integration byte-for-byte; a second install is idempotent.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add opt-in direct native Responses support to the installed qwen launcher.
|
||||
|
||||
The existing launcher remains the source of model selection and MCP settings.
|
||||
Patch only known anchors, keep a private backup, and never change its selected
|
||||
connection. Run with --path to target a non-default installation.
|
||||
"""
|
||||
import argparse
|
||||
import ast
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--path', type=Path, default=Path.home()/'.local/share/codex-qwen/qwen_local.py')
|
||||
args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
original = args.path.read_text()
|
||||
marker = '# Strata Next native Responses integration v1'
|
||||
if marker in original:
|
||||
print('Native integration already installed')
|
||||
raise SystemExit(0)
|
||||
text = original
|
||||
|
||||
def replace(old, new):
|
||||
global text
|
||||
if text.count(old) != 1:
|
||||
raise RuntimeError('Launcher changed: expected one anchor: ' + old[:100])
|
||||
text = text.replace(old, new)
|
||||
|
||||
replace("if target['backend'] not in {'llama', 'strata'}", "if target['backend'] not in {'llama', 'strata', 'strata-native'}")
|
||||
replace("def validate_connection(target):\n", '''def validate_connection(target):
|
||||
if target['backend'] == 'strata-native':
|
||||
from urllib.parse import urlsplit
|
||||
parsed = urlsplit(target['url'])
|
||||
if (parsed.scheme != 'http' or parsed.hostname not in {'127.0.0.1', 'localhost', '::1'}
|
||||
or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path):
|
||||
raise RuntimeError('Native preview needs a plain loopback HTTP URL, without credentials or path')
|
||||
if target.get('key_file'):
|
||||
raise RuntimeError('Native loopback preview uses --no-auth; protect remote access with SSH')
|
||||
return
|
||||
''')
|
||||
|
||||
replace("if state.get('backend') != 'strata': return metadata(state['model'])", "if state.get('backend') not in {'strata', 'strata-native'}: return metadata(state['model'])")
|
||||
replace(" models = read('/v1/models')['data']", ''' if selected['backend'] == 'strata-native':
|
||||
from urllib.parse import urlsplit
|
||||
parsed = urlsplit(selected['url'])
|
||||
if parsed.hostname not in {'127.0.0.1', 'localhost', '::1'}:
|
||||
raise RuntimeError('Native preview requires a loopback URL; use an SSH tunnel for the GPU server')
|
||||
observed = read('/status')
|
||||
if observed.get('service') != 'strata-control' or not observed.get('ready'):
|
||||
raise RuntimeError('Native Strata runtime is not ready')
|
||||
model = observed.get('model', '')
|
||||
if not isinstance(model, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,180}', model):
|
||||
raise RuntimeError('Native runtime must configure its model ID')
|
||||
context = observed.get('max_context')
|
||||
if type(context) is not int or context != 262144:
|
||||
raise RuntimeError('Native preview currently qualifies one 256K context')
|
||||
if read('/status') != observed:
|
||||
raise RuntimeError('Native runtime changed during discovery')
|
||||
return dict(backend='strata-native', model=model, context=context, parallel=1,
|
||||
busy=None, vision=False, upstream=selected['url'])
|
||||
models = read('/v1/models')['data']''')
|
||||
replace("def status():\n", """def status():
|
||||
if connection()['backend'] == 'strata-native':
|
||||
live = discover()
|
||||
print(f"Strata Native: {live['model']} · 1 × 256К · Responses API ready")
|
||||
return {}, live
|
||||
""")
|
||||
replace("choices=['strata', 'llama']", "choices=['strata', 'llama', 'strata-native']")
|
||||
replace("target = dict(backend='strata', url=url,", "target = dict(backend=args.backend, url=url,")
|
||||
replace(" elif args.command == 'stop':\n", """ elif args.command == 'stop':
|
||||
if connection()['backend'] == 'strata-native':
|
||||
raise RuntimeError('Native endpoint is externally managed; stop its owning service on the GPU host')
|
||||
""")
|
||||
replace(" elif args.command == 'logs':\n", """ elif args.command == 'logs':
|
||||
if connection()['backend'] == 'strata-native':
|
||||
print('Native runtime logs are on the GPU host; there is no Responses bridge')
|
||||
return
|
||||
""")
|
||||
replace(" if state.get('backend') == 'strata':\n", ''' if state.get('backend') == 'strata-native':
|
||||
overrides = ['--config', 'model_provider="qwen_native"',
|
||||
'--config', 'model_providers.qwen_native.name="Strata Native"',
|
||||
'--config', 'model_providers.qwen_native.wire_api="responses"',
|
||||
'--config', 'model_providers.qwen_native.base_url=' + json.dumps(selected['url'] + '/v1'),
|
||||
'--config', 'model_providers.qwen_native.stream_idle_timeout_ms=900000',
|
||||
'--config', 'web_search="disabled"']
|
||||
offset = len(command) - len(args) if args else len(command)
|
||||
command[offset:offset] = overrides
|
||||
print('Strata Native Responses · direct connection', flush=True)
|
||||
os.execvpe(binary, command, env)
|
||||
if state.get('backend') == 'strata':
|
||||
''')
|
||||
# Environment override keeps test sessions independent of the user's selection.
|
||||
text += '\n' + marker + '\nif os.environ.get("QWEN_CODEX_PROFILE"):\n PROFILE = Path(os.environ["QWEN_CODEX_PROFILE"]).expanduser().resolve()\n'
|
||||
ast.parse(text)
|
||||
backup = args.path.with_name(args.path.name + '.before-native-' + hashlib.sha256(original.encode()).hexdigest()[:12])
|
||||
if not backup.exists():
|
||||
backup.write_text(original)
|
||||
backup.chmod(0o600)
|
||||
fd, temporary = tempfile.mkstemp(prefix='qwen-native-', dir=args.path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as out: out.write(text)
|
||||
os.chmod(temporary, args.path.stat().st_mode & 0o777)
|
||||
os.replace(temporary, args.path)
|
||||
finally:
|
||||
if os.path.exists(temporary): os.unlink(temporary)
|
||||
print('Native launcher installed; previous connection unchanged; backup:', backup)
|
||||
Reference in New Issue
Block a user