1 //! Headless programmatic mode: `sigit -p "<prompt>"` runs one prompt and exits.
2 //!
3 //! This is the entry point for CI, scripts, cron, and the Cloud Agent sandbox
4 //! runner: no client, no TTY, just plain stdio. Assistant text streams to
5 //! stdout as it is generated (`--quiet` restricts stdout to the final message);
6 //! logs and tool progress go to stderr.
7 //!
8 //! Cross-platform by design — unlike the ratatui TUI this is NOT gated on
9 //! `#[cfg(unix)]`, so Windows gets it too.
10 //!
11 //! Permission model: nobody is around to answer `ask`, so `ask` collapses to a
12 //! denial telling the model the tool was not pre-approved (mentioning
13 //! `--allow-tool`). `--allow-tool <name>` pre-grants a tool for the run's
14 //! session; `--deny-tool <name>` blocks a tool even if settings would allow it.
15 //! `SIGIT_PERMISSIONS=allow` remains the blunt instrument.
16 //!
17 //! Exit codes: 0 — turn completed; 1 — inference/tool-loop or backend
18 //! resolution error; 2 — bad invocation (handled by the caller in `main`).
19
20 use std::collections::HashSet;
21 use std::io::Write;
22 use std::path::PathBuf;
23 use std::sync::Arc;
24
25 use crate::backend::{
26 self, InferenceBackend, OpenAiBackend, ToolResult as BackendToolResult, TurnResult,
27 };
28 use crate::{permissions, provider, session_store, settings, tools};
29
30 /// Session id for headless runs: permission grants and the saved conversation
31 /// live under this key, so a follow-up feature can resume it.
32 pub const HEADLESS_SESSION: &str = "headless";
33
34 pub const USAGE: &str = "Usage: sigit -p \"<prompt>\" [--cwd <dir>] [--quiet] \
35 [--allow-tool <name>]... [--deny-tool <name>]...";
36
37 /// Parsed `sigit -p` invocation.
38 #[derive(Debug, Clone, PartialEq, Eq)]
39 pub struct HeadlessConfig {
40 pub prompt: String,
41 /// Working directory to enter before anything loads (instruction files and
42 /// project-local MCP config then resolve from it).
43 pub cwd: Option<PathBuf>,
44 /// Print only the final assistant message to stdout (no streaming).
45 pub quiet: bool,
46 /// Tools pre-approved for the run (fed to `permissions::grant_for_session`).
47 pub allow_tools: Vec<String>,
48 /// Tools blocked for the run, overriding even settings-level allow.
49 pub deny_tools: Vec<String>,
50 }
51
52 /// Parse the process arguments (without argv[0]) for headless mode.
53 ///
54 /// Returns `Ok(None)` when `-p`/`--prompt` is absent — the invocation is not
55 /// headless and falls through to the TTY/ACP dispatch. Once `-p` is present,
56 /// every remaining argument must be a recognized flag (position-insensitive);
57 /// anything else is a usage error the caller reports on stderr with exit 2.
58 pub fn parse_args(args: &[String]) -> Result<Option<HeadlessConfig>, String> {
59 if !args.iter().any(|arg| arg == "-p" || arg == "--prompt") {
60 return Ok(None);
61 }
62
63 let mut prompt: Option<String> = None;
64 let mut cwd: Option<PathBuf> = None;
65 let mut quiet = false;
66 let mut allow_tools: Vec<String> = Vec::new();
67 let mut deny_tools: Vec<String> = Vec::new();
68
69 let mut iter = args.iter();
70 while let Some(arg) = iter.next() {
71 match arg.as_str() {
72 "-p" | "--prompt" => {
73 let value = iter
74 .next()
75 .ok_or_else(|| format!("{arg} requires a prompt argument"))?;
76 if prompt.is_some() {
77 return Err(format!("{arg} was given more than once"));
78 }
79 prompt = Some(value.clone());
80 }
81 "--cwd" => {
82 let value = iter
83 .next()
84 .ok_or_else(|| "--cwd requires a directory argument".to_string())?;
85 cwd = Some(PathBuf::from(value));
86 }
87 "--quiet" => quiet = true,
88 "--allow-tool" => {
89 let value = iter
90 .next()
91 .ok_or_else(|| "--allow-tool requires a tool name".to_string())?;
92 allow_tools.push(value.clone());
93 }
94 "--deny-tool" => {
95 let value = iter
96 .next()
97 .ok_or_else(|| "--deny-tool requires a tool name".to_string())?;
98 deny_tools.push(value.clone());
99 }
100 other => return Err(format!("unknown argument: {other}")),
101 }
102 }
103
104 // Unreachable in practice (the pre-check saw a `-p` token), unless that
105 // token was consumed as another flag's value — still a usage error.
106 let prompt = prompt.ok_or_else(|| "missing -p/--prompt".to_string())?;
107 if prompt.trim().is_empty() {
108 return Err("the prompt must not be empty".to_string());
109 }
110
111 Ok(Some(HeadlessConfig {
112 prompt,
113 cwd,
114 quiet,
115 allow_tools,
116 deny_tools,
117 }))
118 }
119
120 /// Denial fed to the model when a tool at `ask` level fires in a headless run.
121 fn not_preapproved_denial(tool_name: &str) -> String {
122 format!(
123 "`{tool_name}` was not executed: this is a non-interactive headless run and \
124 nobody can answer a permission prompt, so tools at the `ask` level are denied \
125 unless pre-approved. The user can re-run with `--allow-tool {tool_name}` to \
126 approve it (or set SIGIT_PERMISSIONS=allow). Do not retry the same call; \
127 continue without this tool or report what remains to be done."
128 )
129 }
130
131 /// Denial fed to the model when a tool was blocked with `--deny-tool`.
132 fn deny_flag_denial(tool_name: &str) -> String {
133 format!(
134 "`{tool_name}` is blocked for this headless run (--deny-tool). Do not retry it; \
135 continue without this tool or report what remains to be done."
136 )
137 }
138
139 /// Run one headless prompt to completion. Returns the process exit code.
140 ///
141 /// The caller (`main`) has already applied `--cwd`, initialized logging to
142 /// stderr, set up the model cache, and run MCP discovery.
143 pub async fn run(config: HeadlessConfig) -> i32 {
144 // Fresh permission state for the run, then apply the flag grants.
145 permissions::reset_session(HEADLESS_SESSION);
146 for tool in &config.allow_tools {
147 // No call arguments at grant time: the empty string records the bare
148 // tool name, granting the whole tool — the --allow-tool contract.
149 permissions::grant_for_session(HEADLESS_SESSION, tool, "");
150 }
151 let denied: HashSet<&str> = config.deny_tools.iter().map(String::as_str).collect();
152
153 // Backend resolution mirrors the ACP server: the explicit provider override
154 // first, else the signed-in cloud tier when local inference is off (what
155 // `apply_startup_inference_mode` does at every ACP session entry). There is
156 // never an implicit on-device load — a fresh process has no model in memory
157 // and headless mode must not silently download gigabytes.
158 let provider_cfg = provider::active_provider().or_else(|| {
159 if settings::local_inference_enabled() {
160 None
161 } else {
162 provider::cloud_tier_provider("balanced")
163 }
164 });
165 let Some(cfg) = provider_cfg else {
166 eprintln!(
167 "sigit: headless mode needs a remote inference provider — running on-device \
168 would require loading (and possibly downloading) a local model, which \
169 headless mode never does implicitly. Set OPENAI_BASE_URL and OPENAI_API_KEY \
170 (or configure providers.toml), or sign in with `sigit login` and turn local \
171 inference off."
172 );
173 return 1;
174 };
175
176 log::info!(
177 "headless: using {} (model {}) at {}",
178 cfg.display_name,
179 cfg.model,
180 cfg.base_url
181 );
182 crate::register_subagent_factory_for(&cfg);
183
184 // Same always-on project context the other surfaces inject: cwd guidance
185 // plus AGENTS.md / CLAUDE.md instruction files.
186 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
187 let mut system_prompt = crate::system_prompt_for_model(true).to_string();
188 system_prompt.push_str("\n\n");
189 system_prompt.push_str(&crate::session_context_message(&cwd));
190
191 let backend: Arc<dyn InferenceBackend> = Arc::new(OpenAiBackend::new(
192 cfg.base_url,
193 cfg.api_key,
194 cfg.model,
195 Some(system_prompt),
196 ));
197
198 let outcome = run_prompt(backend.as_ref(), &config, &denied).await;
199
200 // Persist the conversation like the other surfaces, so a follow-up feature
201 // can resume it. Saved even on error: a partial transcript beats none.
202 let snapshot = backend.history_snapshot().await;
203 if let Err(error) = session_store::save(HEADLESS_SESSION, &snapshot) {
204 log::warn!("headless: session save failed: {error}");
205 }
206
207 match outcome {
208 Ok(()) => 0,
209 Err(error) => {
210 eprintln!("sigit: {error}");
211 1
212 }
213 }
214 }
215
216 /// The turn loop: send the prompt, execute tool calls under the permission
217 /// policy, feed results back, repeat up to `MAX_TOOL_ROUNDS` — the same shape
218 /// as the ACP `handle_prompt`, minus the ACP notifications.
219 async fn run_prompt(
220 backend: &dyn InferenceBackend,
221 config: &HeadlessConfig,
222 denied: &HashSet<&str>,
223 ) -> Result<(), backend::BackendError> {
224 let tools = crate::agent_tools_as_specs();
225
226 // Token sink: assistant text streams through this while a turn runs; the
227 // drain loop forwards the visible portion to stdout live. In quiet mode no
228 // sink is passed and only the final message is printed.
229 let (sink, mut sink_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
230 let sink_opt = if config.quiet { None } else { Some(&sink) };
231 let mut assembled = String::new();
232 let mut sent = String::new();
233 let mut streamed_any = false;
234
235 let mut result = drain_to_stdout(
236 backend.send_message_with_tools(&config.prompt, &tools, sink_opt),
237 &mut sink_rx,
238 &mut assembled,
239 &mut sent,
240 &mut streamed_any,
241 )
242 .await?;
243
244 let mut round = 0;
245
246 while !result.tool_calls.is_empty() && round < crate::MAX_TOOL_ROUNDS {
247 round += 1;
248
249 // Auto-compaction: long tool runs grow history fast; fold it into a
250 // summary before the next round rather than blowing the window.
251 let estimate = backend::estimate_tokens(&backend.history_snapshot().await);
252 if estimate > backend::DEFAULT_CONTEXT_TOKEN_BUDGET {
253 log::info!(
254 "headless: history ≈{estimate} tokens exceeds budget {} — compacting",
255 backend::DEFAULT_CONTEXT_TOKEN_BUDGET
256 );
257 if let Err(error) = backend.compact_history(backend::COMPACT_KEEP_LAST).await {
258 log::warn!("headless: compaction failed: {error}");
259 }
260 }
261
262 let mut tool_results = Vec::new();
263
264 for tc in &result.tool_calls {
265 let args_preview: String = tc.arguments.chars().take(120).collect();
266 eprintln!("→ {}({args_preview})", tc.name);
267
268 // The headless deny set outranks everything, including a
269 // settings-level allow and a --allow-tool grant for the same name.
270 let output = if denied.contains(tc.name.as_str()) {
271 log::info!("headless: {} blocked by --deny-tool", tc.name);
272 deny_flag_denial(&tc.name)
273 } else {
274 match permissions::decision_for(HEADLESS_SESSION, &tc.name, &tc.arguments) {
275 permissions::Decision::Allow => {
276 tools::execute_tool(&tc.name, &tc.arguments).await
277 }
278 permissions::Decision::Deny(reason) => {
279 log::info!("headless: {} denied by policy", tc.name);
280 reason
281 }
282 // Nobody can answer an interactive prompt here: ask
283 // collapses to a denial pointing at --allow-tool.
284 permissions::Decision::Ask => {
285 log::info!("headless: {} not pre-approved — denied", tc.name);
286 not_preapproved_denial(&tc.name)
287 }
288 }
289 };
290
291 tool_results.push(BackendToolResult {
292 tool_call_id: tc.id.clone(),
293 content: output,
294 });
295 }
296
297 let next_tools = if round < crate::MAX_TOOL_ROUNDS {
298 Some(tools.as_slice())
299 } else {
300 None // last round: force text
301 };
302
303 result = drain_to_stdout(
304 backend.send_tool_results(tool_results, next_tools, sink_opt),
305 &mut sink_rx,
306 &mut assembled,
307 &mut sent,
308 &mut streamed_any,
309 )
310 .await?;
311 }
312
313 // Final text: in quiet mode nothing streamed, so print the final assistant
314 // message now; otherwise print only what streaming did not already cover.
315 let (_think, final_visible) = crate::chat::strip_think_blocks(result.text.trim());
316 let mut stdout = std::io::stdout();
317 if config.quiet {
318 if !final_visible.is_empty() {
319 let _ = writeln!(stdout, "{final_visible}");
320 }
321 } else if streamed_any {
322 // The reply is already on stdout; end the line for the shell.
323 let _ = writeln!(stdout);
324 } else if !final_visible.is_empty() {
325 let _ = writeln!(stdout, "{final_visible}");
326 }
327 let _ = stdout.flush();
328
329 log::info!("headless: prompt complete — {round} tool round(s)");
330 Ok(())
331 }
332
333 /// Run one inference turn while forwarding streamed tokens to stdout as they
334 /// arrive — the stdio counterpart of `SiGitAgent::drain_turn`.
335 async fn drain_to_stdout<F>(
336 fut: F,
337 sink_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
338 assembled: &mut String,
339 sent: &mut String,
340 streamed_any: &mut bool,
341 ) -> Result<TurnResult, backend::BackendError>
342 where
343 F: std::future::Future<Output = Result<TurnResult, backend::BackendError>>,
344 {
345 tokio::pin!(fut);
346 let result = loop {
347 tokio::select! {
348 done = &mut fut => break done,
349 Some(piece) = sink_rx.recv() => {
350 emit_visible_chunk(&piece, assembled, sent, streamed_any);
351 }
352 }
353 };
354 // Flush tokens that landed between the last poll and the future resolving.
355 while let Ok(piece) = sink_rx.try_recv() {
356 emit_visible_chunk(&piece, assembled, sent, streamed_any);
357 }
358 result
359 }
360
361 /// Append a streamed fragment, strip `<think>` reasoning from the running
362 /// text, and print only the newly revealed visible suffix. Tracking the
363 /// assembled text (not just deltas) keeps think-block stripping correct even
364 /// when a tag spans chunk boundaries — same approach as the ACP path.
365 fn emit_visible_chunk(
366 piece: &str,
367 assembled: &mut String,
368 sent: &mut String,
369 streamed_any: &mut bool,
370 ) {
371 assembled.push_str(piece);
372 let (_think, visible) = crate::chat::strip_think_blocks(assembled);
373 match visible.strip_prefix(sent.as_str()) {
374 Some(extra) if !extra.is_empty() => {
375 print!("{extra}");
376 let _ = std::io::stdout().flush();
377 *sent = visible;
378 *streamed_any = true;
379 }
380 // No new visible text, or the visible prefix changed retroactively
381 // (rare, e.g. a late-closing think tag): resync without reprinting.
382 _ => *sent = visible,
383 }
384 }
385
386 #[cfg(test)]
387 mod tests {
388 use super::*;
389
390 fn args(list: &[&str]) -> Vec<String> {
391 list.iter().map(|s| s.to_string()).collect()
392 }
393
394 #[test]
395 fn absent_prompt_flag_is_not_headless() {
396 assert_eq!(parse_args(&args(&[])), Ok(None));
397 assert_eq!(parse_args(&args(&["login"])), Ok(None));
398 // Flags alone don't trigger headless mode; only -p/--prompt does.
399 assert_eq!(parse_args(&args(&["--quiet"])), Ok(None));
400 }
401
402 #[test]
403 fn parses_minimal_invocation() {
404 let config = parse_args(&args(&["-p", "do the thing"])).unwrap().unwrap();
405 assert_eq!(config.prompt, "do the thing");
406 assert_eq!(config.cwd, None);
407 assert!(!config.quiet);
408 assert!(config.allow_tools.is_empty());
409 assert!(config.deny_tools.is_empty());
410 }
411
412 #[test]
413 fn long_form_prompt_flag_works() {
414 let config = parse_args(&args(&["--prompt", "hello"])).unwrap().unwrap();
415 assert_eq!(config.prompt, "hello");
416 }
417
418 #[test]
419 fn parses_all_flags_position_insensitively() {
420 let config = parse_args(&args(&[
421 "--quiet",
422 "--allow-tool",
423 "run_command",
424 "--cwd",
425 "/tmp/project",
426 "-p",
427 "build it",
428 "--deny-tool",
429 "delete_file",
430 "--allow-tool",
431 "edit_file",
432 ]))
433 .unwrap()
434 .unwrap();
435 assert_eq!(config.prompt, "build it");
436 assert_eq!(config.cwd, Some(PathBuf::from("/tmp/project")));
437 assert!(config.quiet);
438 assert_eq!(config.allow_tools, vec!["run_command", "edit_file"]);
439 assert_eq!(config.deny_tools, vec!["delete_file"]);
440 }
441
442 #[test]
443 fn prompt_value_may_look_like_a_flag() {
444 // -p consumes the next argument verbatim.
445 let config = parse_args(&args(&["-p", "--quiet"])).unwrap().unwrap();
446 assert_eq!(config.prompt, "--quiet");
447 assert!(!config.quiet);
448 }
449
450 #[test]
451 fn unknown_flag_is_a_usage_error() {
452 let error = parse_args(&args(&["-p", "x", "--frobnicate"])).unwrap_err();
453 assert!(error.contains("--frobnicate"), "{error}");
454 }
455
456 #[test]
457 fn missing_values_are_usage_errors() {
458 assert!(parse_args(&args(&["-p"])).is_err());
459 assert!(parse_args(&args(&["-p", "x", "--cwd"])).is_err());
460 assert!(parse_args(&args(&["-p", "x", "--allow-tool"])).is_err());
461 assert!(parse_args(&args(&["-p", "x", "--deny-tool"])).is_err());
462 }
463
464 #[test]
465 fn duplicate_prompt_is_a_usage_error() {
466 assert!(parse_args(&args(&["-p", "a", "--prompt", "b"])).is_err());
467 }
468
469 #[test]
470 fn empty_prompt_is_a_usage_error() {
471 assert!(parse_args(&args(&["-p", " "])).is_err());
472 }
473 }