1pub mod fixes;
8pub mod jobs;
9pub mod security;
10mod welcome;
11
12use std::net::SocketAddr;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15
16use axum::extract::{Query, Request, State};
17use axum::http::{HeaderValue, StatusCode, header};
18use axum::middleware::Next;
19use axum::response::{IntoResponse, Response};
20use axum::routing::{get, post};
21use axum::{Json, Router};
22use serde::Deserialize;
23use serde_json::{Value, json};
24use speccoder_core::actions::Runnable;
25use speccoder_core::{CommandData, CommandResult};
26
27mod bundle {
28 include!(concat!(env!("OUT_DIR"), "/bundle.rs"));
29}
30
31#[derive(Debug, Clone)]
35pub struct Root(Arc<RootCell>);
36
37#[derive(Debug)]
38struct RootCell {
39 start: PathBuf,
40 bound: std::sync::OnceLock<PathBuf>,
41}
42
43impl Root {
44 #[must_use]
46 pub fn new(start: &Path, bound: bool) -> Self {
47 let cell = RootCell {
48 start: start.to_path_buf(),
49 bound: std::sync::OnceLock::new(),
50 };
51 if bound {
52 let _ = cell.bound.set(start.to_path_buf());
53 }
54 Self(Arc::new(cell))
55 }
56
57 #[must_use]
59 pub fn get(&self) -> PathBuf {
60 self.0
61 .bound
62 .get()
63 .cloned()
64 .unwrap_or_else(|| self.0.start.clone())
65 }
66
67 #[must_use]
69 pub fn bound(&self) -> Option<PathBuf> {
70 self.0.bound.get().cloned()
71 }
72
73 #[must_use]
75 pub fn start(&self) -> PathBuf {
76 self.0.start.clone()
77 }
78
79 pub fn bind(&self, project: &Path) -> Result<(), String> {
85 self.0.bound.set(project.to_path_buf()).map_err(|_| {
86 format!(
87 "this host serves {} already: open another project with `speccoder ui -C {}`",
88 self.get().display(),
89 project.display()
90 )
91 })
92 }
93}
94
95#[derive(Debug, Clone)]
97pub struct Shared {
98 pub root: Root,
100 pub token: String,
102 pub port: u16,
104 pub hub: Arc<jobs::Hub>,
106 pub window: bool,
109 pub closing: tokio::sync::watch::Receiver<bool>,
111 pub device: Arc<
114 std::sync::Mutex<
115 Option<(
116 String,
117 String,
118 speccoder_runtime::service::github::auth::Pending,
119 )>,
120 >,
121 >,
122}
123
124const GRACE: std::time::Duration = std::time::Duration::from_secs(2);
126
127async fn off<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
130 let (tx, rx) = tokio::sync::oneshot::channel();
131 std::thread::spawn(move || {
132 let _ = tx.send(f());
133 });
134 match rx.await {
135 Ok(v) => v,
136 Err(_) => std::panic::resume_unwind(Box::new("a request's work stopped unexpectedly")),
139 }
140}
141
142async fn guard(State(s): State<Shared>, req: Request, next: Next) -> Response {
144 let headers = req.headers();
145 if !security::host_ok(s.port, headers) {
146 return (
147 StatusCode::MISDIRECTED_REQUEST,
148 "this host answers on the loopback address only",
149 )
150 .into_response();
151 }
152 if req.uri().path().starts_with("/api/") {
153 if !security::authorised(&s.token, headers) {
154 return (
155 StatusCode::UNAUTHORIZED,
156 Json(json!({ "error": "unauthorised" })),
157 )
158 .into_response();
159 }
160 if !security::origin_ok(s.port, req.method(), headers) {
161 return (
162 StatusCode::FORBIDDEN,
163 Json(json!({ "error": "cross-origin request refused" })),
164 )
165 .into_response();
166 }
167 }
168 let mut res = next.run(req).await;
169 let h = res.headers_mut();
170 h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
171 h.insert(
172 header::REFERRER_POLICY,
173 HeaderValue::from_static("no-referrer"),
174 );
175 h.insert(
176 header::X_CONTENT_TYPE_OPTIONS,
177 HeaderValue::from_static("nosniff"),
178 );
179 h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
180 res
181}
182
183fn content_type(path: &str) -> &'static str {
184 match path.rsplit('.').next() {
185 Some("html") => "text/html; charset=utf-8",
186 Some("js") => "text/javascript; charset=utf-8",
187 Some("css") => "text/css; charset=utf-8",
188 Some("svg") => "image/svg+xml",
189 Some("json") => "application/json",
190 Some("woff2") => "font/woff2",
191 _ => "application/octet-stream",
192 }
193}
194
195async fn asset(uri: axum::http::Uri) -> Response {
198 let want = match uri.path().trim_start_matches('/') {
199 "" => "index.html",
200 p => p,
201 };
202 let csp = [(
203 header::CONTENT_SECURITY_POLICY,
204 security::CONTENT_SECURITY_POLICY,
205 )];
206 if let Some(dir) = std::env::var_os("SPECCODER_UI")
207 && !want.contains("..")
208 && let Ok(bytes) = std::fs::read(Path::new(&dir).join(want))
209 {
210 return (csp, [(header::CONTENT_TYPE, content_type(want))], bytes).into_response();
211 }
212 if bundle::BUNDLE.is_empty() {
213 return (
214 StatusCode::SERVICE_UNAVAILABLE,
215 [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
216 "<!doctype html><meta charset=utf-8><title>speccoder</title><p style=\"font:16px system-ui;max-width:60ch;margin:4rem auto\">This binary was built without its interface (<code>npm run build</code> in <code>crates/speccoder-web/ui</code>). The API and the command line work.",
217 )
218 .into_response();
219 }
220 let name = want.trim_start_matches("assets/");
222 match bundle::BUNDLE
223 .iter()
224 .find(|(p, _)| *p == want || *p == name)
225 {
226 Some((p, bytes)) => {
227 (csp, [(header::CONTENT_TYPE, content_type(p))], *bytes).into_response()
228 }
229 None => match bundle::BUNDLE.iter().find(|(p, _)| *p == "index.html") {
231 Some((_, bytes)) => (
232 csp,
233 [(header::CONTENT_TYPE, content_type("index.html"))],
234 *bytes,
235 )
236 .into_response(),
237 None => (StatusCode::NOT_FOUND, "no such file").into_response(),
238 },
239 }
240}
241
242#[derive(Debug, Deserialize)]
243struct FeatureQuery {
244 feature: Option<String>,
245 task: Option<String>,
246 commit: Option<String>,
247 #[serde(rename = "ref")]
250 reference: Option<String>,
251}
252
253fn revision(q: &FeatureQuery) -> Option<String> {
256 if let Some(c) = q.commit.as_deref() {
257 return (c.len() >= 7 && c.chars().all(|ch| ch.is_ascii_hexdigit())).then(|| c.to_owned());
258 }
259 let r = q.reference.as_deref()?;
260 let rest = r.strip_prefix("refs/speccoder/attempts/")?;
261 let ok = !rest.is_empty()
262 && !r.contains("..")
263 && rest
264 .chars()
265 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '-' | '_' | '.'));
266 ok.then(|| r.to_owned())
267}
268
269fn file_path_ok(path: &str) -> bool {
273 let p = Path::new(path);
274 !path.is_empty()
275 && !p.is_absolute()
276 && p.components()
277 .all(|c| matches!(c, std::path::Component::Normal(_)))
278}
279
280fn envelope(s: &Shared, r: &CommandResult) -> Json<Value> {
283 Json(s.hub.issuer.signing(s.root.get(), || {
284 serde_json::to_value(r).unwrap_or(Value::Null)
285 }))
286}
287
288async fn project(State(s): State<Shared>) -> Json<Value> {
289 let root = s.root.get();
290 let window = s.window;
291 Json(
292 off(move || {
293 let words = speccoder_runtime::service::format_words(&root);
294 let features = speccoder_runtime::service::current::list(&root, None);
295 let name = root
296 .file_name()
297 .map(|n| n.to_string_lossy().into_owned())
298 .unwrap_or_default();
299 json!({
300 "name": name,
301 "root": root.display().to_string(),
302 "format": words.name,
303 "unit": words.unit,
304 "features": features.data().and_then(|d| match d {
305 CommandData::Features(f) => serde_json::to_value(f).ok(),
306 _ => None,
307 }),
308 "version": env!("CARGO_PKG_VERSION"),
309 "os": format!("{} {}", std::env::consts::OS, std::env::consts::ARCH),
310 "window": window,
311 "sandbox": speccoder_runtime::service::person::sandboxed(),
312 "planning": speccoder_runtime::service::planning_words(&root),
313 "sample": welcome::sample_of(&root),
314 })
315 })
316 .await,
317 )
318}
319
320async fn report(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
321 let root = s.root.get();
322 let r = off(move || {
323 speccoder_runtime::service::next::attach(
324 speccoder_runtime::service::status::report(&root, q.feature.as_deref()),
325 q.feature.as_deref(),
326 )
327 })
328 .await;
329 envelope(&s, &r)
330}
331
332async fn review(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
333 let root = s.root.get();
334 let r =
335 off(move || speccoder_runtime::service::review::report(&root, q.feature.as_deref())).await;
336 envelope(&s, &r)
337}
338
339async fn review_comments(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
341 let root = s.root.get();
342 let r = off(move || {
343 speccoder_runtime::service::review::comments(&root, q.feature.as_deref(), None)
344 })
345 .await;
346 envelope(&s, &r)
347}
348
349#[derive(Debug, Deserialize)]
350struct RunQuery {
351 run: String,
352}
353
354async fn account(State(s): State<Shared>, Query(q): Query<RunQuery>) -> Json<Value> {
357 let root = s.root.get();
358 Json(
359 off(
360 move || match speccoder_runtime::service::evidence::account_of(&root, &q.run) {
361 Ok(turns) => json!({ "turns": turns }),
362 Err(e) => json!({ "error": e }),
363 },
364 )
365 .await,
366 )
367}
368
369async fn inbox(State(s): State<Shared>) -> Json<Value> {
370 let root = s.root.get();
371 let issuer = Arc::clone(&s.hub.issuer);
372 Json(
374 off(move || {
375 issuer.signing(root.clone(), || {
376 serde_json::to_value(speccoder_runtime::service::inbox::inbox(&root, None))
377 .unwrap_or(Value::Null)
378 })
379 })
380 .await,
381 )
382}
383
384async fn bug(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
386 let root = s.root.get();
387 let Some(task) = q.task else {
388 return Json(json!({ "error": "a bug is needed: task=<unit>/<task>" }));
389 };
390 let r = off(move || speccoder_runtime::service::bug::show(&root, &task)).await;
391 envelope(&s, &r)
392}
393
394async fn actions(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
395 let root = s.root.get();
396 let issuer = Arc::clone(&s.hub.issuer);
397 Json(
398 off(move || {
399 issuer.signing(root.clone(), || {
401 json!(speccoder_runtime::service::actions::available(
402 &root,
403 q.feature.as_deref(),
404 q.task.as_deref()
405 ))
406 })
407 })
408 .await,
409 )
410}
411
412async fn approvals(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
413 let root = s.root.get();
414 let r =
415 off(move || speccoder_runtime::service::approvals::list(&root, q.feature.as_deref())).await;
416 envelope(&s, &r)
417}
418
419async fn evidence(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
420 let root = s.root.get();
421 Json(
422 off(move || {
423 let report = speccoder_runtime::service::status::report(&root, q.feature.as_deref());
424 let Some(CommandData::Report(r)) = report.data() else {
425 return json!({ "error": report.message() });
426 };
427 let Some(t) = r.tasks.iter().find(|t| Some(&t.id) == q.task.as_ref()) else {
428 return json!({ "error": "no such task" });
429 };
430 let statements = t
431 .commit
432 .as_deref()
433 .map(|c| speccoder_runtime::service::evidence::statements(&root, c))
434 .unwrap_or_default();
435 let (mark, words) = speccoder_runtime::service::evidence::banner(&t.state);
436 json!({
437 "task": t,
438 "banner": { "mark": mark, "words": words },
439 "rows": speccoder_runtime::service::evidence::rows(t, &statements, None),
440 })
441 })
442 .await,
443 )
444}
445
446async fn tour(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
451 let root = s.root.get();
452 Json(
453 off(move || {
454 let Some(task) = q.task else {
455 return json!({ "error": "a task is needed" });
456 };
457 let result =
458 speccoder_runtime::service::tour::of_task(&root, q.feature.as_deref(), &task);
459 serde_json::to_value(&result).unwrap_or_else(|e| json!({ "error": e.to_string() }))
460 })
461 .await,
462 )
463}
464
465async fn diff(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Response {
466 let root = s.root.get();
467 let Some(commit) = revision(&q) else {
468 return (
469 StatusCode::BAD_REQUEST,
470 Json(json!({ "error": "a commit id or an attempt ref is needed" })),
471 )
472 .into_response();
473 };
474 let patch = off(move || speccoder_runtime::service::commit_patch(&root, &commit)).await;
475 Json(json!({ "patch": patch })).into_response()
476}
477
478async fn documents(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
479 let root = s.root.get();
480 Json(
481 off(move || {
482 json!(speccoder_runtime::service::documents::of_feature(
483 &root,
484 q.feature.as_deref()
485 ))
486 })
487 .await,
488 )
489}
490
491async fn doctor(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
492 let root = s.root.get();
493 let r = off(move || speccoder_runtime::service::doctor::run(&root, q.feature.as_deref(), None))
494 .await;
495 envelope(&s, &r)
496}
497
498#[derive(Debug, Deserialize)]
499struct AgentsQuery {
500 #[serde(default = "yes")]
503 probe: bool,
504}
505
506fn yes() -> bool {
507 true
508}
509
510async fn agents(State(s): State<Shared>, Query(q): Query<AgentsQuery>) -> Json<Value> {
512 let root = s.root.get();
513 let r = off(move || speccoder_runtime::service::doctor::agents(&root, None, q.probe)).await;
514 envelope(&s, &r)
515}
516
517async fn config(State(s): State<Shared>) -> Json<Value> {
518 let root = s.root.get();
519 let r = off(move || speccoder_runtime::service::settings::show(&root)).await;
520 envelope(&s, &r)
521}
522
523#[derive(Debug, Deserialize)]
524struct ConfigBody {
525 changes: Vec<speccoder_core::ConfigChange>,
526}
527
528async fn config_save(State(s): State<Shared>, Json(b): Json<ConfigBody>) -> Json<Value> {
532 let root = s.root.get();
533 let r = off(move || speccoder_runtime::service::settings::apply(&root, &b.changes)).await;
534 envelope(&s, &r)
535}
536
537async fn ask(
540 State(s): State<Shared>,
541 Json(b): Json<speccoder_runtime::service::ask::Request>,
542) -> Json<Value> {
543 let root = s.root.get();
544 let sink = s.hub.progress();
545 let r = off(move || speccoder_runtime::service::ask::turn(&root, &b, None, Some(sink))).await;
546 envelope(&s, &r)
547}
548
549#[derive(Debug, Deserialize)]
550struct StopBody {
551 conversation: Option<String>,
552}
553
554async fn ask_stop(Json(b): Json<StopBody>) -> Json<Value> {
557 Json(json!({ "stopped": speccoder_runtime::service::ask::stop(b.conversation.as_deref()) }))
558}
559
560#[derive(Debug, Deserialize)]
561struct AskQuery {
562 id: Option<String>,
563 feature: Option<String>,
564}
565
566async fn explore_list(State(s): State<Shared>) -> Json<Value> {
568 let root = s.root.get();
569 let r = off(move || speccoder_runtime::service::explore::list(&root, None)).await;
570 envelope(&s, &r)
571}
572
573async fn explore_session(State(s): State<Shared>, Query(q): Query<AskQuery>) -> Json<Value> {
575 let root = s.root.get();
576 let r = off(move || {
577 speccoder_runtime::service::explore::session(
578 &root,
579 None,
580 q.id.as_deref().unwrap_or_default(),
581 )
582 })
583 .await;
584 envelope(&s, &r)
585}
586
587async fn ask_conversations(State(s): State<Shared>, Query(q): Query<AskQuery>) -> Json<Value> {
588 let root = s.root.get();
589 let r = off(move || {
590 speccoder_runtime::service::ask::conversations(&root, None, q.feature.as_deref())
591 })
592 .await;
593 envelope(&s, &r)
594}
595
596async fn ask_conversation(State(s): State<Shared>, Query(q): Query<AskQuery>) -> Json<Value> {
597 let root = s.root.get();
598 let r = off(move || {
599 speccoder_runtime::service::ask::thread(&root, None, q.id.as_deref().unwrap_or_default())
600 })
601 .await;
602 envelope(&s, &r)
603}
604
605#[derive(Debug, Deserialize)]
606struct ChangedQuery {
607 path: String,
608 start: Option<u32>,
609 end: Option<u32>,
610 sha: String,
611}
612
613async fn ask_changed(State(s): State<Shared>, Query(q): Query<ChangedQuery>) -> Json<Value> {
616 let root = s.root.get();
617 Json(json!({
618 "changed": off(move || {
619 speccoder_runtime::service::ask::changed_since(&root, &q.path, q.start, q.end, &q.sha)
620 })
621 .await
622 }))
623}
624
625async fn ask_chip(
627 State(s): State<Shared>,
628 Json(b): Json<speccoder_runtime::service::ask::ChipRef>,
629) -> Json<Value> {
630 let root = s.root.get();
631 Json(
632 off(
633 move || match speccoder_runtime::service::ask::chip(&root, "c0", &b) {
634 Ok((chip, text)) => {
635 json!({ "chip": chip, "preview": text.chars().take(400).collect::<String>() })
636 }
637 Err(e) => json!({ "error": e }),
638 },
639 )
640 .await,
641 )
642}
643
644#[derive(Debug, Deserialize)]
645struct ProposalBody {
646 proposal: speccoder_core::ask::Proposal,
647 feature: Option<String>,
648}
649
650async fn ask_proposal(State(s): State<Shared>, Json(b): Json<ProposalBody>) -> Json<Value> {
652 let root = s.root.get();
653 Json(
654 off(move || json!({ "proposal": speccoder_runtime::service::ask::proposal(&root, b.feature.as_deref(), &b.proposal) }))
655 .await,
656 )
657}
658
659#[derive(Debug, Deserialize)]
660struct ShapeBody {
661 field: String,
662 text: String,
663}
664
665async fn shape(State(s): State<Shared>, Json(b): Json<ShapeBody>) -> Json<Value> {
668 let root = s.root.get();
669 let r =
670 off(move || speccoder_runtime::service::shape::shape(&root, &b.field, &b.text, None)).await;
671 envelope(&s, &r)
672}
673
674async fn shape_check(Json(b): Json<ShapeBody>) -> Json<Value> {
676 Json(off(move || json!({ "findings": speccoder_runtime::service::shape::findings(&b.field, &b.text) })).await)
677}
678
679#[derive(Debug, Deserialize)]
680struct JudgeBody {
681 field: String,
682 original: String,
683 proposal: String,
684 #[serde(default)]
685 assumptions: Vec<speccoder_core::shape::Assumption>,
686}
687
688async fn shape_judge(Json(b): Json<JudgeBody>) -> Json<Value> {
690 Json(
691 off(move || {
692 speccoder_runtime::service::shape::judge(
693 &b.field,
694 &b.original,
695 &b.proposal,
696 &b.assumptions,
697 )
698 })
699 .await,
700 )
701}
702
703#[derive(Debug, Deserialize)]
704struct CoverageQuery {
705 key: String,
707 prefix: String,
709}
710
711async fn policy_coverage(State(s): State<Shared>, Query(q): Query<CoverageQuery>) -> Json<Value> {
714 let Some(list) = speccoder_core::actions::PolicyList::of_key(&q.key) else {
715 return Json(
716 json!({ "status": "usage_error", "message": format!("`{}` is not a prefix list", q.key) }),
717 );
718 };
719 let Ok(prefix) = serde_json::from_str::<Vec<String>>(&q.prefix) else {
720 return Json(
721 json!({ "status": "usage_error", "message": "the prefix is a JSON list of strings" }),
722 );
723 };
724 let root = s.root.get();
725 let r = off(move || {
726 let state = speccoder_runtime::service::worktree::state_dir();
727 speccoder_runtime::service::settings::coverage(&root, state.as_deref(), list, &prefix)
728 })
729 .await;
730 envelope(&s, &r)
731}
732
733async fn config_commit(State(s): State<Shared>) -> Json<Value> {
736 let (root, hub) = (s.root.get(), Arc::clone(&s.hub));
737 let r =
738 off(move || hub.exclusive(|| speccoder_runtime::service::settings::commit(&root))).await;
739 match r {
740 Ok(result) => envelope(&s, &result),
741 Err(e) => Json(json!({ "status": "error", "message": e })),
742 }
743}
744
745async fn cost(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
746 let root = s.root.get();
747 let r =
748 off(move || speccoder_runtime::service::controls::cost(&root, q.feature.as_deref())).await;
749 envelope(&s, &r)
750}
751
752async fn changes(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
754 let root = s.root.get();
755 Json(json!(
756 off(move || speccoder_runtime::service::code::changes(&root, q.feature.as_deref())).await
757 ))
758}
759
760async fn tree(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
762 let root = s.root.get();
763 let ((rev, files), worktree) = off(move || {
764 (
765 speccoder_runtime::service::code::tree(&root, q.feature.as_deref()),
766 speccoder_runtime::service::code::worktree_view(&root, q.feature.as_deref()),
767 )
768 })
769 .await;
770 Json(json!({ "rev": rev, "files": files, "worktree": worktree }))
771}
772
773#[derive(Debug, Deserialize)]
774struct FileQuery {
775 feature: Option<String>,
776 path: String,
777}
778
779async fn file(State(s): State<Shared>, Query(q): Query<FileQuery>) -> Json<Value> {
781 let root = s.root.get();
782 if !file_path_ok(&q.path) {
785 return Json(json!({ "error": format!("{} is not a project file", q.path) }));
786 }
787 let markdown = q.path.to_ascii_lowercase().ends_with(".md");
788 let r = off(move || {
790 speccoder_runtime::service::code::file(&root, q.feature.as_deref(), &q.path).or_else(|e| {
791 speccoder_runtime::service::code::worktree_file(&root, q.feature.as_deref(), &q.path)
792 .map_err(|_| e)
793 })
794 })
795 .await;
796 Json(match r {
797 Ok(text) if markdown => {
799 json!({ "text": text, "html": speccoder_runtime::service::documents::render(&text) })
800 }
801 Ok(text) => json!({ "text": text }),
802 Err(e) => json!({ "error": e }),
803 })
804}
805
806async fn setup(State(s): State<Shared>) -> Json<Value> {
809 let root = s.root.get();
810 let (doctor, preview) = off(move || {
811 (
812 speccoder_runtime::service::doctor::run(&root, None, None),
813 speccoder_runtime::service::init::preview(&root),
814 )
815 })
816 .await;
817 Json(json!({ "doctor": doctor, "preview": preview }))
818}
819
820#[derive(Debug, Deserialize)]
821struct SetupBody {
822 provider: Option<String>,
823 model: Option<String>,
824 region: Option<String>,
826}
827
828async fn setup_init(State(s): State<Shared>, Json(b): Json<SetupBody>) -> Json<Value> {
831 if s.hub.job().is_some_and(|j| j.running) {
832 return Json(json!({ "status": "error", "message": "a job is running" }));
833 }
834 let root = s.root.get();
835 let r = off(move || {
836 speccoder_runtime::service::init::prepare(
837 &root,
838 b.provider.as_deref(),
839 b.model.as_deref(),
840 b.region.as_deref(),
841 false,
842 false,
843 )
844 })
845 .await;
846 match r {
847 Err(refused) => envelope(&s, &refused),
848 Ok(p) => {
849 let (to_commit, failed) = (p.to_commit.clone(), p.failed.clone());
850 let Json(mut v) = envelope(&s, &speccoder_runtime::service::init::finish(p));
851 v["to_commit"] = json!(to_commit);
852 v["failed"] = json!(failed);
853 Json(v)
854 }
855 }
856}
857
858#[derive(Debug, Deserialize)]
859struct SetupCommit {
860 paths: Vec<String>,
861}
862
863async fn setup_commit(State(s): State<Shared>, Json(b): Json<SetupCommit>) -> Json<Value> {
865 let (root, hub) = (s.root.get(), Arc::clone(&s.hub));
866 let r = off(move || {
867 hub.exclusive(|| {
868 speccoder_runtime::service::init::commit_written(
869 &speccoder_runtime::service::init::root_of(&root),
870 &b.paths,
871 )
872 })
873 })
874 .await;
875 Json(match r.and_then(|r| r) {
876 Ok(id) => json!({ "status": "ok", "message": format!("committed as {id}") }),
877 Err(e) => json!({ "status": "error", "message": e }),
878 })
879}
880
881async fn github(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
885 let root = s.root.get();
886 Json(
887 off(move || {
888 use speccoder_runtime::service::github;
889 let ctx = github::Ctx::from_env();
890 let status = github::status(&ctx, &root);
891 if !status.ready {
892 return json!({ "status": status });
893 }
894 let issues = github::issues(&ctx, &root, &github::started(&root));
895 let branch = match speccoder_runtime::service::status::report(
896 &root,
897 q.feature.as_deref(),
898 )
899 .data()
900 {
901 Some(speccoder_core::CommandData::Report(r)) => r.branch.clone(),
902 _ => None,
903 };
904 let pull = branch.as_deref().map(|b| github::pr_for(&ctx, &root, b));
905 json!({
906 "status": status,
907 "issues": issues.as_ref().ok(),
908 "issues_error": issues.as_ref().err(),
909 "branch": branch,
910 "pull": pull.as_ref().and_then(|p| p.as_ref().ok()).cloned().flatten(),
911 "pull_error": pull.as_ref().and_then(|p| p.as_ref().err()),
912 })
913 })
914 .await,
915 )
916}
917
918#[derive(Debug, Deserialize)]
919struct IssueQuery {
920 number: String,
921}
922
923async fn github_device(State(s): State<Shared>) -> Json<Value> {
926 let root = s.root.get();
927 let slot = Arc::clone(&s.device);
928 Json(
929 off(move || {
930 use speccoder_runtime::service::github;
931 let host = github::repo(&root, None).map_or_else(|_| "github.com".to_owned(), |r| r.host);
932 let Some(client) = github::auth::client_id(&host) else {
933 return json!({ "error": format!("{host} has no speccoder app: sign in with a token instead") });
934 };
935 match github::auth::start(&github::http::oauth(&host), &client) {
936 Ok(p) => {
937 let shown = json!({ "user_code": p.user_code, "verification_uri": p.verification_uri, "host": host });
938 if let Ok(mut d) = slot.lock() {
939 *d = Some((host, client, p));
940 }
941 shown
942 }
943 Err(e) => json!({ "error": e }),
944 }
945 })
946 .await,
947 )
948}
949
950async fn github_device_wait(State(s): State<Shared>) -> Json<Value> {
953 let root = s.root.get();
954 let slot = Arc::clone(&s.device);
955 let r = off(move || {
956 use speccoder_runtime::service::github;
957 let Some((host, client, pending)) = slot.lock().ok().and_then(|mut d| d.take()) else {
958 return speccoder_core::CommandResult::new(
959 "auth",
960 speccoder_core::CommandStatus::UsageError,
961 "no sign-in is waiting: start it again",
962 );
963 };
964 let ctx = github::Ctx::from_env();
965 match github::auth::wait(&github::http::oauth(&host), &client, &pending) {
966 Ok(token) => {
967 let signed = github::login_with_token(&ctx, &host, token.expose());
968 match (signed.status(), github::reach(&ctx, &root)) {
969 (speccoder_core::CommandStatus::Ok, Some(todo)) => {
970 let message = format!("{}; {todo}", signed.message());
971 signed.reworded(speccoder_core::CommandStatus::Ok, &message)
972 }
973 _ => signed,
974 }
975 }
976 Err(e) => github::refused("auth", &e),
977 }
978 })
979 .await;
980 envelope(&s, &r)
981}
982
983#[derive(Debug, Deserialize)]
984struct TokenBody {
985 token: String,
986}
987
988async fn github_login(State(s): State<Shared>, Json(b): Json<TokenBody>) -> Json<Value> {
991 let root = s.root.get();
992 let r = off(move || {
993 let host = speccoder_runtime::service::github::repo(&root, None)
994 .map_or_else(|_| "github.com".to_owned(), |r| r.host);
995 speccoder_runtime::service::github::login_with_token(
996 &speccoder_runtime::service::github::Ctx::from_env(),
997 &host,
998 &b.token,
999 )
1000 })
1001 .await;
1002 envelope(&s, &r)
1003}
1004
1005async fn github_issue(State(s): State<Shared>, Query(q): Query<IssueQuery>) -> Json<Value> {
1008 let root = s.root.get();
1009 Json(
1010 off(move || {
1011 match speccoder_runtime::service::github::issue(
1012 &speccoder_runtime::service::github::Ctx::from_env(),
1013 &root,
1014 &q.number,
1015 ) {
1016 Ok(issue) => {
1017 json!({
1018 "description": speccoder_runtime::service::github::description(&issue),
1019 "skill": speccoder_runtime::service::create_skill(&root),
1020 "issue": issue,
1021 })
1022 }
1023 Err(e) => json!({ "error": e }),
1024 }
1025 })
1026 .await,
1027 )
1028}
1029
1030async fn pr_preview(State(s): State<Shared>, Query(q): Query<FeatureQuery>) -> Json<Value> {
1032 let root = s.root.get();
1033 let r = off(move || {
1034 speccoder_runtime::service::handoff::pr(
1035 &root,
1036 q.feature.as_deref(),
1037 &speccoder_runtime::service::handoff::PrOptions {
1038 remote: "origin",
1039 base: None,
1040 open: false,
1041 force: false,
1042 github: &speccoder_runtime::service::github::Ctx::from_env(),
1043 },
1044 )
1045 })
1046 .await;
1047 envelope(&s, &r)
1048}
1049
1050async fn live(State(s): State<Shared>) -> Json<Value> {
1054 let root = s.root.get();
1055 Json(
1056 off(move || {
1057 let Some(state) = speccoder_runtime::service::worktree::state_dir() else {
1058 return json!({ "live": null });
1059 };
1060 match speccoder_runtime::service::progress::read_live(&root, &state) {
1061 Some((live, running)) => json!({
1062 "live": live,
1063 "running": running,
1064 "own": live.pid == std::process::id(),
1065 "interrupted": live.finished.is_none() && !running,
1066 "now": std::time::SystemTime::now()
1067 .duration_since(std::time::UNIX_EPOCH)
1068 .map_or(0, |d| d.as_secs()),
1069 }),
1070 None => json!({ "live": null }),
1071 }
1072 })
1073 .await,
1074 )
1075}
1076
1077async fn job(State(s): State<Shared>) -> Json<Value> {
1078 Json(json!({ "job": s.hub.job(), "waiting": s.hub.waiting() }))
1079}
1080
1081#[derive(Debug, Deserialize)]
1082struct Start {
1083 run: Runnable,
1084 input: Option<String>,
1085 feature: Option<String>,
1086 command: String,
1087 #[serde(default)]
1089 root: Option<String>,
1090}
1091
1092async fn start(State(s): State<Shared>, Json(b): Json<Start>) -> Response {
1093 let root = match welcome::job_root(&s.root, &b.run, b.root.as_deref()) {
1094 Ok(r) => r,
1095 Err(e) => return welcome::no_project_yet(&e),
1096 };
1097 match s.hub.start(b.run, b.input, b.feature, b.command, root) {
1098 Ok(id) => Json(json!({ "id": id })).into_response(),
1099 Err(e) => (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
1100 }
1101}
1102
1103#[derive(Debug, Deserialize)]
1104struct AnswerBody {
1105 id: u64,
1106 answer: Option<speccoder_runtime::service::approvals::Answer>,
1107 text: Option<String>,
1108}
1109
1110async fn answer(State(s): State<Shared>, Json(b): Json<AnswerBody>) -> Response {
1111 let reply = match b.answer {
1112 Some(a) => jobs::Reply::Answer(a),
1113 None => jobs::Reply::Text(b.text.filter(|t| !t.trim().is_empty())),
1114 };
1115 match s.hub.answer(b.id, reply) {
1116 Ok(()) => Json(json!({ "ok": true })).into_response(),
1117 Err(e) => (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
1118 }
1119}
1120
1121async fn stop(State(s): State<Shared>) -> Json<Value> {
1122 s.hub.stop();
1123 Json(json!({ "ok": true }))
1124}
1125
1126async fn events(State(s): State<Shared>) -> Response {
1129 use futures_util::StreamExt;
1130 let rx = s.hub.subscribe();
1131 let hello = futures_util::stream::once(async {
1132 Ok::<_, std::convert::Infallible>(
1133 axum::response::sse::Event::default().data(json!({ "type": "hello" }).to_string()),
1134 )
1135 });
1136 let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(|m| async move {
1137 m.ok().map(|text| {
1138 Ok::<_, std::convert::Infallible>(axum::response::sse::Event::default().data(text))
1139 })
1140 });
1141 let mut closing = s.closing.clone();
1144 let stream = stream.take_until(async move {
1145 let _ = closing.wait_for(|c| *c).await;
1146 });
1147 axum::response::sse::Sse::new(hello.chain(stream))
1148 .keep_alive(axum::response::sse::KeepAlive::default())
1149 .into_response()
1150}
1151
1152#[derive(Debug, Deserialize)]
1153struct FixBody {
1154 argvs: Vec<Vec<String>>,
1155 token: String,
1156}
1157
1158async fn fix_run(State(s): State<Shared>, Json(b): Json<FixBody>) -> Response {
1163 let root = s.root.get();
1164 if !s.hub.issuer.issued(&root, &b.argvs, false, &b.token) {
1166 return (
1167 StatusCode::FORBIDDEN,
1168 Json(json!({ "error": "speccoder did not issue this command here to run: only a fix it printed runs from the app, and one that asks questions runs in a terminal" })),
1169 )
1170 .into_response();
1171 }
1172 if b.argvs.iter().any(|a| speccoder_core::step::interactive(a)) {
1173 return (
1174 StatusCode::BAD_REQUEST,
1175 Json(json!({ "error": "it asks you questions as it runs: open it in a terminal" })),
1176 )
1177 .into_response();
1178 }
1179 let started = match b.argvs.as_slice() {
1182 [one] if one.first().map(String::as_str) == Some("speccoder") => {
1183 let args = one[1..].to_vec();
1184 if let [spec, archive, change, ..] = args.as_slice()
1186 && spec == "spec"
1187 && archive == "archive"
1188 && !change.starts_with('-')
1189 {
1190 let (root2, change2) = (root.clone(), change.clone());
1191 let known = off(move || unit_exists(&root2, &change2)).await;
1192 if !known {
1193 return (
1194 StatusCode::FORBIDDEN,
1195 Json(json!({ "error": format!("`{change}` is no unit of this project") })),
1196 )
1197 .into_response();
1198 }
1199 }
1200 s.hub.start_speccoder(args, root)
1201 }
1202 argvs
1203 if argvs
1204 .iter()
1205 .any(|a| a.first().map(String::as_str) == Some("speccoder")) =>
1206 {
1207 return (
1208 StatusCode::FORBIDDEN,
1209 Json(json!({ "error": "speccoder runs on its own, never in a chain" })),
1210 )
1211 .into_response();
1212 }
1213 _ => s.hub.start_fix(b.argvs, root),
1214 };
1215 match started {
1216 Ok(id) => Json(json!({ "id": id })).into_response(),
1217 Err(e) => (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
1218 }
1219}
1220
1221fn unit_exists(root: &Path, name: &str) -> bool {
1223 match speccoder_runtime::service::current::list(root, None).data() {
1224 Some(CommandData::Features(f)) => f.features.iter().any(|e| e.name == name),
1225 _ => false,
1226 }
1227}
1228
1229async fn terminal(State(s): State<Shared>, Json(b): Json<FixBody>) -> Response {
1233 let root = s.root.get();
1234 if !s.window {
1235 return (
1236 StatusCode::BAD_REQUEST,
1237 Json(json!({ "error": "a browser tab opens no terminal: copy the command" })),
1238 )
1239 .into_response();
1240 }
1241 if !s.hub.issuer.issued(&root, &b.argvs, true, &b.token) {
1242 return (
1243 StatusCode::FORBIDDEN,
1244 Json(json!({ "error": "speccoder did not issue this command here for a terminal" })),
1245 )
1246 .into_response();
1247 }
1248 match off(move || speccoder_runtime::service::person::open_terminal(&root)).await {
1249 Ok(()) => Json(json!({ "ok": true })).into_response(),
1250 Err(e) => (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
1251 }
1252}
1253
1254async fn bug_report(State(s): State<Shared>) -> Json<Value> {
1256 let root = s.root.get();
1257 Json(
1258 off(move || {
1259 let doctor = speccoder_runtime::service::doctor::run(&root, None, None);
1260 json!({ "text": speccoder_runtime::service::copy::bug_report(&doctor, &root) })
1261 })
1262 .await,
1263 )
1264}
1265
1266#[derive(Debug, Deserialize)]
1267struct CodeQuery {
1268 code: String,
1269}
1270
1271async fn explain(Query(q): Query<CodeQuery>) -> Json<Value> {
1273 use speccoder_core::{CodeInfo, CommandData, ExplainReport};
1274 let r = match speccoder_core::codes::lookup(&q.code.to_ascii_uppercase()) {
1275 Some(e) => CommandResult::ok("explain", e.name).with_data(CommandData::Explain(Box::new(
1276 ExplainReport {
1277 codes: vec![CodeInfo::of(e)],
1278 },
1279 ))),
1280 None => CommandResult::new(
1281 "explain",
1282 speccoder_core::CommandStatus::UsageError,
1283 &format!("no code `{}`", q.code),
1284 )
1285 .with_code("USAGE-UNKNOWN-CODE"),
1286 };
1287 Json(serde_json::to_value(&r).unwrap_or(Value::Null))
1288}
1289
1290pub fn router(s: Shared) -> Router {
1292 Router::new()
1293 .route("/api/project", get(project))
1294 .route("/api/report", get(report))
1295 .route("/api/actions", get(actions))
1296 .route("/api/inbox", get(inbox))
1297 .route("/api/ask", post(ask))
1298 .route("/api/ask/conversations", get(ask_conversations))
1299 .route("/api/ask/conversation", get(ask_conversation))
1300 .route("/api/ask/stop", post(ask_stop))
1301 .route("/api/ask/changed", get(ask_changed))
1302 .route("/api/explore", get(explore_list))
1303 .route("/api/explore/session", get(explore_session))
1304 .route("/api/ask/chip", post(ask_chip))
1305 .route("/api/ask/proposal", post(ask_proposal))
1306 .route("/api/shape", post(shape))
1307 .route("/api/shape/check", post(shape_check))
1308 .route("/api/shape/judge", post(shape_judge))
1309 .route("/api/bug", get(bug))
1310 .route("/api/account", get(account))
1311 .route("/api/review", get(review))
1312 .route("/api/review/comments", get(review_comments))
1313 .route("/api/approvals", get(approvals))
1314 .route("/api/evidence", get(evidence))
1315 .route("/api/tour", get(tour))
1316 .route("/api/diff", get(diff))
1317 .route("/api/documents", get(documents))
1318 .route("/api/doctor", get(doctor))
1319 .route("/api/agents", get(agents))
1320 .route("/api/job", get(job))
1321 .route("/api/live", get(live))
1322 .route("/api/config", get(config).post(config_save))
1323 .route("/api/config/commit", post(config_commit))
1324 .route("/api/policy/coverage", get(policy_coverage))
1325 .route("/api/cost", get(cost))
1326 .route("/api/changes", get(changes))
1327 .route("/api/tree", get(tree))
1328 .route("/api/file", get(file))
1329 .route("/api/setup", get(setup).post(setup_init))
1330 .route("/api/github", get(github))
1331 .route("/api/github/issue", get(github_issue))
1332 .route("/api/github/login", post(github_login))
1333 .route("/api/github/device", post(github_device))
1334 .route("/api/github/device/wait", post(github_device_wait))
1335 .route("/api/pr/preview", get(pr_preview))
1336 .route("/api/setup/commit", post(setup_commit))
1337 .route("/api/events", get(events))
1338 .route("/api/run", post(start))
1339 .route("/api/answer", post(answer))
1340 .route("/api/stop", post(stop))
1341 .route("/api/fix/run", post(fix_run))
1342 .route("/api/terminal", post(terminal))
1343 .route("/api/bug-report", get(bug_report))
1344 .route("/api/explain", get(explain))
1345 .route("/api/welcome", get(welcome::view))
1346 .route("/api/open", post(welcome::open))
1347 .route("/api/recent/forget", post(welcome::forget))
1348 .route("/api/folders", get(welcome::folders))
1349 .route("/api/new/plan", get(welcome::plan))
1350 .route("/api/new/first-feature", post(welcome::first_feature))
1351 .route("/api/similar", get(welcome::similar))
1352 .route("/api/suggest", get(welcome::suggest))
1353 .route("/api/github/repos", get(welcome::repositories))
1354 .route("/api/skill-cost", get(welcome::skill_cost))
1355 .fallback(get(asset))
1356 .layer(axum::middleware::from_fn_with_state(
1357 s.clone(),
1358 welcome::projectless,
1359 ))
1360 .layer(axum::middleware::from_fn_with_state(s.clone(), guard))
1361 .with_state(s)
1362}
1363
1364pub type Events = tokio::sync::broadcast::Receiver<String>;
1366pub use tokio::sync::broadcast::error::RecvError;
1368
1369#[derive(Debug)]
1371pub struct Started {
1372 pub url: String,
1374 pub port: u16,
1376 pub events: Option<Events>,
1379 pub root: Root,
1382}
1383
1384pub fn serve(
1388 root: &Path,
1389 port: u16,
1390 window: bool,
1391 ready: impl FnOnce(Started) + Send,
1392) -> Result<(), String> {
1393 let rt = tokio::runtime::Builder::new_multi_thread()
1394 .worker_threads(2)
1395 .enable_all()
1396 .build()
1397 .map_err(|e| e.to_string())?;
1398 rt.block_on(async move {
1399 let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port)))
1400 .await
1401 .map_err(|e| format!("127.0.0.1:{port}: {e}"))?;
1402 let port = listener.local_addr().map_err(|e| e.to_string())?.port();
1403 let (close, closed) = tokio::sync::watch::channel(false);
1404 let token = security::token();
1405 if token.is_empty() {
1406 return Err("no random source for the token".to_owned());
1407 }
1408 let Some(issuer) = fixes::Issuer::new() else {
1409 return Err("no random source for the token".to_owned());
1410 };
1411 let root = Root::new(root, welcome::is_project(root));
1412 let shared = Shared {
1413 root: root.clone(),
1414 token: token.clone(),
1415 port,
1416 hub: jobs::Hub::new(root.clone(), Arc::new(issuer)),
1417 window,
1418 closing: closed,
1419 device: Arc::default(),
1420 };
1421 ready(Started {
1422 url: format!("http://127.0.0.1:{port}/#token={token}"),
1423 port,
1424 events: Some(shared.hub.subscribe()),
1425 root,
1426 });
1427 let (stop, stopping) = tokio::sync::oneshot::channel::<()>();
1430 let server = axum::serve(listener, router(shared)).with_graceful_shutdown(async move {
1431 let _ = stopping.await;
1432 });
1433 let signal = async move {
1434 let _ = tokio::signal::ctrl_c().await;
1435 let _ = close.send(true);
1436 let _ = stop.send(());
1437 tokio::time::sleep(GRACE).await;
1438 };
1439 tokio::select! {
1440 served = server => served.map_err(|e| e.to_string()),
1441 () = signal => Ok(()),
1442 }
1443 })
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448 use super::*;
1449
1450 #[test]
1453 fn an_archive_names_a_unit_the_project_has() {
1454 let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
1455 let r = dir.path();
1456 std::fs::create_dir_all(r.join(".specify/memory")).unwrap_or_else(|e| panic!("{e}"));
1457 std::fs::create_dir_all(r.join("specs/001-x")).unwrap_or_else(|e| panic!("{e}"));
1458 std::fs::write(r.join("specs/001-x/spec.md"), "# Spec\n").unwrap_or_else(|e| panic!("{e}"));
1459 assert!(unit_exists(r, "001-x"));
1460 assert!(!unit_exists(r, "002-other"));
1461 assert!(!unit_exists(r, "--yes"));
1462 }
1463
1464 fn q(commit: Option<&str>, reference: Option<&str>) -> FeatureQuery {
1465 FeatureQuery {
1466 feature: None,
1467 task: None,
1468 commit: commit.map(str::to_owned),
1469 reference: reference.map(str::to_owned),
1470 }
1471 }
1472
1473 #[test]
1474 fn only_commits_and_attempt_refs_reach_git_show() {
1475 assert!(revision(&q(Some("e23d4197bb"), None)).is_some());
1476 assert!(revision(&q(Some("e23d"), None)).is_none());
1477 assert!(revision(&q(Some("--output=/tmp/x"), None)).is_none());
1478 let attempt = "refs/speccoder/attempts/001-greet/T001/run_01M5S5VJ";
1479 assert_eq!(revision(&q(None, Some(attempt))).as_deref(), Some(attempt));
1480 for bad in [
1481 "refs/heads/main",
1482 "refs/speccoder/attempts/",
1483 "refs/speccoder/attempts/../../heads/main",
1484 "refs/speccoder/attempts/a b",
1485 "--all",
1486 "HEAD",
1487 ] {
1488 assert!(revision(&q(None, Some(bad))).is_none(), "{bad}");
1489 }
1490 }
1491}