Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

refactor(cli): extract the stream-json handshake assembly

thinhlpg26fea1bc9c2f
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 9f109cf62..ef51e22f0 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1836,51 +1836,8 @@ async fn run_agent_loop(
// than from the printer task for exactly that reason: nothing has been
// spawned yet, so "first line" is a property of the code's order rather than
// a race against the run's own events.
- //
- // The tool names come from the same resolution the first turn uses, so the
- // handshake cannot advertise a set the request does not carry.
if format.is_stream_json() {
- let tools = crate::core::agent::r#loop::context_advertised_tools(
- &args.mcp_servers,
- &args.mcp_settings,
- &args.permissions,
- args.project_root.as_deref(),
- args.run_mode,
- args.subagents_enabled,
- args.max_parallel_subagents,
- args.ask_requests.is_some(),
- args.todo_registry.is_some(),
- )
- .await
- .iter()
- .filter_map(|tool| {
- tool.get("function")?
- .get("name")?
- .as_str()
- .map(str::to_string)
- })
- .collect();
- let cwd = match args.project_root.as_deref() {
- Some(root) => root.to_string_lossy().into_owned(),
- None => std::env::current_dir()
- .map(|d| d.to_string_lossy().into_owned())
- .unwrap_or_default(),
- };
- // A run that does not read stdin accepts nothing, and says so: an empty
- // list is a client's answer that there is no reply path, which is more
- // use than an absent field or a list of kinds the run will ignore.
- let input_kinds = if input_format.is_stream_json() {
- INPUT_KINDS.to_vec()
- } else {
- Vec::new()
- };
- print_json_line(&Init::new(
- &session_id,
- &persist.model,
- &cwd,
- tools,
- input_kinds,
- ));
+ print_json_line(&init_record(&args, &session_id, &persist.model, input_format).await);
}
// The client on stdin, when there is one: it owns every permission decision
@@ -2007,6 +1964,55 @@ async fn run_agent_loop(
result.map(|_| ())
}
+/// The `init` handshake of a `--output-format stream-json` run, assembled from
+/// the same parts the run itself uses: the session it saves under, the model it
+/// dispatches to, and the tools its first turn will advertise, so the record
+/// cannot describe a run other than this one.
+async fn init_record(
+ args: &OrchestrationArgs,
+ session_id: &str,
+ model: &str,
+ input_format: InputFormat,
+) -> Init {
+ let tools = crate::core::agent::r#loop::context_advertised_tools(
+ &args.mcp_servers,
+ &args.mcp_settings,
+ &args.permissions,
+ args.project_root.as_deref(),
+ args.run_mode,
+ args.subagents_enabled,
+ args.max_parallel_subagents,
+ args.ask_requests.is_some(),
+ args.todo_registry.is_some(),
+ )
+ .await
+ .iter()
+ .filter_map(tool_name)
+ .collect();
+ // A CLI run always resolves a project root; "." names the process's own
+ // directory for a caller that set none.
+ let cwd = args
+ .project_root
+ .as_deref()
+ .map(|root| root.to_string_lossy().into_owned())
+ .unwrap_or_else(|| ".".to_string());
+ // A run that does not read stdin accepts nothing, and says so: an empty
+ // list is a client's answer that there is no reply path, which is more use
+ // than an absent field or a list of kinds the run will ignore.
+ let input_kinds = if input_format.is_stream_json() {
+ INPUT_KINDS.to_vec()
+ } else {
+ Vec::new()
+ };
+ Init::new(session_id, model, &cwd, tools, input_kinds)
+}
+
+/// A rendered tool schema's name, out of the OpenAI `{"type":"function",
+/// "function":{"name":…}}` shape the advertised array carries.
+fn tool_name(tool: &serde_json::Value) -> Option<String> {
+ Some(tool.get("function")?.get("name")?.as_str()?.to_string())
+}
+
/// Stop reason reported for a run the client ended with an `abort` message, and
/// the error the run itself returns -- never printed, since an abort exits 0.
const ABORTED_BY_CLIENT: &str = "aborted by client";
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index 646130cb8..ed6354403 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -358,30 +358,28 @@ mod tests {
/// the failure mode of a rewording is a test that says so, not a consumer
/// that meets an unknown tag in production.
fn documented_tags_after<'a>(source: &'a str, marker: &str) -> Vec<&'a str> {
- let start = source
- .find(marker)
+ let after_marker = source
+ .split_once(marker)
.unwrap_or_else(|| panic!("the doc comment no longer says {marker:?}"))
- + marker.len();
+ .1;
+ // The list reads "`tag`, `tag`, ... `last`.", so the backtick-separated
+ // segments alternate gap and tag, and a period in a gap is the sentence
+ // boundary that ends it -- the tag before that gap is still in the list.
+ let mut segments = after_marker.split('`');
let mut tags = Vec::new();
- let mut cursor = start;
- // A period between two backticked words ends the list: that is the
- // sentence boundary, and everything past it is other prose.
- while let Some(open) = source[cursor..].find('`').map(|i| cursor + i) {
- if source[cursor..open].contains('.') {
- break;
- }
- let Some(close) = source[open + 1..].find('`').map(|i| open + 1 + i) else {
- break;
- };
- tags.push(&source[open + 1..close]);
- cursor = close + 1;
+ let mut gap = segments.next().unwrap_or_default();
+ while !gap.contains('.') {
+ let Some(tag) = segments.next() else { break };
+ tags.push(tag);
+ // Missing trailing prose means the list ran to the end of the text.
+ gap = segments.next().unwrap_or(".");
}
tags
}
- /// The variant names the enum declares, read from its own source. The enum
- /// body's variants sit at one indentation level, which is what makes them
- /// distinguishable from the fields inside them.
+ /// The variant names the enum declares, read from its own source. Variants
+ /// sit at one indentation level inside the body and their fields sit
+ /// deeper, which is what tells the two apart.
fn declared_variants(source: &str) -> Vec<&str> {
let body = source
.split_once("pub enum StreamEvent {")
@@ -392,15 +390,17 @@ mod tests {
.expect("the enum is unterminated")
.lines()
.filter_map(|line| {
- let name = line.strip_prefix(" ")?;
- if name.starts_with(' ') || name.starts_with("//") || name.starts_with("#[") {
+ // Four spaces is the body's own indent: anything deeper is a
+ // field inside a variant, and anything else is an attribute or
+ // a comment.
+ let rest = line.strip_prefix(" ")?;
+ if rest.starts_with(' ') || rest.starts_with("//") || rest.starts_with("#[") {
return None;
}
- let end = name
- .find(|c: char| !c.is_alphanumeric())
- .unwrap_or(name.len());
- let name = &name[..end];
- (!name.is_empty() && name.starts_with(char::is_uppercase)).then_some(name)
+ let end = rest
+ .find(|c: char| !c.is_alphanumeric() && c != '_')
+ .unwrap_or(rest.len());
+ rest[..end].starts_with(char::is_uppercase).then_some(&rest[..end])
})
.collect()
}