1 //! siGit Code — local coding agent on Onde Inference.
2 //!
3 //! In TTY mode, all output (log crate, tracing, stray printlns) redirects to
4 //! `$TMPDIR/sigit.log`. Ratatui holds a separate fd to the real terminal so
5 //! the TUI stays clean.
6 //!
7 //! Two modes:
8 //! - ACP over stdio (editor integration, e.g. Zed)
9 //! - interactive terminal (direct TTY)
10 //!
11 //! Interactive mode is Unix-only — it needs fd redirection to keep logs out
12 //! of the TUI. Windows only gets ACP mode for now.
13 //!
14 //! On macOS the HF cache lives in the App Group container shared with the
15 //! siGit desktop app. See [`setup`].
16 //!
17 //! # Zed setup
18 //!
19 //! Add to `~/.config/zed/settings.json`:
20 //! ```json
21 //! {
22 //! "agent_servers": {
23 //! "siGit Code": {
24 //! "type": "custom",
25 //! "command": "/absolute/path/to/target/release/sigit"
26 //! }
27 //! }
28 //! }
29 //! ```
30
31 mod account;
32 mod backend;
33 mod chat;
34 mod credentials;
35 mod headless;
36 mod instructions;
37 mod mcp;
38 mod models;
39 mod permissions;
40 mod provider;
41 mod session_store;
42 mod settings;
43 mod setup;
44 mod skills;
45 mod tools;
46
47 /// Serializes tests that mutate process-global env vars (`SIGIT_CONFIG_DIR`
48 /// etc.). `cargo test` runs tests in parallel within a binary, so without this
49 /// the credentials and settings round-trip tests clobber each other's env.
50 #[cfg(test)]
51 pub(crate) static ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
52
53 use std::io::IsTerminal;
54 #[cfg(unix)]
55 use std::io::{BufWriter, Write};
56 use std::sync::Arc;
57
58 use onde::inference::SamplingConfig;
59
60 // `ProtocolVersion` is a version-agnostic type at the schema root; the rest of the
61 // schema types moved under `schema::v1` in agent-client-protocol 1.0.
62 use agent_client_protocol::schema::ProtocolVersion;
63 use agent_client_protocol::schema::v1::{
64 AgentCapabilities, AuthMethod, AuthMethodAgent, AuthenticateRequest, AuthenticateResponse,
65 AvailableCommand, AvailableCommandInput, AvailableCommandsUpdate, CancelNotification,
66 ConfigOptionUpdate, ContentBlock, ContentChunk, EmbeddedResourceResource, ForkSessionRequest,
67 ForkSessionResponse, Implementation, InitializeRequest, InitializeResponse, LoadSessionRequest,
68 LoadSessionResponse, Meta, NewSessionRequest, NewSessionResponse, PermissionOption,
69 PermissionOptionKind, PromptRequest, PromptResponse, RequestPermissionOutcome,
70 RequestPermissionRequest, SessionCapabilities, SessionConfigOption,
71 SessionConfigOptionCategory, SessionConfigSelectOption, SessionConfigValueId,
72 SessionForkCapabilities, SessionId, SessionNotification, SessionUpdate,
73 SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, StopReason, ToolCall,
74 ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind, UnstructuredCommandInput,
75 };
76 use agent_client_protocol::{Agent, ByteStreams, Client, ConnectionTo, Responder};
77 use onde::inference::{ChatEngine, GgufModelConfig};
78
79 use crate::backend::{
80 InferenceBackend, LocalBackend, OpenAiBackend, ToolResult as BackendToolResult, ToolSpec,
81 TurnResult,
82 };
83 use std::path::PathBuf;
84 use std::sync::atomic::{AtomicBool, Ordering};
85 use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
86 use tracing_subscriber::{EnvFilter, fmt as tracing_fmt};
87
88 #[cfg(unix)]
89 use std::os::unix::io::{AsRawFd, FromRawFd};
90
91 const SYSTEM_PROMPT: &str = "\
92 Your name is siGit — lowercase 's', uppercase 'G', no spaces. \
93 Not 'SiGit', not 'Sigit'. Only say your name if the user asks who you are.
94
95 You are a strong general-purpose coding agent. smbCloud is your home turf, \
96 but you should still be useful in any codebase. When the project is clearly \
97 about smbCloud, use that context directly instead of falling back to vague \
98 cloud-platform advice.
99
100 smbCloud context you should know and use when it helps:
101 - smbCloud is a platform for deploying and managing projects
102 - the main CLI is a Rust workspace with focused crates rather than one giant crate
103 - common areas include auth, project management, deploy flows, networking, \
104 shared models, release tooling, and managed services
105 - deploy branches usually follow `release/service-{name}`
106 - Next.js SSR deploys on smbCloud are not the same as generic git-push deploys; \
107 they often use a local build plus rsync/PM2 style flow
108 - auth has a hard boundary between smbCloud platform users and tenant app users; \
109 platform flows use `/v1/users*`, tenant app flows use `/v1/client/*`, and \
110 you should not casually mix `User`, `TenantMembership`, `AuthApp`, and `AuthUser`
111 - smbCloud authorization is layered; do not flatten platform accounts, tenant \
112 memberships, auth-app collaborators, and tenant end users into one model
113 - `Project` is the umbrella workspace, while app-like resources such as \
114 `FrontendApp`, `AuthApp`, and GresIQ are the deployable units with their own \
115 ownership, sharing, and collaboration rules
116 - `FrontendApp` is many-per-project, while `AuthApp` is intentionally one-per-project; \
117 preserve those cardinality rules unless the code clearly changes them
118 - GresIQ is smbCloud's managed PostgreSQL offering; treat it as a platform \
119 service with its own credentials and boundaries, not as a generic local DB helper
120 - when debugging smbCloud Rails APIs, first classify the request: first-party \
121 smbCloud app or tenant app, then check which endpoint family and validator \
122 should be involved before changing code
123 - when working in smbCloud repos, prefer existing workspace patterns, existing \
124 crate boundaries, existing Rails conventions, and existing command flows over \
125 inventing new abstractions
126
127 CRITICAL RULE — never tell the user to run a command. You have tools. Use them. \
128 When the user asks you to clone a repo, run a build, check git status, or do \
129 anything that involves a shell command, you MUST call the run_command tool and \
130 execute it yourself. Do not print shell commands for the user to copy-paste. \
131 Do not give step-by-step instructions. Do not say \"you can run …\". Just do it. \
132 If a command fails, try to fix the problem and re-run it. If you cannot fix it \
133 after two attempts, explain what went wrong and what you tried.
134
135 Git operations — always use run_command:
136 - git clone: always pass the full absolute destination path as the last argument \
137 and set cwd to an existing writable parent directory. Example: \
138 run_command({\"command\": \"git clone https://github.com/org/repo /Users/me/Repositories/repo\", \
139 \"cwd\": \"/Users/me/Repositories\"})
140 - git init, add, commit, push, pull, fetch, checkout, branch, diff, log, status, \
141 stash, rebase, merge, tag — use run_command with an absolute cwd pointing to \
142 the repo root
143 - never run git clone without an explicit absolute destination path
144 - if a clone or init fails, check the error, fix the cause (wrong path, missing \
145 directory, permissions), and retry
146 - when you create a commit, always end the commit message with a blank line and \
147 then this trailer on its own line: Co-Authored-By: siGit Code <sigit@sigit.si> \
148 — GitHub reads that exact format and credits siGit as co-author. If a commit \
149 lands without it, siGit Code amends the trailer in automatically and the tool \
150 output says so; do not amend again yourself.
151
152 Never introduce yourself unless asked. Jump straight into the answer. \
153 Keep answers short. Write idiomatic code. \
154 Fix root causes, not symptoms.
155
156 You have access to tools that let you read files, read websites directly from \
157 http and https URLs, create directories, list directories, search code, create \
158 new files, edit existing files, delete files, and run shell commands. You can \
159 also use git directly through shell commands, including `git init` and normal \
160 git workflows. Use them proactively. Read the code or website before answering. \
161 Prefer absolute paths when referring to files and directories, especially in \
162 protocol-facing output and tool arguments. Create directories when needed. Run \
163 builds, tests, and git commands after making changes. Ground your answers in \
164 the actual code or fetched page content, not in guesses.
165
166 CRITICAL — you CAN access websites. You are NOT a typical LLM without internet \
167 access. You have a read_website tool that fetches any http or https URL and \
168 returns the page text. When the user gives you a URL or asks you to read, \
169 summarize, or inspect a web page, you MUST call the read_website tool with that \
170 URL. Never say \"I cannot access websites\" or \"I cannot browse the internet\". \
171 You can. Use the tool.
172
173 CRITICAL — before every edit_file call, you MUST call read_file on the target \
174 file first (or the specific line range if one was given). Never rely on file \
175 content you saw in a previous turn — the user may have reverted, edited, or \
176 changed the file externally since then. Always re-read to get the current state \
177 before constructing old_text. \
178 When the user corrects a previous edit (e.g. \"don't remove X, append instead\"), \
179 treat it as a fresh task: re-read the file, identify the current content, and \
180 plan the edit from scratch. Do not assume the file still reflects your last edit.
181
182 Tool-use heuristics:
183 - when the user provides a URL or asks about a web page, ALWAYS call \
184 read_website — never refuse or claim you lack internet access
185 - prefer absolute paths over relative paths when you mention, return, or pass \
186 file and directory paths
187 - if a path does not exist yet, create the directory before creating files in it
188 - if the user asks to clone a repo, immediately call run_command with git clone \
189 and an absolute destination path — do not ask where to put it unless the \
190 request is ambiguous; default to the user's home Repositories directory
191 - if the user asks for a new repo, scaffold, or scratch project, create the \
192 directory, create the first files, and run `git init` without waiting unless \
193 the request says otherwise
194 - if the repo looks like smbCloud CLI code, respect workspace crate boundaries, \
195 shared models, and existing command handlers before adding new abstractions
196 - if the repo looks like smbCloud Rails code, check routes, controllers, \
197 validators, and model boundaries before changing business logic
198 - if the task touches smbCloud auth, first decide whether it is a platform-user \
199 flow or a tenant-app flow, then follow the right endpoint family and model layer
200 - if the task touches smbCloud deploy code, check whether it is the generic \
201 deploy path or the Next.js SSR path before proposing changes
202 - after edits, prefer running the smallest useful verification step first, then \
203 widen to broader checks if needed
204 - use git commands naturally for status checks, repo setup, diffs, and normal \
205 developer workflows when they help move the task forward
206 - if a tool call fails, read the error, try to fix it, and retry — do not \
207 fall back to telling the user what to type
208
209 When the repo is not about smbCloud, act like a normal coding agent and do not \
210 force smbCloud-specific advice into the answer. When it is about smbCloud, be \
211 specific and practical.
212
213 Be direct and brief. Write clean, idiomatic code. When debugging, go for the \
214 root cause, not the symptom. Correct beats clever.";
215
216 /// shorter prompt for models without tool calling (e.g. DeepSeek Coder v1).
217 /// the full [`SYSTEM_PROMPT`] wastes context and confuses them.
218 const SIMPLE_SYSTEM_PROMPT: &str = "\
219 Your name is siGit — a coding assistant. \
220 You are helpful, concise, and write clean, idiomatic code. \
221 Answer any question the user asks — programming, general knowledge, or casual chat. \
222 When debugging, address the root cause, not the symptom. \
223 Be direct and brief.";
224
225 pub(crate) fn system_prompt_for_model(tool_calling: bool) -> &'static str {
226 if tool_calling {
227 SYSTEM_PROMPT
228 } else {
229 SIMPLE_SYSTEM_PROMPT
230 }
231 }
232
233 /// cap tool-call loops so a confused model can't spin forever; auto-compaction
234 /// (see [`backend::DEFAULT_CONTEXT_TOKEN_BUDGET`]) keeps long runs inside the
235 /// context window, so the cap can afford to be generous
236 const MAX_TOOL_ROUNDS: usize = 24;
237
238 /// Outcome of asking the client for permission to run one tool call.
239 enum PermissionVerdict {
240 /// Run the tool.
241 Approved,
242 /// Skip the tool; the string becomes its tool result so the model adapts.
243 Denied(String),
244 /// The client cancelled the turn while the request was pending; stop the
245 /// whole prompt with `StopReason::Cancelled` instead of burning rounds.
246 TurnCancelled,
247 }
248
249 /// Display kind for the permission dialog, so editors can show a fitting icon.
250 fn tool_kind_for(tool_name: &str) -> ToolKind {
251 match tool_name {
252 "edit_file" | "multi_edit" | "create_file" | "create_directory" | "remember" => {
253 ToolKind::Edit
254 }
255 "delete_file" => ToolKind::Delete,
256 "run_command" | "kill_command" => ToolKind::Execute,
257 "read_file" | "list_directory" | "command_output" => ToolKind::Read,
258 "search_files" | "glob" => ToolKind::Search,
259 "read_website" => ToolKind::Fetch,
260 "write_todos" => ToolKind::Think,
261 _ => ToolKind::Other,
262 }
263 }
264
265 /// Shown when a siGit Code Cloud tier is selected without a signed-in account.
266 const CLOUD_LOGIN_PROMPT: &str = "siGit Code Cloud needs an account. Sign in with \
267 `/login <email> <password>` (or the Authenticate button), then pick the tier again. \
268 Create an account at https://sigit.si.";
269
270 /// The per-session context system message: cwd guidance plus any project
271 /// instruction files (`AGENTS.md` / `CLAUDE.md`) found for that directory. Used
272 /// by every session entry point so on-device and cloud backends get the same
273 /// always-on project context.
274 fn session_context_message(cwd: &std::path::Path) -> String {
275 let mut message = format!(
276 "The user's project working directory is {}. \
277 Always use absolute paths under this directory for all file \
278 and directory operations. This is the root of the project \
279 the user has open in their editor.",
280 cwd.display()
281 );
282 if let Some(project_instructions) = instructions::load_project_instructions(cwd) {
283 message.push_str("\n\n");
284 message.push_str(&project_instructions);
285 }
286 message
287 }
288
289 fn agent_tools_as_specs() -> Vec<ToolSpec> {
290 let mut specs: Vec<ToolSpec> = tools::all_tools()
291 .into_iter()
292 .map(|t| ToolSpec {
293 name: t.name.to_string(),
294 description: t.description.to_string(),
295 parameters_schema: t.parameters_schema.to_string(),
296 })
297 .collect();
298
299 // Advertise the `skill` tool only when skills are present, so models without
300 // any skills installed don't see a dangling capability (Agent Skills format,
301 // https://agentskills.io). Discovery metadata lives in the tool description.
302 let discovered = skills::discover_skills();
303 if !discovered.is_empty() {
304 specs.push(ToolSpec {
305 name: skills::SKILL_TOOL_NAME.to_string(),
306 description: skills::skill_tool_description(&discovered),
307 parameters_schema: skills::skill_tool_schema().to_string(),
308 });
309 }
310
311 // Delegated research (`task`) is offered only when a subagent backend can
312 // actually be built — same conditional pattern as the `skill` tool above.
313 if tools::subagent_available() {
314 specs.push(tools::task_tool_spec());
315 }
316
317 // Tools discovered from configured MCP servers (incl. the official one).
318 specs.extend(mcp::tool_specs());
319
320 specs
321 }
322
323 /// Register the `task` tool's subagent factory for an OpenAI-compatible
324 /// provider: each subagent run gets a FRESH `OpenAiBackend` against the same
325 /// endpoint (its own conversation history), seeded with the subagent system
326 /// prompt. The provider config is captured by clone. Called once at startup by
327 /// whichever surface resolved the provider; on-device paths register a factory
328 /// that returns `None` instead (onde has a single shared history, so a second
329 /// concurrent context is not possible yet).
330 fn register_subagent_factory_for(cfg: &provider::ProviderConfig) {
331 let cfg = cfg.clone();
332 tools::set_subagent_factory(Box::new(move || {
333 Some(Arc::new(OpenAiBackend::new(
334 cfg.base_url.clone(),
335 cfg.api_key.clone(),
336 cfg.model.clone(),
337 Some(tools::SUBAGENT_SYSTEM_PROMPT.to_string()),
338 )) as Arc<dyn InferenceBackend>)
339 }));
340 }
341
342 fn initialize_meta() -> Meta {
343 let startup_selection = setup::startup_model_selection();
344
345 let active_model_name = startup_selection
346 .as_ref()
347 .map(|selection| selection.display_name.clone())
348 .unwrap_or_else(|| GgufModelConfig::qwen25_3b().display_name);
349
350 let active_model_id = startup_selection
351 .as_ref()
352 .and_then(|selection| selection.selected_model.as_ref())
353 .map(|selected| selected.model_id.clone())
354 .unwrap_or_else(|| GgufModelConfig::qwen25_3b().model_id);
355
356 let active_model_file = startup_selection
357 .as_ref()
358 .and_then(|selection| selection.selected_model.as_ref())
359 .map(|selected| selected.gguf_file.clone())
360 .unwrap_or_else(|| {
361 GgufModelConfig::qwen25_3b()
362 .files
363 .first()
364 .cloned()
365 .unwrap_or_default()
366 });
367
368 let mut model = serde_json::Map::new();
369 model.insert(
370 "display_name".to_string(),
371 serde_json::Value::String(active_model_name),
372 );
373 model.insert(
374 "model_id".to_string(),
375 serde_json::Value::String(active_model_id),
376 );
377 model.insert(
378 "gguf_file".to_string(),
379 serde_json::Value::String(active_model_file),
380 );
381
382 let mut sigit = serde_json::Map::new();
383 sigit.insert("active_model".to_string(), serde_json::Value::Object(model));
384
385 let mut meta = Meta::new();
386 meta.insert("sigit".to_string(), serde_json::Value::Object(sigit));
387 meta
388 }
389
390 struct SiGitAgent {
391 engine: Arc<ChatEngine>,
392 /// The active inference backend. `LocalBackend` by default; swapped to an
393 /// `OpenAiBackend` when the user selects a siGit Code Cloud tier in the panel.
394 backend: tokio::sync::Mutex<Arc<dyn InferenceBackend>>,
395 /// cwd from the editor — tool calls run here, not where the process started
396 session_cwd: std::sync::Mutex<Option<PathBuf>>,
397 current_model: std::sync::Mutex<GgufModelConfig>,
398 /// flipped once the startup model finishes (success or failure)
399 model_ready: Arc<AtomicBool>,
400 /// guards the one-time lazy startup load for ACP mode
401 startup_model_load_started: Arc<AtomicBool>,
402 /// set if the startup load failed
403 model_load_error: Arc<std::sync::Mutex<Option<String>>>,
404 /// true when the startup model isn't cached yet
405 startup_needs_download: bool,
406 /// for progress UI
407 startup_model_name: String,
408 /// for download-progress polling
409 startup_model_id: String,
410 /// Serializes turn-affecting handlers (prompt, session lifecycle, config
411 /// changes). They run in `cx.spawn`ed tasks so the JSON-RPC dispatch loop
412 /// stays free to route client responses (e.g. permission answers) mid-turn;
413 /// this lock reproduces the strict ordering the dispatch loop used to give
414 /// them for free.
415 turn_lock: Arc<tokio::sync::Mutex<()>>,
416 }
417
418 impl SiGitAgent {
419 fn new(
420 engine: Arc<ChatEngine>,
421 initial_model: GgufModelConfig,
422 model_ready: Arc<AtomicBool>,
423 startup_model_load_started: Arc<AtomicBool>,
424 model_load_error: Arc<std::sync::Mutex<Option<String>>>,
425 startup_needs_download: bool,
426 ) -> Self {
427 let startup_model_name = initial_model.display_name.clone();
428 let startup_model_id = initial_model.model_id.clone();
429 let backend: Arc<dyn InferenceBackend> = Arc::new(LocalBackend::new(Arc::clone(&engine)));
430 Self {
431 engine,
432 backend: tokio::sync::Mutex::new(backend),
433 session_cwd: std::sync::Mutex::new(None),
434 current_model: std::sync::Mutex::new(initial_model),
435 model_ready,
436 startup_model_load_started,
437 model_load_error,
438 startup_needs_download,
439 startup_model_name,
440 startup_model_id,
441 turn_lock: Arc::new(tokio::sync::Mutex::new(())),
442 }
443 }
444
445 fn start_startup_model_load_if_needed(&self) {
446 if self
447 .startup_model_load_started
448 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
449 .is_err()
450 {
451 return;
452 }
453
454 self.model_ready.store(false, Ordering::Release);
455 if let Ok(mut guard) = self.model_load_error.lock() {
456 *guard = None;
457 }
458
459 let startup_config = self.current_model.lock().unwrap().clone();
460 let (max_tokens, tool_calling) = models::local_picker_items()
461 .into_iter()
462 .find(|item| {
463 item.config.model_id == startup_config.model_id
464 && item
465 .config
466 .files
467 .first()
468 .zip(startup_config.files.first())
469 .map(|(left, right)| left == right)
470 .unwrap_or(false)
471 })
472 .map(|item| (item.max_tokens, item.tool_calling))
473 .unwrap_or((4096, false));
474
475 let sampling = SamplingConfig {
476 max_tokens: Some(max_tokens),
477 ..SamplingConfig::default()
478 };
479
480 let loader_engine = Arc::clone(&self.engine);
481 let loader_system_prompt = system_prompt_for_model(tool_calling).to_string();
482 let model_ready = Arc::clone(&self.model_ready);
483 let model_load_error = Arc::clone(&self.model_load_error);
484
485 std::thread::spawn(move || {
486 let result = tokio::runtime::Runtime::new()
487 .map_err(|error| error.to_string())
488 .and_then(|rt| {
489 rt.block_on(loader_engine.load_gguf_model(
490 startup_config,
491 Some(loader_system_prompt),
492 Some(sampling),
493 ))
494 .map(|_| ())
495 .map_err(|error| error.to_string())
496 });
497
498 if let Ok(mut guard) = model_load_error.lock() {
499 *guard = result.err();
500 }
501 model_ready.store(true, Ordering::Release);
502 });
503 }
504
505 /// block until the startup model is ready, showing progress in the session.
506 async fn await_model_ready(
507 &self,
508 cx: &ConnectionTo<Client>,
509 session_id: &SessionId,
510 ) -> agent_client_protocol::Result<()> {
511 if self.model_ready.load(Ordering::Acquire) {
512 // already done — might be a stored error from earlier
513 if let Some(err) = self.model_load_error.lock().unwrap().as_ref() {
514 return Err(agent_client_protocol::Error::new(
515 -32603,
516 format!("model load failed: {err}"),
517 ));
518 }
519 return Ok(());
520 }
521
522 const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
523
524 let tool_call_id = format!("startup-load-{}", uuid::Uuid::new_v4());
525 let title = if self.startup_needs_download {
526 format!("Downloading {}", self.startup_model_name)
527 } else {
528 format!("Loading {}", self.startup_model_name)
529 };
530
531 self.send_tool_call_update(
532 cx,
533 session_id.clone(),
534 SessionUpdate::ToolCall(
535 ToolCall::new(tool_call_id.clone(), &title)
536 .kind(ToolKind::Think)
537 .status(ToolCallStatus::InProgress)
538 .content(vec![format!("{}…", title).into()]),
539 ),
540 )
541 .ok();
542
543 let expected_bytes = if self.startup_needs_download {
544 onde::inference::models::SUPPORTED_MODEL_INFO
545 .iter()
546 .find(|m| m.id == self.startup_model_id)
547 .map(|m| m.expected_size_bytes)
548 .unwrap_or(0)
549 } else {
550 0
551 };
552
553 let load_start = std::time::Instant::now();
554 let mut tick: usize = 0;
555 let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
556 interval.tick().await;
557
558 loop {
559 interval.tick().await;
560 tick += 1;
561
562 if self.model_ready.load(Ordering::Acquire) {
563 break;
564 }
565
566 let frame = SPINNER[tick % SPINNER.len()];
567 let elapsed = load_start.elapsed();
568 let elapsed_str = if elapsed.as_secs() >= 60 {
569 format!("{}m {:02}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
570 } else {
571 format!("{}s", elapsed.as_secs())
572 };
573
574 let (update_title, update_content) =
575 if self.startup_needs_download && expected_bytes > 0 {
576 let cache_path = onde::hf_cache::model_cache_path(&self.startup_model_id);
577 let downloaded = cache_path
578 .as_ref()
579 .filter(|p| p.exists())
580 .map(|p| dir_size_recursive(p))
581 .unwrap_or(0);
582 let pct = ((downloaded as f64 / expected_bytes as f64) * 100.0).min(99.0) as u8;
583 let bar = progress_bar(pct, 20);
584 let size_hint = format!(" (~{})", format_size_human(expected_bytes));
585 (
586 format!(
587 "{frame} Downloading {}{size_hint} ({pct}%)",
588 self.startup_model_name
589 ),
590 format!(
591 "{} — {bar} {pct}% ({} / {})",
592 self.startup_model_name,
593 format_size_human(downloaded),
594 format_size_human(expected_bytes),
595 ),
596 )
597 } else if self.startup_needs_download {
598 let cache_path = onde::hf_cache::model_cache_path(&self.startup_model_id);
599 let downloaded = cache_path
600 .as_ref()
601 .filter(|p| p.exists())
602 .map(|p| dir_size_recursive(p))
603 .unwrap_or(0);
604 (
605 format!("{frame} Downloading {}", self.startup_model_name),
606 format!(
607 "{} — {} downloaded… ({elapsed_str})",
608 self.startup_model_name,
609 format_size_human(downloaded),
610 ),
611 )
612 } else {
613 (
614 format!("{frame} Loading {}", self.startup_model_name),
615 format!(
616 "{frame} Loading {}… ({elapsed_str})",
617 self.startup_model_name
618 ),
619 )
620 };
621
622 self.send_tool_call_update(
623 cx,
624 session_id.clone(),
625 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
626 tool_call_id.clone(),
627 ToolCallUpdateFields::new()
628 .title(update_title)
629 .status(ToolCallStatus::InProgress)
630 .content(vec![update_content.into()]),
631 )),
632 )
633 .ok();
634 }
635
636 // done — check if it blew up
637 let load_error = self.model_load_error.lock().unwrap().clone();
638 if let Some(err) = load_error {
639 self.send_tool_call_update(
640 cx,
641 session_id.clone(),
642 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
643 tool_call_id,
644 ToolCallUpdateFields::new()
645 .title("Model load failed".to_string())
646 .status(ToolCallStatus::Failed)
647 .content(vec![format!("error: {err}").into()]),
648 )),
649 )
650 .ok();
651
652 return Err(agent_client_protocol::Error::new(
653 -32603,
654 format!("model load failed: {err}"),
655 ));
656 }
657
658 let done_title = if self.startup_needs_download {
659 format!("✓ {} downloaded and loaded", self.startup_model_name)
660 } else {
661 format!("✓ {} loaded", self.startup_model_name)
662 };
663
664 self.send_tool_call_update(
665 cx,
666 session_id.clone(),
667 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
668 tool_call_id,
669 ToolCallUpdateFields::new()
670 .title(done_title)
671 .status(ToolCallStatus::Completed),
672 )),
673 )
674 .ok();
675
676 Ok(())
677 }
678
679 fn send_assistant_message(
680 &self,
681 cx: &ConnectionTo<Client>,
682 session_id: SessionId,
683 text: impl Into<String>,
684 ) -> agent_client_protocol::Result<()> {
685 cx.send_notification(SessionNotification::new(
686 session_id,
687 SessionUpdate::AgentMessageChunk(ContentChunk::new(ContentBlock::from(text.into()))),
688 ))
689 }
690
691 /// Run one inference turn (`fut`) while concurrently forwarding any streamed
692 /// tokens to the editor. The sink receiver is drained as the future runs, so
693 /// chunks reach the client live rather than all at once when it resolves.
694 ///
695 /// `assembled`/`sent`/`streamed_any` persist across the turns of a single
696 /// prompt so reasoning is stripped consistently and we never re-send text.
697 #[allow(clippy::too_many_arguments)]
698 async fn drain_turn<F>(
699 &self,
700 cx: &ConnectionTo<Client>,
701 session_id: &SessionId,
702 fut: F,
703 sink_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
704 assembled: &mut String,
705 sent: &mut String,
706 streamed_any: &mut bool,
707 ) -> Result<TurnResult, backend::BackendError>
708 where
709 F: std::future::Future<Output = Result<TurnResult, backend::BackendError>>,
710 {
711 tokio::pin!(fut);
712 let result = loop {
713 tokio::select! {
714 done = &mut fut => break done,
715 Some(piece) = sink_rx.recv() => {
716 self.emit_visible_chunk(cx, session_id, &piece, assembled, sent, streamed_any);
717 }
718 }
719 };
720 // Flush tokens that landed between the last poll and the future resolving.
721 while let Ok(piece) = sink_rx.try_recv() {
722 self.emit_visible_chunk(cx, session_id, &piece, assembled, sent, streamed_any);
723 }
724 result
725 }
726
727 /// Append a streamed fragment, strip `<think>` reasoning from the running
728 /// text, and send only the newly revealed visible suffix as a chunk. Tracking
729 /// the assembled text (not just deltas) keeps think-block stripping correct
730 /// even when a tag spans chunk boundaries.
731 fn emit_visible_chunk(
732 &self,
733 cx: &ConnectionTo<Client>,
734 session_id: &SessionId,
735 piece: &str,
736 assembled: &mut String,
737 sent: &mut String,
738 streamed_any: &mut bool,
739 ) {
740 assembled.push_str(piece);
741 let (_think, visible) = chat::strip_think_blocks(assembled);
742 match visible.strip_prefix(sent.as_str()) {
743 Some(extra) if !extra.is_empty() => {
744 let extra = extra.to_string();
745 *sent = visible;
746 *streamed_any = true;
747 self.send_assistant_message(cx, session_id.clone(), extra)
748 .ok();
749 }
750 // No new visible text, or the visible prefix changed retroactively
751 // (rare, e.g. a late-closing think tag): just resync without
752 // resending what's already on the wire.
753 _ => *sent = visible,
754 }
755 }
756
757 fn send_tool_call_update(
758 &self,
759 cx: &ConnectionTo<Client>,
760 session_id: SessionId,
761 update: SessionUpdate,
762 ) -> agent_client_protocol::Result<()> {
763 cx.send_notification(SessionNotification::new(session_id, update))
764 }
765
766 /// Advertise siGit's slash commands to the client. Editors like Zed parse
767 /// `/`-prefixed input and only forward commands they've been told about, so
768 /// without this `/login`, `/models`, etc. are rejected client-side.
769 fn advertise_commands(&self, cx: &ConnectionTo<Client>, session_id: SessionId) {
770 let with_hint = |name: &str, desc: &str, hint: &str| {
771 AvailableCommand::new(name, desc).input(AvailableCommandInput::Unstructured(
772 UnstructuredCommandInput::new(hint),
773 ))
774 };
775 let commands = vec![
776 AvailableCommand::new("help", "Show available commands"),
777 AvailableCommand::new("models", "List available models").input(
778 AvailableCommandInput::Unstructured(UnstructuredCommandInput::new(
779 "model number to switch to (optional)",
780 )),
781 ),
782 with_hint(
783 "local",
784 "Toggle on-device inference mode",
785 "on|off (optional)",
786 ),
787 AvailableCommand::new("skills", "List available Agent Skills"),
788 AvailableCommand::new("mcp", "List MCP servers and their tools"),
789 AvailableCommand::new("load", "Load the selected on-device model"),
790 with_hint("login", "Sign in to siGit Code Cloud", "<email> <password>"),
791 AvailableCommand::new("logout", "Sign out of siGit Code Cloud"),
792 AvailableCommand::new("whoami", "Show the signed-in account"),
793 AvailableCommand::new("reload", "Re-sync sign-in and model state"),
794 with_hint(
795 "plan",
796 "Plan mode: research only, no edits or commands",
797 "on|off (optional)",
798 ),
799 AvailableCommand::new("permissions", "Show the tool permission policy"),
800 AvailableCommand::new("compact", "Summarize and shrink the conversation history"),
801 AvailableCommand::new("clear", "Wipe the conversation history"),
802 AvailableCommand::new("status", "Show engine status"),
803 ];
804 self.send_tool_call_update(
805 cx,
806 session_id,
807 SessionUpdate::AvailableCommandsUpdate(AvailableCommandsUpdate::new(commands)),
808 )
809 .ok();
810 }
811
812 async fn switch_model_by_id(
813 &self,
814 model_id: &str,
815 ) -> agent_client_protocol::Result<GgufModelConfig> {
816 let (new_config, max_tokens, new_tool_calling) = resolve_model_config(model_id)
817 .ok_or_else(|| {
818 agent_client_protocol::Error::new(
819 -32602,
820 format!("unknown or unavailable model: {model_id}"),
821 )
822 })?;
823
824 log::info!(
825 "switching model to {} (max_tokens={max_tokens})",
826 new_config.display_name
827 );
828
829 let sampling = SamplingConfig {
830 max_tokens: Some(max_tokens),
831 ..SamplingConfig::default()
832 };
833
834 // block_in_place inside spawn_local panics, so run the load on a
835 // dedicated thread with its own runtime (same trick as startup)
836 let (result_tx, result_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
837 let loader_engine = Arc::clone(&self.engine);
838 let loader_config = new_config.clone();
839 let loader_system_prompt = system_prompt_for_model(new_tool_calling).to_string();
840 let loader_sampling = sampling;
841
842 std::thread::spawn(move || {
843 let rt = tokio::runtime::Runtime::new().expect("failed to create loader runtime");
844 let result = rt.block_on(async move {
845 // load_gguf_model already unloads the old model internally;
846 // calling unload first would leave a gap where prompts fail
847 loader_engine
848 .load_gguf_model(
849 loader_config,
850 Some(loader_system_prompt),
851 Some(loader_sampling),
852 )
853 .await
854 });
855 let _ = result_tx.send(result.map(|_| ()).map_err(|e| e.to_string()));
856 });
857
858 result_rx
859 .await
860 .map_err(|_| agent_client_protocol::Error::new(-32603, "model loader thread crashed"))?
861 .map_err(|error| {
862 log::error!("model switch failed: {error}");
863 agent_client_protocol::Error::new(-32603, format!("model switch failed: {error}"))
864 })?;
865
866 self.startup_model_load_started
867 .store(true, Ordering::Release);
868 self.model_ready.store(true, Ordering::Release);
869 if let Ok(mut guard) = self.model_load_error.lock() {
870 *guard = None;
871 }
872
873 if let Some(item) = models::local_picker_items()
874 .iter()
875 .find(|item| item.config.model_id == new_config.model_id)
876 && let Err(err) = setup::save_selected_model(&setup::SelectedModel {
877 model_id: item.config.model_id.clone(),
878 gguf_file: item.config.files.first().cloned().unwrap_or_default(),
879 })
880 {
881 log::warn!("failed to persist model selection: {err}");
882 }
883
884 {
885 let mut guard = self.current_model.lock().unwrap();
886 *guard = new_config.clone();
887 }
888
889 if let Some(cwd) = self.session_cwd.lock().ok().and_then(|g| g.clone()) {
890 self.engine
891 .push_history(onde::inference::ChatMessage::system(
892 session_context_message(&cwd),
893 ))
894 .await;
895 }
896
897 Ok(new_config)
898 }
899 }
900
901 // ── ACP handler implementations ───────────────────────────────────────────────
902
903 impl SiGitAgent {
904 async fn handle_initialize(
905 &self,
906 _req: InitializeRequest,
907 ) -> agent_client_protocol::Result<InitializeResponse> {
908 log::info!("initialize");
909
910 // Agent-handled auth method. We don't use `AuthMethod::Terminal`: editors
911 // like Zed advertise terminal-auth capability but don't actually spawn the
912 // login terminal for *custom* ACP agents, so the button is a silent no-op.
913 // With an Agent method, clicking calls `authenticate`, which returns either
914 // confirmation (already signed in via `/login`) or a message telling the
915 // user to run `/login <email> <password>` — so the button does something.
916 let auth_methods = vec![AuthMethod::Agent(
917 AuthMethodAgent::new("sigit", "Sign in to siGit Code")
918 .description("Sign in with `/login <email> <password>` in the message box."),
919 )];
920
921 Ok(InitializeResponse::new(ProtocolVersion::V1)
922 .agent_info(
923 Implementation::new("sigit", env!("CARGO_PKG_VERSION"))
924 .title("siGit Code - AI Coding Agent"),
925 )
926 .auth_methods(auth_methods)
927 .agent_capabilities(
928 AgentCapabilities::default()
929 .load_session(true)
930 .session_capabilities(
931 SessionCapabilities::new().fork(SessionForkCapabilities::new()),
932 ),
933 )
934 .meta(initialize_meta()))
935 }
936
937 async fn handle_authenticate(
938 &self,
939 req: AuthenticateRequest,
940 ) -> agent_client_protocol::Result<AuthenticateResponse> {
941 log::info!("authenticate: method={}", req.method_id.0);
942
943 // Confirm the stored token works. The button can't collect a password,
944 // so an unsigned-in user is pointed at the `/login` slash command; a user
945 // already signed in via `/login` gets the gate cleared.
946 match account::verify_session().await {
947 Ok(email) => {
948 log::info!("authenticate: verified session for {email}");
949 Ok(AuthenticateResponse::default())
950 }
951 Err(reason) => Err(agent_client_protocol::Error::new(
952 -32000,
953 format!(
954 "Not signed in to siGit Code Cloud ({reason}). \
955 Sign in with `/login <email> <password>` in the message box, \
956 or create an account at https://sigit.si."
957 ),
958 )),
959 }
960 }
961
962 async fn handle_load_session(
963 &self,
964 cx: &ConnectionTo<Client>,
965 args: LoadSessionRequest,
966 ) -> agent_client_protocol::Result<LoadSessionResponse> {
967 log::info!(
968 "load_session: id={}, cwd={}, additional_directories={:?}",
969 args.session_id,
970 args.cwd.display(),
971 args.additional_directories
972 .iter()
973 .map(|p| p.display().to_string())
974 .collect::<Vec<_>>()
975 );
976
977 if let Ok(mut guard) = self.session_cwd.lock() {
978 *guard = Some(args.cwd.clone());
979 }
980
981 // A session boundary: grants and plan mode from the previous life of
982 // this session id must not carry over — and since one shared engine
983 // means one live conversation, state for every other id is dead too.
984 permissions::reset_all();
985
986 // tool calls use relative paths, so we need to match the editor's cwd
987 if args.cwd.is_dir()
988 && let Err(err) = std::env::set_current_dir(&args.cwd)
989 {
990 log::warn!("could not set cwd to {}: {err}", args.cwd.display());
991 }
992
993 // start from a clean slate; a stored session (below) replaces it
994 self.engine.clear_history().await;
995
996 self.engine
997 .push_history(onde::inference::ChatMessage::system(
998 session_context_message(&args.cwd),
999 ))
1000 .await;
1001
1002 // Honor the persisted Local Inference toggle (off + signed in → cloud).
1003 self.apply_startup_inference_mode().await;
1004
1005 // Durable sessions: when this session id was saved before, restore its
1006 // history into the active backend. The snapshot includes the system
1007 // messages that were live when it was saved, so restore replaces the
1008 // freshly seeded state wholesale.
1009 if let Some(history) = session_store::load(&args.session_id.to_string()) {
1010 let restored = history.len();
1011 let backend = self.backend.lock().await.clone();
1012 backend.restore_history(history).await;
1013 log::info!(
1014 "load_session: restored {restored} message(s) for {}",
1015 args.session_id
1016 );
1017 }
1018
1019 let config_options = {
1020 let guard = self.current_model.lock().unwrap();
1021 build_model_config_options(&guard)
1022 };
1023
1024 self.advertise_commands(cx, args.session_id.clone());
1025
1026 Ok(LoadSessionResponse::new().config_options(config_options))
1027 }
1028
1029 async fn handle_fork_session(
1030 &self,
1031 cx: &ConnectionTo<Client>,
1032 args: ForkSessionRequest,
1033 ) -> agent_client_protocol::Result<ForkSessionResponse> {
1034 let new_id = SessionId::new(uuid::Uuid::new_v4().to_string());
1035 // Session boundary: permission grants and plan mode never cross it
1036 // (see handle_load_session), so a fork starts with a clean slate.
1037 permissions::reset_all();
1038 log::info!(
1039 "fork_session: from={} new={new_id}, cwd={}, additional_directories={:?}",
1040 args.session_id,
1041 args.cwd.display(),
1042 args.additional_directories
1043 .iter()
1044 .map(|p| p.display().to_string())
1045 .collect::<Vec<_>>()
1046 );
1047
1048 if let Ok(mut guard) = self.session_cwd.lock() {
1049 *guard = Some(args.cwd.clone());
1050 }
1051 if args.cwd.is_dir()
1052 && let Err(err) = std::env::set_current_dir(&args.cwd)
1053 {
1054 log::warn!("could not set cwd to {}: {err}", args.cwd.display());
1055 }
1056
1057 // no persistence, so fork == fresh session
1058 self.engine.clear_history().await;
1059
1060 self.engine
1061 .push_history(onde::inference::ChatMessage::system(
1062 session_context_message(&args.cwd),
1063 ))
1064 .await;
1065
1066 // Honor the persisted Local Inference toggle (off + signed in → cloud).
1067 self.apply_startup_inference_mode().await;
1068
1069 let config_options = {
1070 let guard = self.current_model.lock().unwrap();
1071 build_model_config_options(&guard)
1072 };
1073
1074 self.advertise_commands(cx, new_id.clone());
1075
1076 Ok(ForkSessionResponse::new(new_id).config_options(config_options))
1077 }
1078
1079 async fn handle_new_session(
1080 &self,
1081 cx: &ConnectionTo<Client>,
1082 args: NewSessionRequest,
1083 ) -> agent_client_protocol::Result<NewSessionResponse> {
1084 let session_id = SessionId::new(uuid::Uuid::new_v4().to_string());
1085 // Session boundary: permission grants and plan mode never cross it
1086 // (see handle_load_session), so stale ids stop accumulating state.
1087 permissions::reset_all();
1088 log::info!(
1089 "new_session: id={session_id}, cwd={}, additional_directories={:?}",
1090 args.cwd.display(),
1091 args.additional_directories
1092 .iter()
1093 .map(|p| p.display().to_string())
1094 .collect::<Vec<_>>()
1095 );
1096
1097 if let Ok(mut guard) = self.session_cwd.lock() {
1098 *guard = Some(args.cwd.clone());
1099 }
1100 if args.cwd.is_dir()
1101 && let Err(err) = std::env::set_current_dir(&args.cwd)
1102 {
1103 log::warn!("could not set cwd to {}: {err}", args.cwd.display());
1104 }
1105
1106 self.engine.clear_history().await;
1107
1108 self.engine
1109 .push_history(onde::inference::ChatMessage::system(
1110 session_context_message(&args.cwd),
1111 ))
1112 .await;
1113
1114 // Honor the persisted Local Inference toggle (off + signed in → cloud).
1115 self.apply_startup_inference_mode().await;
1116
1117 let config_options = {
1118 let guard = self.current_model.lock().unwrap();
1119 build_model_config_options(&guard)
1120 };
1121
1122 self.advertise_commands(cx, session_id.clone());
1123
1124 Ok(NewSessionResponse::new(session_id).config_options(config_options))
1125 }
1126
1127 async fn handle_prompt(
1128 &self,
1129 cx: &ConnectionTo<Client>,
1130 args: PromptRequest,
1131 ) -> agent_client_protocol::Result<PromptResponse> {
1132 let session_id = args.session_id.clone();
1133
1134 // log every block so we can debug @ references and file context
1135 for (i, block) in args.prompt.iter().enumerate() {
1136 match block {
1137 ContentBlock::Text(t) => {
1138 log::info!(
1139 "prompt({}) block[{}]: Text({} chars) = \"{}\"",
1140 session_id,
1141 i,
1142 t.text.len(),
1143 t.text.chars().take(200).collect::<String>()
1144 );
1145 }
1146 ContentBlock::Resource(embedded) => {
1147 log::info!(
1148 "prompt({}) block[{}]: EmbeddedResource = {:?}",
1149 session_id,
1150 i,
1151 match &embedded.resource {
1152 EmbeddedResourceResource::TextResourceContents(t) =>
1153 format!("TextResource(uri={}, {} chars)", t.uri, t.text.len()),
1154 EmbeddedResourceResource::BlobResourceContents(b) =>
1155 format!("BlobResource(uri={})", b.uri),
1156 _ => "Unknown".to_string(),
1157 }
1158 );
1159 }
1160 ContentBlock::ResourceLink(link) => {
1161 log::info!(
1162 "prompt({}) block[{}]: ResourceLink(name={}, uri={}, title={:?}, desc={:?})",
1163 session_id,
1164 i,
1165 link.name,
1166 link.uri,
1167 link.title,
1168 link.description
1169 );
1170 }
1171 other => {
1172 log::info!(
1173 "prompt({}) block[{}]: Other({:?})",
1174 session_id,
1175 i,
1176 std::mem::discriminant(other)
1177 );
1178 }
1179 }
1180 }
1181
1182 let mut parts: Vec<String> = Vec::new();
1183
1184 for block in &args.prompt {
1185 match block {
1186 ContentBlock::Text(t) => {
1187 parts.push(t.text.clone());
1188 }
1189 ContentBlock::Resource(embedded) => {
1190 // editor inlined the file content already
1191 match &embedded.resource {
1192 EmbeddedResourceResource::TextResourceContents(text_resource) => {
1193 parts.push(format!(
1194 "\n--- {} ---\n{}\n--- end {} ---",
1195 text_resource.uri, text_resource.text, text_resource.uri
1196 ));
1197 }
1198 EmbeddedResourceResource::BlobResourceContents(blob) => {
1199 parts.push(format!("[binary resource: {}]", blob.uri));
1200 }
1201 _ => {
1202 log::debug!("ignoring unsupported embedded resource variant");
1203 }
1204 }
1205 }
1206 ContentBlock::ResourceLink(link) => {
1207 // reference without content; read the file ourselves
1208 let label = link.name.clone();
1209
1210 if let Some(raw_path) = link.uri.strip_prefix("file://") {
1211 let (file_path, line_range) = if let Some(hash_pos) = raw_path.rfind('#') {
1212 let fragment = &raw_path[hash_pos + 1..];
1213 let path = &raw_path[..hash_pos];
1214 // Parse "L207:219" or "L207-219" → (207, 219)
1215 let range = fragment.strip_prefix('L').and_then(|rest| {
1216 let sep = if rest.contains(':') { ':' } else { '-' };
1217 let mut parts = rest.splitn(2, sep);
1218 let start = parts.next()?.parse::<usize>().ok()?;
1219 let end = parts.next()?.parse::<usize>().ok()?;
1220 Some((start, end))
1221 });
1222 (path, range)
1223 } else {
1224 (raw_path, None)
1225 };
1226
1227 match std::fs::read_to_string(file_path) {
1228 Ok(contents) => {
1229 let extracted = if let Some((start, end)) = line_range {
1230 let selected: Vec<&str> = contents
1231 .lines()
1232 .enumerate()
1233 .filter(|(i, _)| {
1234 let line_num = i + 1;
1235 line_num >= start && line_num <= end
1236 })
1237 .map(|(_, line)| line)
1238 .collect();
1239 format!(
1240 "\n--- {label} ({file_path} lines {start}-{end}) ---\n{}\n--- end {label} ---",
1241 selected.join("\n")
1242 )
1243 } else {
1244 format!(
1245 "\n--- {label} ({file_path}) ---\n{contents}\n--- end {label} ---"
1246 )
1247 };
1248 parts.push(extracted);
1249 }
1250 Err(err) => {
1251 log::warn!("could not read ResourceLink {}: {err}", link.uri);
1252 parts.push(format!("[referenced file: {label} ({file_path})]"));
1253 }
1254 }
1255 } else {
1256 parts.push(format!("[resource link: {label} ({})]", link.uri));
1257 }
1258 }
1259 _ => {
1260 log::debug!("ignoring unsupported content block type in prompt");
1261 }
1262 }
1263 }
1264
1265 let user_text = parts.join("\n");
1266
1267 if user_text.trim().is_empty() {
1268 return Ok(PromptResponse::new(StopReason::EndTurn));
1269 }
1270
1271 if let Some(command) = parse_slash(&user_text) {
1272 return exec_slash_acp(self, cx, session_id, command).await;
1273 }
1274
1275 log::info!(
1276 "prompt({}): \"{}\"",
1277 session_id,
1278 user_text.chars().take(80).collect::<String>()
1279 );
1280
1281 // The active backend drives the turn. Snapshot it once so a mid-turn
1282 // model switch doesn't split the conversation across backends.
1283 let backend = self.backend.lock().await.clone();
1284
1285 // Only on-device inference needs a local model in memory. Cloud tiers run
1286 // over the network, so they never need a local model. We never load the
1287 // on-device model implicitly: the user loads it explicitly with `/load`
1288 // (or by picking one in `/models`). If a prompt arrives before that, guide
1289 // them rather than blocking on a multi-minute download/load.
1290 if !backend.is_remote()
1291 && self.engine.info().await.status == onde::inference::EngineStatus::Unloaded
1292 {
1293 self.send_assistant_message(
1294 cx,
1295 session_id,
1296 "No on-device model is loaded. Run `/load` to load the selected model, \
1297 or `/models` to choose one.",
1298 )
1299 .ok();
1300 return Ok(PromptResponse::new(StopReason::EndTurn));
1301 }
1302
1303 // ── tool-calling loop ────────────────────────────────────────────
1304 // send message → execute any tool calls → feed results back
1305 // repeat up to MAX_TOOL_ROUNDS, then force a text reply
1306
1307 let tools = agent_tools_as_specs();
1308
1309 // Token sink: backends stream assistant text through this while a turn
1310 // runs. We forward the visible portion to the editor as agent-message
1311 // chunks live (see `drain_turn` / `emit_visible_chunk`). The sink stays
1312 // alive for the whole prompt so `recv()` only ends when a turn future
1313 // resolves, never because every sender was dropped.
1314 let (sink, mut sink_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
1315 let mut assembled = String::new();
1316 let mut sent = String::new();
1317 let mut streamed_any = false;
1318
1319 let mut result = self
1320 .drain_turn(
1321 cx,
1322 &session_id,
1323 backend.send_message_with_tools(&user_text, &tools, Some(&sink)),
1324 &mut sink_rx,
1325 &mut assembled,
1326 &mut sent,
1327 &mut streamed_any,
1328 )
1329 .await
1330 .map_err(|error| {
1331 log::error!("send_message_with_tools failed: {error}");
1332 agent_client_protocol::Error::new(-32603, format!("inference failed: {error}"))
1333 })?;
1334
1335 let mut round = 0;
1336
1337 while !result.tool_calls.is_empty() && round < MAX_TOOL_ROUNDS {
1338 round += 1;
1339 log::info!(
1340 "prompt({}) tool round {} — {} call(s)",
1341 session_id,
1342 round,
1343 result.tool_calls.len()
1344 );
1345
1346 // Auto-compaction: long tool runs grow history fast; fold it into
1347 // a summary before the next round rather than blowing the window.
1348 let estimate = backend::estimate_tokens(&backend.history_snapshot().await);
1349 if estimate > backend::DEFAULT_CONTEXT_TOKEN_BUDGET {
1350 log::info!(
1351 "prompt({}) history ≈{} tokens exceeds budget {} — compacting",
1352 session_id,
1353 estimate,
1354 backend::DEFAULT_CONTEXT_TOKEN_BUDGET
1355 );
1356 match backend.compact_history(backend::COMPACT_KEEP_LAST).await {
1357 Ok(()) => {
1358 let after = backend::estimate_tokens(&backend.history_snapshot().await);
1359 log::info!("prompt({}) compacted to ≈{} tokens", session_id, after);
1360 }
1361 Err(error) => log::warn!("prompt({}) compaction failed: {error}", session_id),
1362 }
1363 }
1364
1365 let mut tool_results = Vec::new();
1366
1367 for (call_index, tc) in result.tool_calls.iter().enumerate() {
1368 log::info!(
1369 " → {}({})",
1370 tc.name,
1371 tc.arguments.chars().take(120).collect::<String>()
1372 );
1373
1374 // Permission gate: read-only tools pass straight through; a
1375 // mutating tool consults policy and may ask the client.
1376 let output = match permissions::decision_for(&session_id.to_string(), &tc.name) {
1377 permissions::Decision::Allow => {
1378 tools::execute_tool(&tc.name, &tc.arguments).await
1379 }
1380 permissions::Decision::Deny(reason) => {
1381 log::info!(" ✗ {} denied by policy", tc.name);
1382 reason
1383 }
1384 permissions::Decision::Ask => {
1385 match self
1386 .request_tool_permission(cx, &session_id, &tc.name, &tc.arguments)
1387 .await
1388 {
1389 PermissionVerdict::Approved => {
1390 tools::execute_tool(&tc.name, &tc.arguments).await
1391 }
1392 PermissionVerdict::Denied(reason) => {
1393 log::info!(" ✗ {} denied by user", tc.name);
1394 reason
1395 }
1396 PermissionVerdict::TurnCancelled => {
1397 log::info!("prompt({}) cancelled at permission gate", session_id);
1398 // The assistant message carrying these tool
1399 // calls is already in the backend history;
1400 // leaving any of them unanswered makes strict
1401 // OpenAI-compatible endpoints reject every
1402 // later request in the session. Close out this
1403 // call and the ones this round never reached.
1404 for pending in &result.tool_calls[call_index..] {
1405 tool_results.push(BackendToolResult {
1406 tool_call_id: pending.id.clone(),
1407 content: format!(
1408 "`{}` was not executed: the user cancelled the turn \
1409 at the permission prompt.",
1410 pending.name
1411 ),
1412 });
1413 }
1414 backend.record_cancelled_tool_results(tool_results).await;
1415 return Ok(PromptResponse::new(StopReason::Cancelled));
1416 }
1417 }
1418 }
1419 };
1420
1421 log::info!(" ← {} chars", output.len());
1422
1423 tool_results.push(BackendToolResult {
1424 tool_call_id: tc.id.clone(),
1425 content: output,
1426 });
1427 }
1428
1429 let next_tools = if round < MAX_TOOL_ROUNDS {
1430 Some(tools.as_slice())
1431 } else {
1432 None // last round: force text
1433 };
1434
1435 result = self
1436 .drain_turn(
1437 cx,
1438 &session_id,
1439 backend.send_tool_results(tool_results, next_tools, Some(&sink)),
1440 &mut sink_rx,
1441 &mut assembled,
1442 &mut sent,
1443 &mut streamed_any,
1444 )
1445 .await
1446 .map_err(|e| agent_client_protocol::Error::new(-32603, e.to_string()))?;
1447 }
1448
1449 // ── Final text response ───────────────────────────────────────────
1450 // If anything streamed, the visible reply is already on the wire; only
1451 // send a trailing block for the non-streamed path (e.g. on-device direct
1452 // answers, which onde can't stream while tools are on offer).
1453 if !streamed_any {
1454 let reply_text = result.text.trim().to_string();
1455 let final_text = if reply_text.is_empty() {
1456 if round > 0 {
1457 log::warn!(
1458 "prompt({}) — model returned empty reply after {} tool round(s)",
1459 session_id,
1460 round
1461 );
1462 "Something went wrong — the edits didn't go through. Try rephrasing what you need, or point me at the specific lines.".to_string()
1463 } else {
1464 log::warn!(
1465 "prompt({}) — model returned empty reply (no tool rounds)",
1466 session_id
1467 );
1468 String::new()
1469 }
1470 } else {
1471 // strip <think> blocks so reasoning tokens stay hidden
1472 let (_think, visible) = chat::strip_think_blocks(&reply_text);
1473 visible
1474 };
1475
1476 if !final_text.is_empty() {
1477 self.send_assistant_message(cx, session_id.clone(), final_text)
1478 .ok();
1479 }
1480 }
1481
1482 // Persist the completed turn so a restart (or session/load) can pick
1483 // the conversation back up.
1484 let snapshot = backend.history_snapshot().await;
1485 if let Err(error) = session_store::save(&session_id.to_string(), &snapshot) {
1486 log::warn!("prompt({}) session save failed: {error}", session_id);
1487 }
1488
1489 log::info!("prompt({}) complete — {} tool round(s)", session_id, round);
1490 Ok(PromptResponse::new(StopReason::EndTurn))
1491 }
1492
1493 /// Ask the ACP client for permission to run one tool call. Presents
1494 /// allow-once / allow-for-session / deny; an "always allow" choice is
1495 /// recorded via [`permissions::grant_for_session`]. Only safe to call from
1496 /// a spawned task (see the handler registration in `run_acp_server`): the
1497 /// dispatch loop must be free to route the client's answer back to us.
1498 async fn request_tool_permission(
1499 &self,
1500 cx: &ConnectionTo<Client>,
1501 session_id: &SessionId,
1502 tool_name: &str,
1503 arguments: &str,
1504 ) -> PermissionVerdict {
1505 // The user decides from this dialog, so show the arguments with any
1506 // truncation flagged (a silently clipped command could hide its tail
1507 // from the person approving it). The full arguments also travel as
1508 // `raw_input` for clients that render it.
1509 let args_preview = permissions::approval_preview(arguments);
1510 let title = if args_preview.is_empty() {
1511 tool_name.to_string()
1512 } else {
1513 format!("{tool_name}({args_preview})")
1514 };
1515 let raw_input: serde_json::Value = serde_json::from_str(arguments)
1516 .unwrap_or_else(|_| serde_json::Value::String(arguments.to_string()));
1517
1518 let request = RequestPermissionRequest::new(
1519 session_id.clone(),
1520 ToolCallUpdate::new(
1521 format!("perm-{}", uuid::Uuid::new_v4()),
1522 ToolCallUpdateFields::new()
1523 .title(title)
1524 .kind(tool_kind_for(tool_name))
1525 .status(ToolCallStatus::Pending)
1526 .raw_input(raw_input),
1527 ),
1528 vec![
1529 PermissionOption::new("allow_once", "Allow once", PermissionOptionKind::AllowOnce),
1530 PermissionOption::new(
1531 "allow_session",
1532 "Allow for this session",
1533 PermissionOptionKind::AllowAlways,
1534 ),
1535 PermissionOption::new("reject_once", "Deny", PermissionOptionKind::RejectOnce),
1536 ],
1537 );
1538
1539 match cx.send_request(request).block_task().await {
1540 Ok(response) => match response.outcome {
1541 RequestPermissionOutcome::Selected(selected) => {
1542 match selected.option_id.0.as_ref() {
1543 "allow_once" => PermissionVerdict::Approved,
1544 "allow_session" => {
1545 permissions::grant_for_session(&session_id.to_string(), tool_name);
1546 PermissionVerdict::Approved
1547 }
1548 _ => PermissionVerdict::Denied(permissions::user_denial(tool_name)),
1549 }
1550 }
1551 RequestPermissionOutcome::Cancelled => PermissionVerdict::TurnCancelled,
1552 // The outcome enum is non_exhaustive; treat anything unknown as
1553 // a denial rather than running a mutating tool unapproved.
1554 _ => PermissionVerdict::Denied(permissions::user_denial(tool_name)),
1555 },
1556 Err(error) => {
1557 log::warn!("permission request for `{tool_name}` failed: {error}");
1558 PermissionVerdict::Denied(format!(
1559 "`{tool_name}` was not executed: this client could not answer the \
1560 permission request ({error}). The user can pre-approve tools in \
1561 settings.toml under [permissions], or set SIGIT_PERMISSIONS=allow \
1562 for clients without permission support."
1563 ))
1564 }
1565 }
1566 }
1567
1568 async fn handle_cancel(&self, args: CancelNotification) -> agent_client_protocol::Result<()> {
1569 log::info!("cancel requested for session {}", args.session_id);
1570 Ok(())
1571 }
1572
1573 /// Swap the active backend to a siGit Code Cloud tier and reflect it as the
1574 /// current model so the picker shows it selected. Returns the tier's display
1575 /// name on success, or `None` when no account is signed in (caller prompts
1576 /// for login). Shared by the panel picker and the `/models` slash command.
1577 async fn switch_to_cloud_tier(&self, tier: &str) -> Option<String> {
1578 let cfg = crate::provider::cloud_tier_provider(tier)?;
1579 let mut system_prompt = system_prompt_for_model(true).to_string();
1580 // Mirror the cwd guidance and project instruction files the local engine
1581 // gets at session load, so the cloud model shares the same project context.
1582 if let Some(cwd) = self.session_cwd.lock().ok().and_then(|g| g.clone()) {
1583 system_prompt.push_str("\n\n");
1584 system_prompt.push_str(&session_context_message(&cwd));
1585 }
1586 let cloud_backend: Arc<dyn InferenceBackend> = Arc::new(OpenAiBackend::new(
1587 cfg.base_url,
1588 cfg.api_key,
1589 cfg.model,
1590 Some(system_prompt),
1591 ));
1592 *self.backend.lock().await = cloud_backend;
1593
1594 let cloud_config = GgufModelConfig {
1595 model_id: format!("sigit-cloud:{tier}"),
1596 files: Vec::new(),
1597 tok_model_id: None,
1598 display_name: cfg.display_name.clone(),
1599 approx_memory: "Cloud".to_string(),
1600 chat_template: None,
1601 };
1602 {
1603 let mut guard = self.current_model.lock().unwrap();
1604 *guard = cloud_config;
1605 }
1606
1607 // Explicitly choosing a cloud tier puts us in cloud mode.
1608 let _ = settings::set_local_inference(false);
1609
1610 log::info!("switched to cloud tier {tier}");
1611 Some(cfg.display_name)
1612 }
1613
1614 /// Apply the persisted Local Inference mode at session start. When local
1615 /// inference is off and an account is signed in, route to a cloud tier so the
1616 /// on-device model is never loaded; otherwise leave the on-device backend in
1617 /// place. Call after the session cwd is set so the cloud system prompt picks
1618 /// it up. Does not flip the stored setting on the not-signed-in fallback.
1619 async fn apply_startup_inference_mode(&self) {
1620 if settings::local_inference_enabled() {
1621 return;
1622 }
1623 if self.switch_to_cloud_tier("balanced").await.is_some() {
1624 log::info!("startup: local inference off; routing inference to siGit Code Cloud");
1625 } else {
1626 log::warn!(
1627 "local inference is off but no account is signed in; staying on-device. \
1628 Run /login or set Local Inference on."
1629 );
1630 }
1631 }
1632
1633 /// Route inference back on-device. Used after leaving a cloud tier for a
1634 /// local model. The `LocalBackend` reads the live `engine`, so this just
1635 /// repoints the active backend.
1636 async fn reset_to_local_backend(&self) {
1637 let local_backend: Arc<dyn InferenceBackend> =
1638 Arc::new(LocalBackend::new(Arc::clone(&self.engine)));
1639 *self.backend.lock().await = local_backend;
1640 }
1641
1642 /// Re-attempt the lazy startup model load if the previous attempt failed.
1643 /// Clears the one-shot guard so the next load runs; a healthy load is left
1644 /// untouched so `/reload` doesn't needlessly reload a working model.
1645 fn retry_startup_model_load_if_failed(&self) {
1646 let had_error = self
1647 .model_load_error
1648 .lock()
1649 .map(|guard| guard.is_some())
1650 .unwrap_or(false);
1651 if had_error {
1652 self.startup_model_load_started
1653 .store(false, Ordering::Release);
1654 self.start_startup_model_load_if_needed();
1655 }
1656 }
1657
1658 /// Re-sync session state in place — no new session needed. Re-applies the
1659 /// active backend from current credentials (so a fresh `/login` token is
1660 /// picked up), retries a failed model load, and pushes refreshed commands +
1661 /// picker so the editor's UI reflects the current state.
1662 async fn handle_reload(&self, cx: &ConnectionTo<Client>, session_id: SessionId) {
1663 let signed_in = account::status_line().await;
1664
1665 let on_cloud_tier = {
1666 let guard = self.current_model.lock().unwrap();
1667 guard
1668 .model_id
1669 .strip_prefix("sigit-cloud:")
1670 .map(str::to_string)
1671 };
1672
1673 let backend_note = match on_cloud_tier {
1674 Some(tier) => match self.switch_to_cloud_tier(&tier).await {
1675 Some(name) => format!("Active: {name}."),
1676 None => {
1677 self.reset_to_local_backend().await;
1678 "Signed out — back to on-device. Pick a model with /models.".to_string()
1679 }
1680 },
1681 None => {
1682 self.reset_to_local_backend().await;
1683 self.retry_startup_model_load_if_failed();
1684 let guard = self.current_model.lock().unwrap();
1685 format!("Active: {}.", guard.display_name)
1686 }
1687 };
1688
1689 // Push refreshed picker + commands so the editor reflects current state.
1690 let config_options = {
1691 let guard = self.current_model.lock().unwrap();
1692 build_model_config_options(&guard)
1693 };
1694 self.send_tool_call_update(
1695 cx,
1696 session_id.clone(),
1697 SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(config_options)),
1698 )
1699 .ok();
1700 self.advertise_commands(cx, session_id.clone());
1701
1702 self.send_assistant_message(
1703 cx,
1704 session_id,
1705 format!("Reloaded. {signed_in} {backend_note}"),
1706 )
1707 .ok();
1708 }
1709
1710 async fn handle_set_session_config_option(
1711 &self,
1712 cx: &ConnectionTo<Client>,
1713 args: SetSessionConfigOptionRequest,
1714 ) -> agent_client_protocol::Result<SetSessionConfigOptionResponse> {
1715 log::info!(
1716 "set_session_config_option: config_id={}, value={:?}",
1717 args.config_id,
1718 args.value
1719 );
1720
1721 // ── Local Inference toggle ──────────────────────────────────────────
1722 if args.config_id.0.as_ref() == LOCAL_INFERENCE_CONFIG_ID {
1723 let enabled = match args.value.0.as_ref() {
1724 LOCAL_INFERENCE_ON => true,
1725 LOCAL_INFERENCE_OFF => false,
1726 other => {
1727 return Err(agent_client_protocol::Error::new(
1728 -32602,
1729 format!("unknown Local Inference value: {other}"),
1730 ));
1731 }
1732 };
1733 if let Err(error) = settings::set_local_inference(enabled) {
1734 return Err(agent_client_protocol::Error::new(
1735 -32603,
1736 format!("could not save Local Inference setting: {error}"),
1737 ));
1738 }
1739 let message = if enabled {
1740 "Local inference is on. On-device models are highlighted; pick one from Model."
1741 } else {
1742 "Local inference is off. siGit Code Cloud tiers are highlighted; pick one from Model."
1743 };
1744 self.send_assistant_message(cx, args.session_id.clone(), format!("\n\n{message}"))
1745 .ok();
1746 // Rebuild so the Model picker reflects the new emphasis/order.
1747 let current = self.current_model.lock().unwrap().clone();
1748 let config_options = build_model_config_options(&current);
1749 return Ok(SetSessionConfigOptionResponse::new(config_options));
1750 }
1751
1752 if args.config_id.0.as_ref() != MODEL_CONFIG_ID {
1753 return Err(agent_client_protocol::Error::new(
1754 -32602,
1755 format!("unknown config option: {}", args.config_id.0),
1756 ));
1757 }
1758
1759 let model_id = args.value.0.as_ref();
1760
1761 // can't switch while the startup model is still loading — the old
1762 // weights are in GPU memory and the new load gets "does not fit"
1763 if self.startup_model_load_started.load(Ordering::Acquire)
1764 && !self.model_ready.load(Ordering::Acquire)
1765 {
1766 log::info!("set_session_config_option: waiting for startup model to finish loading");
1767 while !self.model_ready.load(Ordering::Acquire) {
1768 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1769 }
1770 }
1771
1772 // Zed re-fires the last selection when a thread opens. That re-fire must
1773 // not load anything: on-device models are loaded only on an explicit
1774 // request (`/load`, or actively picking a *different* model below), so a
1775 // re-fire of the already-current selection is a no-op. Otherwise opening a
1776 // new thread would silently load the local model — exactly what we avoid.
1777 {
1778 let current = self.current_model.lock().unwrap();
1779 if current.model_id == model_id {
1780 log::info!(
1781 "set_session_config_option: {} is already the active selection, skipping",
1782 current.display_name
1783 );
1784 let config_options = build_model_config_options(&current);
1785 return Ok(SetSessionConfigOptionResponse::new(config_options));
1786 }
1787 }
1788
1789 // ── siGit Code Cloud tier: no local load; sign-in gated ─────────────
1790 if let Some(tier) = model_id.strip_prefix("sigit-cloud:") {
1791 let message = match self.switch_to_cloud_tier(tier).await {
1792 Some(display_name) => format!("Switched to {display_name}."),
1793 None => CLOUD_LOGIN_PROMPT.to_string(),
1794 };
1795 // Start on a fresh line: ACP clients concatenate consecutive
1796 // agent-message chunks into one block, so without this the switch
1797 // confirmation runs onto the end of the previous assistant message.
1798 self.send_assistant_message(cx, args.session_id.clone(), format!("\n\n{message}"))
1799 .ok();
1800
1801 let current = self.current_model.lock().unwrap().clone();
1802 let config_options = build_model_config_options(&current);
1803 return Ok(SetSessionConfigOptionResponse::new(config_options));
1804 }
1805
1806 let needs_download = models::local_picker_items()
1807 .into_iter()
1808 .find(|item| item.config.model_id == model_id)
1809 .map(|item| item.cache_health == setup::ModelCacheHealth::NotDownloaded)
1810 .unwrap_or(false);
1811
1812 // tells the progress poller to stop
1813 let stop_flag = Arc::new(AtomicBool::new(false));
1814
1815 let tool_call_id = format!("model-switch-{}", uuid::Uuid::new_v4());
1816
1817 if needs_download {
1818 let model_id_owned = model_id.to_string();
1819 let expected_bytes = onde::inference::models::SUPPORTED_MODEL_INFO
1820 .iter()
1821 .find(|m| m.id == model_id_owned)
1822 .map(|m| m.expected_size_bytes)
1823 .unwrap_or(0);
1824
1825 let display_name = models::local_picker_items()
1826 .into_iter()
1827 .find(|item| item.config.model_id == model_id_owned)
1828 .map(|item| item.display_name.clone())
1829 .unwrap_or_else(|| model_id_owned.clone());
1830
1831 let size_hint = if expected_bytes > 0 {
1832 format!(" (~{})", format_size_human(expected_bytes))
1833 } else {
1834 String::new()
1835 };
1836
1837 self.send_tool_call_update(
1838 cx,
1839 args.session_id.clone(),
1840 SessionUpdate::ToolCall(
1841 ToolCall::new(
1842 tool_call_id.clone(),
1843 format!("⏬ Downloading {display_name}{size_hint}"),
1844 )
1845 .kind(ToolKind::Think)
1846 .status(ToolCallStatus::InProgress)
1847 .content(vec![
1848 format!(
1849 "Preparing download for {display_name}. This may take a few minutes."
1850 )
1851 .into(),
1852 ]),
1853 ),
1854 )
1855 .ok();
1856
1857 // poll download progress and update the spinner in Zed
1858 let cx_for_poller = cx.clone();
1859 let poller_session = args.session_id.clone();
1860 let poller_model_id = model_id_owned.clone();
1861 let poller_stop = Arc::clone(&stop_flag);
1862 let poller_tool_call_id = tool_call_id.clone();
1863
1864 cx.spawn(async move {
1865 const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
1866 let cache_path = onde::hf_cache::model_cache_path(&poller_model_id);
1867 let mut tick: usize = 0;
1868 let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
1869 interval.tick().await; // consume the immediate first tick
1870
1871 while !poller_stop.load(Ordering::Relaxed) {
1872 interval.tick().await;
1873
1874 if poller_stop.load(Ordering::Relaxed) {
1875 break;
1876 }
1877
1878 let downloaded = cache_path
1879 .as_ref()
1880 .filter(|p| p.exists())
1881 .map(|p| dir_size_recursive(p))
1882 .unwrap_or(0);
1883
1884 let frame = SPINNER[tick % SPINNER.len()];
1885 tick += 1;
1886
1887 let title = if expected_bytes > 0 {
1888 let pct =
1889 ((downloaded as f64 / expected_bytes as f64) * 100.0).min(99.0) as u8;
1890 format!("{frame} Downloading {display_name}{size_hint} ({pct}%)")
1891 } else {
1892 format!("{frame} Downloading {display_name}{size_hint}")
1893 };
1894
1895 let msg = if expected_bytes > 0 {
1896 let pct =
1897 ((downloaded as f64 / expected_bytes as f64) * 100.0).min(99.0) as u8;
1898 let bar = progress_bar(pct, 20);
1899 format!(
1900 "{display_name} — {bar} {pct}% ({} / {})",
1901 format_size_human(downloaded),
1902 format_size_human(expected_bytes),
1903 )
1904 } else {
1905 format!(
1906 "{display_name} — {} downloaded…",
1907 format_size_human(downloaded)
1908 )
1909 };
1910
1911 let notification = SessionNotification::new(
1912 poller_session.clone(),
1913 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1914 poller_tool_call_id.clone(),
1915 ToolCallUpdateFields::new()
1916 .title(title)
1917 .status(ToolCallStatus::InProgress)
1918 .content(vec![msg.into()]),
1919 )),
1920 );
1921 if cx_for_poller.send_notification(notification).is_err() {
1922 break;
1923 }
1924 }
1925 Ok(())
1926 })
1927 .ok();
1928 }
1929
1930 // cached models still take 10-30s to load weights; show a spinner
1931 if !needs_download {
1932 let cached_display_name = models::local_picker_items()
1933 .into_iter()
1934 .find(|item| item.config.model_id == model_id)
1935 .map(|item| item.display_name.clone())
1936 .unwrap_or_else(|| model_id.to_string());
1937
1938 self.send_tool_call_update(
1939 cx,
1940 args.session_id.clone(),
1941 SessionUpdate::ToolCall(
1942 ToolCall::new(
1943 tool_call_id.clone(),
1944 format!("Loading {cached_display_name}"),
1945 )
1946 .kind(ToolKind::Think)
1947 .status(ToolCallStatus::InProgress)
1948 .content(vec![format!("Loading {cached_display_name}…").into()]),
1949 ),
1950 )
1951 .ok();
1952
1953 // tick every 5s so the user knows we haven't frozen
1954 let cx_for_spinner = cx.clone();
1955 let spinner_session = args.session_id.clone();
1956 let spinner_name = cached_display_name.clone();
1957 let spinner_stop = Arc::clone(&stop_flag);
1958 let spinner_tool_call_id = tool_call_id.clone();
1959 let load_start = std::time::Instant::now();
1960
1961 cx.spawn(async move {
1962 const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
1963 let mut tick: usize = 0;
1964 let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
1965 interval.tick().await; // consume the immediate first tick
1966
1967 while !spinner_stop.load(Ordering::Relaxed) {
1968 interval.tick().await;
1969
1970 if spinner_stop.load(Ordering::Relaxed) {
1971 break;
1972 }
1973
1974 let elapsed = load_start.elapsed();
1975 let elapsed_str = if elapsed.as_secs() >= 60 {
1976 format!("{}m {:02}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
1977 } else {
1978 format!("{}s", elapsed.as_secs())
1979 };
1980 let frame = SPINNER[tick % SPINNER.len()];
1981 tick += 1;
1982
1983 let msg = format!("{frame} Loading {spinner_name}… ({elapsed_str})");
1984 let notification = SessionNotification::new(
1985 spinner_session.clone(),
1986 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1987 spinner_tool_call_id.clone(),
1988 ToolCallUpdateFields::new()
1989 .status(ToolCallStatus::InProgress)
1990 .content(vec![msg.into()]),
1991 )),
1992 );
1993 if cx_for_spinner.send_notification(notification).is_err() {
1994 break;
1995 }
1996 }
1997 Ok(())
1998 })
1999 .ok();
2000 }
2001
2002 let switch_result = self.switch_model_by_id(model_id).await;
2003
2004 stop_flag.store(true, Ordering::Relaxed);
2005
2006 match switch_result {
2007 Ok(new_config) => {
2008 // Route inference back on-device (in case we were on a cloud tier).
2009 self.reset_to_local_backend().await;
2010 // Selecting an on-device model puts us in local mode.
2011 let _ = settings::set_local_inference(true);
2012
2013 let completion_title = if needs_download {
2014 format!("✓ {} downloaded and loaded", new_config.display_name)
2015 } else {
2016 format!("✓ Switched to {}", new_config.display_name)
2017 };
2018 let completion_body = if needs_download {
2019 format!("✓ {} downloaded and loaded.", new_config.display_name)
2020 } else {
2021 format!("✓ Switched to {}.", new_config.display_name)
2022 };
2023
2024 self.send_tool_call_update(
2025 cx,
2026 args.session_id.clone(),
2027 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
2028 tool_call_id,
2029 ToolCallUpdateFields::new()
2030 .title(completion_title)
2031 .status(ToolCallStatus::Completed)
2032 .content(vec![completion_body.into()]),
2033 )),
2034 )
2035 .ok();
2036
2037 let config_options = {
2038 let guard = self.current_model.lock().unwrap();
2039 build_model_config_options(&guard)
2040 };
2041
2042 log::info!("model switch complete");
2043 Ok(SetSessionConfigOptionResponse::new(config_options))
2044 }
2045 Err(err) => {
2046 self.send_tool_call_update(
2047 cx,
2048 args.session_id.clone(),
2049 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
2050 tool_call_id,
2051 ToolCallUpdateFields::new()
2052 .title("Model switch failed".to_string())
2053 .status(ToolCallStatus::Failed)
2054 .content(vec![format!("error loading model: {}", err.message).into()]),
2055 )),
2056 )
2057 .ok();
2058
2059 Err(err)
2060 }
2061 }
2062 }
2063 }
2064
2065 // ── Config option helpers ─────────────────────────────────────────────────────
2066
2067 /// config option ID for the model picker in Zed's agent panel
2068 const MODEL_CONFIG_ID: &str = "sigit-model";
2069
2070 /// config option ID for the Local Inference on/off toggle. Surfaced as a
2071 /// two-option `select` so ACP clients without slash-command support (e.g. Xcode)
2072 /// can still flip the mode from the agent panel.
2073 const LOCAL_INFERENCE_CONFIG_ID: &str = "sigit-local-inference";
2074
2075 /// `select` value ids for the Local Inference toggle.
2076 const LOCAL_INFERENCE_ON: &str = "local-inference-on";
2077 const LOCAL_INFERENCE_OFF: &str = "local-inference-off";
2078
2079 /// Replace non-ASCII chars so a downstream byte-index truncation can't split a
2080 /// multi-byte char. Zed slices the model-picker label at a fixed byte offset
2081 /// (`agent_ui/src/config_options.rs`) and panics — crashing the whole editor —
2082 /// when the cut lands mid-glyph (e.g. inside `☁` or `·`). Mapping to `-` keeps
2083 /// separators readable; ASCII bytes are always char boundaries.
2084 fn ascii_safe(s: &str) -> String {
2085 s.chars()
2086 .map(|c| if c.is_ascii() { c } else { '-' })
2087 .collect()
2088 }
2089
2090 fn build_model_config_options(current_model: &GgufModelConfig) -> Vec<SessionConfigOption> {
2091 // The full list, including the siGit Code Cloud tiers, so the panel picker
2092 // mirrors the TUI `/models`. Cloud entries are sign-in gated at selection.
2093 let items = models::build_model_picker_items();
2094 let active_kind = models::active_inference_kind();
2095
2096 let options: Vec<SessionConfigSelectOption> = items
2097 .iter()
2098 .filter(|item| item.cache_health != setup::ModelCacheHealth::Incomplete)
2099 .map(|item| {
2100 let mut desc_parts = Vec::new();
2101 // Mark options in the inactive mode so the active group reads as the
2102 // recommended set (the list is already ordered active-group-first).
2103 if item.source.kind() != active_kind {
2104 desc_parts.push("inactive mode".to_string());
2105 }
2106 if item.tool_calling {
2107 desc_parts.push("tool calling".to_string());
2108 }
2109 desc_parts.push(item.description.clone());
2110 if item.cache_health == setup::ModelCacheHealth::NotDownloaded {
2111 desc_parts.push("download on select".to_string());
2112 }
2113 // ASCII-only for the same reason as the name (see `ascii_safe`).
2114 let description = ascii_safe(&desc_parts.join(" - "));
2115 // Keep badges ASCII: Zed truncates the picker label at a fixed byte
2116 // offset and panics if the cut splits a multi-byte char. See
2117 // `ascii_safe` below.
2118 let source_badge = if item.cloud_tier.is_some() {
2119 " [siGit Code Cloud]"
2120 } else if item.cache_health == setup::ModelCacheHealth::NotDownloaded {
2121 " [Onde]"
2122 } else {
2123 match item.source_label.as_str() {
2124 "Onde" => " [Onde]",
2125 "HuggingFace" => " [HuggingFace]",
2126 _ => "",
2127 }
2128 };
2129 // For cloud tiers use just the tier title (e.g. "Balanced") so the
2130 // label reads "Balanced [siGit Code Cloud]" instead of repeating the
2131 // brand. The display name can carry non-ASCII (the cloud tier label
2132 // is "siGit Code Cloud · Balanced"), so sanitize the whole label.
2133 let base_name = match &item.cloud_tier {
2134 Some(tier) => crate::provider::tier_title(tier),
2135 None => item.display_name.clone(),
2136 };
2137 let name = ascii_safe(&format!("{base_name}{source_badge}"));
2138 SessionConfigSelectOption::new(
2139 SessionConfigValueId::new(item.config.model_id.as_str()),
2140 name,
2141 )
2142 .description(description)
2143 })
2144 .collect();
2145
2146 // Local Inference on/off toggle, modeled as a two-option select so panel-only
2147 // ACP clients (no slash commands) can flip the mode.
2148 let local_on = settings::local_inference_enabled();
2149 let local_current = SessionConfigValueId::new(if local_on {
2150 LOCAL_INFERENCE_ON
2151 } else {
2152 LOCAL_INFERENCE_OFF
2153 });
2154 let local_options = vec![
2155 SessionConfigSelectOption::new(
2156 SessionConfigValueId::new(LOCAL_INFERENCE_ON),
2157 "On (on-device)".to_string(),
2158 )
2159 .description("Run inference on-device; on-device models are highlighted".to_string()),
2160 SessionConfigSelectOption::new(
2161 SessionConfigValueId::new(LOCAL_INFERENCE_OFF),
2162 "Off (siGit Code Cloud)".to_string(),
2163 )
2164 .description("Use siGit Code Cloud; cloud tiers are highlighted".to_string()),
2165 ];
2166 let local_option = SessionConfigOption::select(
2167 LOCAL_INFERENCE_CONFIG_ID,
2168 "Local Inference",
2169 local_current,
2170 local_options,
2171 )
2172 .description("Toggle on-device inference; changes which models are highlighted");
2173
2174 if options.is_empty() {
2175 return vec![local_option];
2176 }
2177
2178 let current_value = SessionConfigValueId::new(current_model.model_id.as_str());
2179
2180 vec![
2181 SessionConfigOption::select(MODEL_CONFIG_ID, "Model", current_value, options)
2182 .category(SessionConfigOptionCategory::Model)
2183 .description("Select an on-device model or a siGit Code Cloud tier"),
2184 local_option,
2185 ]
2186 }
2187
2188 /// returns `(config, max_tokens, tool_calling)` for a picker model_id, or None
2189 fn resolve_model_config(model_id: &str) -> Option<(GgufModelConfig, u64, bool)> {
2190 let items = models::local_picker_items();
2191 items
2192 .into_iter()
2193 .find(|item| {
2194 item.config.model_id == model_id
2195 && item.cache_health != setup::ModelCacheHealth::Incomplete
2196 })
2197 .map(|item| (item.config, item.max_tokens, item.tool_calling))
2198 }
2199
2200 // ── Slash commands ────────────────────────────────────────────────────────────
2201
2202 #[derive(Debug, Clone)]
2203 enum SlashCommand {
2204 Help,
2205 Clear,
2206 Status,
2207 Models(Option<usize>),
2208 /// toggle on-device inference mode. `Some(true/false)` sets it, `None` flips it.
2209 Local(Option<bool>),
2210 /// List discovered Agent Skills.
2211 Skills,
2212 /// List configured MCP servers and their tools.
2213 Mcp,
2214 /// Explicitly load the selected (or default) on-device model.
2215 Load,
2216 /// `/login <email> <password>` — the raw argument, parsed when executed.
2217 Login(Option<String>),
2218 Logout,
2219 Whoami,
2220 /// Re-sync session state (auth, backend, picker) without a new session.
2221 Reload,
2222 /// Toggle plan mode (read-only research; mutating tools denied with a
2223 /// prompt to present a plan). `Some(true/false)` sets it, `None` flips it.
2224 Plan(Option<bool>),
2225 /// Show the effective permission policy for this session.
2226 Permissions,
2227 /// Summarize-and-shrink the conversation history on demand.
2228 Compact,
2229 Exit,
2230 Unknown(String),
2231 }
2232
2233 fn parse_slash(input: &str) -> Option<SlashCommand> {
2234 let trimmed = input.trim();
2235 if !trimmed.starts_with('/') {
2236 return None;
2237 }
2238 let mut parts = trimmed.splitn(2, char::is_whitespace);
2239 let command = parts.next().unwrap_or("");
2240 let argument = parts.next().map(str::trim);
2241 Some(match command {
2242 "/help" => SlashCommand::Help,
2243 "/clear" => SlashCommand::Clear,
2244 "/status" => SlashCommand::Status,
2245 "/models" => SlashCommand::Models(argument.and_then(|v| v.parse::<usize>().ok())),
2246 "/local" => SlashCommand::Local(parse_on_off(argument)),
2247 "/skills" => SlashCommand::Skills,
2248 "/mcp" => SlashCommand::Mcp,
2249 "/load" => SlashCommand::Load,
2250 "/login" => SlashCommand::Login(argument.map(str::to_string)),
2251 "/logout" => SlashCommand::Logout,
2252 "/whoami" => SlashCommand::Whoami,
2253 "/reload" => SlashCommand::Reload,
2254 "/plan" => SlashCommand::Plan(parse_on_off(argument)),
2255 "/permissions" => SlashCommand::Permissions,
2256 "/compact" => SlashCommand::Compact,
2257 "/exit" | "/quit" | "/q" => SlashCommand::Exit,
2258 other => SlashCommand::Unknown(other.to_string()),
2259 })
2260 }
2261
2262 /// `on`/`off` (and synonyms) → `Some(bool)`; missing or unrecognized → `None`
2263 /// (meaning "toggle the current value").
2264 fn parse_on_off(arg: Option<&str>) -> Option<bool> {
2265 match arg.map(|s| s.trim().to_ascii_lowercase())?.as_str() {
2266 "on" | "true" | "1" | "yes" => Some(true),
2267 "off" | "false" | "0" | "no" => Some(false),
2268 _ => None,
2269 }
2270 }
2271
2272 fn format_models_list(current_model: &GgufModelConfig) -> String {
2273 let items = models::build_model_picker_items();
2274 if items.is_empty() {
2275 return "No local models found. siGit will use the platform default model.".to_string();
2276 }
2277
2278 let mut lines = vec!["Available models:".to_string()];
2279 let mut last_source: Option<&str> = None;
2280
2281 for (index, item) in items.iter().enumerate() {
2282 let source_key = match item.source_label.as_str() {
2283 "Onde" => "Onde",
2284 "HuggingFace" => "HuggingFace",
2285 "siGit Code Cloud" => "Cloud",
2286 _ => "Fallback",
2287 };
2288
2289 if last_source != Some(source_key) {
2290 if last_source.is_some() {
2291 lines.push(String::new());
2292 }
2293 let section = match source_key {
2294 "Onde" => "Onde Inference",
2295 "HuggingFace" => "Hugging Face cache",
2296 "Cloud" => "siGit Code Cloud",
2297 _ => "Fallback",
2298 };
2299 lines.push(section.to_string());
2300 // Blank line so the following "N." items render as an ordered list.
2301 // CommonMark only lets an ordered list interrupt a paragraph when it
2302 // starts at 1, so without this the cloud section (items 9+) would be
2303 // absorbed into the header paragraph.
2304 lines.push(String::new());
2305 last_source = Some(source_key);
2306 }
2307
2308 let number = index + 1;
2309 let current_badge = if item.config.model_id == current_model.model_id {
2310 " <- current"
2311 } else {
2312 ""
2313 };
2314 let tool_badge = if item.tool_calling {
2315 " tool calling"
2316 } else {
2317 ""
2318 };
2319 let health_badge = match item.cache_health {
2320 setup::ModelCacheHealth::Complete => "",
2321 setup::ModelCacheHealth::Incomplete => " ! incomplete cache",
2322 setup::ModelCacheHealth::NotDownloaded => " ↓ download on select",
2323 };
2324 let source = match source_key {
2325 "Onde" => " [Onde]",
2326 "HuggingFace" => " [HuggingFace]",
2327 "Cloud" => " [☁ Cloud]",
2328 _ => " [default]",
2329 };
2330
2331 lines.push(format!(
2332 "{number}. {} {}{}{}{}{}",
2333 item.display_name, item.description, tool_badge, health_badge, current_badge, source,
2334 ));
2335 }
2336
2337 lines.push(String::new());
2338 lines.push("Use /models N to switch models.".to_string());
2339 lines.join("\n")
2340 }
2341
2342 async fn exec_slash_acp(
2343 agent: &SiGitAgent,
2344 cx: &ConnectionTo<Client>,
2345 session_id: SessionId,
2346 command: SlashCommand,
2347 ) -> agent_client_protocol::Result<PromptResponse> {
2348 match command {
2349 SlashCommand::Help => {
2350 agent
2351 .send_assistant_message(
2352 cx,
2353 session_id,
2354 "/help - show this message\n\
2355 /models - list available models\n\
2356 /models N - switch to model N\n\
2357 /local [on|off]- toggle on-device inference mode\n\
2358 /skills - list available Agent Skills\n\
2359 /mcp - list MCP servers and their tools\n\
2360 /load - load the selected on-device model\n\
2361 /login E P - sign in to siGit Code Cloud\n\
2362 /logout - sign out\n\
2363 /whoami - show the signed-in account\n\
2364 /reload - re-sync sign-in and model state\n\
2365 /plan [on|off] - plan mode: research only, no edits or commands\n\
2366 /permissions - show the tool permission policy\n\
2367 /compact - summarize and shrink conversation history\n\
2368 /clear - wipe conversation history\n\
2369 /status - show engine status\n\
2370 /exit - end this turn",
2371 )
2372 .ok();
2373 }
2374 SlashCommand::Clear => {
2375 let cleared = agent.engine.clear_history().await;
2376 permissions::reset_session(&session_id.to_string());
2377 // The saved session must not resurrect what the user just wiped.
2378 session_store::delete(&session_id.to_string());
2379 agent
2380 .send_assistant_message(
2381 cx,
2382 session_id,
2383 format!("Cleared {cleared} turn(s). History is empty."),
2384 )
2385 .ok();
2386 }
2387 SlashCommand::Plan(value) => {
2388 let session_key = session_id.to_string();
2389 let enabled = value.unwrap_or_else(|| !permissions::plan_mode(&session_key));
2390 permissions::set_plan_mode(&session_key, enabled);
2391 let message = if enabled {
2392 "Plan mode ON — the agent researches with read-only tools and presents a \
2393 plan; edits and commands are blocked until /plan off."
2394 } else {
2395 "Plan mode OFF — the agent may execute tools again (subject to the \
2396 permission policy)."
2397 };
2398 agent.send_assistant_message(cx, session_id, message).ok();
2399 }
2400 SlashCommand::Permissions => {
2401 let summary = permissions::describe(&session_id.to_string());
2402 agent.send_assistant_message(cx, session_id, summary).ok();
2403 }
2404 SlashCommand::Compact => {
2405 let backend = agent.backend.lock().await.clone();
2406 let before = backend::estimate_tokens(&backend.history_snapshot().await);
2407 let message = match backend.compact_history(backend::COMPACT_KEEP_LAST).await {
2408 Ok(()) => {
2409 let snapshot = backend.history_snapshot().await;
2410 let after = backend::estimate_tokens(&snapshot);
2411 // Keep the saved session in step with the compacted state.
2412 if let Err(error) = session_store::save(&session_id.to_string(), &snapshot) {
2413 log::warn!("session save after /compact failed: {error}");
2414 }
2415 format!("Compacted history: ~{before} → ~{after} tokens (estimated).")
2416 }
2417 Err(error) => format!("Compaction failed: {error}"),
2418 };
2419 agent.send_assistant_message(cx, session_id, message).ok();
2420 }
2421 SlashCommand::Status => {
2422 let info = agent.engine.info().await;
2423 let model = info.model_name.as_deref().unwrap_or("(none)");
2424 let memory = info.approx_memory.as_deref().unwrap_or("unknown");
2425 agent
2426 .send_assistant_message(
2427 cx,
2428 session_id,
2429 format!(
2430 "status: {:?} model: {} memory: {} history: {} turns",
2431 info.status, model, memory, info.history_length,
2432 ),
2433 )
2434 .ok();
2435 }
2436 SlashCommand::Models(None) => {
2437 let current_model = agent.current_model.lock().unwrap().clone();
2438 agent
2439 .send_assistant_message(cx, session_id, format_models_list(&current_model))
2440 .ok();
2441 }
2442 SlashCommand::Skills => {
2443 agent
2444 .send_assistant_message(cx, session_id, skills::format_skills_list())
2445 .ok();
2446 }
2447 SlashCommand::Mcp => {
2448 agent
2449 .send_assistant_message(cx, session_id, mcp::status_summary())
2450 .ok();
2451 }
2452 SlashCommand::Models(Some(number)) => {
2453 let items = models::build_model_picker_items();
2454 let index = number.saturating_sub(1);
2455 match items.get(index).cloned() {
2456 None => {
2457 agent
2458 .send_assistant_message(
2459 cx,
2460 session_id,
2461 format!("error: no model #{number} - type /models to see the list."),
2462 )
2463 .ok();
2464 }
2465 Some(model) if model.cloud_tier.is_some() => {
2466 // siGit Code Cloud tier: swap backend, sign-in gated.
2467 let tier = model.cloud_tier.clone().unwrap_or_default();
2468 let message = match agent.switch_to_cloud_tier(&tier).await {
2469 Some(display_name) => format!("Switched to {display_name}."),
2470 None => CLOUD_LOGIN_PROMPT.to_string(),
2471 };
2472 agent.send_assistant_message(cx, session_id, message).ok();
2473 }
2474 Some(model) => {
2475 if model.cache_health == setup::ModelCacheHealth::Incomplete {
2476 agent
2477 .send_assistant_message(
2478 cx,
2479 session_id,
2480 format!(
2481 "error: {} has an incomplete local cache and cannot be selected yet.",
2482 model.display_name
2483 ),
2484 )
2485 .ok();
2486 } else if model.cache_health == setup::ModelCacheHealth::NotDownloaded {
2487 agent
2488 .send_assistant_message(
2489 cx,
2490 session_id.clone(),
2491 format!(
2492 "Downloading and loading {} ({})… this may take a few minutes.",
2493 model.display_name, model.description
2494 ),
2495 )
2496 .ok();
2497
2498 match agent.switch_model_by_id(&model.config.model_id).await {
2499 Ok(new_config) => {
2500 agent.reset_to_local_backend().await;
2501 let _ = settings::set_local_inference(true);
2502 agent.engine.clear_history().await;
2503 agent
2504 .send_assistant_message(
2505 cx,
2506 session_id,
2507 format!(
2508 "✓ Downloaded and switched to {}",
2509 new_config.display_name
2510 ),
2511 )
2512 .ok();
2513 }
2514 Err(err) => {
2515 agent
2516 .send_assistant_message(
2517 cx,
2518 session_id,
2519 format!("error downloading model: {}", err.message),
2520 )
2521 .ok();
2522 }
2523 }
2524 } else {
2525 agent
2526 .send_assistant_message(
2527 cx,
2528 session_id.clone(),
2529 format!("Loading {}...", model.display_name),
2530 )
2531 .ok();
2532
2533 let switched = agent.switch_model_by_id(&model.config.model_id).await?;
2534 agent.reset_to_local_backend().await;
2535 let _ = settings::set_local_inference(true);
2536 agent.engine.clear_history().await;
2537
2538 agent
2539 .send_assistant_message(
2540 cx,
2541 session_id,
2542 format!("Switched to {}.", switched.display_name),
2543 )
2544 .ok();
2545 }
2546 }
2547 }
2548 }
2549 SlashCommand::Local(value) => {
2550 let enabled = value.unwrap_or(!settings::local_inference_enabled());
2551 let message = match settings::set_local_inference(enabled) {
2552 Ok(()) if enabled => "Local inference is on. On-device models are highlighted; \
2553 pick one with /models."
2554 .to_string(),
2555 Ok(()) => "Local inference is off. siGit Code Cloud tiers are highlighted; \
2556 pick one with /models."
2557 .to_string(),
2558 Err(error) => format!("error: could not save local inference setting: {error}"),
2559 };
2560 agent
2561 .send_assistant_message(cx, session_id.clone(), message)
2562 .ok();
2563 // Refresh the panel so the Model picker reflects the new emphasis.
2564 let config_options = {
2565 let current = agent.current_model.lock().unwrap();
2566 build_model_config_options(&current)
2567 };
2568 agent
2569 .send_tool_call_update(
2570 cx,
2571 session_id,
2572 SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(config_options)),
2573 )
2574 .ok();
2575 }
2576 SlashCommand::Load => {
2577 // Explicitly load the on-device model. This is the only path that
2578 // brings a local model into memory; prompts never do it implicitly.
2579 // If a cloud tier is active, fall back to a local default so we don't
2580 // try to load the (file-less) cloud config as GGUF.
2581 let on_cloud = {
2582 let guard = agent.current_model.lock().unwrap();
2583 guard.model_id.starts_with("sigit-cloud:")
2584 };
2585 if on_cloud {
2586 let default_config = default_local_model_config();
2587 *agent.current_model.lock().unwrap() = default_config;
2588 agent.reset_to_local_backend().await;
2589 }
2590 // Loading an on-device model puts us in local inference mode.
2591 let _ = settings::set_local_inference(true);
2592 // `await_model_ready` drives the download/load progress UI and reports
2593 // success or failure to the editor.
2594 agent.start_startup_model_load_if_needed();
2595 agent.await_model_ready(cx, &session_id).await?;
2596 }
2597 SlashCommand::Login(argument) => {
2598 let message = match argument.as_deref().and_then(account::parse_login_args) {
2599 Some((email, password)) => match account::authenticate(&email, &password).await {
2600 Ok(email) => format!(
2601 "Signed in as {email}. Pick a siGit Code Cloud tier in /models to use it."
2602 ),
2603 Err(error) => format!("Login failed: {error}"),
2604 },
2605 None => "usage: /login <email> <password>".to_string(),
2606 };
2607 agent.send_assistant_message(cx, session_id, message).ok();
2608 }
2609 SlashCommand::Logout => {
2610 // If we're on a cloud tier, drop back to local — the token is gone.
2611 let on_cloud = {
2612 let guard = agent.current_model.lock().unwrap();
2613 guard.model_id.starts_with("sigit-cloud:")
2614 };
2615 let message = account::end_session().await;
2616 if on_cloud {
2617 agent.reset_to_local_backend().await;
2618 }
2619 agent.send_assistant_message(cx, session_id, message).ok();
2620 }
2621 SlashCommand::Whoami => {
2622 let message = account::status_line().await;
2623 agent.send_assistant_message(cx, session_id, message).ok();
2624 }
2625 SlashCommand::Reload => {
2626 agent.handle_reload(cx, session_id).await;
2627 }
2628 SlashCommand::Exit => {
2629 agent
2630 .send_assistant_message(
2631 cx,
2632 session_id,
2633 "Use the panel controls to close or switch threads.",
2634 )
2635 .ok();
2636 }
2637 SlashCommand::Unknown(command) => {
2638 agent
2639 .send_assistant_message(cx, session_id, format!("unknown command: {command}"))
2640 .ok();
2641 }
2642 }
2643
2644 Ok(PromptResponse::new(StopReason::EndTurn))
2645 }
2646
2647 // ── Request dispatch helper ───────────────────────────────────────────────────
2648
2649 fn handle_response<T: agent_client_protocol::JsonRpcResponse>(
2650 responder: Responder<T>,
2651 result: agent_client_protocol::Result<T>,
2652 ) -> agent_client_protocol::Result<()> {
2653 match result {
2654 Ok(resp) => responder.respond(resp),
2655 Err(err) => responder.respond_with_error(err),
2656 }
2657 }
2658
2659 // ── Download progress helpers ─────────────────────────────────────────────────
2660
2661 /// total bytes on disk under `path`. needed because hf-hub uses staging
2662 /// names during download, so we can't just stat the final blobs.
2663 fn dir_size_recursive(path: &std::path::Path) -> u64 {
2664 let mut total: u64 = 0;
2665 let Ok(entries) = std::fs::read_dir(path) else {
2666 return 0;
2667 };
2668 for entry in entries.flatten() {
2669 let entry_path = entry.path();
2670 if entry_path.is_dir() {
2671 total += dir_size_recursive(&entry_path);
2672 } else if let Ok(meta) = entry_path.metadata() {
2673 total += meta.len();
2674 }
2675 }
2676 total
2677 }
2678
2679 fn format_size_human(bytes: u64) -> String {
2680 const GB: u64 = 1_073_741_824;
2681 const MB: u64 = 1_048_576;
2682 const KB: u64 = 1_024;
2683 if bytes >= GB {
2684 format!("{:.2} GB", bytes as f64 / GB as f64)
2685 } else if bytes >= MB {
2686 format!("{:.1} MB", bytes as f64 / MB as f64)
2687 } else if bytes >= KB {
2688 format!("{:.0} KB", bytes as f64 / KB as f64)
2689 } else {
2690 format!("{bytes} B")
2691 }
2692 }
2693
2694 fn progress_bar(pct: u8, width: usize) -> String {
2695 let filled = ((pct as usize) * width) / 100;
2696 let empty = width.saturating_sub(filled);
2697 format!("[{}{}]", "█".repeat(filled), "░".repeat(empty))
2698 }
2699
2700 // ── Output capture ────────────────────────────────────────────────────────────
2701
2702 /// redirect stdout+stderr to `$TMPDIR/sigit.log` at the fd level so
2703 /// mistralrs/tracing noise never hits the terminal. returns two dup'd
2704 /// fds to the real tty: one for ratatui, one for cleanup (ratatui 0.29
2705 /// doesn't expose `writer_mut()`).
2706 #[cfg(unix)]
2707 fn redirect_output_to_log() -> anyhow::Result<(std::fs::File, std::fs::File)> {
2708 let log_path = std::env::temp_dir().join("sigit.log");
2709 let log_file = std::fs::File::create(&log_path)?;
2710 let log_fd = log_file.as_raw_fd();
2711
2712 // two copies: ratatui needs one, cleanup needs another
2713 let saved_tui = unsafe { libc::dup(libc::STDOUT_FILENO) };
2714 anyhow::ensure!(
2715 saved_tui >= 0,
2716 "dup(stdout) for tui failed: {}",
2717 std::io::Error::last_os_error()
2718 );
2719 let saved_cleanup = unsafe { libc::dup(libc::STDOUT_FILENO) };
2720 anyhow::ensure!(
2721 saved_cleanup >= 0,
2722 "dup(stdout) for cleanup failed: {}",
2723 std::io::Error::last_os_error()
2724 );
2725
2726 unsafe {
2727 libc::dup2(log_fd, libc::STDOUT_FILENO);
2728 libc::dup2(log_fd, libc::STDERR_FILENO);
2729 }
2730
2731 // safe to drop log_file; dup2 keeps the fd alive via stdout/stderr
2732
2733 Ok((unsafe { std::fs::File::from_raw_fd(saved_tui) }, unsafe {
2734 std::fs::File::from_raw_fd(saved_cleanup)
2735 }))
2736 }
2737
2738 // ── Logging ───────────────────────────────────────────────────────────────────
2739
2740 /// in TUI mode stderr is the log file (redirected earlier);
2741 /// in ACP mode it's real stderr. either way, write there.
2742 fn init_logging(is_tty: bool) {
2743 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
2744 let _ = tracing_fmt::Subscriber::builder()
2745 .with_env_filter(filter)
2746 .with_writer(std::io::stderr)
2747 .with_ansi(!is_tty)
2748 .try_init();
2749 }
2750
2751 // ── Interactive TUI mode ──────────────────────────────────────────────────────
2752
2753 /// boot the TUI and load the model on a background thread.
2754 /// `tty` goes to ratatui; `cleanup_tty` is a separate fd for
2755 /// LeaveAlternateScreen (ratatui 0.29 hides `writer_mut()`).
2756 #[cfg(unix)]
2757 async fn run_interactive(tty: std::fs::File, mut cleanup_tty: std::fs::File) -> anyhow::Result<()> {
2758 let engine = Arc::new(ChatEngine::new());
2759
2760 let startup_selection = setup::startup_model_selection();
2761 let startup_model_name = startup_selection
2762 .as_ref()
2763 .map(|selection| selection.display_name.clone())
2764 .unwrap_or_else(|| GgufModelConfig::qwen25_3b().display_name);
2765
2766 // Signals the loading phase to finish. On-device models are no longer loaded
2767 // at startup, so this resolves immediately for both backends; it stays a
2768 // channel so the loading-phase plumbing in `chat::run_with` is unchanged.
2769 let (load_tx, load_rx) = std::sync::mpsc::channel::<Result<(), String>>();
2770
2771 // Project instruction files (AGENTS.md / CLAUDE.md) for the launch directory,
2772 // injected into the system prompt so the TUI shares the same always-on
2773 // project context the ACP sessions get.
2774 let project_instructions = std::env::current_dir()
2775 .ok()
2776 .and_then(|cwd| instructions::load_project_instructions(&cwd));
2777 let with_instructions = |base: String| match &project_instructions {
2778 Some(extra) => format!("{base}\n\n{extra}"),
2779 None => base,
2780 };
2781
2782 // Pick the inference backend: a configured provider if present, else on-device.
2783 let (inference_backend, startup_model_name): (Arc<dyn InferenceBackend>, String) =
2784 match provider::active_provider() {
2785 Some(provider) => {
2786 log::info!(
2787 "inference: using {} (model {}) at {}",
2788 provider.display_name,
2789 provider.model,
2790 provider.base_url
2791 );
2792 // No local model to load; the endpoint is ready immediately.
2793 let _ = load_tx.send(Ok(()));
2794 let label = provider.display_name.clone();
2795 register_subagent_factory_for(&provider);
2796 let backend = Arc::new(OpenAiBackend::new(
2797 provider.base_url,
2798 provider.api_key,
2799 provider.model,
2800 Some(with_instructions(SYSTEM_PROMPT.to_string())),
2801 )) as Arc<dyn InferenceBackend>;
2802 (backend, label)
2803 }
2804 None => {
2805 // Honor the Local Inference toggle: when off and signed in, start
2806 // on a cloud tier. Otherwise bring up on-device WITHOUT loading a
2807 // model — the user loads it explicitly with /load (or /models), so
2808 // the UI comes up immediately. Project instructions are injected at
2809 // load time in `chat.rs`.
2810 let cloud_when_off = if settings::local_inference_enabled() {
2811 None
2812 } else {
2813 provider::cloud_tier_provider("balanced")
2814 };
2815
2816 match cloud_when_off {
2817 Some(provider) => {
2818 log::info!(
2819 "inference: local inference off; using {} (model {})",
2820 provider.display_name,
2821 provider.model
2822 );
2823 let _ = load_tx.send(Ok(()));
2824 let label = provider.display_name.clone();
2825 register_subagent_factory_for(&provider);
2826 let backend = Arc::new(OpenAiBackend::new(
2827 provider.base_url,
2828 provider.api_key,
2829 provider.model,
2830 Some(with_instructions(SYSTEM_PROMPT.to_string())),
2831 )) as Arc<dyn InferenceBackend>;
2832 (backend, label)
2833 }
2834 None => {
2835 if !settings::local_inference_enabled() {
2836 log::warn!(
2837 "local inference is off but no account is signed in; \
2838 bringing up on-device. Run /login or /local on."
2839 );
2840 }
2841 let _ = load_tx.send(Ok(()));
2842 // On-device inference has a single shared history; no
2843 // subagent context is possible yet.
2844 tools::set_subagent_factory(Box::new(|| None));
2845 let backend = Arc::new(LocalBackend::new(Arc::clone(&engine)))
2846 as Arc<dyn InferenceBackend>;
2847 (backend, startup_model_name)
2848 }
2849 }
2850 }
2851 };
2852
2853 crossterm::terminal::enable_raw_mode()?;
2854 let mut tty = BufWriter::new(tty);
2855 crossterm::execute!(tty, crossterm::terminal::EnterAlternateScreen)?;
2856 let term_backend = ratatui::backend::CrosstermBackend::new(tty);
2857 let mut terminal = ratatui::Terminal::new(term_backend)?;
2858
2859 // polls load_rx with try_recv() each tick, no blocking
2860 let chat_result = chat::run_with(
2861 &mut terminal,
2862 engine,
2863 inference_backend,
2864 load_rx,
2865 startup_model_name,
2866 )
2867 .await;
2868
2869 // cleanup fd because backend's writer is private
2870 crossterm::execute!(cleanup_tty, crossterm::terminal::LeaveAlternateScreen)?;
2871 cleanup_tty.flush()?;
2872 crossterm::terminal::disable_raw_mode()?;
2873
2874 // restore real stdout/stderr for post-TUI error output
2875 #[cfg(unix)]
2876 {
2877 let cleanup_fd = cleanup_tty.as_raw_fd();
2878 unsafe {
2879 libc::dup2(cleanup_fd, libc::STDOUT_FILENO);
2880 libc::dup2(cleanup_fd, libc::STDERR_FILENO);
2881 }
2882 }
2883
2884 chat_result
2885 }
2886
2887 // ── ACP server mode ───────────────────────────────────────────────────────────
2888
2889 /// The on-device model `/load` should bring up by default: the persisted
2890 /// selection if it still resolves to a known local model, otherwise the built-in
2891 /// default (`qwen25_3b`).
2892 fn default_local_model_config() -> GgufModelConfig {
2893 setup::startup_model_selection()
2894 .as_ref()
2895 .and_then(|selection| {
2896 selection.selected_model.as_ref().and_then(|selected| {
2897 models::local_picker_items()
2898 .into_iter()
2899 .find(|item| {
2900 item.config.model_id == selected.model_id
2901 && item
2902 .config
2903 .files
2904 .iter()
2905 .any(|file| file == &selected.gguf_file)
2906 })
2907 .map(|item| item.config)
2908 })
2909 })
2910 .unwrap_or_else(GgufModelConfig::qwen25_3b)
2911 }
2912
2913 async fn run_acp_server() -> anyhow::Result<()> {
2914 log::info!("ACP mode — starting agent server");
2915
2916 let config = default_local_model_config();
2917
2918 let needs_download = models::local_picker_items()
2919 .iter()
2920 .find(|item| item.config.model_id == config.model_id)
2921 .map(|item| item.cache_health != setup::ModelCacheHealth::Complete)
2922 .unwrap_or(true);
2923
2924 log::info!(
2925 "ACP startup model selected: {} ({})",
2926 config.display_name,
2927 if needs_download {
2928 "needs download"
2929 } else {
2930 "cached"
2931 }
2932 );
2933
2934 let engine = Arc::new(ChatEngine::new());
2935
2936 // The on-device model is never loaded implicitly; the user loads it with
2937 // `/load` (or by picking one in `/models`). So initialize/session/new stay
2938 // lightweight and `model_ready` starts true (nothing is loading).
2939 let model_ready = Arc::new(AtomicBool::new(true));
2940 let startup_model_load_started = Arc::new(AtomicBool::new(false));
2941 let model_load_error: Arc<std::sync::Mutex<Option<String>>> =
2942 Arc::new(std::sync::Mutex::new(None));
2943
2944 let state = Arc::new(SiGitAgent::new(
2945 engine,
2946 config,
2947 model_ready,
2948 startup_model_load_started,
2949 model_load_error,
2950 needs_download,
2951 ));
2952
2953 // Honor the explicit provider override (OPENAI_BASE_URL/OPENAI_API_KEY or
2954 // an active providers.toml profile) in ACP mode too — the interactive
2955 // client already does. Without this the override was silently ignored here
2956 // and prompts insisted on a local model. It is also what lets the ACP
2957 // integration test drive the agent against a scripted endpoint
2958 // (tests/acp_permissions.rs). The model picker still shows the local
2959 // selection; overrides are a power-user escape hatch, not a tier.
2960 if let Some(cfg) = provider::active_provider() {
2961 log::info!(
2962 "inference: using {} (model {}) at {}",
2963 cfg.display_name,
2964 cfg.model,
2965 cfg.base_url
2966 );
2967 register_subagent_factory_for(&cfg);
2968 let override_backend: Arc<dyn InferenceBackend> = Arc::new(OpenAiBackend::new(
2969 cfg.base_url,
2970 cfg.api_key,
2971 cfg.model,
2972 Some(system_prompt_for_model(true).to_string()),
2973 ));
2974 *state.backend.lock().await = override_backend;
2975 } else {
2976 // On-device inference has a single shared conversation history, so a
2977 // second concurrent subagent context is not possible yet.
2978 tools::set_subagent_factory(Box::new(|| None));
2979 }
2980
2981 let stdin = tokio::io::stdin().compat();
2982 let stdout = tokio::io::stdout().compat_write();
2983 let transport = ByteStreams::new(stdout, stdin);
2984
2985 Agent
2986 .builder()
2987 .on_receive_request(
2988 {
2989 let state = Arc::clone(&state);
2990 async move |req: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
2991 handle_response(responder, state.handle_initialize(req).await)
2992 }
2993 },
2994 agent_client_protocol::on_receive_request!(),
2995 )
2996 .on_receive_request(
2997 {
2998 let state = Arc::clone(&state);
2999 async move |req: AuthenticateRequest, responder, _cx: ConnectionTo<Client>| {
3000 handle_response(responder, state.handle_authenticate(req).await)
3001 }
3002 },
3003 agent_client_protocol::on_receive_request!(),
3004 )
3005 // Turn-affecting handlers below run in spawned tasks, serialized by
3006 // `turn_lock`, so the dispatch loop stays free to route client
3007 // responses (permission answers) while a turn is in flight. Awaiting a
3008 // client request from *inside* a handler would deadlock: the dispatch
3009 // loop can't read the response while the handler blocks it.
3010 .on_receive_request(
3011 {
3012 let state = Arc::clone(&state);
3013 async move |req: LoadSessionRequest, responder, cx: ConnectionTo<Client>| {
3014 let state = Arc::clone(&state);
3015 let task_cx = cx.clone();
3016 cx.spawn(async move {
3017 let _turn = state.turn_lock.lock().await;
3018 handle_response(responder, state.handle_load_session(&task_cx, req).await)
3019 })
3020 }
3021 },
3022 agent_client_protocol::on_receive_request!(),
3023 )
3024 .on_receive_request(
3025 {
3026 let state = Arc::clone(&state);
3027 async move |req: ForkSessionRequest, responder, cx: ConnectionTo<Client>| {
3028 let state = Arc::clone(&state);
3029 let task_cx = cx.clone();
3030 cx.spawn(async move {
3031 let _turn = state.turn_lock.lock().await;
3032 handle_response(responder, state.handle_fork_session(&task_cx, req).await)
3033 })
3034 }
3035 },
3036 agent_client_protocol::on_receive_request!(),
3037 )
3038 .on_receive_request(
3039 {
3040 let state = Arc::clone(&state);
3041 async move |req: NewSessionRequest, responder, cx: ConnectionTo<Client>| {
3042 let state = Arc::clone(&state);
3043 let task_cx = cx.clone();
3044 cx.spawn(async move {
3045 let _turn = state.turn_lock.lock().await;
3046 handle_response(responder, state.handle_new_session(&task_cx, req).await)
3047 })
3048 }
3049 },
3050 agent_client_protocol::on_receive_request!(),
3051 )
3052 .on_receive_request(
3053 {
3054 let state = Arc::clone(&state);
3055 async move |req: PromptRequest, responder, cx: ConnectionTo<Client>| {
3056 let state = Arc::clone(&state);
3057 let task_cx = cx.clone();
3058 cx.spawn(async move {
3059 let _turn = state.turn_lock.lock().await;
3060 handle_response(responder, state.handle_prompt(&task_cx, req).await)
3061 })
3062 }
3063 },
3064 agent_client_protocol::on_receive_request!(),
3065 )
3066 .on_receive_request(
3067 {
3068 let state = Arc::clone(&state);
3069 async move |req: SetSessionConfigOptionRequest,
3070 responder,
3071 cx: ConnectionTo<Client>| {
3072 let state = Arc::clone(&state);
3073 let task_cx = cx.clone();
3074 cx.spawn(async move {
3075 let _turn = state.turn_lock.lock().await;
3076 handle_response(
3077 responder,
3078 state.handle_set_session_config_option(&task_cx, req).await,
3079 )
3080 })
3081 }
3082 },
3083 agent_client_protocol::on_receive_request!(),
3084 )
3085 .on_receive_notification(
3086 {
3087 let state = Arc::clone(&state);
3088 async move |notif: CancelNotification, _cx: ConnectionTo<Client>| {
3089 state.handle_cancel(notif).await
3090 }
3091 },
3092 agent_client_protocol::on_receive_notification!(),
3093 )
3094 .connect_to(transport)
3095 .await
3096 .map_err(|e| anyhow::anyhow!("ACP connection error: {e}"))?;
3097
3098 log::info!("siGit shutting down");
3099 Ok(())
3100 }
3101
3102 // ── Entry point ──────────────────────────────────────────────────────────────
3103
3104 #[tokio::main]
3105 async fn main() -> anyhow::Result<()> {
3106 // Account subcommands. The editor launches `sigit login` in an embedded
3107 // terminal for ACP terminal-based authentication; the same verbs are handy
3108 // directly from a shell. These must be handled before the TTY/ACP split.
3109 if let Some(verb) = std::env::args().nth(1) {
3110 match verb.as_str() {
3111 "login" => {
3112 init_logging(true);
3113 match account::interactive_login().await {
3114 Ok(email) => {
3115 println!("Signed in to siGit Code Cloud as {email}.");
3116 return Ok(());
3117 }
3118 Err(error) => {
3119 eprintln!("Login failed: {error}");
3120 std::process::exit(1);
3121 }
3122 }
3123 }
3124 "logout" => {
3125 init_logging(true);
3126 println!("{}", account::end_session().await);
3127 return Ok(());
3128 }
3129 "whoami" => {
3130 init_logging(true);
3131 println!("{}", account::status_line().await);
3132 return Ok(());
3133 }
3134 "run" => {
3135 // Headless one-shot mode: stdout carries JSONL run events, so
3136 // logs go to stderr exactly like ACP mode.
3137 init_logging(false);
3138 setup::setup_shared_model_cache();
3139 // Best-effort MCP discovery so `mcp__*` tools are offered
3140 // (`SIGIT_MCP=off` skips this, the cloud-runner default).
3141 mcp::init().await;
3142 log::info!(
3143 "siGit v{} starting (headless run)",
3144 env!("CARGO_PKG_VERSION")
3145 );
3146 return headless::run(std::env::args().skip(2)).await;
3147 }
3148 _ => {}
3149 }
3150 }
3151
3152 let is_tty = std::io::stdin().is_terminal();
3153
3154 if is_tty {
3155 // must redirect before any library code touches stdout
3156 #[cfg(unix)]
3157 {
3158 let (tty, cleanup_tty) = redirect_output_to_log()?;
3159 init_logging(true);
3160 setup::setup_shared_model_cache();
3161 // Best-effort: discover MCP servers (incl. the official one) before
3162 // the first turn so their tools are offered to the model.
3163 mcp::init().await;
3164 run_interactive(tty, cleanup_tty).await
3165 }
3166 #[cfg(not(unix))]
3167 {
3168 anyhow::bail!("interactive mode requires Unix (macOS / Linux)");
3169 }
3170 } else {
3171 // ACP mode: keep stdout untouched for protocol JSON only.
3172 // Logs already go to stderr via `init_logging(false)`.
3173 init_logging(false);
3174 setup::setup_shared_model_cache();
3175 // Best-effort MCP discovery (incl. the official server) before serving.
3176 mcp::init().await;
3177 log::info!("siGit v{} starting (ACP mode)", env!("CARGO_PKG_VERSION"));
3178 run_acp_server().await
3179 }
3180 }
3181
3182 #[cfg(test)]
3183 mod tests {
3184 use super::*;
3185
3186 #[test]
3187 fn system_prompt_advertises_the_commit_co_author_trailer() {
3188 // The prompt instructs the model with the exact trailer that
3189 // `tools::ensure_commit_co_author` enforces; if the two drift apart the
3190 // safety net would re-amend commits the model already attributed.
3191 assert!(
3192 SYSTEM_PROMPT.contains(tools::COMMIT_CO_AUTHOR_TRAILER),
3193 "SYSTEM_PROMPT must quote tools::COMMIT_CO_AUTHOR_TRAILER verbatim"
3194 );
3195 }
3196
3197 #[test]
3198 fn ascii_safe_replaces_multibyte_chars() {
3199 // The exact label that crashed Zed: the cloud tier name plus the old
3200 // "[☁ siGit Code Cloud]" badge. After sanitizing it must be pure ASCII so
3201 // Zed's fixed byte-offset truncation can never split a glyph.
3202 let crashing = "siGit Code Cloud · Balanced [☁ siGit Code Cloud]";
3203 let safe = ascii_safe(crashing);
3204 assert!(safe.is_ascii(), "sanitized label must be ASCII: {safe:?}");
3205 assert_eq!(safe, "siGit Code Cloud - Balanced [- siGit Code Cloud]");
3206 }
3207
3208 #[test]
3209 fn ascii_safe_leaves_ascii_untouched() {
3210 let plain = "Qwen 2.5 3B [Onde]";
3211 assert_eq!(ascii_safe(plain), plain);
3212 }
3213
3214 #[test]
3215 fn ascii_safe_output_has_only_char_boundaries() {
3216 // Every byte index in an ASCII string is a valid char boundary, so any
3217 // downstream truncation is panic-free regardless of where it cuts.
3218 let safe = ascii_safe("Onde · ◉ ↓ ☁ ○ test");
3219 for i in 0..=safe.len() {
3220 assert!(safe.is_char_boundary(i));
3221 }
3222 }
3223 }