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(
1377 &session_id.to_string(),
1378 &tc.name,
1379 &tc.arguments,
1380 ) {
1381 permissions::Decision::Allow => {
1382 tools::execute_tool(&tc.name, &tc.arguments).await
1383 }
1384 permissions::Decision::Deny(reason) => {
1385 log::info!(" ✗ {} denied by policy", tc.name);
1386 reason
1387 }
1388 permissions::Decision::Ask => {
1389 match self
1390 .request_tool_permission(cx, &session_id, &tc.name, &tc.arguments)
1391 .await
1392 {
1393 PermissionVerdict::Approved => {
1394 tools::execute_tool(&tc.name, &tc.arguments).await
1395 }
1396 PermissionVerdict::Denied(reason) => {
1397 log::info!(" ✗ {} denied by user", tc.name);
1398 reason
1399 }
1400 PermissionVerdict::TurnCancelled => {
1401 log::info!("prompt({}) cancelled at permission gate", session_id);
1402 // The assistant message carrying these tool
1403 // calls is already in the backend history;
1404 // leaving any of them unanswered makes strict
1405 // OpenAI-compatible endpoints reject every
1406 // later request in the session. Close out this
1407 // call and the ones this round never reached.
1408 for pending in &result.tool_calls[call_index..] {
1409 tool_results.push(BackendToolResult {
1410 tool_call_id: pending.id.clone(),
1411 content: format!(
1412 "`{}` was not executed: the user cancelled the turn \
1413 at the permission prompt.",
1414 pending.name
1415 ),
1416 });
1417 }
1418 backend.record_cancelled_tool_results(tool_results).await;
1419 return Ok(PromptResponse::new(StopReason::Cancelled));
1420 }
1421 }
1422 }
1423 };
1424
1425 log::info!(" ← {} chars", output.len());
1426
1427 tool_results.push(BackendToolResult {
1428 tool_call_id: tc.id.clone(),
1429 content: output,
1430 });
1431 }
1432
1433 let next_tools = if round < MAX_TOOL_ROUNDS {
1434 Some(tools.as_slice())
1435 } else {
1436 None // last round: force text
1437 };
1438
1439 result = self
1440 .drain_turn(
1441 cx,
1442 &session_id,
1443 backend.send_tool_results(tool_results, next_tools, Some(&sink)),
1444 &mut sink_rx,
1445 &mut assembled,
1446 &mut sent,
1447 &mut streamed_any,
1448 )
1449 .await
1450 .map_err(|e| agent_client_protocol::Error::new(-32603, e.to_string()))?;
1451 }
1452
1453 // ── Final text response ───────────────────────────────────────────
1454 // If anything streamed, the visible reply is already on the wire; only
1455 // send a trailing block for the non-streamed path (e.g. on-device direct
1456 // answers, which onde can't stream while tools are on offer).
1457 if !streamed_any {
1458 let reply_text = result.text.trim().to_string();
1459 let final_text = if reply_text.is_empty() {
1460 if round > 0 {
1461 log::warn!(
1462 "prompt({}) — model returned empty reply after {} tool round(s)",
1463 session_id,
1464 round
1465 );
1466 "Something went wrong — the edits didn't go through. Try rephrasing what you need, or point me at the specific lines.".to_string()
1467 } else {
1468 log::warn!(
1469 "prompt({}) — model returned empty reply (no tool rounds)",
1470 session_id
1471 );
1472 String::new()
1473 }
1474 } else {
1475 // strip <think> blocks so reasoning tokens stay hidden
1476 let (_think, visible) = chat::strip_think_blocks(&reply_text);
1477 visible
1478 };
1479
1480 if !final_text.is_empty() {
1481 self.send_assistant_message(cx, session_id.clone(), final_text)
1482 .ok();
1483 }
1484 }
1485
1486 // Persist the completed turn so a restart (or session/load) can pick
1487 // the conversation back up.
1488 let snapshot = backend.history_snapshot().await;
1489 if let Err(error) = session_store::save(&session_id.to_string(), &snapshot) {
1490 log::warn!("prompt({}) session save failed: {error}", session_id);
1491 }
1492
1493 log::info!("prompt({}) complete — {} tool round(s)", session_id, round);
1494 Ok(PromptResponse::new(StopReason::EndTurn))
1495 }
1496
1497 /// Ask the ACP client for permission to run one tool call. Presents
1498 /// allow-once / allow-for-session / deny; an "always allow" choice is
1499 /// recorded via [`permissions::grant_for_session`]. Only safe to call from
1500 /// a spawned task (see the handler registration in `run_acp_server`): the
1501 /// dispatch loop must be free to route the client's answer back to us.
1502 async fn request_tool_permission(
1503 &self,
1504 cx: &ConnectionTo<Client>,
1505 session_id: &SessionId,
1506 tool_name: &str,
1507 arguments: &str,
1508 ) -> PermissionVerdict {
1509 // The user decides from this dialog, so show the arguments with any
1510 // truncation flagged (a silently clipped command could hide its tail
1511 // from the person approving it). The full arguments also travel as
1512 // `raw_input` for clients that render it.
1513 let args_preview = permissions::approval_preview(arguments);
1514 let title = if args_preview.is_empty() {
1515 tool_name.to_string()
1516 } else {
1517 format!("{tool_name}({args_preview})")
1518 };
1519 let raw_input: serde_json::Value = serde_json::from_str(arguments)
1520 .unwrap_or_else(|_| serde_json::Value::String(arguments.to_string()));
1521
1522 let request = RequestPermissionRequest::new(
1523 session_id.clone(),
1524 ToolCallUpdate::new(
1525 format!("perm-{}", uuid::Uuid::new_v4()),
1526 ToolCallUpdateFields::new()
1527 .title(title)
1528 .kind(tool_kind_for(tool_name))
1529 .status(ToolCallStatus::Pending)
1530 .raw_input(raw_input),
1531 ),
1532 vec![
1533 PermissionOption::new("allow_once", "Allow once", PermissionOptionKind::AllowOnce),
1534 PermissionOption::new(
1535 "allow_session",
1536 "Allow for this session",
1537 PermissionOptionKind::AllowAlways,
1538 ),
1539 PermissionOption::new("reject_once", "Deny", PermissionOptionKind::RejectOnce),
1540 ],
1541 );
1542
1543 match cx.send_request(request).block_task().await {
1544 Ok(response) => match response.outcome {
1545 RequestPermissionOutcome::Selected(selected) => {
1546 match selected.option_id.0.as_ref() {
1547 "allow_once" => PermissionVerdict::Approved,
1548 "allow_session" => {
1549 permissions::grant_for_session(
1550 &session_id.to_string(),
1551 tool_name,
1552 arguments,
1553 );
1554 PermissionVerdict::Approved
1555 }
1556 _ => PermissionVerdict::Denied(permissions::user_denial(tool_name)),
1557 }
1558 }
1559 RequestPermissionOutcome::Cancelled => PermissionVerdict::TurnCancelled,
1560 // The outcome enum is non_exhaustive; treat anything unknown as
1561 // a denial rather than running a mutating tool unapproved.
1562 _ => PermissionVerdict::Denied(permissions::user_denial(tool_name)),
1563 },
1564 Err(error) => {
1565 log::warn!("permission request for `{tool_name}` failed: {error}");
1566 PermissionVerdict::Denied(format!(
1567 "`{tool_name}` was not executed: this client could not answer the \
1568 permission request ({error}). The user can pre-approve tools in \
1569 settings.toml under [permissions], or set SIGIT_PERMISSIONS=allow \
1570 for clients without permission support."
1571 ))
1572 }
1573 }
1574 }
1575
1576 async fn handle_cancel(&self, args: CancelNotification) -> agent_client_protocol::Result<()> {
1577 log::info!("cancel requested for session {}", args.session_id);
1578 Ok(())
1579 }
1580
1581 /// Swap the active backend to a siGit Code Cloud tier and reflect it as the
1582 /// current model so the picker shows it selected. Returns the tier's display
1583 /// name on success, or `None` when no account is signed in (caller prompts
1584 /// for login). Shared by the panel picker and the `/models` slash command.
1585 async fn switch_to_cloud_tier(&self, tier: &str) -> Option<String> {
1586 let cfg = crate::provider::cloud_tier_provider(tier)?;
1587 let mut system_prompt = system_prompt_for_model(true).to_string();
1588 // Mirror the cwd guidance and project instruction files the local engine
1589 // gets at session load, so the cloud model shares the same project context.
1590 if let Some(cwd) = self.session_cwd.lock().ok().and_then(|g| g.clone()) {
1591 system_prompt.push_str("\n\n");
1592 system_prompt.push_str(&session_context_message(&cwd));
1593 }
1594 let cloud_backend: Arc<dyn InferenceBackend> = Arc::new(OpenAiBackend::new(
1595 cfg.base_url,
1596 cfg.api_key,
1597 cfg.model,
1598 Some(system_prompt),
1599 ));
1600 *self.backend.lock().await = cloud_backend;
1601
1602 let cloud_config = GgufModelConfig {
1603 model_id: format!("sigit-cloud:{tier}"),
1604 files: Vec::new(),
1605 tok_model_id: None,
1606 display_name: cfg.display_name.clone(),
1607 approx_memory: "Cloud".to_string(),
1608 chat_template: None,
1609 };
1610 {
1611 let mut guard = self.current_model.lock().unwrap();
1612 *guard = cloud_config;
1613 }
1614
1615 // Explicitly choosing a cloud tier puts us in cloud mode.
1616 let _ = settings::set_local_inference(false);
1617
1618 log::info!("switched to cloud tier {tier}");
1619 Some(cfg.display_name)
1620 }
1621
1622 /// Apply the persisted Local Inference mode at session start. When local
1623 /// inference is off and an account is signed in, route to a cloud tier so the
1624 /// on-device model is never loaded; otherwise leave the on-device backend in
1625 /// place. Call after the session cwd is set so the cloud system prompt picks
1626 /// it up. Does not flip the stored setting on the not-signed-in fallback.
1627 async fn apply_startup_inference_mode(&self) {
1628 if settings::local_inference_enabled() {
1629 return;
1630 }
1631 if self.switch_to_cloud_tier("balanced").await.is_some() {
1632 log::info!("startup: local inference off; routing inference to siGit Code Cloud");
1633 } else {
1634 log::warn!(
1635 "local inference is off but no account is signed in; staying on-device. \
1636 Run /login or set Local Inference on."
1637 );
1638 }
1639 }
1640
1641 /// Route inference back on-device. Used after leaving a cloud tier for a
1642 /// local model. The `LocalBackend` reads the live `engine`, so this just
1643 /// repoints the active backend.
1644 async fn reset_to_local_backend(&self) {
1645 let local_backend: Arc<dyn InferenceBackend> =
1646 Arc::new(LocalBackend::new(Arc::clone(&self.engine)));
1647 *self.backend.lock().await = local_backend;
1648 }
1649
1650 /// Re-attempt the lazy startup model load if the previous attempt failed.
1651 /// Clears the one-shot guard so the next load runs; a healthy load is left
1652 /// untouched so `/reload` doesn't needlessly reload a working model.
1653 fn retry_startup_model_load_if_failed(&self) {
1654 let had_error = self
1655 .model_load_error
1656 .lock()
1657 .map(|guard| guard.is_some())
1658 .unwrap_or(false);
1659 if had_error {
1660 self.startup_model_load_started
1661 .store(false, Ordering::Release);
1662 self.start_startup_model_load_if_needed();
1663 }
1664 }
1665
1666 /// Re-sync session state in place — no new session needed. Re-applies the
1667 /// active backend from current credentials (so a fresh `/login` token is
1668 /// picked up), retries a failed model load, and pushes refreshed commands +
1669 /// picker so the editor's UI reflects the current state.
1670 async fn handle_reload(&self, cx: &ConnectionTo<Client>, session_id: SessionId) {
1671 let signed_in = account::status_line().await;
1672
1673 let on_cloud_tier = {
1674 let guard = self.current_model.lock().unwrap();
1675 guard
1676 .model_id
1677 .strip_prefix("sigit-cloud:")
1678 .map(str::to_string)
1679 };
1680
1681 let backend_note = match on_cloud_tier {
1682 Some(tier) => match self.switch_to_cloud_tier(&tier).await {
1683 Some(name) => format!("Active: {name}."),
1684 None => {
1685 self.reset_to_local_backend().await;
1686 "Signed out — back to on-device. Pick a model with /models.".to_string()
1687 }
1688 },
1689 None => {
1690 self.reset_to_local_backend().await;
1691 self.retry_startup_model_load_if_failed();
1692 let guard = self.current_model.lock().unwrap();
1693 format!("Active: {}.", guard.display_name)
1694 }
1695 };
1696
1697 // Push refreshed picker + commands so the editor reflects current state.
1698 let config_options = {
1699 let guard = self.current_model.lock().unwrap();
1700 build_model_config_options(&guard)
1701 };
1702 self.send_tool_call_update(
1703 cx,
1704 session_id.clone(),
1705 SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(config_options)),
1706 )
1707 .ok();
1708 self.advertise_commands(cx, session_id.clone());
1709
1710 self.send_assistant_message(
1711 cx,
1712 session_id,
1713 format!("Reloaded. {signed_in} {backend_note}"),
1714 )
1715 .ok();
1716 }
1717
1718 async fn handle_set_session_config_option(
1719 &self,
1720 cx: &ConnectionTo<Client>,
1721 args: SetSessionConfigOptionRequest,
1722 ) -> agent_client_protocol::Result<SetSessionConfigOptionResponse> {
1723 log::info!(
1724 "set_session_config_option: config_id={}, value={:?}",
1725 args.config_id,
1726 args.value
1727 );
1728
1729 // ── Local Inference toggle ──────────────────────────────────────────
1730 if args.config_id.0.as_ref() == LOCAL_INFERENCE_CONFIG_ID {
1731 let enabled = match args.value.0.as_ref() {
1732 LOCAL_INFERENCE_ON => true,
1733 LOCAL_INFERENCE_OFF => false,
1734 other => {
1735 return Err(agent_client_protocol::Error::new(
1736 -32602,
1737 format!("unknown Local Inference value: {other}"),
1738 ));
1739 }
1740 };
1741 if let Err(error) = settings::set_local_inference(enabled) {
1742 return Err(agent_client_protocol::Error::new(
1743 -32603,
1744 format!("could not save Local Inference setting: {error}"),
1745 ));
1746 }
1747 let message = if enabled {
1748 "Local inference is on. On-device models are highlighted; pick one from Model."
1749 } else {
1750 "Local inference is off. siGit Code Cloud tiers are highlighted; pick one from Model."
1751 };
1752 self.send_assistant_message(cx, args.session_id.clone(), format!("\n\n{message}"))
1753 .ok();
1754 // Rebuild so the Model picker reflects the new emphasis/order.
1755 let current = self.current_model.lock().unwrap().clone();
1756 let config_options = build_model_config_options(&current);
1757 return Ok(SetSessionConfigOptionResponse::new(config_options));
1758 }
1759
1760 if args.config_id.0.as_ref() != MODEL_CONFIG_ID {
1761 return Err(agent_client_protocol::Error::new(
1762 -32602,
1763 format!("unknown config option: {}", args.config_id.0),
1764 ));
1765 }
1766
1767 let model_id = args.value.0.as_ref();
1768
1769 // can't switch while the startup model is still loading — the old
1770 // weights are in GPU memory and the new load gets "does not fit"
1771 if self.startup_model_load_started.load(Ordering::Acquire)
1772 && !self.model_ready.load(Ordering::Acquire)
1773 {
1774 log::info!("set_session_config_option: waiting for startup model to finish loading");
1775 while !self.model_ready.load(Ordering::Acquire) {
1776 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1777 }
1778 }
1779
1780 // Zed re-fires the last selection when a thread opens. That re-fire must
1781 // not load anything: on-device models are loaded only on an explicit
1782 // request (`/load`, or actively picking a *different* model below), so a
1783 // re-fire of the already-current selection is a no-op. Otherwise opening a
1784 // new thread would silently load the local model — exactly what we avoid.
1785 {
1786 let current = self.current_model.lock().unwrap();
1787 if current.model_id == model_id {
1788 log::info!(
1789 "set_session_config_option: {} is already the active selection, skipping",
1790 current.display_name
1791 );
1792 let config_options = build_model_config_options(&current);
1793 return Ok(SetSessionConfigOptionResponse::new(config_options));
1794 }
1795 }
1796
1797 // ── siGit Code Cloud tier: no local load; sign-in gated ─────────────
1798 if let Some(tier) = model_id.strip_prefix("sigit-cloud:") {
1799 let message = match self.switch_to_cloud_tier(tier).await {
1800 Some(display_name) => format!("Switched to {display_name}."),
1801 None => CLOUD_LOGIN_PROMPT.to_string(),
1802 };
1803 // Start on a fresh line: ACP clients concatenate consecutive
1804 // agent-message chunks into one block, so without this the switch
1805 // confirmation runs onto the end of the previous assistant message.
1806 self.send_assistant_message(cx, args.session_id.clone(), format!("\n\n{message}"))
1807 .ok();
1808
1809 let current = self.current_model.lock().unwrap().clone();
1810 let config_options = build_model_config_options(&current);
1811 return Ok(SetSessionConfigOptionResponse::new(config_options));
1812 }
1813
1814 let needs_download = models::local_picker_items()
1815 .into_iter()
1816 .find(|item| item.config.model_id == model_id)
1817 .map(|item| item.cache_health == setup::ModelCacheHealth::NotDownloaded)
1818 .unwrap_or(false);
1819
1820 // tells the progress poller to stop
1821 let stop_flag = Arc::new(AtomicBool::new(false));
1822
1823 let tool_call_id = format!("model-switch-{}", uuid::Uuid::new_v4());
1824
1825 if needs_download {
1826 let model_id_owned = model_id.to_string();
1827 let expected_bytes = onde::inference::models::SUPPORTED_MODEL_INFO
1828 .iter()
1829 .find(|m| m.id == model_id_owned)
1830 .map(|m| m.expected_size_bytes)
1831 .unwrap_or(0);
1832
1833 let display_name = models::local_picker_items()
1834 .into_iter()
1835 .find(|item| item.config.model_id == model_id_owned)
1836 .map(|item| item.display_name.clone())
1837 .unwrap_or_else(|| model_id_owned.clone());
1838
1839 let size_hint = if expected_bytes > 0 {
1840 format!(" (~{})", format_size_human(expected_bytes))
1841 } else {
1842 String::new()
1843 };
1844
1845 self.send_tool_call_update(
1846 cx,
1847 args.session_id.clone(),
1848 SessionUpdate::ToolCall(
1849 ToolCall::new(
1850 tool_call_id.clone(),
1851 format!("⏬ Downloading {display_name}{size_hint}"),
1852 )
1853 .kind(ToolKind::Think)
1854 .status(ToolCallStatus::InProgress)
1855 .content(vec![
1856 format!(
1857 "Preparing download for {display_name}. This may take a few minutes."
1858 )
1859 .into(),
1860 ]),
1861 ),
1862 )
1863 .ok();
1864
1865 // poll download progress and update the spinner in Zed
1866 let cx_for_poller = cx.clone();
1867 let poller_session = args.session_id.clone();
1868 let poller_model_id = model_id_owned.clone();
1869 let poller_stop = Arc::clone(&stop_flag);
1870 let poller_tool_call_id = tool_call_id.clone();
1871
1872 cx.spawn(async move {
1873 const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
1874 let cache_path = onde::hf_cache::model_cache_path(&poller_model_id);
1875 let mut tick: usize = 0;
1876 let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
1877 interval.tick().await; // consume the immediate first tick
1878
1879 while !poller_stop.load(Ordering::Relaxed) {
1880 interval.tick().await;
1881
1882 if poller_stop.load(Ordering::Relaxed) {
1883 break;
1884 }
1885
1886 let downloaded = cache_path
1887 .as_ref()
1888 .filter(|p| p.exists())
1889 .map(|p| dir_size_recursive(p))
1890 .unwrap_or(0);
1891
1892 let frame = SPINNER[tick % SPINNER.len()];
1893 tick += 1;
1894
1895 let title = if expected_bytes > 0 {
1896 let pct =
1897 ((downloaded as f64 / expected_bytes as f64) * 100.0).min(99.0) as u8;
1898 format!("{frame} Downloading {display_name}{size_hint} ({pct}%)")
1899 } else {
1900 format!("{frame} Downloading {display_name}{size_hint}")
1901 };
1902
1903 let msg = if expected_bytes > 0 {
1904 let pct =
1905 ((downloaded as f64 / expected_bytes as f64) * 100.0).min(99.0) as u8;
1906 let bar = progress_bar(pct, 20);
1907 format!(
1908 "{display_name} — {bar} {pct}% ({} / {})",
1909 format_size_human(downloaded),
1910 format_size_human(expected_bytes),
1911 )
1912 } else {
1913 format!(
1914 "{display_name} — {} downloaded…",
1915 format_size_human(downloaded)
1916 )
1917 };
1918
1919 let notification = SessionNotification::new(
1920 poller_session.clone(),
1921 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1922 poller_tool_call_id.clone(),
1923 ToolCallUpdateFields::new()
1924 .title(title)
1925 .status(ToolCallStatus::InProgress)
1926 .content(vec![msg.into()]),
1927 )),
1928 );
1929 if cx_for_poller.send_notification(notification).is_err() {
1930 break;
1931 }
1932 }
1933 Ok(())
1934 })
1935 .ok();
1936 }
1937
1938 // cached models still take 10-30s to load weights; show a spinner
1939 if !needs_download {
1940 let cached_display_name = models::local_picker_items()
1941 .into_iter()
1942 .find(|item| item.config.model_id == model_id)
1943 .map(|item| item.display_name.clone())
1944 .unwrap_or_else(|| model_id.to_string());
1945
1946 self.send_tool_call_update(
1947 cx,
1948 args.session_id.clone(),
1949 SessionUpdate::ToolCall(
1950 ToolCall::new(
1951 tool_call_id.clone(),
1952 format!("Loading {cached_display_name}"),
1953 )
1954 .kind(ToolKind::Think)
1955 .status(ToolCallStatus::InProgress)
1956 .content(vec![format!("Loading {cached_display_name}…").into()]),
1957 ),
1958 )
1959 .ok();
1960
1961 // tick every 5s so the user knows we haven't frozen
1962 let cx_for_spinner = cx.clone();
1963 let spinner_session = args.session_id.clone();
1964 let spinner_name = cached_display_name.clone();
1965 let spinner_stop = Arc::clone(&stop_flag);
1966 let spinner_tool_call_id = tool_call_id.clone();
1967 let load_start = std::time::Instant::now();
1968
1969 cx.spawn(async move {
1970 const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
1971 let mut tick: usize = 0;
1972 let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
1973 interval.tick().await; // consume the immediate first tick
1974
1975 while !spinner_stop.load(Ordering::Relaxed) {
1976 interval.tick().await;
1977
1978 if spinner_stop.load(Ordering::Relaxed) {
1979 break;
1980 }
1981
1982 let elapsed = load_start.elapsed();
1983 let elapsed_str = if elapsed.as_secs() >= 60 {
1984 format!("{}m {:02}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
1985 } else {
1986 format!("{}s", elapsed.as_secs())
1987 };
1988 let frame = SPINNER[tick % SPINNER.len()];
1989 tick += 1;
1990
1991 let msg = format!("{frame} Loading {spinner_name}… ({elapsed_str})");
1992 let notification = SessionNotification::new(
1993 spinner_session.clone(),
1994 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1995 spinner_tool_call_id.clone(),
1996 ToolCallUpdateFields::new()
1997 .status(ToolCallStatus::InProgress)
1998 .content(vec![msg.into()]),
1999 )),
2000 );
2001 if cx_for_spinner.send_notification(notification).is_err() {
2002 break;
2003 }
2004 }
2005 Ok(())
2006 })
2007 .ok();
2008 }
2009
2010 let switch_result = self.switch_model_by_id(model_id).await;
2011
2012 stop_flag.store(true, Ordering::Relaxed);
2013
2014 match switch_result {
2015 Ok(new_config) => {
2016 // Route inference back on-device (in case we were on a cloud tier).
2017 self.reset_to_local_backend().await;
2018 // Selecting an on-device model puts us in local mode.
2019 let _ = settings::set_local_inference(true);
2020
2021 let completion_title = if needs_download {
2022 format!("✓ {} downloaded and loaded", new_config.display_name)
2023 } else {
2024 format!("✓ Switched to {}", new_config.display_name)
2025 };
2026 let completion_body = if needs_download {
2027 format!("✓ {} downloaded and loaded.", new_config.display_name)
2028 } else {
2029 format!("✓ Switched to {}.", new_config.display_name)
2030 };
2031
2032 self.send_tool_call_update(
2033 cx,
2034 args.session_id.clone(),
2035 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
2036 tool_call_id,
2037 ToolCallUpdateFields::new()
2038 .title(completion_title)
2039 .status(ToolCallStatus::Completed)
2040 .content(vec![completion_body.into()]),
2041 )),
2042 )
2043 .ok();
2044
2045 let config_options = {
2046 let guard = self.current_model.lock().unwrap();
2047 build_model_config_options(&guard)
2048 };
2049
2050 log::info!("model switch complete");
2051 Ok(SetSessionConfigOptionResponse::new(config_options))
2052 }
2053 Err(err) => {
2054 self.send_tool_call_update(
2055 cx,
2056 args.session_id.clone(),
2057 SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
2058 tool_call_id,
2059 ToolCallUpdateFields::new()
2060 .title("Model switch failed".to_string())
2061 .status(ToolCallStatus::Failed)
2062 .content(vec![format!("error loading model: {}", err.message).into()]),
2063 )),
2064 )
2065 .ok();
2066
2067 Err(err)
2068 }
2069 }
2070 }
2071 }
2072
2073 // ── Config option helpers ─────────────────────────────────────────────────────
2074
2075 /// config option ID for the model picker in Zed's agent panel
2076 const MODEL_CONFIG_ID: &str = "sigit-model";
2077
2078 /// config option ID for the Local Inference on/off toggle. Surfaced as a
2079 /// two-option `select` so ACP clients without slash-command support (e.g. Xcode)
2080 /// can still flip the mode from the agent panel.
2081 const LOCAL_INFERENCE_CONFIG_ID: &str = "sigit-local-inference";
2082
2083 /// `select` value ids for the Local Inference toggle.
2084 const LOCAL_INFERENCE_ON: &str = "local-inference-on";
2085 const LOCAL_INFERENCE_OFF: &str = "local-inference-off";
2086
2087 /// Replace non-ASCII chars so a downstream byte-index truncation can't split a
2088 /// multi-byte char. Zed slices the model-picker label at a fixed byte offset
2089 /// (`agent_ui/src/config_options.rs`) and panics — crashing the whole editor —
2090 /// when the cut lands mid-glyph (e.g. inside `☁` or `·`). Mapping to `-` keeps
2091 /// separators readable; ASCII bytes are always char boundaries.
2092 fn ascii_safe(s: &str) -> String {
2093 s.chars()
2094 .map(|c| if c.is_ascii() { c } else { '-' })
2095 .collect()
2096 }
2097
2098 fn build_model_config_options(current_model: &GgufModelConfig) -> Vec<SessionConfigOption> {
2099 // The full list, including the siGit Code Cloud tiers, so the panel picker
2100 // mirrors the TUI `/models`. Cloud entries are sign-in gated at selection.
2101 let items = models::build_model_picker_items();
2102 let active_kind = models::active_inference_kind();
2103
2104 let options: Vec<SessionConfigSelectOption> = items
2105 .iter()
2106 .filter(|item| item.cache_health != setup::ModelCacheHealth::Incomplete)
2107 .map(|item| {
2108 let mut desc_parts = Vec::new();
2109 // Mark options in the inactive mode so the active group reads as the
2110 // recommended set (the list is already ordered active-group-first).
2111 if item.source.kind() != active_kind {
2112 desc_parts.push("inactive mode".to_string());
2113 }
2114 if item.tool_calling {
2115 desc_parts.push("tool calling".to_string());
2116 }
2117 desc_parts.push(item.description.clone());
2118 if item.cache_health == setup::ModelCacheHealth::NotDownloaded {
2119 desc_parts.push("download on select".to_string());
2120 }
2121 // ASCII-only for the same reason as the name (see `ascii_safe`).
2122 let description = ascii_safe(&desc_parts.join(" - "));
2123 // Keep badges ASCII: Zed truncates the picker label at a fixed byte
2124 // offset and panics if the cut splits a multi-byte char. See
2125 // `ascii_safe` below.
2126 let source_badge = if item.cloud_tier.is_some() {
2127 " [siGit Code Cloud]"
2128 } else if item.cache_health == setup::ModelCacheHealth::NotDownloaded {
2129 " [Onde]"
2130 } else {
2131 match item.source_label.as_str() {
2132 "Onde" => " [Onde]",
2133 "HuggingFace" => " [HuggingFace]",
2134 _ => "",
2135 }
2136 };
2137 // For cloud tiers use just the tier title (e.g. "Balanced") so the
2138 // label reads "Balanced [siGit Code Cloud]" instead of repeating the
2139 // brand. The display name can carry non-ASCII (the cloud tier label
2140 // is "siGit Code Cloud · Balanced"), so sanitize the whole label.
2141 let base_name = match &item.cloud_tier {
2142 Some(tier) => crate::provider::tier_title(tier),
2143 None => item.display_name.clone(),
2144 };
2145 let name = ascii_safe(&format!("{base_name}{source_badge}"));
2146 SessionConfigSelectOption::new(
2147 SessionConfigValueId::new(item.config.model_id.as_str()),
2148 name,
2149 )
2150 .description(description)
2151 })
2152 .collect();
2153
2154 // Local Inference on/off toggle, modeled as a two-option select so panel-only
2155 // ACP clients (no slash commands) can flip the mode.
2156 let local_on = settings::local_inference_enabled();
2157 let local_current = SessionConfigValueId::new(if local_on {
2158 LOCAL_INFERENCE_ON
2159 } else {
2160 LOCAL_INFERENCE_OFF
2161 });
2162 let local_options = vec![
2163 SessionConfigSelectOption::new(
2164 SessionConfigValueId::new(LOCAL_INFERENCE_ON),
2165 "On (on-device)".to_string(),
2166 )
2167 .description("Run inference on-device; on-device models are highlighted".to_string()),
2168 SessionConfigSelectOption::new(
2169 SessionConfigValueId::new(LOCAL_INFERENCE_OFF),
2170 "Off (siGit Code Cloud)".to_string(),
2171 )
2172 .description("Use siGit Code Cloud; cloud tiers are highlighted".to_string()),
2173 ];
2174 let local_option = SessionConfigOption::select(
2175 LOCAL_INFERENCE_CONFIG_ID,
2176 "Local Inference",
2177 local_current,
2178 local_options,
2179 )
2180 .description("Toggle on-device inference; changes which models are highlighted");
2181
2182 if options.is_empty() {
2183 return vec![local_option];
2184 }
2185
2186 let current_value = SessionConfigValueId::new(current_model.model_id.as_str());
2187
2188 vec![
2189 SessionConfigOption::select(MODEL_CONFIG_ID, "Model", current_value, options)
2190 .category(SessionConfigOptionCategory::Model)
2191 .description("Select an on-device model or a siGit Code Cloud tier"),
2192 local_option,
2193 ]
2194 }
2195
2196 /// returns `(config, max_tokens, tool_calling)` for a picker model_id, or None
2197 fn resolve_model_config(model_id: &str) -> Option<(GgufModelConfig, u64, bool)> {
2198 let items = models::local_picker_items();
2199 items
2200 .into_iter()
2201 .find(|item| {
2202 item.config.model_id == model_id
2203 && item.cache_health != setup::ModelCacheHealth::Incomplete
2204 })
2205 .map(|item| (item.config, item.max_tokens, item.tool_calling))
2206 }
2207
2208 // ── Slash commands ────────────────────────────────────────────────────────────
2209
2210 #[derive(Debug, Clone)]
2211 enum SlashCommand {
2212 Help,
2213 Clear,
2214 Status,
2215 Models(Option<usize>),
2216 /// toggle on-device inference mode. `Some(true/false)` sets it, `None` flips it.
2217 Local(Option<bool>),
2218 /// List discovered Agent Skills.
2219 Skills,
2220 /// List configured MCP servers and their tools.
2221 Mcp,
2222 /// Explicitly load the selected (or default) on-device model.
2223 Load,
2224 /// `/login <email> <password>` — the raw argument, parsed when executed.
2225 Login(Option<String>),
2226 Logout,
2227 Whoami,
2228 /// Re-sync session state (auth, backend, picker) without a new session.
2229 Reload,
2230 /// Toggle plan mode (read-only research; mutating tools denied with a
2231 /// prompt to present a plan). `Some(true/false)` sets it, `None` flips it.
2232 Plan(Option<bool>),
2233 /// Show the effective permission policy for this session.
2234 Permissions,
2235 /// Summarize-and-shrink the conversation history on demand.
2236 Compact,
2237 Exit,
2238 Unknown(String),
2239 }
2240
2241 fn parse_slash(input: &str) -> Option<SlashCommand> {
2242 let trimmed = input.trim();
2243 if !trimmed.starts_with('/') {
2244 return None;
2245 }
2246 let mut parts = trimmed.splitn(2, char::is_whitespace);
2247 let command = parts.next().unwrap_or("");
2248 let argument = parts.next().map(str::trim);
2249 Some(match command {
2250 "/help" => SlashCommand::Help,
2251 "/clear" => SlashCommand::Clear,
2252 "/status" => SlashCommand::Status,
2253 "/models" => SlashCommand::Models(argument.and_then(|v| v.parse::<usize>().ok())),
2254 "/local" => SlashCommand::Local(parse_on_off(argument)),
2255 "/skills" => SlashCommand::Skills,
2256 "/mcp" => SlashCommand::Mcp,
2257 "/load" => SlashCommand::Load,
2258 "/login" => SlashCommand::Login(argument.map(str::to_string)),
2259 "/logout" => SlashCommand::Logout,
2260 "/whoami" => SlashCommand::Whoami,
2261 "/reload" => SlashCommand::Reload,
2262 "/plan" => SlashCommand::Plan(parse_on_off(argument)),
2263 "/permissions" => SlashCommand::Permissions,
2264 "/compact" => SlashCommand::Compact,
2265 "/exit" | "/quit" | "/q" => SlashCommand::Exit,
2266 other => SlashCommand::Unknown(other.to_string()),
2267 })
2268 }
2269
2270 /// `on`/`off` (and synonyms) → `Some(bool)`; missing or unrecognized → `None`
2271 /// (meaning "toggle the current value").
2272 fn parse_on_off(arg: Option<&str>) -> Option<bool> {
2273 match arg.map(|s| s.trim().to_ascii_lowercase())?.as_str() {
2274 "on" | "true" | "1" | "yes" => Some(true),
2275 "off" | "false" | "0" | "no" => Some(false),
2276 _ => None,
2277 }
2278 }
2279
2280 fn format_models_list(current_model: &GgufModelConfig) -> String {
2281 let items = models::build_model_picker_items();
2282 if items.is_empty() {
2283 return "No local models found. siGit will use the platform default model.".to_string();
2284 }
2285
2286 let mut lines = vec!["Available models:".to_string()];
2287 let mut last_source: Option<&str> = None;
2288
2289 for (index, item) in items.iter().enumerate() {
2290 let source_key = match item.source_label.as_str() {
2291 "Onde" => "Onde",
2292 "HuggingFace" => "HuggingFace",
2293 "siGit Code Cloud" => "Cloud",
2294 _ => "Fallback",
2295 };
2296
2297 if last_source != Some(source_key) {
2298 if last_source.is_some() {
2299 lines.push(String::new());
2300 }
2301 let section = match source_key {
2302 "Onde" => "Onde Inference",
2303 "HuggingFace" => "Hugging Face cache",
2304 "Cloud" => "siGit Code Cloud",
2305 _ => "Fallback",
2306 };
2307 lines.push(section.to_string());
2308 // Blank line so the following "N." items render as an ordered list.
2309 // CommonMark only lets an ordered list interrupt a paragraph when it
2310 // starts at 1, so without this the cloud section (items 9+) would be
2311 // absorbed into the header paragraph.
2312 lines.push(String::new());
2313 last_source = Some(source_key);
2314 }
2315
2316 let number = index + 1;
2317 let current_badge = if item.config.model_id == current_model.model_id {
2318 " <- current"
2319 } else {
2320 ""
2321 };
2322 let tool_badge = if item.tool_calling {
2323 " tool calling"
2324 } else {
2325 ""
2326 };
2327 let health_badge = match item.cache_health {
2328 setup::ModelCacheHealth::Complete => "",
2329 setup::ModelCacheHealth::Incomplete => " ! incomplete cache",
2330 setup::ModelCacheHealth::NotDownloaded => " ↓ download on select",
2331 };
2332 let source = match source_key {
2333 "Onde" => " [Onde]",
2334 "HuggingFace" => " [HuggingFace]",
2335 "Cloud" => " [☁ Cloud]",
2336 _ => " [default]",
2337 };
2338
2339 lines.push(format!(
2340 "{number}. {} {}{}{}{}{}",
2341 item.display_name, item.description, tool_badge, health_badge, current_badge, source,
2342 ));
2343 }
2344
2345 lines.push(String::new());
2346 lines.push("Use /models N to switch models.".to_string());
2347 lines.join("\n")
2348 }
2349
2350 async fn exec_slash_acp(
2351 agent: &SiGitAgent,
2352 cx: &ConnectionTo<Client>,
2353 session_id: SessionId,
2354 command: SlashCommand,
2355 ) -> agent_client_protocol::Result<PromptResponse> {
2356 match command {
2357 SlashCommand::Help => {
2358 agent
2359 .send_assistant_message(
2360 cx,
2361 session_id,
2362 "/help - show this message\n\
2363 /models - list available models\n\
2364 /models N - switch to model N\n\
2365 /local [on|off]- toggle on-device inference mode\n\
2366 /skills - list available Agent Skills\n\
2367 /mcp - list MCP servers and their tools\n\
2368 /load - load the selected on-device model\n\
2369 /login E P - sign in to siGit Code Cloud\n\
2370 /logout - sign out\n\
2371 /whoami - show the signed-in account\n\
2372 /reload - re-sync sign-in and model state\n\
2373 /plan [on|off] - plan mode: research only, no edits or commands\n\
2374 /permissions - show the tool permission policy\n\
2375 /compact - summarize and shrink conversation history\n\
2376 /clear - wipe conversation history\n\
2377 /status - show engine status\n\
2378 /exit - end this turn",
2379 )
2380 .ok();
2381 }
2382 SlashCommand::Clear => {
2383 let cleared = agent.engine.clear_history().await;
2384 permissions::reset_session(&session_id.to_string());
2385 // The saved session must not resurrect what the user just wiped.
2386 session_store::delete(&session_id.to_string());
2387 agent
2388 .send_assistant_message(
2389 cx,
2390 session_id,
2391 format!("Cleared {cleared} turn(s). History is empty."),
2392 )
2393 .ok();
2394 }
2395 SlashCommand::Plan(value) => {
2396 let session_key = session_id.to_string();
2397 let enabled = value.unwrap_or_else(|| !permissions::plan_mode(&session_key));
2398 permissions::set_plan_mode(&session_key, enabled);
2399 let message = if enabled {
2400 "Plan mode ON — the agent researches with read-only tools and presents a \
2401 plan; edits and commands are blocked until /plan off."
2402 } else {
2403 "Plan mode OFF — the agent may execute tools again (subject to the \
2404 permission policy)."
2405 };
2406 agent.send_assistant_message(cx, session_id, message).ok();
2407 }
2408 SlashCommand::Permissions => {
2409 let summary = permissions::describe(&session_id.to_string());
2410 agent.send_assistant_message(cx, session_id, summary).ok();
2411 }
2412 SlashCommand::Compact => {
2413 let backend = agent.backend.lock().await.clone();
2414 let before = backend::estimate_tokens(&backend.history_snapshot().await);
2415 let message = match backend.compact_history(backend::COMPACT_KEEP_LAST).await {
2416 Ok(()) => {
2417 let snapshot = backend.history_snapshot().await;
2418 let after = backend::estimate_tokens(&snapshot);
2419 // Keep the saved session in step with the compacted state.
2420 if let Err(error) = session_store::save(&session_id.to_string(), &snapshot) {
2421 log::warn!("session save after /compact failed: {error}");
2422 }
2423 format!("Compacted history: ~{before} → ~{after} tokens (estimated).")
2424 }
2425 Err(error) => format!("Compaction failed: {error}"),
2426 };
2427 agent.send_assistant_message(cx, session_id, message).ok();
2428 }
2429 SlashCommand::Status => {
2430 let info = agent.engine.info().await;
2431 let model = info.model_name.as_deref().unwrap_or("(none)");
2432 let memory = info.approx_memory.as_deref().unwrap_or("unknown");
2433 agent
2434 .send_assistant_message(
2435 cx,
2436 session_id,
2437 format!(
2438 "status: {:?} model: {} memory: {} history: {} turns",
2439 info.status, model, memory, info.history_length,
2440 ),
2441 )
2442 .ok();
2443 }
2444 SlashCommand::Models(None) => {
2445 let current_model = agent.current_model.lock().unwrap().clone();
2446 agent
2447 .send_assistant_message(cx, session_id, format_models_list(&current_model))
2448 .ok();
2449 }
2450 SlashCommand::Skills => {
2451 agent
2452 .send_assistant_message(cx, session_id, skills::format_skills_list())
2453 .ok();
2454 }
2455 SlashCommand::Mcp => {
2456 agent
2457 .send_assistant_message(cx, session_id, mcp::status_summary())
2458 .ok();
2459 }
2460 SlashCommand::Models(Some(number)) => {
2461 let items = models::build_model_picker_items();
2462 let index = number.saturating_sub(1);
2463 match items.get(index).cloned() {
2464 None => {
2465 agent
2466 .send_assistant_message(
2467 cx,
2468 session_id,
2469 format!("error: no model #{number} - type /models to see the list."),
2470 )
2471 .ok();
2472 }
2473 Some(model) if model.cloud_tier.is_some() => {
2474 // siGit Code Cloud tier: swap backend, sign-in gated.
2475 let tier = model.cloud_tier.clone().unwrap_or_default();
2476 let message = match agent.switch_to_cloud_tier(&tier).await {
2477 Some(display_name) => format!("Switched to {display_name}."),
2478 None => CLOUD_LOGIN_PROMPT.to_string(),
2479 };
2480 agent.send_assistant_message(cx, session_id, message).ok();
2481 }
2482 Some(model) => {
2483 if model.cache_health == setup::ModelCacheHealth::Incomplete {
2484 agent
2485 .send_assistant_message(
2486 cx,
2487 session_id,
2488 format!(
2489 "error: {} has an incomplete local cache and cannot be selected yet.",
2490 model.display_name
2491 ),
2492 )
2493 .ok();
2494 } else if model.cache_health == setup::ModelCacheHealth::NotDownloaded {
2495 agent
2496 .send_assistant_message(
2497 cx,
2498 session_id.clone(),
2499 format!(
2500 "Downloading and loading {} ({})… this may take a few minutes.",
2501 model.display_name, model.description
2502 ),
2503 )
2504 .ok();
2505
2506 match agent.switch_model_by_id(&model.config.model_id).await {
2507 Ok(new_config) => {
2508 agent.reset_to_local_backend().await;
2509 let _ = settings::set_local_inference(true);
2510 agent.engine.clear_history().await;
2511 agent
2512 .send_assistant_message(
2513 cx,
2514 session_id,
2515 format!(
2516 "✓ Downloaded and switched to {}",
2517 new_config.display_name
2518 ),
2519 )
2520 .ok();
2521 }
2522 Err(err) => {
2523 agent
2524 .send_assistant_message(
2525 cx,
2526 session_id,
2527 format!("error downloading model: {}", err.message),
2528 )
2529 .ok();
2530 }
2531 }
2532 } else {
2533 agent
2534 .send_assistant_message(
2535 cx,
2536 session_id.clone(),
2537 format!("Loading {}...", model.display_name),
2538 )
2539 .ok();
2540
2541 let switched = agent.switch_model_by_id(&model.config.model_id).await?;
2542 agent.reset_to_local_backend().await;
2543 let _ = settings::set_local_inference(true);
2544 agent.engine.clear_history().await;
2545
2546 agent
2547 .send_assistant_message(
2548 cx,
2549 session_id,
2550 format!("Switched to {}.", switched.display_name),
2551 )
2552 .ok();
2553 }
2554 }
2555 }
2556 }
2557 SlashCommand::Local(value) => {
2558 let enabled = value.unwrap_or(!settings::local_inference_enabled());
2559 let message = match settings::set_local_inference(enabled) {
2560 Ok(()) if enabled => "Local inference is on. On-device models are highlighted; \
2561 pick one with /models."
2562 .to_string(),
2563 Ok(()) => "Local inference is off. siGit Code Cloud tiers are highlighted; \
2564 pick one with /models."
2565 .to_string(),
2566 Err(error) => format!("error: could not save local inference setting: {error}"),
2567 };
2568 agent
2569 .send_assistant_message(cx, session_id.clone(), message)
2570 .ok();
2571 // Refresh the panel so the Model picker reflects the new emphasis.
2572 let config_options = {
2573 let current = agent.current_model.lock().unwrap();
2574 build_model_config_options(&current)
2575 };
2576 agent
2577 .send_tool_call_update(
2578 cx,
2579 session_id,
2580 SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(config_options)),
2581 )
2582 .ok();
2583 }
2584 SlashCommand::Load => {
2585 // Explicitly load the on-device model. This is the only path that
2586 // brings a local model into memory; prompts never do it implicitly.
2587 // If a cloud tier is active, fall back to a local default so we don't
2588 // try to load the (file-less) cloud config as GGUF.
2589 let on_cloud = {
2590 let guard = agent.current_model.lock().unwrap();
2591 guard.model_id.starts_with("sigit-cloud:")
2592 };
2593 if on_cloud {
2594 let default_config = default_local_model_config();
2595 *agent.current_model.lock().unwrap() = default_config;
2596 agent.reset_to_local_backend().await;
2597 }
2598 // Loading an on-device model puts us in local inference mode.
2599 let _ = settings::set_local_inference(true);
2600 // `await_model_ready` drives the download/load progress UI and reports
2601 // success or failure to the editor.
2602 agent.start_startup_model_load_if_needed();
2603 agent.await_model_ready(cx, &session_id).await?;
2604 }
2605 SlashCommand::Login(argument) => {
2606 let message = match argument.as_deref().and_then(account::parse_login_args) {
2607 Some((email, password)) => match account::authenticate(&email, &password).await {
2608 Ok(email) => format!(
2609 "Signed in as {email}. Pick a siGit Code Cloud tier in /models to use it."
2610 ),
2611 Err(error) => format!("Login failed: {error}"),
2612 },
2613 None => "usage: /login <email> <password>".to_string(),
2614 };
2615 agent.send_assistant_message(cx, session_id, message).ok();
2616 }
2617 SlashCommand::Logout => {
2618 // If we're on a cloud tier, drop back to local — the token is gone.
2619 let on_cloud = {
2620 let guard = agent.current_model.lock().unwrap();
2621 guard.model_id.starts_with("sigit-cloud:")
2622 };
2623 let message = account::end_session().await;
2624 if on_cloud {
2625 agent.reset_to_local_backend().await;
2626 }
2627 agent.send_assistant_message(cx, session_id, message).ok();
2628 }
2629 SlashCommand::Whoami => {
2630 let message = account::status_line().await;
2631 agent.send_assistant_message(cx, session_id, message).ok();
2632 }
2633 SlashCommand::Reload => {
2634 agent.handle_reload(cx, session_id).await;
2635 }
2636 SlashCommand::Exit => {
2637 agent
2638 .send_assistant_message(
2639 cx,
2640 session_id,
2641 "Use the panel controls to close or switch threads.",
2642 )
2643 .ok();
2644 }
2645 SlashCommand::Unknown(command) => {
2646 agent
2647 .send_assistant_message(cx, session_id, format!("unknown command: {command}"))
2648 .ok();
2649 }
2650 }
2651
2652 Ok(PromptResponse::new(StopReason::EndTurn))
2653 }
2654
2655 // ── Request dispatch helper ───────────────────────────────────────────────────
2656
2657 fn handle_response<T: agent_client_protocol::JsonRpcResponse>(
2658 responder: Responder<T>,
2659 result: agent_client_protocol::Result<T>,
2660 ) -> agent_client_protocol::Result<()> {
2661 match result {
2662 Ok(resp) => responder.respond(resp),
2663 Err(err) => responder.respond_with_error(err),
2664 }
2665 }
2666
2667 // ── Download progress helpers ─────────────────────────────────────────────────
2668
2669 /// total bytes on disk under `path`. needed because hf-hub uses staging
2670 /// names during download, so we can't just stat the final blobs.
2671 fn dir_size_recursive(path: &std::path::Path) -> u64 {
2672 let mut total: u64 = 0;
2673 let Ok(entries) = std::fs::read_dir(path) else {
2674 return 0;
2675 };
2676 for entry in entries.flatten() {
2677 let entry_path = entry.path();
2678 if entry_path.is_dir() {
2679 total += dir_size_recursive(&entry_path);
2680 } else if let Ok(meta) = entry_path.metadata() {
2681 total += meta.len();
2682 }
2683 }
2684 total
2685 }
2686
2687 fn format_size_human(bytes: u64) -> String {
2688 const GB: u64 = 1_073_741_824;
2689 const MB: u64 = 1_048_576;
2690 const KB: u64 = 1_024;
2691 if bytes >= GB {
2692 format!("{:.2} GB", bytes as f64 / GB as f64)
2693 } else if bytes >= MB {
2694 format!("{:.1} MB", bytes as f64 / MB as f64)
2695 } else if bytes >= KB {
2696 format!("{:.0} KB", bytes as f64 / KB as f64)
2697 } else {
2698 format!("{bytes} B")
2699 }
2700 }
2701
2702 fn progress_bar(pct: u8, width: usize) -> String {
2703 let filled = ((pct as usize) * width) / 100;
2704 let empty = width.saturating_sub(filled);
2705 format!("[{}{}]", "█".repeat(filled), "░".repeat(empty))
2706 }
2707
2708 // ── Output capture ────────────────────────────────────────────────────────────
2709
2710 /// redirect stdout+stderr to `$TMPDIR/sigit.log` at the fd level so
2711 /// mistralrs/tracing noise never hits the terminal. returns two dup'd
2712 /// fds to the real tty: one for ratatui, one for cleanup (ratatui 0.29
2713 /// doesn't expose `writer_mut()`).
2714 #[cfg(unix)]
2715 fn redirect_output_to_log() -> anyhow::Result<(std::fs::File, std::fs::File)> {
2716 let log_path = std::env::temp_dir().join("sigit.log");
2717 let log_file = std::fs::File::create(&log_path)?;
2718 let log_fd = log_file.as_raw_fd();
2719
2720 // two copies: ratatui needs one, cleanup needs another
2721 let saved_tui = unsafe { libc::dup(libc::STDOUT_FILENO) };
2722 anyhow::ensure!(
2723 saved_tui >= 0,
2724 "dup(stdout) for tui failed: {}",
2725 std::io::Error::last_os_error()
2726 );
2727 let saved_cleanup = unsafe { libc::dup(libc::STDOUT_FILENO) };
2728 anyhow::ensure!(
2729 saved_cleanup >= 0,
2730 "dup(stdout) for cleanup failed: {}",
2731 std::io::Error::last_os_error()
2732 );
2733
2734 unsafe {
2735 libc::dup2(log_fd, libc::STDOUT_FILENO);
2736 libc::dup2(log_fd, libc::STDERR_FILENO);
2737 }
2738
2739 // safe to drop log_file; dup2 keeps the fd alive via stdout/stderr
2740
2741 Ok((unsafe { std::fs::File::from_raw_fd(saved_tui) }, unsafe {
2742 std::fs::File::from_raw_fd(saved_cleanup)
2743 }))
2744 }
2745
2746 // ── Logging ───────────────────────────────────────────────────────────────────
2747
2748 /// in TUI mode stderr is the log file (redirected earlier);
2749 /// in ACP mode it's real stderr. either way, write there.
2750 fn init_logging(is_tty: bool) {
2751 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
2752 let _ = tracing_fmt::Subscriber::builder()
2753 .with_env_filter(filter)
2754 .with_writer(std::io::stderr)
2755 .with_ansi(!is_tty)
2756 .try_init();
2757 }
2758
2759 // ── Interactive TUI mode ──────────────────────────────────────────────────────
2760
2761 /// boot the TUI and load the model on a background thread.
2762 /// `tty` goes to ratatui; `cleanup_tty` is a separate fd for
2763 /// LeaveAlternateScreen (ratatui 0.29 hides `writer_mut()`).
2764 #[cfg(unix)]
2765 async fn run_interactive(tty: std::fs::File, mut cleanup_tty: std::fs::File) -> anyhow::Result<()> {
2766 let engine = Arc::new(ChatEngine::new());
2767
2768 let startup_selection = setup::startup_model_selection();
2769 let startup_model_name = startup_selection
2770 .as_ref()
2771 .map(|selection| selection.display_name.clone())
2772 .unwrap_or_else(|| GgufModelConfig::qwen25_3b().display_name);
2773
2774 // Signals the loading phase to finish. On-device models are no longer loaded
2775 // at startup, so this resolves immediately for both backends; it stays a
2776 // channel so the loading-phase plumbing in `chat::run_with` is unchanged.
2777 let (load_tx, load_rx) = std::sync::mpsc::channel::<Result<(), String>>();
2778
2779 // Project instruction files (AGENTS.md / CLAUDE.md) for the launch directory,
2780 // injected into the system prompt so the TUI shares the same always-on
2781 // project context the ACP sessions get.
2782 let project_instructions = std::env::current_dir()
2783 .ok()
2784 .and_then(|cwd| instructions::load_project_instructions(&cwd));
2785 let with_instructions = |base: String| match &project_instructions {
2786 Some(extra) => format!("{base}\n\n{extra}"),
2787 None => base,
2788 };
2789
2790 // Pick the inference backend: a configured provider if present, else on-device.
2791 let (inference_backend, startup_model_name): (Arc<dyn InferenceBackend>, String) =
2792 match provider::active_provider() {
2793 Some(provider) => {
2794 log::info!(
2795 "inference: using {} (model {}) at {}",
2796 provider.display_name,
2797 provider.model,
2798 provider.base_url
2799 );
2800 // No local model to load; the endpoint is ready immediately.
2801 let _ = load_tx.send(Ok(()));
2802 let label = provider.display_name.clone();
2803 register_subagent_factory_for(&provider);
2804 let backend = Arc::new(OpenAiBackend::new(
2805 provider.base_url,
2806 provider.api_key,
2807 provider.model,
2808 Some(with_instructions(SYSTEM_PROMPT.to_string())),
2809 )) as Arc<dyn InferenceBackend>;
2810 (backend, label)
2811 }
2812 None => {
2813 // Honor the Local Inference toggle: when off and signed in, start
2814 // on a cloud tier. Otherwise bring up on-device WITHOUT loading a
2815 // model — the user loads it explicitly with /load (or /models), so
2816 // the UI comes up immediately. Project instructions are injected at
2817 // load time in `chat.rs`.
2818 let cloud_when_off = if settings::local_inference_enabled() {
2819 None
2820 } else {
2821 provider::cloud_tier_provider("balanced")
2822 };
2823
2824 match cloud_when_off {
2825 Some(provider) => {
2826 log::info!(
2827 "inference: local inference off; using {} (model {})",
2828 provider.display_name,
2829 provider.model
2830 );
2831 let _ = load_tx.send(Ok(()));
2832 let label = provider.display_name.clone();
2833 register_subagent_factory_for(&provider);
2834 let backend = Arc::new(OpenAiBackend::new(
2835 provider.base_url,
2836 provider.api_key,
2837 provider.model,
2838 Some(with_instructions(SYSTEM_PROMPT.to_string())),
2839 )) as Arc<dyn InferenceBackend>;
2840 (backend, label)
2841 }
2842 None => {
2843 if !settings::local_inference_enabled() {
2844 log::warn!(
2845 "local inference is off but no account is signed in; \
2846 bringing up on-device. Run /login or /local on."
2847 );
2848 }
2849 let _ = load_tx.send(Ok(()));
2850 // On-device inference has a single shared history; no
2851 // subagent context is possible yet.
2852 tools::set_subagent_factory(Box::new(|| None));
2853 let backend = Arc::new(LocalBackend::new(Arc::clone(&engine)))
2854 as Arc<dyn InferenceBackend>;
2855 (backend, startup_model_name)
2856 }
2857 }
2858 }
2859 };
2860
2861 crossterm::terminal::enable_raw_mode()?;
2862 let mut tty = BufWriter::new(tty);
2863 crossterm::execute!(tty, crossterm::terminal::EnterAlternateScreen)?;
2864 let term_backend = ratatui::backend::CrosstermBackend::new(tty);
2865 let mut terminal = ratatui::Terminal::new(term_backend)?;
2866
2867 // polls load_rx with try_recv() each tick, no blocking
2868 let chat_result = chat::run_with(
2869 &mut terminal,
2870 engine,
2871 inference_backend,
2872 load_rx,
2873 startup_model_name,
2874 )
2875 .await;
2876
2877 // cleanup fd because backend's writer is private
2878 crossterm::execute!(cleanup_tty, crossterm::terminal::LeaveAlternateScreen)?;
2879 cleanup_tty.flush()?;
2880 crossterm::terminal::disable_raw_mode()?;
2881
2882 // restore real stdout/stderr for post-TUI error output
2883 #[cfg(unix)]
2884 {
2885 let cleanup_fd = cleanup_tty.as_raw_fd();
2886 unsafe {
2887 libc::dup2(cleanup_fd, libc::STDOUT_FILENO);
2888 libc::dup2(cleanup_fd, libc::STDERR_FILENO);
2889 }
2890 }
2891
2892 chat_result
2893 }
2894
2895 // ── ACP server mode ───────────────────────────────────────────────────────────
2896
2897 /// The on-device model `/load` should bring up by default: the persisted
2898 /// selection if it still resolves to a known local model, otherwise the built-in
2899 /// default (`qwen25_3b`).
2900 fn default_local_model_config() -> GgufModelConfig {
2901 setup::startup_model_selection()
2902 .as_ref()
2903 .and_then(|selection| {
2904 selection.selected_model.as_ref().and_then(|selected| {
2905 models::local_picker_items()
2906 .into_iter()
2907 .find(|item| {
2908 item.config.model_id == selected.model_id
2909 && item
2910 .config
2911 .files
2912 .iter()
2913 .any(|file| file == &selected.gguf_file)
2914 })
2915 .map(|item| item.config)
2916 })
2917 })
2918 .unwrap_or_else(GgufModelConfig::qwen25_3b)
2919 }
2920
2921 async fn run_acp_server() -> anyhow::Result<()> {
2922 log::info!("ACP mode — starting agent server");
2923
2924 let config = default_local_model_config();
2925
2926 let needs_download = models::local_picker_items()
2927 .iter()
2928 .find(|item| item.config.model_id == config.model_id)
2929 .map(|item| item.cache_health != setup::ModelCacheHealth::Complete)
2930 .unwrap_or(true);
2931
2932 log::info!(
2933 "ACP startup model selected: {} ({})",
2934 config.display_name,
2935 if needs_download {
2936 "needs download"
2937 } else {
2938 "cached"
2939 }
2940 );
2941
2942 let engine = Arc::new(ChatEngine::new());
2943
2944 // The on-device model is never loaded implicitly; the user loads it with
2945 // `/load` (or by picking one in `/models`). So initialize/session/new stay
2946 // lightweight and `model_ready` starts true (nothing is loading).
2947 let model_ready = Arc::new(AtomicBool::new(true));
2948 let startup_model_load_started = Arc::new(AtomicBool::new(false));
2949 let model_load_error: Arc<std::sync::Mutex<Option<String>>> =
2950 Arc::new(std::sync::Mutex::new(None));
2951
2952 let state = Arc::new(SiGitAgent::new(
2953 engine,
2954 config,
2955 model_ready,
2956 startup_model_load_started,
2957 model_load_error,
2958 needs_download,
2959 ));
2960
2961 // Honor the explicit provider override (OPENAI_BASE_URL/OPENAI_API_KEY or
2962 // an active providers.toml profile) in ACP mode too — the interactive
2963 // client already does. Without this the override was silently ignored here
2964 // and prompts insisted on a local model. It is also what lets the ACP
2965 // integration test drive the agent against a scripted endpoint
2966 // (tests/acp_permissions.rs). The model picker still shows the local
2967 // selection; overrides are a power-user escape hatch, not a tier.
2968 if let Some(cfg) = provider::active_provider() {
2969 log::info!(
2970 "inference: using {} (model {}) at {}",
2971 cfg.display_name,
2972 cfg.model,
2973 cfg.base_url
2974 );
2975 register_subagent_factory_for(&cfg);
2976 let override_backend: Arc<dyn InferenceBackend> = Arc::new(OpenAiBackend::new(
2977 cfg.base_url,
2978 cfg.api_key,
2979 cfg.model,
2980 Some(system_prompt_for_model(true).to_string()),
2981 ));
2982 *state.backend.lock().await = override_backend;
2983 } else {
2984 // On-device inference has a single shared conversation history, so a
2985 // second concurrent subagent context is not possible yet.
2986 tools::set_subagent_factory(Box::new(|| None));
2987 }
2988
2989 let stdin = tokio::io::stdin().compat();
2990 let stdout = tokio::io::stdout().compat_write();
2991 let transport = ByteStreams::new(stdout, stdin);
2992
2993 Agent
2994 .builder()
2995 .on_receive_request(
2996 {
2997 let state = Arc::clone(&state);
2998 async move |req: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
2999 handle_response(responder, state.handle_initialize(req).await)
3000 }
3001 },
3002 agent_client_protocol::on_receive_request!(),
3003 )
3004 .on_receive_request(
3005 {
3006 let state = Arc::clone(&state);
3007 async move |req: AuthenticateRequest, responder, _cx: ConnectionTo<Client>| {
3008 handle_response(responder, state.handle_authenticate(req).await)
3009 }
3010 },
3011 agent_client_protocol::on_receive_request!(),
3012 )
3013 // Turn-affecting handlers below run in spawned tasks, serialized by
3014 // `turn_lock`, so the dispatch loop stays free to route client
3015 // responses (permission answers) while a turn is in flight. Awaiting a
3016 // client request from *inside* a handler would deadlock: the dispatch
3017 // loop can't read the response while the handler blocks it.
3018 .on_receive_request(
3019 {
3020 let state = Arc::clone(&state);
3021 async move |req: LoadSessionRequest, responder, cx: ConnectionTo<Client>| {
3022 let state = Arc::clone(&state);
3023 let task_cx = cx.clone();
3024 cx.spawn(async move {
3025 let _turn = state.turn_lock.lock().await;
3026 handle_response(responder, state.handle_load_session(&task_cx, req).await)
3027 })
3028 }
3029 },
3030 agent_client_protocol::on_receive_request!(),
3031 )
3032 .on_receive_request(
3033 {
3034 let state = Arc::clone(&state);
3035 async move |req: ForkSessionRequest, responder, cx: ConnectionTo<Client>| {
3036 let state = Arc::clone(&state);
3037 let task_cx = cx.clone();
3038 cx.spawn(async move {
3039 let _turn = state.turn_lock.lock().await;
3040 handle_response(responder, state.handle_fork_session(&task_cx, req).await)
3041 })
3042 }
3043 },
3044 agent_client_protocol::on_receive_request!(),
3045 )
3046 .on_receive_request(
3047 {
3048 let state = Arc::clone(&state);
3049 async move |req: NewSessionRequest, responder, cx: ConnectionTo<Client>| {
3050 let state = Arc::clone(&state);
3051 let task_cx = cx.clone();
3052 cx.spawn(async move {
3053 let _turn = state.turn_lock.lock().await;
3054 handle_response(responder, state.handle_new_session(&task_cx, req).await)
3055 })
3056 }
3057 },
3058 agent_client_protocol::on_receive_request!(),
3059 )
3060 .on_receive_request(
3061 {
3062 let state = Arc::clone(&state);
3063 async move |req: PromptRequest, responder, cx: ConnectionTo<Client>| {
3064 let state = Arc::clone(&state);
3065 let task_cx = cx.clone();
3066 cx.spawn(async move {
3067 let _turn = state.turn_lock.lock().await;
3068 handle_response(responder, state.handle_prompt(&task_cx, req).await)
3069 })
3070 }
3071 },
3072 agent_client_protocol::on_receive_request!(),
3073 )
3074 .on_receive_request(
3075 {
3076 let state = Arc::clone(&state);
3077 async move |req: SetSessionConfigOptionRequest,
3078 responder,
3079 cx: ConnectionTo<Client>| {
3080 let state = Arc::clone(&state);
3081 let task_cx = cx.clone();
3082 cx.spawn(async move {
3083 let _turn = state.turn_lock.lock().await;
3084 handle_response(
3085 responder,
3086 state.handle_set_session_config_option(&task_cx, req).await,
3087 )
3088 })
3089 }
3090 },
3091 agent_client_protocol::on_receive_request!(),
3092 )
3093 .on_receive_notification(
3094 {
3095 let state = Arc::clone(&state);
3096 async move |notif: CancelNotification, _cx: ConnectionTo<Client>| {
3097 state.handle_cancel(notif).await
3098 }
3099 },
3100 agent_client_protocol::on_receive_notification!(),
3101 )
3102 .connect_to(transport)
3103 .await
3104 .map_err(|e| anyhow::anyhow!("ACP connection error: {e}"))?;
3105
3106 log::info!("siGit shutting down");
3107 Ok(())
3108 }
3109
3110 // ── Entry point ──────────────────────────────────────────────────────────────
3111
3112 #[tokio::main]
3113 async fn main() -> anyhow::Result<()> {
3114 // Account subcommands. The editor launches `sigit login` in an embedded
3115 // terminal for ACP terminal-based authentication; the same verbs are handy
3116 // directly from a shell. These must be handled before the TTY/ACP split.
3117 if let Some(verb) = std::env::args().nth(1) {
3118 match verb.as_str() {
3119 "login" => {
3120 init_logging(true);
3121 match account::interactive_login().await {
3122 Ok(email) => {
3123 println!("Signed in to siGit Code Cloud as {email}.");
3124 return Ok(());
3125 }
3126 Err(error) => {
3127 eprintln!("Login failed: {error}");
3128 std::process::exit(1);
3129 }
3130 }
3131 }
3132 "logout" => {
3133 init_logging(true);
3134 println!("{}", account::end_session().await);
3135 return Ok(());
3136 }
3137 "whoami" => {
3138 init_logging(true);
3139 println!("{}", account::status_line().await);
3140 return Ok(());
3141 }
3142 _ => {}
3143 }
3144 }
3145
3146 // Headless programmatic mode: `sigit -p "<prompt>"` runs one prompt and
3147 // exits. Plain stdio and cross-platform (unlike the Unix-only TUI), so it
3148 // is dispatched here, before the TTY/ACP split, like the account
3149 // subcommands above.
3150 let cli_args: Vec<String> = std::env::args().skip(1).collect();
3151 match headless::parse_args(&cli_args) {
3152 Ok(None) => {}
3153 Ok(Some(config)) => {
3154 // Logs to stderr; stdout stays clean for the assistant's answer.
3155 init_logging(false);
3156 // Enter --cwd before anything loads, so instruction files and
3157 // project-local MCP config resolve from it (the headless
3158 // counterpart of the ACP session cwd handling).
3159 if let Some(dir) = &config.cwd
3160 && let Err(error) = std::env::set_current_dir(dir)
3161 {
3162 eprintln!("sigit: cannot use --cwd {}: {error}", dir.display());
3163 std::process::exit(2);
3164 }
3165 setup::setup_shared_model_cache();
3166 // Best-effort MCP discovery (incl. the official server), like the
3167 // other entry points, so MCP tools are offered to the model.
3168 mcp::init().await;
3169 log::info!(
3170 "siGit v{} starting (headless mode)",
3171 env!("CARGO_PKG_VERSION")
3172 );
3173 std::process::exit(headless::run(config).await);
3174 }
3175 Err(error) => {
3176 eprintln!("sigit: {error}\n{}", headless::USAGE);
3177 std::process::exit(2);
3178 }
3179 }
3180
3181 let is_tty = std::io::stdin().is_terminal();
3182
3183 if is_tty {
3184 // must redirect before any library code touches stdout
3185 #[cfg(unix)]
3186 {
3187 let (tty, cleanup_tty) = redirect_output_to_log()?;
3188 init_logging(true);
3189 setup::setup_shared_model_cache();
3190 // Best-effort: discover MCP servers (incl. the official one) before
3191 // the first turn so their tools are offered to the model.
3192 mcp::init().await;
3193 run_interactive(tty, cleanup_tty).await
3194 }
3195 #[cfg(not(unix))]
3196 {
3197 anyhow::bail!("interactive mode requires Unix (macOS / Linux)");
3198 }
3199 } else {
3200 // ACP mode: keep stdout untouched for protocol JSON only.
3201 // Logs already go to stderr via `init_logging(false)`.
3202 init_logging(false);
3203 setup::setup_shared_model_cache();
3204 // Best-effort MCP discovery (incl. the official server) before serving.
3205 mcp::init().await;
3206 log::info!("siGit v{} starting (ACP mode)", env!("CARGO_PKG_VERSION"));
3207 run_acp_server().await
3208 }
3209 }
3210
3211 #[cfg(test)]
3212 mod tests {
3213 use super::*;
3214
3215 #[test]
3216 fn system_prompt_advertises_the_commit_co_author_trailer() {
3217 // The prompt instructs the model with the exact trailer that
3218 // `tools::ensure_commit_co_author` enforces; if the two drift apart the
3219 // safety net would re-amend commits the model already attributed.
3220 assert!(
3221 SYSTEM_PROMPT.contains(tools::COMMIT_CO_AUTHOR_TRAILER),
3222 "SYSTEM_PROMPT must quote tools::COMMIT_CO_AUTHOR_TRAILER verbatim"
3223 );
3224 }
3225
3226 #[test]
3227 fn ascii_safe_replaces_multibyte_chars() {
3228 // The exact label that crashed Zed: the cloud tier name plus the old
3229 // "[☁ siGit Code Cloud]" badge. After sanitizing it must be pure ASCII so
3230 // Zed's fixed byte-offset truncation can never split a glyph.
3231 let crashing = "siGit Code Cloud · Balanced [☁ siGit Code Cloud]";
3232 let safe = ascii_safe(crashing);
3233 assert!(safe.is_ascii(), "sanitized label must be ASCII: {safe:?}");
3234 assert_eq!(safe, "siGit Code Cloud - Balanced [- siGit Code Cloud]");
3235 }
3236
3237 #[test]
3238 fn ascii_safe_leaves_ascii_untouched() {
3239 let plain = "Qwen 2.5 3B [Onde]";
3240 assert_eq!(ascii_safe(plain), plain);
3241 }
3242
3243 #[test]
3244 fn ascii_safe_output_has_only_char_boundaries() {
3245 // Every byte index in an ASCII string is a valid char boundary, so any
3246 // downstream truncation is panic-free regardless of where it cuts.
3247 let safe = ascii_safe("Onde · ◉ ↓ ☁ ○ test");
3248 for i in 0..=safe.len() {
3249 assert!(safe.is_char_boundary(i));
3250 }
3251 }
3252 }