Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Unattended turns: 25 model calls, one automatic continuation, state assumptions instead of asking

Lin (kwant bot)41ed924ebb5e
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 0783a110..806b9fb6 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -6,6 +6,18 @@ use serde_json::{json, Value};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
+/// Starts the note an API turn ends with when it ran out of model calls (see [`hit_call_cap`]).
+pub const CALL_CAP_NOTE: &str = "(Stopped: reached the limit of ";
+
+/// Whether a reply ended because the turn used all its model calls for tools, not because the
+/// model was done.
+pub fn hit_call_cap(text: &str) -> bool {
+ text.trim_end()
+ .rsplit("\n\n")
+ .next()
+ .is_some_and(|last| last.starts_with(CALL_CAP_NOTE) && last.ends_with("model calls for MCP tools this turn.)"))
+}
+
fn is_ollama(model: &str) -> bool {
model == "local_ollama" || model.starts_with("ollama/")
}
@@ -508,7 +520,7 @@ impl ApiDriver {
));
};
if round + 1 == max_calls {
- let note = format!("(Stopped: reached the limit of {max_calls} model calls for MCP tools this turn.)");
+ let note = format!("{CALL_CAP_NOTE}{max_calls} model calls for MCP tools this turn.)");
let text = match content.filter(|c| !c.trim().is_empty()) {
Some(c) => format!("{c}\n\n{note}"),
None => note,
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index d5a7f394..c0ed17b1 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -28,7 +28,9 @@ pub const RESERVED_SERVER_NAME: &str = "kwnt";
/// Server name of the agents' own continuity tools (`mcp__kwnt_tools__memory_add`, …).
pub const SELF_SERVER_NAME: &str = "kwnt_tools";
pub const DEFAULT_TIMEOUT_SECS: i64 = 30;
-pub const DEFAULT_MAX_TOOL_ITERATIONS: usize = 8;
+/// Model calls an API-driver turn may make for tools; routines and delegations also get one
+/// automatic continuation when a turn runs out (see `routes::continue_once_if_capped`).
+pub const DEFAULT_MAX_TOOL_ITERATIONS: usize = 25;
/// Longest tool result kept in a message's `tool_calls` record.
pub const RECORD_RESULT_MAX_CHARS: usize = 4000;
/// How long an MCP tool call waits for the user's approval before it is denied.
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 7045eef5..82c62b28 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -123,6 +123,9 @@ pub async fn prompt_block(
clearly want: a shopping list with a meal plan; with a new routine, a sample of what it will send (a \
motivation, the reminder's checklist); a monthly routine that sends a report you wrote. When a plan has \
a start date or deadline, schedule a check-in with `follow_up_create` a few days in.\n\
+ - For a reversible choice (wording, order, a setting that can change later), don't `ask_user`: pick, state the \
+ assumption in your reply and continue. Ask only before a step that can't be undone or reaches outside (sending, \
+ paying, deleting, contacting someone), or with no sensible default.\n\
- Don't ask permission for reversible extras: do them. End by naming every extra, including a \
list or tips in your reply (\"I also added a shopping list and tips.\"). Only app changes get a card with Undo; saved notes don't. \
Stay within 10 changes per turn. Never add one that costs money, contacts anyone or uses an outside service; offer \
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index ee963b77..72171571 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -2,7 +2,7 @@
//! specialist that runs in its own thread in the background and reports back to the chat it came
//! from. See `design-A.md` (batch 2) for the API and SSE contract.
-use super::routes::{scope_for, try_kwant_turn, TurnOpts};
+use super::routes::{continue_once_if_capped, scope_for, try_kwant_turn, TurnOpts};
use super::AppState;
use crate::db::models::{Kwant, MessageExtra, NewMessage};
use crate::db::spaces::SpaceId;
@@ -292,6 +292,7 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
opts.retried = retried;
opts.delegation_id = Some(d.id.clone());
let outcome = try_kwant_turn(&scope, &specialist, prompt, opts).await;
+ let outcome = continue_once_if_capped(&scope, &specialist, outcome).await;
let outcome = match outcome {
Err(_) if job.token.is_cancelled() => Err("stopped".to_string()),
other => other,
diff --git a/src/server/questions.rs b/src/server/questions.rs
index 5a65ed47..232a1ffa 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -143,12 +143,19 @@ async fn close(state: &AppState, id: &str, status: &str, answer: Option<&str>) -
// Agent tool
+/// When to ask: only for a step that can't be undone or reaches outside, or a choice with no
+/// sensible default. Reversible choices are made, stated and carried on with.
+pub const ASK_USER_DESCRIPTION: &str = "Ask the user one short question, only when you can't go on without their decision: \
+ a step that can't be undone or reaches outside (sending, publishing, paying, deleting, contacting someone), or a choice \
+ with no sensible default. For a reversible choice (wording, order, which of two fine options, a setting that can be \
+ changed later) don't ask: pick the sensible option, state the assumption in your reply and continue. \
+ Give 2 to 5 short choices; the user can also type their own answer. Your turn waits for the answer \
+ (a few minutes at most) and the tool returns it. Don't ask what you can find out or decide yourself.";
+
pub fn tools() -> Vec<Value> {
vec![json!({
"name": "ask_user",
- "description": "Ask the user one short question when you can't sensibly go on without their decision. \
- Give 2 to 5 short choices; the user can also type their own answer. Your turn waits for the answer \
- (a few minutes at most) and the tool returns it. Don't ask what you can find out or decide yourself.",
+ "description": ASK_USER_DESCRIPTION,
"inputSchema": {
"type": "object",
"properties": {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 2582a22e..f7efb08f 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -821,6 +821,7 @@ pub(super) async fn run_routine_turn(
let job = state.turns.start_job([context_key.clone()]);
let scope = scope_for(state, kwant, channel_id, thread_id, &job, 0).await?;
let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts::default()).await;
+ let reply = continue_once_if_capped(&scope, kwant, reply).await;
match reply {
Ok(text) => {
let reply_id = state
@@ -840,6 +841,30 @@ pub(super) async fn run_routine_turn(
}
}
+/// The prompt of the one automatic continuation a routine's or delegation's turn gets when it ran
+/// out of model calls (see [`continue_once_if_capped`]).
+pub const CONTINUE_PROMPT: &str = "[kwnt: your last turn stopped at the limit of model calls before you finished. \
+This is your one automatic continuation: pick up where you left off, finish the task, and end with a complete answer.]";
+
+/// For turns nobody is watching (routines, delegations): a turn that stopped at the model-call
+/// cap gets one more turn to finish, never more. Returns both replies joined, so a delegation's
+/// result has all of it. A turn that didn't hit the cap, or failed, is returned as it is.
+pub(super) async fn continue_once_if_capped(scope: &TurnScope, kwant: &Kwant, first: Result<String, String>) -> Result<String, String> {
+ let Ok(text) = &first else {
+ return first;
+ };
+ if !crate::drivers::api::hit_call_cap(text) || scope.cancel_token.is_cancelled() {
+ return first;
+ }
+ tracing::info!(kwant = %kwant.id, "turn hit the model-call cap: one automatic continuation");
+ let mut opts = TurnOpts::default();
+ opts.label = Some("Automatic continuation (once): the last turn ran out of model calls".into());
+ match try_kwant_turn(scope, kwant, CONTINUE_PROMPT.to_string(), opts).await {
+ Ok(more) => Ok(format!("{}\n\n{more}", text.trim_end())),
+ Err(_) => first,
+ }
+}
+
/// Lets teammates that kwants @mentioned in `replies` answer in turn, so kwants can delegate to each other.
/// `already_spoken` kwants are not handed the turn again.
/// [`run_handoffs`] for a lead's follow-up after delegation results: boxed with a named type,
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index f9ad621c..6724d892 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -6,6 +6,7 @@
//! (the last marker counts, and each marker runs once: later turns see it again in history).
//! - `REPLYTAG:<tag>`: reply "answer <tag>" (after any tool call).
//! - `QUOTAONCE:<tag>` / `QUOTAALWAYS`: fail with Claude's usage-limit error, once / every time.
+//! - `CAPPED:<tag>` / `CAPALWAYS:<tag>`: end at the model-call cap; the continuation doesn't / does too.
//!
//! Each test file that uses it is its own binary, because it changes PATH.
#![allow(dead_code)]
@@ -44,6 +45,17 @@ if "QUOTAALWAYS" in prompt or (flag and not os.path.exists(flag)):
print(json.dumps({"type": "result", "is_error": True, "num_turns": 1,
"result": "Claude AI usage limit reached|%d" % (int(time.time()) + 2)}))
sys.exit(1)
+# CAPPED:<tag>: end like an API turn that ran out of model calls; the automatic continuation
+# answers "continued <tag>" (CAPALWAYS: and runs out again)
+cap = re.findall(r"CAP(?:PED|ALWAYS):([A-Za-z0-9_]+)", prompt)
+if cap:
+ note = "\n\n(Stopped: reached the limit of 25 model calls for MCP tools this turn.)"
+ if "[kwnt: your last turn stopped at the limit" in prompt:
+ text = "continued " + cap[-1] + (note if "CAPALWAYS" in prompt else "")
+ else:
+ text = "partial " + cap[-1] + note
+ print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": text}))
+ sys.exit(0)
reply = []
m = ([None] + list(re.finditer(r"CALLTOOL:([a-z_]+):([A-Za-z0-9+/=]+)", prompt)))[-1]
done = None
diff --git a/tests/initiative_test.rs b/tests/initiative_test.rs
index 0828dddf..4a17c386 100644
--- a/tests/initiative_test.rs
+++ b/tests/initiative_test.rs
@@ -333,7 +333,7 @@ async fn bots_with_tools_are_told_how_to_work_and_bots_without_are_not() {
let section = &with[with.find("[How to work]").unwrap()..];
let section = &section[..section[1..].find("\n\n[").map_or(section.len(), |i| i + 1)];
// Proactive extras and check-ins, but never ones that cost money or reach outside, and no asking for reversible ones
- for words in ["Be proactive", "shopping list", "a few days in", "Don't ask permission", "End by naming every extra", "I also added a shopping list", "list or tips in your reply", "Undo", "10 changes", "costs money", "Never redo what the person undid", "a sample of what it will send", "saved notes don't"] {
+ for words in ["Be proactive", "shopping list", "a few days in", "Don't ask permission", "End by naming every extra", "I also added a shopping list", "list or tips in your reply", "Undo", "10 changes", "costs money", "Never redo what the person undid", "a sample of what it will send", "saved notes don't", "state the assumption in your reply", "can't be undone or reaches outside"] {
assert!(section.contains(words), "{words}: {section}");
}
// Bots' own tools can only be refused by name: the prompt says where the person switches them
diff --git a/tests/unattended_test.rs b/tests/unattended_test.rs
new file mode 100644
index 00000000..a21e80f7
--- /dev/null
+++ b/tests/unattended_test.rs
@@ -0,0 +1,85 @@
+//! Unattended turns keep going: a routine's or delegation's turn that runs out of model calls
+//! gets one automatic continuation (never two; chats with the person get none), the API cap is
+//! 25, and `ask_user` tells bots to state an assumption for reversible choices.
+
+mod common;
+
+use common::*;
+use serde_json::json;
+use std::time::Duration;
+
+async fn run_routine(env: &Env, kwant: &str, instructions: &str) {
+ let (s, r) = call(
+ &env.app,
+ "POST",
+ "/api/routines",
+ Some(json!({"kwant_id": kwant, "name": "Nightly", "instructions": instructions,
+ "schedule": {"type": "daily", "time": "03:00", "tz": "UTC"}})),
+ )
+ .await;
+ assert_eq!(s.as_u16(), 201, "{r}");
+ let (s, v) = call(&env.app, "POST", &format!("/api/routines/{}/run", r["id"].as_str().unwrap()), None).await;
+ assert!(s.is_success(), "{v}");
+}
+
+#[tokio::test]
+async fn a_routine_that_runs_out_of_model_calls_continues_once() {
+ let env = setup().await;
+ run_routine(&env, &env.a, "Sort the inbox CAPPED:r1").await;
+ let done = wait_reply(&env, &env.a, "continued r1").await;
+ assert!(done.reasoning_content.as_deref().unwrap_or("").contains("Automatic continuation"), "{done:?}");
+ assert_eq!(invocations_with("CAPPED:r1").len(), 2, "the turn and one continuation");
+}
+
+#[tokio::test]
+async fn the_continuation_happens_only_once() {
+ let env = setup().await;
+ run_routine(&env, &env.b, "Sort everything CAPALWAYS:r2").await;
+ wait_reply(&env, &env.b, "continued r2").await;
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ assert_eq!(invocations_with("CAPALWAYS:r2").len(), 2, "never a second continuation");
+}
+
+#[tokio::test]
+async fn a_chat_with_the_person_gets_no_automatic_continuation() {
+ let env = setup().await;
+ send_direct(&env, &env.a, "Sort it CAPPED:d1", json!({})).await;
+ wait_reply(&env, &env.a, "partial d1").await;
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ assert_eq!(invocations_with("CAPPED:d1").len(), 1);
+}
+
+#[tokio::test]
+async fn a_delegation_continues_once_and_reports_both_parts() {
+ let env = setup().await;
+ let (s, d) = call(
+ &env.app,
+ "POST",
+ "/api/delegations",
+ Some(json!({"lead_kwant_id": env.a, "specialist_kwant_id": env.b, "kwant_id": env.a,
+ "task": "Research CAPPED:g1", "title": "Long research", "continue_lead": false})),
+ )
+ .await;
+ assert_eq!(s.as_u16(), 202, "{d}");
+ let result = wait_reply(&env, &env.a, "continued g1").await;
+ assert!(result.text.contains("partial g1"), "{}", result.text);
+ assert_eq!(invocations_with("CAPPED:g1").len(), 2);
+}
+
+#[test]
+fn the_cap_note_is_recognised_and_the_default_is_25() {
+ use kwnt::drivers::api::hit_call_cap;
+ assert_eq!(kwnt::mcp::DEFAULT_MAX_TOOL_ITERATIONS, 25);
+ assert!(hit_call_cap("Half done.\n\n(Stopped: reached the limit of 25 model calls for MCP tools this turn.)"));
+ assert!(hit_call_cap("(Stopped: reached the limit of 3 model calls for MCP tools this turn.)\n"));
+ assert!(!hit_call_cap("I quoted “(Stopped: reached the limit of 25 model calls for MCP tools this turn.)” earlier.\n\nAll done."));
+ assert!(!hit_call_cap("All done."));
+}
+
+#[test]
+fn ask_user_says_state_the_assumption_for_reversible_choices() {
+ let d = kwnt::server::questions::ASK_USER_DESCRIPTION;
+ assert!(d.contains("state the assumption") && d.contains("reversible"), "{d}");
+ assert!(d.contains("can't be undone or reaches outside"), "outward steps still ask: {d}");
+ assert_eq!(kwnt::server::questions::tools()[0]["description"], d);
+}