Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): host-tool-only delegation and a verbatim host system prompt over RPC
Akarshan Biswas31bea295d58d
diff --git a/adk/python/jan_adk/_generated.py b/adk/python/jan_adk/_generated.pyindex e4fdf1137..bee3d63ef 100644--- a/adk/python/jan_adk/_generated.py+++ b/adk/python/jan_adk/_generated.py@@ -216,6 +216,10 @@ class SessionStartParams(TypedDict):tools: NotRequired[list[HostToolDeclSchema]]# `false` advertises only the host tools: no built-ins, MCP, plugin, `ask`, `todo`, subagent or monitor tools.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. Children keep their own prompts.+ systemPrompt: NotRequired[Union[str, None]]permissions: NotRequired[PermissionOwner]class SessionIdParams(TypedDict):diff --git a/adk/python/jan_adk/runtime.py b/adk/python/jan_adk/runtime.pyindex d10dd9a7a..a13a658ea 100644--- a/adk/python/jan_adk/runtime.py+++ b/adk/python/jan_adk/runtime.py@@ -205,11 +205,17 @@ class JanRuntime:model: Optional[str] = None,ephemeral: Optional[bool] = None,builtins: Optional[bool] = None,+ subagents: Optional[bool] = None,+ system_prompt: Optional[str] = None,permissions: Optional[str] = None,tools: Sequence[HostTool] = (),) -> JanSession:"""Start a session. ``tools`` are host tools this session may call.+ ``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.+``permissions`` says who gates a host tool call: ``"host"`` when thisprocess runs and gates its own tools, so the runtime never prompts forthem, and ``"jan"`` (the default) to leave the gate with the runtime -@@ -223,6 +229,10 @@ class JanRuntime:params["ephemeral"] = ephemeralif builtins is not None:params["builtins"] = builtins+ if subagents is not None:+ params["subagents"] = subagents+ if system_prompt is not None:+ params["systemPrompt"] = system_promptif permissions is not None and permissions != "jan":params["permissions"] = permissionsif tools:diff --git a/docs/src/pages/docs/agent/protocol.mdx b/docs/src/pages/docs/agent/protocol.mdxindex 653cc1bf5..6ffa9fd46 100644--- a/docs/src/pages/docs/agent/protocol.mdx+++ b/docs/src/pages/docs/agent/protocol.mdx@@ -84,16 +84,19 @@ and the host's answer becomes the model's tool message. Request and parameter sh### Declaring tools-`session/start` accepts three optional fields next to `cwd`, `model` and `ephemeral`:+`session/start` accepts these optional fields next to `cwd`, `model` and `ephemeral`:| Field | Default | Meaning || --- | --- | --- || `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`, subagent or monitor tools. |+| `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. Jan adds nothing to it: no identity, guides, environment, date, git state, plan/todo guidance or project memory. 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-advertises (with `builtins: false`, only the host tools). `toolSpecs` echoes the schemas of the+advertises (with `builtins: false`, only the host tools, plus the two subagent tools when+`subagents: true`). `toolSpecs` echoes the schemas of thehost tools that are actually advertised, so a host can compare them with what it sent and see atool that a deny list or Plan mode withheld. A declaration Jan refuses (reserved name, duplicate,unknown key, non-object `parameters`) fails the whole call with `-32602` and@@ -137,14 +140,14 @@ turn's `turn/completed`. When stdin closes, pending requests are cancelled the s| --- | --- | --- || `session/tools/get` | `{sessionId}` | `{tools, toolSpecs}` || `session/tools/set` | `{sessionId, tools}` | `{tools, toolSpecs}`. Replaces the host set; refusals are `invalid_tools`. |-| `session/model/set` | `{sessionId, model}` | `{model}`. History, host tools, `builtins` and `permissions` are kept. A model no configured provider can serve fails here with `-32602` rather than being substituted at the next turn; the check is servability, so it does not fetch (or refresh) the credential the model's provider needs - the next turn resolves that, and reports a credential failure as its own. |+| `session/model/set` | `{sessionId, model}` | `{model}`. History, host tools, `builtins`, `subagents`, `systemPrompt` and `permissions` are kept. A model no configured provider can serve fails here with `-32602` rather than being substituted at the next turn; the check is servability, so it does not fetch (or refresh) the credential the model's provider needs - the next turn resolves that, and reports a credential failure as its own. || `session/reset` | `{sessionId}` | `{tools, toolSpecs}`. History is cleared; model and tools are kept. |These four methods are refused while that session's turn is running: `-32001` with`data: {"retryable": true, "kind": "turn_active"}`. Retry after `turn/completed`. (`session/fork`and `session/archive` of a busy session, and a second `turn/start`, keep their plain retryable`-32001`.) An unknown `sessionId` is `-32602`. `session/fork` copies the host-tools, `builtins` and `permissions`, but pending requests are never shared between sessions.+tools, `builtins`, `subagents`, `systemPrompt` and `permissions`, but pending requests are never shared between sessions.`session/list` entries include `hostTools`, the number of declared host tools.`provider/model` is explicit selection: the provider is taken from the name, so a provider thatdiff --git a/packages/adk/src/generated/rpc-types.d.ts b/packages/adk/src/generated/rpc-types.d.tsindex f4814821e..91560b56e 100644--- a/packages/adk/src/generated/rpc-types.d.ts+++ b/packages/adk/src/generated/rpc-types.d.ts@@ -173,6 +173,10 @@ export interface SessionStartParams {"tools"?: HostToolDeclSchema[]/** `false` advertises only the host tools: no built-ins, MCP, plugin, `ask`, `todo`, subagent or monitor tools. */"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. 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.tsindex 651f9881f..d2709b0c9 100644--- a/packages/adk/src/index.d.ts+++ b/packages/adk/src/index.d.ts@@ -123,6 +123,18 @@ export interface CreateSessionOptions {ephemeral?: boolean/** `false` advertises only the host tools, no built-ins or MCP. */builtins?: boolean+ /**+ * Whether the model may delegate to subagents; defaults to `builtins`. With+ * `builtins: false` it adds only `dispatch_subagent` and `list_subagents`,+ * and every child is limited to this session's host tools.+ */+ 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.+ * Subagents keep their own prompts. Must not be blank.+ */+ systemPrompt?: string/*** Who gates a host tool call. `'host'` when this process runs and gates its* own tools, so the runtime never prompts for them. `'jan'` (the default)diff --git a/packages/adk/src/index.js b/packages/adk/src/index.jsindex 3e0034596..8341ba5a6 100644--- a/packages/adk/src/index.js+++ b/packages/adk/src/index.js@@ -617,11 +617,13 @@ export class JanRuntime {// Start a session. `tools` are host tools this session may call: each// declares what it does (`capability: 'read'` for a sensor, `'actuator'` for// something that moves) and carries the `handler` that runs it here.- async createSession({ cwd, model, ephemeral, builtins, permissions = 'jan', tools = [] } = {}) {+ async createSession({ cwd, model, ephemeral, builtins, subagents, systemPrompt, permissions = 'jan', tools = [] } = {}) {const params = { cwd: cwd ?? this.cwd ?? process.cwd() }if (model !== undefined) params.model = modelif (ephemeral !== undefined) params.ephemeral = ephemeralif (builtins !== undefined) params.builtins = builtins+ if (subagents !== undefined) params.subagents = subagents+ if (systemPrompt !== undefined) params.systemPrompt = systemPromptif (permissions !== 'jan') params.permissions = permissionsif (tools.length) params.tools = tools.map(toDeclaration)const view = await this.request('session/start', params)diff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.jsonindex c236efbee..6f393c058 100644--- a/protocol/rpc-schema.json+++ b/protocol/rpc-schema.json@@ -96,6 +96,22 @@"type": "boolean","default": true},+ "subagents": {+ "description": "Whether the session may delegate to subagents; defaults to `builtins`.\nWith `builtins: false` it adds only `dispatch_subagent` and\n`list_subagents`, and every child is held to the session's host tools.\n`false` withholds subagent tools even from a session with built-ins.",+ "type": [+ "boolean",+ "null"+ ],+ "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. Children keep their own prompts.",+ "type": [+ "string",+ "null"+ ],+ "default": null+ },"permissions": {"$ref": "#/$defs/PermissionOwner","default": "jan"diff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rsindex fada5cafd..e525fda2a 100644--- a/src-tauri/jan-cli/tests/agent_rpc.rs+++ b/src-tauri/jan-cli/tests/agent_rpc.rs@@ -544,6 +544,15 @@ const PROSE: &str = concat!(/// has to land for the round trip to mean anything.fn scripted_provider(replies: &'static [&'static str],+) -> (String, std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>>) {+ routed_provider(move |index, _| replies[index.min(replies.len() - 1)])+}++/// Serve whatever `reply` picks for each request, from its arrival index and+/// body, and keep every body. A run with children sends requests from more+/// than one conversation at once, so their order is not the script's to fix.+fn routed_provider(+ reply: impl Fn(usize, &serde_json::Value) -> &'static str + Send + 'static,) -> (String, std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>>) {let listener = TcpListener::bind("127.0.0.1:0").unwrap();let url = format!("http://{}/v1", listener.local_addr().unwrap());@@ -570,10 +579,10 @@ fn scripted_provider(if std::io::Read::read_exact(&mut reader, &mut request).is_err() {continue;}- sink.lock()- .unwrap()- .push(serde_json::from_slice(&request).unwrap_or(serde_json::Value::Null));- let reply = replies[index.min(replies.len() - 1)];+ let body: serde_json::Value =+ serde_json::from_slice(&request).unwrap_or(serde_json::Value::Null);+ let reply = reply(index, &body);+ sink.lock().unwrap().push(body);let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len());}});@@ -1045,3 +1054,214 @@ fn an_ephemeral_session_neither_indexes_nor_recalls_project_memory() {rpc.close();let _ = std::fs::remove_dir_all(scratch);}++/// One streamed assistant turn that calls `name` with `args`, as the provider+/// would send it.+fn tool_call_reply(name: &str, args: serde_json::Value) -> &'static str {+ let call = serde_json::json!({+ "id":"stub-3","object":"chat.completion.chunk","created":1,"model":"stub-model",+ "choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call-9","type":"function",+ "function":{"name":name,"arguments":args.to_string()}}]},"finish_reason":null}]+ });+ let end = serde_json::json!({+ "id":"stub-3","object":"chat.completion.chunk","created":1,"model":"stub-model",+ "choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],+ "usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}+ });+ Box::leak(format!("data: {call}\n\ndata: {end}\n\ndata: [DONE]\n\n").into_boxed_str())+}++fn advertised(request: &serde_json::Value) -> Vec<String> {+ request["tools"]+ .as_array()+ .map(|tools| {+ tools+ .iter()+ .filter_map(|tool| tool["function"]["name"].as_str().map(str::to_owned))+ .collect()+ })+ .unwrap_or_default()+}++fn system_text(request: &serde_json::Value) -> Option<String> {+ request["messages"]+ .as_array()?+ .iter()+ .find(|message| message["role"] == "system")+ .map(|message| match &message["content"] {+ serde_json::Value::String(text) => text.clone(),+ other => other.to_string(),+ })+}++/// A session with only host tools can still delegate. The parent is offered+/// dispatch and nothing else of Jan's; the child is held to the parent's host+/// tools -- no shell, files, web or skills -- even though the model names the+/// tool by the bare name the host declared; and the child's call reaches the+/// host attributed to the child.+#[test]+fn a_host_only_session_delegates_to_a_child_held_to_its_host_tools() {+ let scratch = scratch("host-delegate");+ let home = scratch.join("home");+ let dispatch = tool_call_reply(+ "dispatch_subagent",+ serde_json::json!({"subagents":[{"name":"mover","task":"move the arm to bin","allowed_tools":["robot_arm_move"]}]}),+ );+ let (url, seen) = routed_provider(move |_, body| {+ let answered = body["messages"]+ .as_array()+ .is_some_and(|messages| messages.iter().any(|m| m["role"] == "tool"));+ let parent = advertised(body).iter().any(|name| name == "dispatch_subagent");+ match (parent, answered) {+ (true, false) => dispatch,+ (false, false) => HOST_TOOL_CALL,+ _ => PROSE,+ }+ });+ configure(&home, &url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");++ let started = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{+ "cwd":project,"model":"stub-model","tools":[arm_tool()],"builtins":false,"subagents":true,+ "permissions":"host","ephemeral":true,"systemPrompt":"You drive the arm."+ }}));+ assert_eq!(+ started["result"]["tools"],+ serde_json::json!(["dispatch_subagent", "list_subagents", "host__robot_arm_move"]),+ "{started}"+ );+ let session_id = started["result"]["sessionId"].as_str().unwrap().to_owned();++ let turn = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"delegate the move"}}));+ assert!(turn["result"]["turnId"].is_string(), "{turn}");+ let request = rpc+ .read_until(|record| record["method"] == "item/tool_request")+ .expect("the child's call reaches the host");+ let event = &request["params"]["event"];+ assert_eq!(event["tool_name"], "robot_arm_move", "{request}");+ assert!(+ event["run_id"].as_str().is_some_and(|id| id.starts_with("sub-mover")),+ "the call is attributed to the child: {request}"+ );+ let request_id = event["request_id"].as_str().unwrap().to_owned();+ rpc.send(serde_json::json!({"jsonrpc":"2.0","id":5,"method":"tool/respond","params":{"requestId":request_id,"content":"moved"}}));+ let terminal = rpc+ .read_until(|record| record["method"] == "turn/completed")+ .expect("the turn completes");+ assert_eq!(terminal["params"]["stopReason"], "completed", "{terminal}");++ let requests = seen.lock().unwrap();+ let child: Vec<&serde_json::Value> = requests+ .iter()+ .filter(|body| !advertised(body).iter().any(|name| name == "dispatch_subagent"))+ .collect();+ assert!(!child.is_empty(), "the child made no request");+ for body in &child {+ assert_eq!(advertised(body), ["host__robot_arm_move"], "{body}");+ assert_ne!(+ system_text(body).as_deref(),+ Some("You drive the arm."),+ "a child runs on its own prompt, not the host's"+ );+ }+ drop(requests);++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// A child a host-only session dispatches with no allowlist of its own is+/// still held to the session's host tools: without the parent's allowlist it+/// would inherit Jan's whole toolset, shell included.+#[test]+fn a_child_dispatched_without_an_allowlist_inherits_the_host_only_set() {+ let scratch = scratch("host-delegate-inherit");+ let home = scratch.join("home");+ let dispatch = tool_call_reply(+ "dispatch_subagent",+ serde_json::json!({"subagents":[{"name":"mover","task":"say hi"}]}),+ );+ let (url, seen) = routed_provider(move |_, body| {+ let answered = body["messages"]+ .as_array()+ .is_some_and(|messages| messages.iter().any(|m| m["role"] == "tool"));+ let parent = advertised(body).iter().any(|name| name == "dispatch_subagent");+ if parent && !answered { dispatch } else { PROSE }+ });+ configure(&home, &url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");+ let started = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{+ "cwd":project,"model":"stub-model","tools":[arm_tool()],"builtins":false,"subagents":true,"permissions":"host"+ }}));+ let session_id = started["result"]["sessionId"].as_str().unwrap_or_else(|| panic!("{started}")).to_owned();+ complete_turn(&mut rpc, 4, &session_id);++ let requests = seen.lock().unwrap();+ let child: Vec<Vec<String>> = requests+ .iter()+ .map(advertised)+ .filter(|names| !names.iter().any(|name| name == "dispatch_subagent"))+ .collect();+ assert_eq!(child, [["host__robot_arm_move"]], "{requests:?}");+ drop(requests);++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// `systemPrompt` is the whole system prompt, byte for byte: no Jan identity,+/// guides, environment, date or git state around it. A model switch and a fork+/// keep it; a blank one is refused rather than read as "no prompt".+#[test]+fn a_host_system_prompt_is_sent_verbatim_and_kept() {+ let scratch = scratch("host-system-prompt");+ 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 blank = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{+ "cwd":project,"model":"stub-model","systemPrompt":" "+ }}));+ assert_eq!(blank["error"]["code"], -32602, "{blank}");++ let prompt = "You are the arm controller.\nAnswer in one line.";+ let started = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"session/start","params":{+ "cwd":project,"model":"stub-model","tools":[arm_tool()],"builtins":false,"systemPrompt":prompt+ }}));+ let session_id = started["result"]["sessionId"].as_str().unwrap_or_else(|| panic!("{started}")).to_owned();+ complete_turn(&mut rpc, 5, &session_id);+ let set = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":6,"method":"session/model/set","params":{"sessionId":session_id,"model":"stub-model"}}));+ assert_eq!(set["result"]["model"], "stub-model", "{set}");+ complete_turn(&mut rpc, 7, &session_id);+ let fork = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":8,"method":"session/fork","params":{"sessionId":session_id}}));+ let fork = fork["result"]["sessionId"].as_str().unwrap_or_else(|| panic!("{fork}")).to_owned();+ complete_turn(&mut rpc, 9, &fork);++ let requests = seen.lock().unwrap();+ assert_eq!(requests.len(), 3, "{requests:?}");+ for body in requests.iter() {+ let systems: Vec<&serde_json::Value> = body["messages"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|message| message["role"] == "system")+ .collect();+ assert_eq!(systems.len(), 1, "{body}");+ assert_eq!(system_text(body).as_deref(), Some(prompt), "{body}");+ let wire = body.to_string();+ for jan_text in ["Jan agent harness", "Today's date is", "# Working Directory"] {+ assert!(!wire.contains(jan_text), "{jan_text:?} leaked into {body}");+ }+ }+ drop(requests);++ 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.rsindex 40f1df2a4..86b4a9509 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -100,6 +100,13 @@ pub(crate) struct OrchestrationArgs {/// shared project-context and tool-use prompt assembled for normal runs./// Child turns remain excluded from project memory recall/indexing.pub system_prompt_override: Option<String>,+ /// A host's whole system prompt (RPC `session/start` `systemPrompt`), sent+ /// verbatim in place of the composed one: no identity, guides, environment,+ /// date, git state, plan/todo guidance or project memory. A host that owns+ /// the prompt owns all of it; Jan's guides would describe tools a host-only+ /// session does not have. Never inherited by a child, which runs on its+ /// definition's prompt.+ pub host_system_prompt: Option<String>,/// Whether the run recalls project memory into its prompt and indexes its/// final answer into it. `false` for an ephemeral RPC session, whose/// answers must neither outlive it nor reach a later session in the same@@ -509,6 +516,10 @@ struct SubagentContext {/// resends the reasoning of its own tool-call turns, so an opt-out that/// stopped at the parent would still break a strict provider.send_reasoning: bool,+ /// The parent's per-request allowlist, the ceiling every child's tool set+ /// is held to (see+ /// [`crate::core::agent::subagent::ParentRun::tool_ceiling`]).+ tool_ceiling: Option<Vec<String>>,/// Background children of this run, aborted when the run ends.bg: std::sync::Arc<crate::core::agent::subagent::BackgroundSubagents>,/// The registry's teardown generation when this run started. A dispatch may@@ -1283,6 +1294,7 @@ impl CompositeToolInvoker {budget_remaining: ctx.max_session_tokens,send_reasoning: ctx.send_reasoning,cost_remaining: ctx.cost_ceiling,+ tool_ceiling: ctx.tool_ceiling.clone(),},&self.events,// Unconfined means no scratch: the tools see the real@@ -2343,6 +2355,7 @@ pub(crate) async fn run_server_side_openai_orchestration(ask_requests: None,todo_registry: None,system_prompt_override: None,+ host_system_prompt: None,project_memory: true,subagents_enabled: false,max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,@@ -2906,6 +2919,7 @@ async fn orchestrate_inner(ask_requests,todo_registry,system_prompt_override,+ host_system_prompt,project_memory,subagents_enabled,max_parallel_subagents,@@ -2969,34 +2983,46 @@ async fn orchestrate_inner(.as_ref().map(|s| s.prompt.clone()).unwrap_or_default();- let stable_system = build_run_system_prompt(- assistant_instructions.as_deref(),- system_prompt_override.as_deref(),- project_root.as_deref(),- session_id.as_deref(),- *subagents_enabled,- settings.as_ref().is_some_and(|s| s.sandbox),- &prompt_policy,- )?;+ // A host prompt replaces the composition outright: nothing Jan writes is+ // placed around it, above the cache line or below the history.+ let stable_system = match host_system_prompt.as_deref() {+ Some(prompt) => Some(ComposedPrompt {+ prefix: prompt.to_string(),+ tail: Vec::new(),+ }),+ None => build_run_system_prompt(+ assistant_instructions.as_deref(),+ system_prompt_override.as_deref(),+ project_root.as_deref(),+ session_id.as_deref(),+ *subagents_enabled,+ settings.as_ref().is_some_and(|s| s.sandbox),+ &prompt_policy,+ )?,+ };+ let jan_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.- volatile_parts.push((- Composer::Date,- format!(- "Today's date is {}.",- chrono::Local::now().format("%Y-%m-%d")- ),- ));+ if jan_prompt {+ volatile_parts.push((+ Composer::Date,+ format!(+ "Today's date is {}.",+ chrono::Local::now().format("%Y-%m-%d")+ ),+ ));+ }// 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() {+ if let Some(root) = project_root.as_deref().filter(|_| jan_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.- let use_memory = *project_memory && system_prompt_override.is_none();+ // 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 {if let Some(root) = project_root {if let Some(query) = latest_user_text(&conversation_messages) {@@ -3020,13 +3046,17 @@ 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;- 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()));+ // 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()));+ }}// One tail message, built from every block the policy kept below the cache@@ -3225,6 +3255,11 @@ async fn orchestrate_inner(max_session_tokens,cost_ceiling,send_reasoning: body_send_reasoning(json_body),+ tool_ceiling: allowed_names.as_ref().map(|names| {+ let mut names: Vec<String> = names.iter().cloned().collect();+ names.sort_unstable();+ names+ }),bg_generation: bg.generation(),bg: bg.clone(),});diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex c6cb30403..0892b26dd 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -496,6 +496,82 @@ pub fn intersect_allowed_tools(}}+/// Hold a resolved child tool set to the parent's `ceiling`.+///+/// With no ceiling the resolved set stands. Under one, a child that asked for+/// nothing inherits the ceiling itself (the parent's whole set, never Jan's+/// 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`.+///+/// 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+/// may hand out so the model can retry. The forced skill tools a child is+/// normally given are dropped here unless the ceiling holds them.+fn capped_tools(+ resolved: Option<Vec<String>>,+ ceiling: Option<&[String]>,+ child: &str,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+) -> Result<Option<Vec<String>>, SubagentError> {+ let resolved = resolved.map(|tools| qualify_host_names(tools, parent_args));+ let Some(ceiling) = ceiling else {+ return Ok(resolved);+ };+ let Some(requested) = resolved else {+ return Ok(Some(ceiling.to_vec()));+ };+ let mut kept: Vec<String> = Vec::new();+ for tool in &requested {+ if ceiling.contains(tool) && !kept.contains(tool) {+ kept.push(tool.clone());+ }+ }+ if kept.is_empty() {+ return Err(SubagentError::PermissionDenied(format!(+ "none of the tools asked for subagent '{child}' ({}) is available to it; this \+ session can give a subagent: {}. Omit allowed_tools to give it all of them.",+ requested.join(", "),+ ceiling.join(", ")+ )));+ }+ Ok(Some(kept))+}++/// Rewrite each tool a host declared from the name it declared (`observe`,+/// `arm.move`) to the wire name the child is offered it under. Looked up in the+/// declarations rather than prefixed: a dotted name maps to a hashed wire name+/// only the declaration still knows. Every other name passes through.+#[cfg(feature = "cli")]+fn qualify_host_names(+ tools: Vec<String>,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+) -> Vec<String> {+ let mut out: Vec<String> = Vec::with_capacity(tools.len());+ for tool in tools {+ let wire = parent_args+ .host_tools+ .all()+ .iter()+ .find(|host| host.name == tool)+ .map_or(tool, |host| host.qualified_name.clone());+ if !out.contains(&wire) {+ out.push(wire);+ }+ }+ out+}++/// No host tools outside the headless build, so there is nothing to rewrite.+#[cfg(not(feature = "cli"))]+fn qualify_host_names(+ tools: Vec<String>,+ _parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+) -> Vec<String> {+ tools+}+/// One subagent within a phased dispatch. When `name` matches a saved definition/// that definition's role and tools are used (and `allowed_tools` further narrows/// it); otherwise the subagent runs as a focused general-purpose agent defined by@@ -1173,6 +1249,13 @@ pub(crate) struct ParentRun {/// child of budget mid-task fails the run the user asked for. The parent's/// own ceiling still stops the run once those charges land on it.pub(crate) cost_remaining: Option<crate::core::agent::session::CostCeiling>,+ /// The parent's own per-request allowlist, or `None` when it runs with no+ /// allowlist. A child can never be offered more than its parent was: a+ /// host-only RPC session sets one so its delegates cannot reach the shell,+ /// files or web the session itself was never given. The forced skill+ /// tools are no exception here, since they are Jan's and the session+ /// excluded Jan's tools.+ pub(crate) tool_ceiling: Option<Vec<String>>,}/// The model a dispatch will actually be billed for: the definition's own when@@ -1313,6 +1396,10 @@ async fn run_subagent(let name = resolved.definition.name.clone();let mut child_args = parent_args;child_args.system_prompt_override = Some(resolved.definition.system_prompt.clone());+ // The host wrote its prompt for the conversation it drives, not for a+ // delegate with a task of its own; left in place it would also replace the+ // definition's prompt set just above.+ child_args.host_system_prompt = None;child_args.subagents_enabled = false;// A subagent's own interactive question (if any) belongs to its parent's// conversation, not a client waiting on this child's ask_requests -- and@@ -1446,6 +1533,16 @@ pub(crate) fn spawn_subagent(..parent.clone()};+ let resolved = ResolvedDispatch {+ allowed_tools: capped_tools(+ resolved.allowed_tools,+ parent.tool_ceiling.as_deref(),+ &req.name,+ parent_args,+ )?,+ ..resolved+ };+let name = resolved.definition.name.clone();let run_id = next_subagent_run_id(&name);let (tx, rx) = tokio::sync::oneshot::channel();@@ -1676,6 +1773,12 @@ pub(crate) fn spawn_dispatch_plan(for phase in &plan.phases {for req in &phase.subagents {let resolved = resolve_dispatch(®istry, req, &parent_args.permissions)?;+ capped_tools(+ resolved.allowed_tools.clone(),+ parent.tool_ceiling.as_deref(),+ &req.name,+ parent_args,+ )?;// Priced up front for the same reason the permission check is: a// later phase naming an unpriceable model must fail the whole plan// now, not after the earlier phases have already been billed.@@ -2695,6 +2798,7 @@ mod tests {budget_remaining: None,send_reasoning: true,cost_remaining: None,+ tool_ceiling: None,}}@@ -3174,6 +3278,76 @@ mod tests {// ── max-parallel admission (semaphore queue) ───────────────────────────+ /// A parent whose host declared `observe` and the dotted `arm.move`.+ #[cfg(feature = "cli")]+ fn host_parent() -> crate::core::agent::r#loop::OrchestrationArgs {+ let root = unique_root("capped-tools");+ let mut args = max_par_args(&root);+ args.host_tools = crate::core::agent::host_tools::HostToolSet::declare(+ ["observe", "arm.move"]+ .map(|name| serde_json::from_value(serde_json::json!({ "name": name })).unwrap())+ .into(),+ )+ .unwrap();+ args+ }++ #[cfg(feature = "cli")]+ fn names(tools: &[&str]) -> Vec<String> {+ tools.iter().map(|t| (*t).to_string()).collect()+ }++ /// The model names a host tool the way the host's prompt does. Under no+ /// ceiling (a session with built-ins) that name used to reach the child's+ /// allowlist unchanged, match nothing, and leave it only the skill tools.+ #[cfg(feature = "cli")]+ #[test]+ fn a_declared_host_name_resolves_to_its_wire_name() {+ let parent = host_parent();+ let arm = parent.host_tools.all()[1].qualified_name.clone();+ assert_ne!(arm, "host__arm.move", "a dotted name is mapped");+ let out = capped_tools(+ Some(names(&["observe", "arm.move", "host__observe", "skill_read"])),+ None,+ "probe",+ &parent,+ )+ .unwrap();+ assert_eq!(out, Some(vec!["host__observe".to_string(), arm, "skill_read".to_string()]));+ }++ /// Under a ceiling a child is never offered more than its parent: no+ /// allowlist inherits the ceiling, not Jan's whole set, and a list is+ /// narrowed to it, forced skill tools included.+ #[cfg(feature = "cli")]+ #[test]+ fn a_child_is_held_to_the_parents_ceiling() {+ let parent = host_parent();+ let ceiling = names(&["dispatch_subagent", "host__observe"]);+ assert_eq!(+ capped_tools(None, Some(&ceiling), "probe", &parent).unwrap(),+ Some(ceiling.clone())+ );+ assert_eq!(+ capped_tools(Some(names(&["observe", "bash", "skill_list"])), Some(&ceiling), "probe", &parent)+ .unwrap(),+ Some(names(&["host__observe"]))+ );+ }++ /// A list that keeps nothing fails the dispatch, naming what the parent+ /// may hand out, instead of starting a child with no tools at all.+ #[cfg(feature = "cli")]+ #[test]+ fn a_list_the_ceiling_keeps_nothing_of_is_refused() {+ let parent = host_parent();+ let ceiling = names(&["host__observe"]);+ let err = capped_tools(Some(names(&["bash"])), Some(&ceiling), "probe", &parent).unwrap_err();+ let message = err.to_string();+ assert!(matches!(err, SubagentError::PermissionDenied(_)), "{message}");+ assert!(message.contains("host__observe") && message.contains("probe"), "{message}");+ }+/// Minimal run args for queue tests: empty providers (so dispatched/// children fail fast instead of hanging), a real project root holding the/// subagent def, subagents enabled, cap 1.@@ -3204,6 +3378,7 @@ mod tests {ask_requests: None,todo_registry: None,system_prompt_override: None,+ host_system_prompt: None,project_memory: true,subagents_enabled: true,max_parallel_subagents: 1,diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 4161f0eb2..c0e2a8433 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1175,6 +1175,7 @@ fn build_cli_orchestration_args(ask_requests: None,todo_registry: None,system_prompt_override: None,+ host_system_prompt: None,project_memory: true,subagents_enabled: true,max_parallel_subagents,diff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsindex daebb2060..f99308a51 100644--- a/src-tauri/src/core/cli/rpc.rs+++ b/src-tauri/src/core/cli/rpc.rs@@ -33,6 +33,29 @@ struct Session {/// `false` restricts every turn to the host tools, through the same/// per-request `allowed_tools` allowlist an API caller uses.builtins: bool,+ /// Whether the turn may delegate. Mirrored into the agent's+ /// `subagents_enabled`; kept here because a rebuilt agent starts from the+ /// project default and has to be told again.+ 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.+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(host_names(&session.agent.args.host_tools));+ names+ })}struct ActiveTurn {@@ -129,8 +152,8 @@ async fn tools_view(session: &Session) -> Value {.iter().filter_map(|tool| tool["function"]["name"].as_str().map(str::to_owned)).collect();- if !session.builtins {- tools.retain(|name| args.host_tools.is_host_tool(name));+ if let Some(allowed) = session_allowlist(session) {+ tools.retain(|name| allowed.contains(name));}let specs: Vec<Value> = args.host_tools@@ -327,8 +350,8 @@ fn start_turn(.map_err(|_| "RPC output queue is full; retry after draining notifications".to_owned())?;session.history.push(json!({"role":"user","content":input}));let mut body = session.agent.body(json!(session.history));- if !session.builtins {- body["allowed_tools"] = json!(host_names(&session.agent.args.host_tools));+ if let Some(allowed) = session_allowlist(session) {+ body["allowed_tools"] = json!(allowed);}let args = session.agent.args.clone();let (events, receiver) = mpsc::channel(64);@@ -394,6 +417,8 @@ fn rebuild_agent(source: &Session, model: Option<String>) -> Result<AgentSessionagent.args.host_tools = source.agent.args.host_tools.clone();agent.args.host_owns_gate = source.agent.args.host_owns_gate;agent.args.project_memory = source.agent.args.project_memory;+ agent.args.subagents_enabled = source.subagents;+ agent.args.host_system_prompt = source.agent.args.host_system_prompt.clone();Ok(agent)}@@ -533,6 +558,10 @@ pub async fn serve() -> Result<(), String> {match serde_json::from_value::<SessionStartParams>(params.clone()) {Err(_) => error(&id, -32602, "session/start requires cwd and supported options"),Ok(start) if !std::path::Path::new(&start.cwd).is_dir() => error(&id, -32602, "cwd is not a directory"),+ // A blank prompt is almost certainly a host bug (an unset+ // template), and sending it would run a model with no+ // instructions at all rather than with Jan's.+ Ok(start) if start.system_prompt.as_deref().is_some_and(|p| p.trim().is_empty()) => error(&id, -32602, "systemPrompt must not be blank; omit it to use Jan's"),// Declared before the session is built: a tool set the// host got wrong is refused before anything is spent.Ok(start) => match declare_tools(start.tools) {@@ -544,13 +573,16 @@ pub async fn serve() -> Result<(), String> {// "Not saved" covers project memory too: an ephemeral// session's answers must not reach a later session.agent.args.project_memory = !start.ephemeral;+ let subagents = start.subagents.unwrap_or(start.builtins);+ agent.args.subagents_enabled = subagents;+ agent.args.host_system_prompt = start.system_prompt;let sid = uuid::Uuid::new_v4().to_string();// The run reports the session by the id this client holds, not// by the private one the agent was built with: provenance and the// correlation id are the client's handle on the session, and an id// nothing else can name is not a handle.agent.args.session_id = Some(sid.clone());- let session = Session { agent, history: Vec::new(), id: sid.clone(), turns: 0, ephemeral: start.ephemeral, builtins: start.builtins };+ let session = Session { agent, history: Vec::new(), id: sid.clone(), turns: 0, ephemeral: start.ephemeral, builtins: start.builtins, subagents };let mut result = tools_view(&session).await;result["sessionId"] = json!(sid);result["model"] = json!(session.agent.model);@@ -697,7 +729,8 @@ pub async fn serve() -> Result<(), String> {let history = source.history.clone();let ephemeral = source.ephemeral;let builtins = source.builtins;- sessions.insert(fork.clone(), Session { agent, history, id: fork.clone(), turns: 0, ephemeral, builtins });+ let subagents = source.subagents;+ sessions.insert(fork.clone(), Session { agent, history, id: fork.clone(), turns: 0, ephemeral, builtins, subagents });response(&id, json!({"sessionId":fork}))}Err(message) => error(&id, -32602, &message),diff --git a/src-tauri/src/core/cli/rpc_schema.rs b/src-tauri/src/core/cli/rpc_schema.rsindex 8e1ac3ab6..a5ca72d69 100644--- a/src-tauri/src/core/cli/rpc_schema.rs+++ b/src-tauri/src/core/cli/rpc_schema.rs@@ -48,6 +48,17 @@ pub struct SessionStartParams {/// `ask`, `todo`, subagent or monitor tools.#[serde(default = "builtins_default")]pub builtins: 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.+ #[serde(default)]+ 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. Children keep their own prompts.+ #[serde(default)]+ pub system_prompt: Option<String>,#[serde(default)]pub permissions: PermissionOwner,}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 8742f2f0c..ea7f40dce 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -25273,6 +25273,7 @@ mod tests {ask_requests: None,todo_registry: None,system_prompt_override: None,+ host_system_prompt: None,project_memory: true,subagents_enabled: true,max_parallel_subagents: 4,