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
2 changes: 2 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions core/continuum-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ name = "forge-custodian"
path = "src/bin/forge_custodian.rs"

[dependencies]
tool-working-set = { path = "../tool-working-set" } # one relevance seam: commands/help ranks a query the way the learned tool head reads relevance
continuum-tool-protocol = { path = "../continuum-tool-protocol" }
tokio.workspace = true
expert-pager-policy = { path = "../expert-pager-policy" }
Expand Down
1 change: 1 addition & 0 deletions core/continuum-core/src/commands/ai/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ fn parse_request(params: &Value) -> Result<TextGenerationRequest, String> {
.json_opt("stop_sequences")
.or_else(|| p.json_opt("stopSequences")),
tools: p.json_opt("tools"),
tail_tools: None,
tool_choice: p.json_opt("tool_choice"),
response_format: None,
active_adapters: p.json_opt("activeAdapters"),
Expand Down
67 changes: 65 additions & 2 deletions core/continuum-core/src/commands/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ pub struct CommandsHelpParams {
#[serde(default)]
#[ts(optional)]
pub name: Option<String>,
/// What you want to do, when you do not know the command's name: the best matches, ranked.
#[serde(default)]
#[ts(optional)]
pub query: Option<String>,
}

#[derive(Debug, Clone, Serialize, TS)]
Expand Down Expand Up @@ -65,8 +69,8 @@ impl ActionCommand for CommandsHelp {
const NATIVE: bool = true; // discovery pair — the on-demand "how do I call this?" tool
const ACCESS: AccessLevel = AccessLevel::AiSafe;
const DESCRIPTION: &'static str =
"Show how to CALL a command: the exact tool-call format to emit + its arguments. \
Pass the command name (e.g. code/read). Use it when unsure how to invoke a tool.";
"Show how to CALL a command: its exact tool-call format + arguments. Pass `name` \
(e.g. code/read), or `query` (what you want to do) to find one.";
type Params = CommandsHelpParams;
type Output = CommandsHelpResult;

Expand All @@ -83,6 +87,11 @@ impl ActionCommand for CommandsHelp {
.filter(|d| is_command_authorized(d.name, trust))
.collect();

// A query → the commands that best match what she wants to do, ranked, one line each.
if let Some(query) = p.query.as_deref().filter(|q| !q.trim().is_empty()).filter(|_| p.name.is_none()) {
return Ok(ranked_matches(query, &authorized));
}

// No name → the INDEX: every command you can call, one line each. This is the
// orientation an agent needs FIRST; erroring here (the old "missing field name")
// dead-ends the very first discovery move.
Expand Down Expand Up @@ -132,11 +141,65 @@ impl ActionCommand for CommandsHelp {

crate::register_stateless_command!(CommandsHelp);

/// The authorized commands whose name and description best match `query`, through the same
/// relevance seam the learned tool head reads (`tool_working_set::relevance`).
fn ranked_matches(query: &str, authorized: &[crate::sdk_codegen::CommandDescriptor]) -> CommandsHelpResult {
use tool_working_set::relevance::{Lexical, Relevance};
use tool_working_set::vocab::{ToolSchema, Vocabulary};
let schemas: Vec<ToolSchema> = authorized
.iter()
.map(|d| ToolSchema { name: d.name.to_string(), description: d.description.to_string(), tokens: 0 })
.collect();
let lines = match Vocabulary::new(schemas) {
Ok(vocab) => {
let relevance = Lexical::new(&vocab).relevance(query);
let mut ranked: Vec<(f32, tool_working_set::ToolId)> =
vocab.ids().map(|tool| (relevance[tool.index()], tool)).filter(|(score, _)| *score > 0.0).collect();
ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
ranked
.into_iter()
.take(crate::sdk_codegen::ai_help::SUGGESTION_WINDOW)
.map(|(_, tool)| format!("- {} — {}", vocab.name(tool), vocab.schema(tool).description))
.collect::<Vec<_>>()
}
Err(refused) => vec![format!("(the registry could not be ranked: {refused})")],
};
let manual = if lines.is_empty() {
format!("No command matches \"{query}\". Call `commands/help` with no arguments for the full index.")
} else {
format!(
"The commands that best match \"{query}\". Call `commands/help` with the `name` you choose for its exact call; \
it is then callable on your next act.\n\n{}",
lines.join("\n")
)
};
CommandsHelpResult {
name: String::new(),
description: format!("commands matching \"{query}\""),
access_level: "ai-safe".to_string(),
manual,
}
}

#[cfg(test)]
mod tests {
use super::*;
use serde_json::{json, Value};

// what this catches: a mind that does not know a verb's name having no way to find it
// once her head no longer lists every verb: a query in her words must reach the verb
// over the LIVE registry, ranked first, within the shared window.
#[test]
fn a_query_in_her_words_ranks_the_verb_she_means_over_the_live_registry() {
let registry = command_registry_live();
let result = ranked_matches("open a pull request on github", &registry);
let names: Vec<&str> = result.manual.lines().filter_map(|l| l.strip_prefix("- ")).map(|l| l.split(" — ").next().unwrap_or(l)).collect(); // unwrap_or: a line without a description is all name
assert!(names.first().is_some_and(|n| n.contains("pr-create")), "{}", result.manual);
assert!(names.len() <= crate::sdk_codegen::ai_help::SUGGESTION_WINDOW);
let none = ranked_matches("zzqx", &registry);
assert!(none.manual.starts_with("No command matches"), "{}", none.manual);
}

// what this catches: an underscored bare guess getting NO suggestion at all, which
// is what let a citizen re-issue `list_cards` 31 times (2026-09-05). Neither
// `commands/list` nor `work/list` shares the category prefix `list_cards` or a whole
Expand Down
2 changes: 2 additions & 0 deletions core/continuum-core/src/commands/models/try_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ async fn run_text_probe(registry: &AdapterRegistry, model_id: &str) -> (bool, Op
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down Expand Up @@ -207,6 +208,7 @@ async fn run_vision_probe(registry: &AdapterRegistry, model_id: &str) -> (bool,
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
1 change: 1 addition & 0 deletions core/continuum-core/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ async fn messages_handler(
repeat_last_n: None,
stop_sequences: req.stop_sequences.clone(),
tools: None, // Tool calls handled by Claude Code, not the local model
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters,
Expand Down
1 change: 1 addition & 0 deletions core/continuum-core/src/modules/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@ async fn call_llm(
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
request_id: None,
user_id: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,11 @@ fn tool_surface_is_a_category_index_plus_discovery_pair() {
// 17238 -> 17298 (PR #5112, 2026-10-16): work/list gains `limit` (default 40,
// claimable first) so a board of 776 cards is never one 198k-char line again;
// one optional field and its one-line doc, measured locally at 17298.
const AGENTIC_SURFACE_CEILING: u32 = 17298;
// 17298 -> 17335 (goal 10 slice 2, card ecd5dff3, 2026-10-24): commands/help gains
// `query`, the way a mind finds a verb by what she wants to do once her learned head no
// longer lists every verb. Its text was cut to one line (it measured 17427 first); the
// 37 left are the param itself, the feature. Measured locally at 17335.
const AGENTIC_SURFACE_CEILING: u32 = 17335;
let surface = faculty.describe_tool_tokens() as u32 + faculty.framing_floor_tokens();
println!("agentic surface: {surface} guard tokens; ceiling {AGENTIC_SURFACE_CEILING}");
assert!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
single_resident_model: false,
dynamic_model_catalog: false,
llamacpp_sampling_extensions: false,
tail_tools: false,
});
let catalog_default = gateway.default_model().to_string();
assert_eq!(gateway.served_model_ids(), vec![catalog_default.clone()]);
Expand Down
6 changes: 6 additions & 0 deletions core/continuum-engine/src/ai/adapter/inference_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,12 @@ pub trait AIProviderAdapter: Send + Sync {
AdapterCapabilities::text_only()
}

/// Whether this adapter's server accepts `tail_tools` (callable verbs outside the rendered
/// head). Default `false`: only a server that declares it gets a learned tool head.
fn accepts_tail_tools(&self) -> bool {
false
}

/// Get API style.
///
/// Default: `Local` (in-process inference). Cloud adapters override
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/ai/heuristic_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,7 @@ mod tests {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
2 changes: 2 additions & 0 deletions core/continuum-engine/src/ai/openai_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ pub struct OpenAICompatibleConfig {
/// `Provider.capabilities.llamacpp_sampling_extensions` (#55) — replaces
/// the `id == "docker-model-runner"` `repeat_penalty` branch.
pub llamacpp_sampling_extensions: bool,
/// The server accepts `tail_tools`. From `Provider.capabilities.tail_tools`.
pub tail_tools: bool,
}

/// What the serving backend told us when we asked it `GET /lora-adapters`.
Expand Down
4 changes: 4 additions & 0 deletions core/continuum-engine/src/ai/openai_adapter/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ impl AIProviderAdapter for OpenAICompatibleAdapter {
&self.config.provider_id
}

fn accepts_tail_tools(&self) -> bool {
self.config.tail_tools
}

/// The live set the daemon's reconcile / `/v1/models` refresh verified
/// (`runtime_models`), sorted for stable output; the catalog default only
/// when nothing has been verified yet. `config.default_model` is a
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/ai/openai_adapter/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ impl OpenAICompatibleAdapter {
single_resident_model: provider.capabilities.single_resident_model,
dynamic_model_catalog: provider.capabilities.dynamic_model_catalog,
llamacpp_sampling_extensions: provider.capabilities.llamacpp_sampling_extensions,
tail_tools: provider.capabilities.tail_tools,
})
}

Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/ai/openai_adapter/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,6 @@ fn test_adapter() -> OpenAICompatibleAdapter {
single_resident_model: false,
dynamic_model_catalog: false,
llamacpp_sampling_extensions: false,
tail_tools: false,
})
}
7 changes: 7 additions & 0 deletions core/continuum-engine/src/ai/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,13 @@ pub struct TextGenerationRequest {
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub tools: Option<Vec<NativeToolSpec>>,
/// Verbs she loaded into the TAIL this epoch: callable natively (the engine's parser and
/// grammar accept them) but never rendered in the head, so the cached prefix is unchanged
/// (goal 10, card ecd5dff3). Their schemas ride the conversation, after the cache point.
/// Sent only to a llama.cpp-family server; one that predates the field ignores it.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub tail_tools: Option<Vec<NativeToolSpec>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub tool_choice: Option<ToolChoice>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ fn req(text: &str) -> TextGenerationRequest {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ mod tests {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ fn req(text: &str) -> RemoteInferenceRequest {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/handle_module/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ fn empty_request() -> TextGenerationRequest {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/handle_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ mod tests {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/llamacpp_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ impl AIProviderAdapter for LlamaCppAdapter {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
2 changes: 2 additions & 0 deletions core/continuum-engine/src/inference/llamacpp_adapter/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ fn text_request(response_format: Option<ResponseFormat>) -> TextGenerationReques
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format,
active_adapters: None,
Expand Down Expand Up @@ -285,6 +286,7 @@ async fn owned_gene_page_in_changes_output() {
repeat_last_n: None,
stop_sequences: None,
tools: None,
tail_tools: None,
tool_choice: None,
response_format: Some(ResponseFormat::Text),
active_adapters: adapters,
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/llm_module_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ pub(super) async fn run_adapter_inference(
Some(request.stop_sequences.clone())
},
tools: None,
tail_tools: None,
tool_choice: None,
response_format: None,
active_adapters: None,
Expand Down
54 changes: 54 additions & 0 deletions core/continuum-engine/src/inference/request_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,13 @@ pub(crate) fn finish_body(
== crate::model_registry::ToolProtocol::NativeFunctionCalling
{
body["tools"] = json!(openai_tools(tools));
if let Some(tail) = request.tail_tools.as_deref().filter(|tail| !tail.is_empty()) {
// Our fork's field: only a server that declares it gets it (a cloud provider
// would reject an unknown field, a stock llama-server would ignore it).
if cfg.tail_tools {
body["tail_tools"] = json!(openai_tools(tail));
}
}

// Add tool_choice if specified
if let Some(choice) = &request.tool_choice {
Expand Down Expand Up @@ -215,6 +222,7 @@ pub(crate) fn finish_body(
class = "ai.request.tool_surface",
model = %model,
tools_n = body.get("tools").and_then(|t| t.as_array()).map_or(0, |a| a.len()),
tail_tools_n = body.get("tail_tools").and_then(|t| t.as_array()).map_or(0, |a| a.len()),
tool_choice = body.get("tool_choice").is_some(),
stops_n = body.get("stop").and_then(|s| s.as_array()).map_or(0, |a| a.len()),
msgs_n = body.get("messages").and_then(|m| m.as_array()).map_or(0, |a| a.len()),
Expand Down Expand Up @@ -681,4 +689,50 @@ mod tests {
let mut none = json!({ "model": "m" });
assert_eq!(apply_reasoning_budget(None, &mut none), None);
}

// what this catches: a tail-loaded verb not reaching a llama.cpp-family server (she could
// read its schema and never call it), or the non-standard field going to a cloud provider
// that rejects unknown fields.
#[test]
fn tail_tools_reach_only_a_llamacpp_family_server_and_never_join_the_head() {
let spec = |name: &str| crate::ai::types::NativeToolSpec {
name: name.to_owned(),
description: format!("{name} does one thing"),
input_schema: crate::ai::types::ToolInputSchema {
schema_type: "object".to_owned(),
properties: json!({}),
required: None,
definitions: None,
},
};
let request = TextGenerationRequest {
tools: Some(vec![spec("commands_help")]),
tail_tools: Some(vec![spec("code_git_apply")]),
..Default::default()
};
let cfg = |llamacpp: bool| OpenAICompatibleConfig {
provider_id: "test-gateway".into(),
name: "Test Gateway".into(),
base_url: "http://127.0.0.1:0".into(),
api_key_env: None,
default_model: "test-model".into(),
capabilities: [Capability::ToolUse].into_iter().collect(),
models: Vec::new(),
model_prefixes: Vec::new(),
requires_auth: false,
tool_protocol: crate::model_registry::ToolProtocol::NativeFunctionCalling,
thinking: ThinkingMode::Default,
single_resident_model: false,
dynamic_model_catalog: false,
llamacpp_sampling_extensions: llamacpp,
tail_tools: llamacpp,
};
let mut served = json!({ "model": "m" });
finish_body(&cfg(true), &request, "m", &mut served);
assert_eq!(served["tools"].as_array().map(Vec::len), Some(1), "the head holds only its own verbs");
assert_eq!(served["tail_tools"][0]["function"]["name"], "code_git_apply");
let mut cloud = json!({ "model": "m" });
finish_body(&cfg(false), &request, "m", &mut cloud);
assert!(cloud.get("tail_tools").is_none(), "{cloud}");
}
}
Loading
Loading