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.

fix(agent): follow-ups to host delegation and systemPrompt (#9081) (#9086)

Akarshan Biswasdf9b139c17df
diff --git a/adk/python/README.md b/adk/python/README.md
index c6b9e3e9f..826713599 100644
--- a/adk/python/README.md
+++ b/adk/python/README.md
@@ -190,6 +190,10 @@ An unanswered request parks the turn: nothing moves until it is answered, the
turn is interrupted, or the runtime is closed. A `read` tool is never prompted
for, in either mode.
+With `builtins=False`, `subagents=True` still lets the model delegate: each
+subagent is held to these host tools, and its calls arrive here with its
+`run_id`. `system_prompt=` replaces Jan's whole system prompt with yours.
+
## Process ownership
```python
diff --git a/adk/python/jan_adk/_generated.py b/adk/python/jan_adk/_generated.py
index acccb4af9..11dbb4dc1 100644
--- a/adk/python/jan_adk/_generated.py
+++ b/adk/python/jan_adk/_generated.py
@@ -218,7 +218,7 @@ class SessionStartParams(TypedDict):
builtins: NotRequired[bool]
# Whether the session may delegate to subagents; defaults to `builtins`. With `builtins: false` it adds only `dispatch_subagent` and `list_subagents`, and every child is held to the session's host tools. `false` withholds subagent tools even from a session with built-ins.
subagents: NotRequired[Union[bool, None]]
- # The session's whole system prompt, sent byte for byte in place of the one Jan composes: no Jan identity, guides, environment, date, git state or project memory, and the session neither recalls nor indexes project memory. Jan may still append runtime notices to the conversation. Children keep their own prompts.
+ # The session's whole system prompt, sent byte for byte in place of the one Jan composes: no Jan identity, guides, environment, date, git state or recalled project memory. Its answers are still indexed for later sessions unless it is `ephemeral`. Jan may still append runtime notices to the conversation. Children keep their own prompts.
systemPrompt: NotRequired[Union[str, None]]
permissions: NotRequired[PermissionOwner]
diff --git a/adk/python/jan_adk/runtime.py b/adk/python/jan_adk/runtime.py
index 66144d595..3dadf4581 100644
--- a/adk/python/jan_adk/runtime.py
+++ b/adk/python/jan_adk/runtime.py
@@ -215,8 +215,9 @@ class JanRuntime:
``subagents`` lets the model delegate (default: same as ``builtins``);
with ``builtins=False`` every child is limited to these host tools.
``system_prompt`` is sent exactly as given in place of Jan's prompt;
- the session then neither recalls nor indexes project memory, and Jan
- may still append runtime notices to the conversation.
+ no project memory is recalled into it (answers are still indexed
+ unless ``ephemeral``), and Jan may still append runtime notices to the
+ conversation.
``permissions`` says who gates a host tool call: ``"host"`` when this
process runs and gates its own tools, so the runtime never prompts for
diff --git a/docs/src/pages/docs/agent/adk-tools.mdx b/docs/src/pages/docs/agent/adk-tools.mdx
index 372e4987d..38dd80f02 100644
--- a/docs/src/pages/docs/agent/adk-tools.mdx
+++ b/docs/src/pages/docs/agent/adk-tools.mdx
@@ -140,6 +140,32 @@ A `read` tool such as the clock is not prompted. For an `actuator`:
`builtins: false` / `builtins=False` keeps this example limited to your declared tools. It is not
an operating-system sandbox for your callback: that function still has your process's access.
+## Delegate and bring your own prompt
+
+Two more session options suit an app that drives Jan with only its own tools:
+
+- **`subagents: true` / `subagents=True`** lets the model delegate with `dispatch_subagent` and
+ `list_subagents`, even with `builtins: false`. Every subagent is limited to your session's
+ host tools (no shell, files or web), and its calls reach your handlers like the parent's,
+ with the subagent's `run_id` on the request. Subagents are off by default when `builtins` is
+ off.
+- **`systemPrompt` / `system_prompt=`** replaces Jan's whole system prompt with yours, byte for
+ byte. Jan adds no identity, guides, environment, date or recalled memory, though it may still
+ append runtime notices (such as a finished subagent) to the conversation. Subagents keep their
+ own prompts. The session's answers are still saved to project memory for later sessions;
+ only `ephemeral` turns that off, and it also stops the thread being saved.
+
+```js
+const session = await runtime.createSession({
+ builtins: false,
+ subagents: true,
+ systemPrompt: 'You control a robot arm. Delegate camera checks to a subagent.',
+ tools: [/* your host tools */],
+})
+```
+
+See [`session/start`](/docs/agent/protocol) for the exact rules.
+
## Change tools or stop a callback
Between turns, use `session.setTools(...)` / `session.set_tools(...)` to replace the host tool set.
diff --git a/docs/src/pages/docs/agent/protocol.mdx b/docs/src/pages/docs/agent/protocol.mdx
index 0831dd56d..ced18822d 100644
--- a/docs/src/pages/docs/agent/protocol.mdx
+++ b/docs/src/pages/docs/agent/protocol.mdx
@@ -91,7 +91,7 @@ and the host's answer becomes the model's tool message. Request and parameter sh
| `tools` | `[]` | Declarations `{name, description?, parameters?, capability?}`. `capability` is `read` or `actuator`; absent is opaque. |
| `builtins` | `true` | `false` advertises only the host tools: no built-ins, MCP, plugin, `ask`, `todo` or monitor tools. `subagents: true` adds back only `dispatch_subagent` and `list_subagents`. |
| `subagents` | same as `builtins` | Whether the model may delegate. With `builtins: false`, `true` adds only `dispatch_subagent` and `list_subagents`, and every child is limited to the session's host tools (no shell, files, web or skills). A child's host tool call arrives as an ordinary `item/tool_request` with `run_id` set. `false` removes subagent tools even when built-ins are on. |
-| `systemPrompt` | none | The whole system prompt, sent exactly as given: no identity, guides, environment, date, git state, plan/todo guidance or project memory recall, and the session does not index project memory either. The system prompt is exactly yours; Jan may still append runtime notices to the conversation (`<SYSTEM>` notes such as a finished subagent, cost or token-budget notices, and compaction summaries). Subagents keep their own prompts. Kept across `session/model/set` and `session/fork`. A blank string fails with `-32602`. |
+| `systemPrompt` | none | The whole system prompt, sent exactly as given: no identity, guides, environment, date, git state, todo guidance or recalled project memory. The session's answers are still indexed into project memory for later sessions; `ephemeral` is the only way to turn that off, and it also stops the thread being saved. The system prompt is exactly yours; Jan may still append runtime notices to the conversation (`<SYSTEM>` notes such as a finished subagent, cost or token-budget notices, and compaction summaries). Subagents keep their own prompts. Kept across `session/model/set` and `session/fork`. A blank string fails with `-32602`. |
| `permissions` | `"jan"` | `"host"` means the host's callback is the gate: Jan never sends a `permission_request` for a host tool. Built-ins are unaffected. |
The result is `{sessionId, model, tools, toolSpecs}`. `tools` lists the names the next turn
diff --git a/packages/adk/README.md b/packages/adk/README.md
index 56b254fa4..907d72c81 100644
--- a/packages/adk/README.md
+++ b/packages/adk/README.md
@@ -108,7 +108,7 @@ handler that runs it here:
```js
const session = await runtime.createSession({
model: 'gpt-4o-mini',
- builtins: false, // only the tools below, no shell/editor/subagent tools
+ builtins: false, // only the tools below, no shell/editor tools
permissions: 'host', // this process runs and gates these tools itself
tools: [
{
@@ -186,6 +186,10 @@ An unanswered request parks the turn: nothing moves until it is answered, the
turn is interrupted, or the runtime is closed. A `read` tool is never prompted
for, in either mode.
+With `builtins: false`, `subagents: true` still lets the model delegate: each
+subagent is held to these host tools, and its calls arrive here with its
+`run_id`. `systemPrompt` replaces Jan's whole system prompt with yours.
+
## Process ownership
```js
diff --git a/packages/adk/src/generated/rpc-types.d.ts b/packages/adk/src/generated/rpc-types.d.ts
index 9060bc00e..1b3887291 100644
--- a/packages/adk/src/generated/rpc-types.d.ts
+++ b/packages/adk/src/generated/rpc-types.d.ts
@@ -175,7 +175,7 @@ export interface SessionStartParams {
"builtins"?: boolean
/** Whether the session may delegate to subagents; defaults to `builtins`. With `builtins: false` it adds only `dispatch_subagent` and `list_subagents`, and every child is held to the session's host tools. `false` withholds subagent tools even from a session with built-ins. */
"subagents"?: boolean | null
- /** The session's whole system prompt, sent byte for byte in place of the one Jan composes: no Jan identity, guides, environment, date, git state or project memory, and the session neither recalls nor indexes project memory. Jan may still append runtime notices to the conversation. Children keep their own prompts. */
+ /** The session's whole system prompt, sent byte for byte in place of the one Jan composes: no Jan identity, guides, environment, date, git state or recalled project memory. Its answers are still indexed for later sessions unless it is `ephemeral`. Jan may still append runtime notices to the conversation. Children keep their own prompts. */
"systemPrompt"?: string | null
"permissions"?: PermissionOwner
}
diff --git a/packages/adk/src/index.d.ts b/packages/adk/src/index.d.ts
index 3ec6da0bd..15d51033d 100644
--- a/packages/adk/src/index.d.ts
+++ b/packages/adk/src/index.d.ts
@@ -131,9 +131,10 @@ export interface CreateSessionOptions {
subagents?: boolean
/**
* The whole system prompt, sent exactly as given in place of Jan's: no Jan
- * identity, guides, environment, date, git state or project memory (none is
- * recalled or indexed). Jan may still append runtime notices to the
- * conversation. Subagents keep their own prompts. Must not be blank.
+ * identity, guides, environment, date, git state or recalled project memory.
+ * Answers are still indexed for later sessions unless `ephemeral`. Jan may
+ * still append runtime notices to the conversation. Subagents keep their own
+ * prompts. Must not be blank.
*/
systemPrompt?: string
/**
diff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.json
index 21d107b0d..5e850cef6 100644
--- a/protocol/rpc-schema.json
+++ b/protocol/rpc-schema.json
@@ -105,7 +105,7 @@
"default": null
},
"systemPrompt": {
- "description": "The session's whole system prompt, sent byte for byte in place of the\none Jan composes: no Jan identity, guides, environment, date, git state\nor project memory, and the session neither recalls nor indexes project\nmemory. Jan may still append runtime notices to the conversation.\nChildren keep their own prompts.",
+ "description": "The session's whole system prompt, sent byte for byte in place of the\none Jan composes: no Jan identity, guides, environment, date, git state\nor recalled project memory. Its answers are still indexed for later\nsessions unless it is `ephemeral`. Jan may still append runtime notices\nto the conversation.\nChildren keep their own prompts.",
"type": [
"string",
"null"
diff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rs
index e808afd09..614610965 100644
--- a/src-tauri/jan-cli/tests/agent_rpc.rs
+++ b/src-tauri/jan-cli/tests/agent_rpc.rs
@@ -1260,6 +1260,21 @@ fn a_host_system_prompt_is_sent_verbatim_and_kept() {
assert!(!wire.contains(jan_text), "{jan_text:?} leaked into {body}");
}
}
+ // Prefix stability on the host path, measured on the real requests: the
+ // second turn's body extends the first byte for byte (same tools, same
+ // system message, same history), so a provider's prompt cache holds. Jan
+ // puts no per-turn tail on a host prompt, so nothing -- not even the date
+ // -- can move bytes the host owns.
+ let bytes = |body: &serde_json::Value, key: &str| serde_json::to_string(&body[key]).unwrap();
+ assert_eq!(bytes(&requests[0], "tools"), bytes(&requests[1], "tools"));
+ let first = requests[0]["messages"].as_array().unwrap();
+ let second = requests[1]["messages"].as_array().unwrap();
+ assert!(second.len() > first.len(), "{second:?}");
+ assert_eq!(
+ serde_json::to_string(first).unwrap(),
+ serde_json::to_string(&second[..first.len()]).unwrap(),
+ "the second turn rewrote bytes the first had sent"
+ );
drop(requests);
rpc.close();
@@ -1331,3 +1346,46 @@ fn a_child_keeps_the_parents_tool_over_a_host_tool_of_the_same_name() {
rpc.close();
let _ = std::fs::remove_dir_all(scratch);
}
+
+/// A host-prompted session still leaves its answers for later recall -- only
+/// the recall block itself, which Jan would write into the host's prompt, is
+/// withheld. The later Jan-prompted session in the same project proves the
+/// answer was indexed; the host-prompted turns prove nothing was recalled
+/// into them.
+#[test]
+fn a_host_prompted_session_indexes_memory_but_is_never_sent_recall() {
+ let scratch = scratch("host-prompt-memory");
+ let home = scratch.join("home");
+ let (url, seen) = scripted_provider(&[PROSE]);
+ configure(&home, &url);
+ let mut rpc = Rpc::open(&home);
+ rpc.handshake();
+ let project = scratch.join("project");
+
+ let host_session = |rpc: &mut Rpc, id: u64| {
+ let started = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":id,"method":"session/start","params":{
+ "cwd":project,"model":"stub-model","systemPrompt":"You drive the arm."
+ }}));
+ started["result"]["sessionId"].as_str().unwrap_or_else(|| panic!("{started}")).to_owned()
+ };
+ let first = host_session(&mut rpc, 3);
+ complete_turn(&mut rpc, 4, &first);
+ let second = host_session(&mut rpc, 5);
+ complete_turn(&mut rpc, 6, &second);
+ assert_eq!(recalled(&seen), 0, "no host-prompted turn is sent recall");
+ // The saved thread keeps the prompt it was written under, so reopening it
+ // (the TUI's `/resume`) does not fall back to Jan's.
+ let thread = std::fs::read_to_string(
+ store(&home, &project).join("threads").join(&first).join("thread.json"),
+ )
+ .expect("the host-prompted session was saved");
+ let thread: serde_json::Value = serde_json::from_str(&thread).unwrap();
+ assert_eq!(thread["metadata"]["system_prompt"], "You drive the arm.", "{thread}");
+
+ let jan = start_with(&mut rpc, 7, &project, false);
+ complete_turn(&mut rpc, 8, &jan);
+ assert_eq!(recalled(&seen), 1, "the host-prompted answers were indexed");
+
+ rpc.close();
+ let _ = std::fs::remove_dir_all(scratch);
+}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 69320b091..45b62c84e 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -2882,6 +2882,31 @@ async fn todo_prompt_addendum(
has_todos.then_some(crate::core::agent::context::TODO_UPKEEP_PROMPT_ADDENDUM)
}
+/// The per-turn guidance block for this run, if any. Plan mode's is kept even
+/// under a host prompt: a TUI `/resume` of a host-prompted thread can run in
+/// Plan mode, and without the warning the model only learns of it from
+/// refusals. It sits in the tail, so the host's cached prefix is unaffected.
+/// Todo guidance is Jan's own prose and is withheld like every other block.
+async fn turn_addendum(
+ run_mode: crate::core::agent::plan::RunMode,
+ jan_owns_prompt: bool,
+ eager_todo_plan: bool,
+ todo_registry: &Option<crate::core::agent::todo::TodoRegistry>,
+) -> Option<(Composer, &'static str)> {
+ if run_mode == crate::core::agent::plan::RunMode::Plan {
+ return Some((
+ Composer::PlanAddendum,
+ crate::core::agent::plan::plan_mode_prompt_addendum(),
+ ));
+ }
+ if !jan_owns_prompt {
+ return None;
+ }
+ todo_prompt_addendum(eager_todo_plan, todo_registry)
+ .await
+ .map(|addendum| (Composer::TodoAddendum, addendum))
+}
+
/// True when this turn should be forced to stage a plan: a `/goal` run whose
/// list is still empty. Forcing is deliberately limited to goal mode -- an
/// unattended loop needs a plan to work against, while an ordinary turn is the
@@ -3012,11 +3037,11 @@ async fn orchestrate_inner(
&prompt_policy,
)?,
};
- let jan_prompt = host_system_prompt.is_none();
+ let jan_owns_prompt = host_system_prompt.is_none();
let mut volatile_parts: Vec<(Composer, String)> = Vec::new();
// Always tell the model today's date, including isolated child runs.
- if jan_prompt {
+ if jan_owns_prompt {
volatile_parts.push((
Composer::Date,
format!(
@@ -3028,14 +3053,15 @@ async fn orchestrate_inner(
// Which checkout the work applies to. Per-turn rather than part of the
// environment block above, because anything that switches branch -- the
// agent included -- would otherwise move every byte behind it.
- if let Some(root) = project_root.as_deref().filter(|_| jan_prompt) {
+ if let Some(root) = project_root.as_deref().filter(|_| jan_owns_prompt) {
volatile_parts.push((Composer::GitState, git_state_block(root)));
}
// Normal parent runs recall project memory for the current query before it
- // is indexed. Child runs keep their isolated history and skip memory, and
- // so does a host-prompted run: recall is a block Jan would write into it.
- let use_memory = *project_memory && system_prompt_override.is_none() && jan_prompt;
- if use_memory {
+ // is indexed. Child runs keep their isolated history and skip memory. A
+ // host-prompted run still indexes its answers but is never sent recall:
+ // that is a block Jan would write into a prompt the host owns.
+ let use_memory = *project_memory && system_prompt_override.is_none();
+ if use_memory && jan_owns_prompt {
if let Some(root) = project_root {
if let Some(query) = latest_user_text(&conversation_messages) {
if let Some(mem) = crate::core::agent::memory::retrieve_block(root, &query) {
@@ -3058,17 +3084,10 @@ async fn orchestrate_inner(
let eager_todo_plan = run_mode != crate::core::agent::plan::RunMode::Plan
&& system_prompt_override.is_none()
&& should_force_goal_todo_plan(goal_mode, todo_registry).await;
- // Under a host prompt Plan mode is still enforced by the gate; only its
- // prose is withheld, like every other block Jan writes.
- if jan_prompt {
- if run_mode == crate::core::agent::plan::RunMode::Plan {
- volatile_parts.push((
- Composer::PlanAddendum,
- crate::core::agent::plan::plan_mode_prompt_addendum().to_string(),
- ));
- } else if let Some(addendum) = todo_prompt_addendum(eager_todo_plan, todo_registry).await {
- volatile_parts.push((Composer::TodoAddendum, addendum.to_string()));
- }
+ if let Some((composer, addendum)) =
+ turn_addendum(run_mode, jan_owns_prompt, eager_todo_plan, todo_registry).await
+ {
+ volatile_parts.push((composer, addendum.to_string()));
}
// One tail message, built from every block the policy kept below the cache
@@ -3470,8 +3489,9 @@ async fn orchestrate_inner(
},
)
.await;
- // The same gate as the recall: an ephemeral session or a child run
- // leaves no answer behind for a later session to recall.
+ // The recall's gate minus the prompt-ownership half: an ephemeral
+ // session or a child run leaves no answer behind for a later session
+ // to recall, while a host-prompted run does.
if use_memory {
if let Ok(completion) = &result {
if let Some(answer) = extract_choice_message(completion).and_then(|m| {
@@ -5111,6 +5131,30 @@ mod tests {
assert!(!should_force_goal_todo_plan(true, &None).await);
}
+ #[tokio::test]
+ async fn plan_guidance_reaches_a_host_prompted_turn_but_todo_guidance_does_not() {
+ use crate::core::agent::plan::RunMode;
+ let staged = Some(staged_todo_registry());
+ for jan_owns_prompt in [true, false] {
+ assert_eq!(
+ turn_addendum(RunMode::Plan, jan_owns_prompt, false, &staged).await,
+ Some((
+ Composer::PlanAddendum,
+ crate::core::agent::plan::plan_mode_prompt_addendum()
+ )),
+ "jan_owns_prompt={jan_owns_prompt}"
+ );
+ }
+ assert_eq!(
+ turn_addendum(RunMode::Normal, true, false, &staged).await,
+ Some((
+ Composer::TodoAddendum,
+ crate::core::agent::context::TODO_UPKEEP_PROMPT_ADDENDUM
+ ))
+ );
+ assert_eq!(turn_addendum(RunMode::Normal, false, false, &staged).await, None);
+ }
+
#[tokio::test]
async fn todo_addendum_is_upkeep_only_outside_goal_mode() {
let staged = Some(staged_todo_registry());
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index d8a4215d6..343cd749a 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -503,7 +503,9 @@ pub fn intersect_allowed_tools(
/// whole set), and a child that asked for tools keeps those the ceiling
/// contains. A requested name matches either exactly or as the bare name a host
/// declared, since that is the name the host's prompt and the model use for
-/// it: `robot_arm_move` resolves to `host__robot_arm_move`.
+/// it: `robot_arm_move` resolves to `host__robot_arm_move`. A dispatch has
+/// already qualified its names in [`resolve_dispatch`]; doing it again here is
+/// a no-op on wire names and keeps this function correct on its own.
///
/// Fails closed on a list that keeps nothing -- the child would otherwise run
/// with no tools, the silent "skill tools only" child -- naming what the parent
@@ -622,17 +624,24 @@ struct ResolvedDispatch {
/// Resolve a dispatch request against the registry and parent permissions,
/// without running anything. Errors on an unknown name or a permission conflict.
+///
+/// `qualify` maps each tool name to the wire name it stands for before any
+/// comparison, so a definition listing `host__observe` and a call asking for
+/// the host's bare `observe` agree on the same tool.
fn resolve_dispatch(
registry: &SubagentRegistry,
req: &SubagentRequest,
parent: &ToolPermissions,
+ qualify: impl Fn(Vec<String>) -> Vec<String>,
) -> Result<ResolvedDispatch, SubagentError> {
+ let requested = req.allowed_tools.clone().map(&qualify);
match registry.get(&req.name).cloned() {
- Some(definition) => {
+ Some(mut definition) => {
+ definition.allowed_tools = definition.allowed_tools.map(&qualify);
// Registered definition: the call-site allowlist further narrows it.
let allowed_tools = intersect_allowed_tools(
definition.allowed_tools.as_deref(),
- req.allowed_tools.as_deref(),
+ requested.as_deref(),
parent,
)?;
Ok(ResolvedDispatch {
@@ -648,7 +657,7 @@ fn resolve_dispatch(
name: req.name.clone(),
description: req.description.clone(),
system_prompt: ephemeral_subagent_prompt(&req.name),
- allowed_tools: req.allowed_tools.clone(),
+ allowed_tools: requested,
model: None,
scope: SubagentScope::Project,
};
@@ -1541,7 +1550,9 @@ pub(crate) fn spawn_subagent(
.as_ref()
.ok_or_else(|| SubagentError::Upstream("subagents require an active project".to_string()))?;
let registry = SubagentRegistry::load(project_root);
- let resolved = resolve_dispatch(&registry, &req, &parent_args.permissions)?;
+ let resolved = resolve_dispatch(&registry, &req, &parent_args.permissions, |tools| {
+ qualify_host_names(tools, &parent.known_tools, parent_args)
+ })?;
// Re-priced before anything is spawned: a child whose own model cannot be
// metered under this ceiling fails the dispatch here rather than running on
// the parent's prices.
@@ -1789,7 +1800,9 @@ pub(crate) fn spawn_dispatch_plan(
let registry = SubagentRegistry::load(project_root);
for phase in &plan.phases {
for req in &phase.subagents {
- let resolved = resolve_dispatch(&registry, req, &parent_args.permissions)?;
+ let resolved = resolve_dispatch(&registry, req, &parent_args.permissions, |tools| {
+ qualify_host_names(tools, &parent.known_tools, parent_args)
+ })?;
capped_tools(
resolved.allowed_tools.clone(),
parent,
@@ -2134,12 +2147,23 @@ pub(crate) async fn await_subagent(
/// The model-callable subagent tools, handled by the loop's tool invoker ahead
/// of the built-in fs/exec gate and the MCP fallback.
pub fn is_subagent_tool(name: &str) -> bool {
- matches!(
- name,
- "dispatch_subagent" | "await_subagent" | "create_subagent" | "list_subagents"
- )
+ SUBAGENT_TOOLS.contains(&name)
}
+/// Every subagent tool name, the one list [`is_subagent_tool`] and
+/// [`DELEGATE_ONLY_TOOLS`] are drawn from.
+const SUBAGENT_TOOLS: [&str; 4] = [
+ "dispatch_subagent",
+ "await_subagent",
+ "create_subagent",
+ "list_subagents",
+];
+
+/// The subagent tools a session limited to its host's tools is offered when it
+/// may delegate: dispatching and listing, not `create_subagent`, which writes a
+/// definition into the project, nor `await_subagent`, which is never advertised.
+pub const DELEGATE_ONLY_TOOLS: [&str; 2] = [SUBAGENT_TOOLS[0], SUBAGENT_TOOLS[3]];
+
/// One-line "name [scope]: description" per definition; shadowed user-scope
/// entries are listed alongside their project-scope shadows.
pub fn format_subagent_list(registry: &SubagentRegistry) -> String {
@@ -2820,6 +2844,16 @@ mod tests {
}
}
+ /// `resolve_dispatch` with no host-name qualification, for tests whose
+ /// tools are all built-ins.
+ fn resolve_dispatch_plain(
+ reg: &SubagentRegistry,
+ req: &SubagentRequest,
+ p: &ToolPermissions,
+ ) -> Result<ResolvedDispatch, SubagentError> {
+ resolve_dispatch(reg, req, p, |t| t)
+ }
+
/// A capped parent's children are capped too. Subagents are where a run's
/// spend multiplies, so a ceiling that stopped at the parent would be one
/// any run could spend around by dispatching.
@@ -2827,7 +2861,7 @@ mod tests {
fn child_body_inherits_the_parents_cost_ceiling() {
let reg = registry_with("reviewer", None);
let p = ToolPermissions::allow_all();
- let resolved = resolve_dispatch(&reg, &req("reviewer", None), &p).expect("resolves");
+ let resolved = resolve_dispatch_plain(&reg, &req("reviewer", None), &p).expect("resolves");
let uncapped = child_body(&resolved, "task", &parent_run());
assert!(
@@ -2913,7 +2947,7 @@ mod tests {
fn child_body_forwards_the_parents_send_reasoning_opt_out() {
let reg = registry_with("reviewer", None);
let p = ToolPermissions::allow_all();
- let resolved = resolve_dispatch(&reg, &req("reviewer", None), &p).expect("resolves");
+ let resolved = resolve_dispatch_plain(&reg, &req("reviewer", None), &p).expect("resolves");
let on = child_body(&resolved, "task", &parent_run());
assert!(
on.get("send_reasoning").is_none(),
@@ -2941,7 +2975,7 @@ mod tests {
description: "task".to_string(),
allowed_tools: Some(vec!["read".to_string()]),
};
- let resolved = resolve_dispatch(&reg, &request, &p).unwrap();
+ let resolved = resolve_dispatch_plain(&reg, &request, &p).unwrap();
assert_eq!(resolved.definition.name, "one-off");
assert!(resolved.definition.system_prompt.contains("one-off"));
assert_eq!(
@@ -3031,7 +3065,7 @@ mod tests {
);
let p = ToolPermissions::allow_all();
let resolved =
- resolve_dispatch(&reg, &req("reviewer", Some(vec!["read".to_string()])), &p).unwrap();
+ resolve_dispatch_plain(&reg, &req("reviewer", Some(vec!["read".to_string()])), &p).unwrap();
assert_eq!(
resolved.allowed_tools,
Some(vec![
@@ -3043,12 +3077,27 @@ mod tests {
assert_eq!(resolved.definition.system_prompt, "sp");
}
+ /// A saved definition written against wire names and a call using the
+ /// host's bare name mean the same tool: names are qualified before the
+ /// definition's list narrows the call's, not after.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn a_bare_host_name_matches_a_definition_listing_its_wire_name() {
+ let reg = registry_with("reviewer", Some(vec!["host__observe".to_string()]));
+ let args = host_parent();
+ let qualify = |tools| qualify_host_names(tools, &[], &args);
+ let request = req("reviewer", Some(vec!["observe".to_string()]));
+ let resolved = resolve_dispatch(&reg, &request, &ToolPermissions::allow_all(), qualify)
+ .expect("observe is the definition's host__observe");
+ assert_eq!(resolved.allowed_tools.unwrap()[0], "host__observe");
+ }
+
#[test]
fn resolve_rejects_tool_outside_definition() {
let reg = registry_with("reviewer", Some(vec!["read".to_string()]));
let p = ToolPermissions::allow_all();
let err =
- resolve_dispatch(&reg, &req("reviewer", Some(vec!["bash".to_string()])), &p).unwrap_err();
+ resolve_dispatch_plain(&reg, &req("reviewer", Some(vec!["bash".to_string()])), &p).unwrap_err();
assert!(matches!(err, SubagentError::PermissionDenied(_)));
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 83f09652d..96af108bb 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -468,6 +468,11 @@ pub(crate) fn rebuild_wire_history(messages: &[serde_json::Value]) -> Vec<serde_
/// (where every thread is a root) renders as today's flat list.
pub const FORKED_FROM_KEY: &str = "forked_from";
+/// Key in a thread's `metadata` holding an RPC host's `systemPrompt`. Saved so
+/// a thread reopened elsewhere (the TUI's `/resume`) keeps running on the
+/// prompt it was written under instead of falling back to Jan's.
+pub const SYSTEM_PROMPT_KEY: &str = "system_prompt";
+
/// True for a `user` message the user actually authored. Hidden reminders ride
/// in on the `user` role but are not turns: a rewind target, a fork point, a
/// recall entry or a checkpoint key built from one would be a row the user never
diff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rs
index f99308a51..8ee87846c 100644
--- a/src-tauri/src/core/cli/rpc.rs
+++ b/src-tauri/src/core/cli/rpc.rs
@@ -39,11 +39,6 @@ struct Session {
subagents: bool,
}
-/// The subagent tools a host-only session is offered when it may delegate:
-/// dispatching and listing, not `create_subagent`, which writes a definition
-/// into the project.
-const HOST_ONLY_SUBAGENT_TOOLS: [&str; 2] = ["dispatch_subagent", "list_subagents"];
-
/// The allowlist a host-only session's turns run under, or `None` for a
/// session with built-ins. A child inherits it as its ceiling, so this is also
/// what keeps a delegate from reaching Jan's shell or files.
@@ -51,7 +46,7 @@ fn session_allowlist(session: &Session) -> Option<Vec<String>> {
(!session.builtins).then(|| {
let mut names = Vec::new();
if session.subagents {
- names.extend(HOST_ONLY_SUBAGENT_TOOLS.map(str::to_owned));
+ names.extend(crate::core::agent::subagent::DELEGATE_ONLY_TOOLS.map(str::to_owned));
}
names.extend(host_names(&session.agent.args.host_tools));
names
@@ -468,7 +463,9 @@ fn finish_turn(
Some(&session.id),
&session.agent.model,
&session.history,
- None,
+ session.agent.args.host_system_prompt.as_ref().map(|prompt| {
+ json!({ super::SYSTEM_PROMPT_KEY: prompt })
+ }),
) {
error_message = Some(format!("could not save session: {message}"));
}
diff --git a/src-tauri/src/core/cli/rpc_schema.rs b/src-tauri/src/core/cli/rpc_schema.rs
index f2e567a29..084944e13 100644
--- a/src-tauri/src/core/cli/rpc_schema.rs
+++ b/src-tauri/src/core/cli/rpc_schema.rs
@@ -57,8 +57,9 @@ pub struct SessionStartParams {
pub subagents: Option<bool>,
/// The session's whole system prompt, sent byte for byte in place of the
/// one Jan composes: no Jan identity, guides, environment, date, git state
- /// or project memory, and the session neither recalls nor indexes project
- /// memory. Jan may still append runtime notices to the conversation.
+ /// or recalled project memory. Its answers are still indexed for later
+ /// sessions unless it is `ephemeral`. Jan may still append runtime notices
+ /// to the conversation.
/// Children keep their own prompts.
#[serde(default)]
pub system_prompt: Option<String>,
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index ba66a2ee6..c5de0cda3 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -2815,6 +2815,22 @@ impl App {
self.workspace = workspace;
}
+ /// Run the session on `prompt` in place of Jan's system prompt, or back on
+ /// Jan's with `None`. Only a thread an RPC host wrote carries one; the run
+ /// args are swapped rather than edited because they are shared behind an
+ /// `Arc` with any run already spawned from them.
+ fn set_host_system_prompt(&mut self, prompt: Option<String>) {
+ let Some(args) = self.args.as_ref() else {
+ return;
+ };
+ if args.host_system_prompt == prompt {
+ return;
+ }
+ let mut next = (**args).clone();
+ next.host_system_prompt = prompt;
+ self.args = Some(Arc::new(next));
+ }
+
/// Drop the current conversation and all transient turn state, detaching from
/// the saved thread so the next message starts a fresh one. Backs `/clear` and
/// `/new`; the model/MCP setup and picker state are untouched.
@@ -2830,6 +2846,7 @@ impl App {
// A fresh session is a root, whatever the one it replaced was, and it
// owns the checkout this session is working in.
self.forked_from = None;
+ self.set_host_system_prompt(None);
self.workspace_record = self.workspace.clone();
self.snap_queue.clear();
self.base_requested = false;
@@ -4788,16 +4805,23 @@ impl App {
// Persist metadata when snapshots, a goal, or plan mode are present; each
// must survive restart/resume even in a non-git project (no snapshots).
let planning = self.run_mode == crate::core::agent::plan::RunMode::Plan;
+ let host_prompt = self.args.as_ref().and_then(|a| a.host_system_prompt.clone());
if self.base_snapshot.is_none()
&& self.goal.is_none()
&& !planning
&& self.todos.is_empty()
&& self.forked_from.is_none()
&& self.workspace_record.is_none()
+ && host_prompt.is_none()
{
return None;
}
let mut meta = serde_json::Map::new();
+ // Metadata is replaced whole on save, so a prompt a host wrote the
+ // thread under is carried or it is lost.
+ if let Some(prompt) = host_prompt {
+ meta.insert(super::SYSTEM_PROMPT_KEY.to_string(), serde_json::json!(prompt));
+ }
if let Some(workspace) = self.workspace_record.as_ref() {
meta.insert(
super::worktree::WORKTREE_KEY.to_string(),
@@ -16420,6 +16444,26 @@ fn restore_run_mode(app: &mut App, metadata: Option<&serde_json::Value>) {
}
}
+/// Reload the system prompt an RPC host wrote a thread under, or return to
+/// Jan's for a thread with none, so the resumed conversation keeps the prompt
+/// its history was produced under.
+fn restore_host_system_prompt(app: &mut App, metadata: Option<&serde_json::Value>) {
+ let prompt = metadata
+ .and_then(|m| m.get(super::SYSTEM_PROMPT_KEY))
+ .and_then(|v| v.as_str())
+ .filter(|p| !p.trim().is_empty())
+ .map(str::to_owned);
+ if prompt.is_some() {
+ // The prompt was written for the host's tools, which a TUI session
+ // does not have; the user should know before the model reaches for them.
+ app.note(
+ "resumed on the host's system prompt from this thread; the host's tools are \
+ not available here. /new returns to Jan's prompt",
+ );
+ }
+ app.set_host_system_prompt(prompt);
+}
+
/// Reload the canonical todo list for a resumed thread from its persisted
/// metadata into the TUI projection. The caller also mirrors it into the shared
/// registry so the model's next `todo` op operates on the reconstructed state.
@@ -16938,6 +16982,7 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value, verb: &str) {
restore_goal(app, thread.get("metadata"));
restore_run_mode(app, thread.get("metadata"));
restore_todos(app, thread.get("metadata"));
+ restore_host_system_prompt(app, thread.get("metadata"));
app.forked_from = thread
.get("metadata")
.and_then(|m| m.get(super::FORKED_FROM_KEY))
@@ -20123,8 +20168,8 @@ mod tests {
message_text, note_update, open_config_screen, open_fork_picker, open_rewind_picker,
open_tree_picker, pairs_to_str, parse_command, partial_json_field,
provider_label_for_model, rebuild_recall, replay_display_log, restore_goal,
- restore_run_mode, restore_todos, resume_hint, rewind_to, route_paste_event, row_width,
- run_command, running_group_rows, selection_text, spans_width, spawn_branch_poll,
+ restore_host_system_prompt, restore_run_mode, restore_todos, resume_hint, rewind_to,
+ route_paste_event, row_width, run_command, running_group_rows, selection_text, spans_width, spawn_branch_poll,
split_reasoning, starting_call_lines, startup_modes, strip_system_xml_tags,
subagent_activity, subagent_name_from_run_id, summarize_result, sync_output_for,
thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,
@@ -34987,6 +35032,28 @@ mod tests {
assert!(restored.message_queue.is_empty());
}
+ /// A thread an RPC host wrote under its own system prompt resumes on that
+ /// prompt, carries it on the next save, and `/new` returns to Jan's.
+ #[test]
+ fn a_host_system_prompt_round_trips_through_thread_metadata() {
+ let mut app = test_app();
+ app.args = Some(test_args(&app, std::collections::HashMap::new()));
+ let meta = serde_json::json!({ super::super::SYSTEM_PROMPT_KEY: "You drive the arm." });
+ restore_host_system_prompt(&mut app, Some(&meta));
+ let prompt = |app: &App| app.args.as_ref().and_then(|a| a.host_system_prompt.clone());
+ assert_eq!(prompt(&app).as_deref(), Some("You drive the arm."));
+ let saved = app.thread_metadata().expect("the prompt alone is worth saving");
+ assert_eq!(saved[super::super::SYSTEM_PROMPT_KEY], "You drive the arm.");
+
+ app.reset_session();
+ assert_eq!(prompt(&app), None, "a fresh session is Jan's again");
+ assert!(app.thread_metadata().is_none());
+
+ restore_host_system_prompt(&mut app, Some(&meta));
+ restore_host_system_prompt(&mut app, Some(&serde_json::json!({})));
+ assert_eq!(prompt(&app), None, "a thread without one resumes on Jan's");
+ }
+
#[test]
fn normal_mode_omits_run_mode_from_metadata() {
// Old threads / normal sessions keep clean, backward-compatible metadata.