-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforge_cli.py
More file actions
4747 lines (4146 loc) · 204 KB
/
forge_cli.py
File metadata and controls
4747 lines (4146 loc) · 204 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Nova Forge Interactive CLI — your AI build assistant.
Launch: python forge_cli.py
or: forge chat
Describe what you want. Nova builds it.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import random
import shutil
import sys
import time
from pathlib import Path
from typing import Any
try:
from prompt_toolkit import PromptSession # noqa: F811
except ModuleNotFoundError:
print("\n Missing dependencies. Run this first:\n")
print(" ./setup.sh")
print(" source .venv/bin/activate\n")
print(" Or manually:")
print(" python3 -m venv .venv && source .venv/bin/activate")
print(" pip install -r requirements.txt\n")
sys.exit(1)
from prompt_toolkit.history import FileHistory
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import Style as PTStyle
from rich.markdown import Markdown
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table
from rich.text import Text
from rich import box
from rich.columns import Columns
from rich.rule import Rule
from forge_theme import (
console, gradient_text, status_bar, file_tree, wave_header,
SPINNERS, BRAND,
)
from forge_prompt import (
ask_select, ask_confirm, ask_text, ask_checkbox,
ask_text_optional, build_model_choices, Separator,
)
from questionary import Choice
from forge_assistant import ForgeAssistant
# ── Setup ────────────────────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).parent))
from config import (
MODEL_ALIASES, DEFAULT_MODELS, resolve_model, get_model_config, get_provider,
ForgeProject, init_forge_dir, compute_turn_budget,
)
logger = logging.getLogger("forge.cli")
# ── Theme (from forge_theme.py) ──────────────────────────────────────────────
PT_STYLE = PTStyle.from_dict({
"prompt": "#c084fc bold",
"": "#e4e4f0",
})
VERSION = "0.4.0"
# ── Concurrency limits per provider ──────────────────────────────────────────
PROVIDER_CONCURRENCY: dict[str, int] = {
"bedrock": 3,
"openai": 6, # OpenRouter
"anthropic": 4,
}
# ── Persistent state & config ────────────────────────────────────────────────
STATE_DIR = Path.home() / ".forge"
STATE_FILE = STATE_DIR / "cli_state.json"
CONFIG_FILE = STATE_DIR / "config.json"
HISTORY_FILE = Path.home() / ".forge_history"
# Default config
DEFAULT_CONFIG: dict[str, Any] = {
"default_model": "nova-lite",
"model_preset": "nova", # "nova" = AWS-only, "mixed" = best-per-task, "premium" = Nova Pro
"project_dir": str(Path.home() / "projects"),
"max_turns": 50,
"temperature": 0.3,
"auto_build": True, # Auto-confirm builds in guided flow
"show_tips": True,
"theme": "default",
}
def _load_config() -> dict:
config = dict(DEFAULT_CONFIG)
if CONFIG_FILE.exists():
try:
saved = json.loads(CONFIG_FILE.read_text())
config.update(saved)
except (json.JSONDecodeError, OSError):
pass
return config
def _save_config(config: dict) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
# Only save non-default values
to_save = {k: v for k, v in config.items() if k in DEFAULT_CONFIG}
CONFIG_FILE.write_text(json.dumps(to_save, indent=2) + "\n")
def _load_state() -> dict:
if STATE_FILE.exists():
try:
return json.loads(STATE_FILE.read_text())
except (json.JSONDecodeError, OSError):
pass
return {"recent_projects": [], "first_run": True, "builds_completed": 0}
def _save_state(state: dict) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
STATE_FILE.write_text(json.dumps(state, indent=2) + "\n")
def _add_recent_project(state: dict, path: str, name: str) -> None:
projects = state.get("recent_projects", [])
projects = [p for p in projects if p["path"] != path]
projects.insert(0, {"path": path, "name": name, "last_used": time.strftime("%Y-%m-%d")})
state["recent_projects"] = projects[:10]
# ── Credential detection ─────────────────────────────────────────────────────
PROVIDER_CREDS = {
"bedrock": {
"env_vars": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"],
"display": "Amazon Bedrock (Nova models)",
"setup_hint": (
"Set AWS credentials:\n"
" export AWS_ACCESS_KEY_ID=your-key\n"
" export AWS_SECRET_ACCESS_KEY=your-secret\n"
" export AWS_DEFAULT_REGION=us-east-1\n\n"
" Or: aws configure"
),
"models": ["nova-lite", "nova-pro", "nova-premier"],
},
"openrouter": {
"env_vars": ["OPENROUTER_API_KEY"],
"display": "OpenRouter (Gemini, Claude, etc.)",
"setup_hint": (
"Set your OpenRouter API key:\n"
" export OPENROUTER_API_KEY=your-key\n\n"
" Get a key at: https://openrouter.ai/keys"
),
"models": ["gemini-flash", "gemini-pro"],
},
"anthropic": {
"env_vars": ["ANTHROPIC_API_KEY"],
"display": "Anthropic (Claude models)",
"setup_hint": (
"Set your Anthropic API key:\n"
" export ANTHROPIC_API_KEY=your-key\n\n"
" Get a key at: https://console.anthropic.com/"
),
"models": ["claude-sonnet", "claude-haiku"],
},
}
def _check_provider(provider: str) -> bool:
"""Check if a provider's credentials are available in the environment."""
info = PROVIDER_CREDS.get(provider, {})
return all(os.environ.get(var) for var in info.get("env_vars", []))
def _check_all_providers() -> dict[str, bool]:
"""Return {provider: is_configured} for all providers."""
return {name: _check_provider(name) for name in PROVIDER_CREDS}
def _provider_for_model(alias: str) -> str:
"""Get which provider a model alias requires."""
for prov, info in PROVIDER_CREDS.items():
if alias in info["models"]:
return prov
return "bedrock"
def _available_models() -> list[str]:
"""Return model aliases that have working credentials."""
providers = _check_all_providers()
available = []
for alias in MODEL_ALIASES:
prov = _provider_for_model(alias)
if providers.get(prov, False):
available.append(alias)
return available
def _try_load_env_file(path: str) -> bool:
"""Load a shell env file (KEY=VALUE format) into os.environ."""
p = Path(path).expanduser()
if not p.exists():
return False
try:
for line in p.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
# Handle export KEY=VALUE and KEY=VALUE
if line.startswith("export "):
line = line[7:]
if "=" in line:
key, _, val = line.partition("=")
key = key.strip()
val = val.strip().strip('"').strip("'")
if key and val:
os.environ[key] = val
return True
except OSError:
return False
# ── ASCII Art & Branding ─────────────────────────────────────────────────────
LOGO = r"""[#c084fc]
_ __ ______
/ | / /___ _ ______ _ / ____/___ _________ ____
/ |/ / __ \ | / / __ `// /_ / __ \/ ___/ __ `/ _ \
/ /| / /_/ / |/ / /_/ // __/ / /_/ / / / /_/ / __/
/_/ |_/\____/|___/\__,_//_/ \____/_/ \__, /\___/
/____/[/]"""
_TAGLINE_TEXT = "AI Build Orchestrator"
WELCOME_FIRST_RUN = """
[bold bright_white]Welcome to Nova Forge![/]
Nova Forge is an open-source AI build system powered by [brand]Amazon Nova[/].
Tell it what you want to build, and it writes the code — start to finish.
[step]How it works:[/]
[accent]1.[/] You describe what you want [muted]"a REST API for bookmarks"[/]
[accent]2.[/] Nova plans the project [muted]spec, tasks, architecture[/]
[accent]3.[/] Nova builds it, wave by wave [muted]real code, not stubs[/]
[accent]4.[/] You get a working project [muted]ready to run[/]
[hint]Just describe your idea — Nova handles the rest.[/]
"""
WELCOME_RETURNING = """[bold bright_white]Welcome back![/] [muted]Nova Forge v{version}[/]"""
IDEAS = [
"a REST API for managing bookmarks",
"a weather dashboard with Flask",
"a task tracker with SQLite",
"a URL shortener service",
"a blog engine with markdown support",
"a chat server with WebSockets",
"a file organizer CLI tool",
"a habit tracker with streaks",
]
TIPS = [
"You can say [accent]\"build me X\"[/] and Nova will plan + build automatically.",
"Type [accent]/status[/] anytime to see your project's progress.",
"After a build, check the generated files — they're real, runnable code.",
"Use [accent]/tasks[/] to see the full task breakdown with dependencies.",
"Nova works best with clear, specific descriptions of what you want.",
"You can change the AI model with [accent]/models[/] — Nova, Gemini, Claude all work.",
"Type [accent]/help[/] to see all available commands.",
"Nova builds wave-by-wave — later tasks can depend on earlier ones.",
]
HELP_TEXT = """
[bold bright_white]Getting Started[/]
[accent]/guide[/] Smart setup wizard — recommends formation, autonomy, model
[accent]/interview[/] 5-step guided project setup (advanced)
[accent]/autonomy[/] View or change how much Nova asks for approval
[accent]/autonomy ?[/] Explain all 5 autonomy levels
[accent]/autonomy[/] [muted]0-5[/] Set level [muted](0=Manual · 2=Supervised · 4=Autonomous · 5=Unattended)[/]
[bold bright_white]Build[/]
[accent]/plan[/] [muted]<goal>[/] Plan a project from a description
[accent]/build[/] Execute the plan — Nova writes all the code
[accent]/preview[/] Launch Cloudflare Tunnel for live preview
[accent]/deploy[/] Ship to production with Docker + nginx
[accent]/status[/] Progress bar and project overview
[accent]/tasks[/] See all tasks with status and dependencies
[bold bright_white]Configuration[/]
[accent]/model[/] Switch AI model [muted](interactive selector, or /model nova-lite)[/]
[accent]/models[/] Show all available models + credential status
[accent]/config[/] Edit settings [muted](interactive, or /config key value)[/]
[accent]/login[/] Set up API credentials for a provider
[bold bright_white]Project[/]
[accent]/resume[/] Resume a recent project [muted](interactive, or /resume 1)[/]
[accent]/new[/] [muted]<name>[/] Start a fresh project directory
[accent]/cd[/] [muted]<path>[/] Switch project directory
[accent]/pwd[/] Show current project location
[accent]/formation[/] View agent formations [muted](interactive selector)[/]
[accent]/audit[/] View the build audit log
[accent]/builds[/] Build history with proof-of-work detail
[accent]/health[/] System health dashboard
[accent]/competition[/] Hackathon submission readiness
[bold bright_white]General[/]
[accent]/clear[/] Clear the screen
[accent]/help[/] This screen
[accent]/quit[/] Exit
[bold bright_white]Quick Start[/] [muted]Or just type what you want to build[/]
[muted]>[/] Build me a REST API for managing recipes
[muted]>[/] Create a CLI tool that converts CSV to JSON
[muted]>[/] I need a todo app with a SQLite backend
"""
# ── Interactive Shell ────────────────────────────────────────────────────────
class ForgeShell:
"""Interactive CLI shell for Nova Forge — guided, eager, friendly."""
def __init__(self, project_path: str | Path = ".", default_model: str | None = None):
self.config = _load_config()
self.project_path = Path(project_path).resolve()
self.state = _load_state()
self.session_builds = 0
self._chat_history: Any = None # Lazy-loaded ChatHistory
self._preview_mgr: Any = None # PreviewManager instance
self.assistant = ForgeAssistant(self) # Smart assistant layer
# Apply model preset (must happen before model resolution so formations are patched)
preset_name = self.config.get("model_preset", "nova")
try:
from forge_models import apply_preset
apply_preset(preset_name)
except (KeyError, ImportError):
preset_name = ""
# Resolve model: CLI flag > saved config > preset default > hardcoded default
if default_model:
self.model = resolve_model(default_model)
elif self.config.get("default_model"):
self.model = resolve_model(self.config["default_model"])
else:
self.model = DEFAULT_MODELS["planning"]
self._ensure_project()
def _ensure_project(self) -> None:
forge_dir = self.project_path / ".forge"
if not forge_dir.exists():
init_forge_dir(self.project_path)
@property
def chat_history(self):
if self._chat_history is None:
from forge_memory import ChatHistory
self._chat_history = ChatHistory(self.project_path)
return self._chat_history
# ── Main entry ────────────────────────────────────────────────────────
async def run(self) -> None:
"""Main REPL — welcome, onboard, build."""
console.clear()
console.print(LOGO)
subtitle = gradient_text(f" {_TAGLINE_TEXT}")
console.print(subtitle)
console.print(f" [dim]v{VERSION}[/]")
console.print()
# Try auto-loading credentials from known locations
self._auto_load_credentials()
is_first = self.state.get("first_run", True)
if is_first:
# Check credentials before onboarding
if not self._check_credentials_status(quiet=True):
await self._setup_wizard()
await self._onboard_first_run()
else:
# Show credential status if nothing is configured
if not self._check_credentials_status(quiet=True):
self._show_credential_warning()
await self._onboard_returning()
# Main loop
session = PromptSession(
history=FileHistory(str(HISTORY_FILE)),
style=PT_STYLE,
)
while True:
try:
# Show autonomy level in prompt (e.g. "nova [A2] > ")
autonomy_lvl = self.assistant.read_autonomy_level()
prompt_str = HTML(f"<prompt>nova [A{autonomy_lvl}] > </prompt>")
user_input = await asyncio.get_event_loop().run_in_executor(
None,
lambda: session.prompt(prompt_str),
)
except (EOFError, KeyboardInterrupt):
self._goodbye()
break
user_input = user_input.strip()
if not user_input:
continue
if user_input.startswith("/"):
should_quit = await self._handle_slash(user_input)
if should_quit:
break
else:
await self._handle_natural(user_input)
console.print()
# ── First-run onboarding ─────────────────────────────────────────────
async def _onboard_first_run(self) -> None:
# Ask skill level before welcoming, so we can adapt verbosity
skill_choice = await ask_select(
"How would you describe your experience level?",
[
Choice(
title="Beginner",
value="beginner",
description="New to coding or new to Nova Forge — extra guidance and explanations",
),
Choice(
title="Intermediate",
value="intermediate",
description="Comfortable with code and CLIs — balanced guidance",
),
Choice(
title="Expert",
value="expert",
description="Experienced developer — minimal explanations, just build",
),
],
default="beginner",
use_shortcuts=True,
)
if skill_choice:
self.assistant.set_skill_level(skill_choice)
else:
self.assistant.detect_skill_level()
# Show skill-adaptive welcome
console.print()
console.print(self.assistant.welcome_message())
console.print()
# Recommend autonomy level based on skill
rec_level, rec_reason = self.assistant.get_autonomy_recommendation()
console.print(f" [step]Recommended autonomy:[/] A{rec_level} ({rec_reason})")
console.print(f" [hint]You can change this anytime with /autonomy[/]")
console.print()
# Apply recommended autonomy
self.assistant.set_autonomy_level(rec_level)
# Mark first run complete
self.state["first_run"] = False
_save_state(self.state)
# Immediately ask what to build
console.print(Rule("[bold bright_white]Let's build something[/]", style="bright_magenta"))
console.print()
idea = random.choice(IDEAS)
console.print(f" [hint]Try something like: \"{idea}\"[/]")
console.print()
goal = await ask_text("What do you want to build?")
if goal is None:
self._goodbye()
return
goal = goal.strip()
if goal:
await self._guided_build(goal)
# ── Returning user onboarding ────────────────────────────────────────
async def _onboard_returning(self) -> None:
builds = self.state.get("builds_completed", 0)
# Detect skill level from history
self.assistant.detect_skill_level()
console.print(WELCOME_RETURNING.format(version=VERSION))
if builds > 0:
console.print(f" [muted]{builds} project{'s' if builds != 1 else ''} built so far[/]")
# Show autonomy level
autonomy_lvl = self.assistant.read_autonomy_level()
autonomy_bar = self.assistant.format_autonomy_bar(autonomy_lvl)
console.print(f" [muted]Autonomy:[/] {autonomy_bar} [dim](/autonomy to change)[/]")
from forge_models import get_active_preset, MODEL_PRESETS
active = get_active_preset()
if active:
desc = MODEL_PRESETS[active]["description"]
console.print(f" [nova]Preset:[/] {active} [muted]— {desc}[/]")
# Show contextual hint for returning expert
if self.assistant.skill_level == "expert":
hint = self.assistant.contextual_hint("returning_expert")
if hint:
console.print(f" [hint]{hint}[/]")
console.print()
# Auto-resume: find the most recent project with pending/failed work
resumed = self._try_auto_resume()
if resumed:
return
# Second pass: if no pending/failed, auto-switch to most recent completed project
recent = self.state.get("recent_projects", [])
for proj in recent:
p = Path(proj["path"])
if not p.exists():
continue
summary = self._get_task_summary_for(p)
if summary and summary["total"] > 0 and summary["completed"] == summary["total"]:
self.project_path = p
self._ensure_project()
console.print(Panel(
f"[bold]{proj['name']}[/]\n"
f" [success]{summary['total']}/{summary['total']} tasks complete[/]\n"
f" [muted]{p}[/]\n\n"
f" [hint]/preview[/] — share a live URL\n"
f" [hint]/deploy[/] — ship to production\n"
f" Tell me to add features, or describe a new project!",
border_style="green",
title="[bold green] Project Ready [/]",
padding=(1, 2),
))
console.print()
return
# Show recent projects with status
if recent:
console.print(" [step]Recent projects:[/]")
for i, proj in enumerate(recent[:5], 1):
p = Path(proj["path"])
if not p.exists():
console.print(f" [accent]{i}.[/] [muted]{proj['name']} (deleted)[/]")
continue
summary = self._get_task_summary_for(p)
if summary and summary["total"] > 0:
done = summary["completed"]
total = summary["total"]
failed = summary["failed"]
if done == total:
tag = "[success]complete[/]"
elif failed > 0:
tag = f"[yellow]{done}/{total} done, {failed} failed[/]"
else:
tag = f"[cyan]{done}/{total} done[/]"
else:
tag = "[muted]empty[/]"
console.print(f" [accent]{i}.[/] {proj['name']:30s} {tag}")
console.print(f" [muted]{proj['path']}[/]")
console.print()
console.print(f" [hint]Type [accent]/resume[/] or [accent]/resume 1[/] to continue a project[/]")
console.print()
if self.config.get("show_tips", True):
console.print(f" [hint]Tip: {random.choice(TIPS)}[/]")
console.print()
def _try_auto_resume(self) -> bool:
"""Auto-switch to the most recent project that has pending/failed work."""
recent = self.state.get("recent_projects", [])
for proj in recent:
p = Path(proj["path"])
if not p.exists():
continue
summary = self._get_task_summary_for(p)
if summary and (summary["pending"] > 0 or summary["failed"] > 0 or summary.get("in_progress", 0) > 0):
# Found a project with work to do — switch to it
self.project_path = p
self._ensure_project()
done = summary["completed"]
total = summary["total"]
pending = summary["pending"]
failed = summary["failed"]
remaining = pending + failed + summary.get("in_progress", 0)
console.print(Panel(
f"[bold]{proj['name']}[/]\n"
f" {done}/{total} tasks done, {remaining} remaining\n"
f" [muted]{p}[/]\n\n"
f" Type [accent]/build[/] to continue, or describe something new.",
border_style="bright_magenta",
title="[bold bright_magenta] Resuming [/]",
padding=(1, 2),
))
console.print()
return True
return False
# ── Guided build flow (the magic) ────────────────────────────────────
async def _guided_build(self, goal: str, scope_context: str | None = None) -> None:
"""The full guided pipeline: goal → interview → plan → confirm → build → celebrate."""
# Step 1: Derive project name
name = self._derive_project_name(goal)
console.print()
console.print(f" [step]Project:[/] [bold]{name}[/]")
console.print(f" [step]Goal:[/] {goal}")
console.print()
# Check credentials before doing anything
active_prov = _provider_for_model(
next((a for a, fid in MODEL_ALIASES.items() if fid == self.model), "nova-lite")
)
if not _check_provider(active_prov):
info = PROVIDER_CREDS.get(active_prov, {})
console.print(f" [warning]Need {info.get('display', active_prov)} credentials first.[/]")
console.print(f" [hint]Run /login to set up, or /model to switch models.[/]")
return
# Create project directory
base_dir = Path(self.config.get("project_dir", str(Path.home() / "projects")))
project_dir = base_dir / name
if project_dir.exists():
# Add suffix if exists
for i in range(2, 100):
candidate = base_dir / f"{name}-{i}"
if not candidate.exists():
project_dir = candidate
break
project_dir.mkdir(parents=True, exist_ok=True)
self.project_path = project_dir
self._ensure_project()
console.print(f" [success]Created[/] {project_dir}")
console.print()
# Step 2: Smart planning — Nova proposes, user confirms
if scope_context is None:
scope_context = await self._smart_planning(goal)
if scope_context is None:
console.print(" [muted]Planning cancelled.[/]")
return
# Step 3: Plan
console.print(Rule(f"[bold {BRAND['accent']}] Planning [/]", style=BRAND["accent"]))
console.print()
await self._cmd_plan(goal, scope_context=scope_context)
# Step 3: Confirm build
if not self._has_tasks():
console.print(" [warning]Planning didn't produce tasks. Try a more specific description.[/]")
return
# Post-plan hint from assistant
from forge_display import display_assistant_hint
summary_after_plan = self._get_task_summary()
if summary_after_plan:
task_count = summary_after_plan["total"]
try:
waves = []
from forge_tasks import TaskStore
from config import ForgeProject as _FP
_store = TaskStore(_FP(root=self.project_path).tasks_file)
waves = _store.compute_waves()
except Exception:
waves = []
guidance = self.assistant.post_plan_guidance(task_count, len(waves))
console.print(f" [hint]{guidance}[/]")
console.print()
console.print(Rule(f"[bold {BRAND['cyan']}] Build [/]", style=BRAND["cyan"]))
console.print()
if not await ask_confirm("Ready to build?"):
console.print(" [muted]No problem. You can edit the plan and run /build when ready.[/]")
return
# Step 4: Build!
await self._cmd_build("")
# Step 5: Celebrate + next steps
self._celebrate()
# Track in state
self.state["builds_completed"] = self.state.get("builds_completed", 0) + 1
_add_recent_project(self.state, str(self.project_path), name)
_save_state(self.state)
# Step 6: Offer to preview if build succeeded
summary = self._get_task_summary()
if summary and summary.get("failed", 0) == 0 and summary.get("completed", 0) > 0:
console.print()
if await ask_confirm("Launch a live preview?", default=True):
await self._cmd_preview("")
# ── Celebration ──────────────────────────────────────────────────────
def _celebrate(self) -> None:
"""Show build results and next steps."""
tasks_summary = self._get_task_summary()
if not tasks_summary:
return
total = tasks_summary["total"]
done = tasks_summary["completed"]
failed = tasks_summary["failed"]
console.print()
if failed == 0 and done == total:
# Show file tree of the built project
all_files = self._list_project_files()
tree_str = ""
if all_files:
tree = file_tree(all_files[:15], str(self.project_path))
from io import StringIO
from rich.console import Console as _C
buf = StringIO()
_C(file=buf, force_terminal=True).print(tree)
tree_str = "\n" + buf.getvalue()
console.print(Panel(
f"[bold {BRAND['green']}]\u2713 Build complete![/]\n\n"
f" {status_bar(done, total, 20)}\n"
f"{tree_str}\n"
f" [step]Quick actions:[/]\n"
f" [{BRAND['accent2']}]/preview[/] \u2192 Share a live URL\n"
f" [{BRAND['cyan']}]/deploy[/] \u2192 Ship to production\n"
f" [{BRAND['accent']}]/tasks[/] \u2192 Review task details",
border_style=BRAND["green"],
title=f"[bold {BRAND['green']}] Done! [/]",
padding=(1, 2),
))
elif done > 0:
console.print(Panel(
f"[bold {BRAND['orange']}]Build partially complete[/]\n\n"
f" {status_bar(done, total, 20)}\n"
f" [success]{done}[/] passed [error]{failed}[/] failed "
f"out of {total} tasks\n\n"
f" Type [{BRAND['cyan']}]/build[/] to retry failed tasks,\n"
f" or tell me what to fix.",
border_style=BRAND["orange"],
title=f"[bold {BRAND['orange']}] Almost there [/]",
padding=(1, 2),
))
else:
console.print(f" [error]Build had issues.[/] Type [accent]/tasks[/] to see what went wrong.")
console.print(f" [hint]You can describe the problem and I'll help fix it.[/]")
# ── Goodbye ──────────────────────────────────────────────────────────
def _goodbye(self) -> None:
_save_state(self.state)
builds = self.state.get("builds_completed", 0)
console.print()
if builds > 0:
console.print(f" [{BRAND['accent2']}]\u2728[/] [muted]{builds} project{'s' if builds != 1 else ''} built. See you next time.[/]")
else:
console.print(f" [{BRAND['accent2']}]\u2728[/] [muted]Come back when you're ready to build.[/]")
console.print()
# ── Credential management ────────────────────────────────────────────
def _auto_load_credentials(self) -> None:
"""Try loading credentials from common locations."""
env_paths = [
"~/.secrets/hercules.env",
"~/.forge/credentials.env",
"~/.env",
".env",
]
for path in env_paths:
if _try_load_env_file(path):
logger.debug("Loaded credentials from %s", path)
def _check_credentials_status(self, quiet: bool = False) -> bool:
"""Check and optionally display credential status. Returns True if any provider works."""
providers = _check_all_providers()
any_configured = any(providers.values())
if not quiet:
console.print()
console.print(" [step]Provider Status[/]")
for name, configured in providers.items():
info = PROVIDER_CREDS[name]
icon = "[success]ready[/]" if configured else "[muted]not configured[/]"
models = ", ".join(info["models"])
console.print(f" {info['display']:40s} {icon}")
if configured:
console.print(f" [muted]Models: {models}[/]")
console.print()
if any_configured:
avail = _available_models()
console.print(f" [success]{len(avail)} models available:[/] {', '.join(avail)}")
else:
console.print(f" [warning]No providers configured.[/] Run [accent]/login[/] to set up.")
console.print()
return any_configured
def _show_credential_warning(self) -> None:
"""Show a gentle warning about missing credentials."""
providers = _check_all_providers()
active_prov = _provider_for_model(
next((a for a, fid in MODEL_ALIASES.items() if fid == self.model), "nova-lite")
)
if not providers.get(active_prov, False):
console.print(Panel(
f"[warning]Your active model ({_short_model(self.model)}) needs credentials.[/]\n\n"
f" Run [accent]/login[/] to set up, or [accent]/model[/] to switch.\n"
f" [muted]You can also: source ~/.secrets/hercules.env[/]",
border_style="yellow",
padding=(0, 2),
))
console.print()
async def _setup_wizard(self) -> None:
"""Interactive credential setup wizard."""
console.print(Rule("[step] Setup [/]", style="cyan"))
console.print()
console.print(" Nova Forge needs API credentials to talk to AI models.")
console.print(" Let's get you set up. [muted](You can skip and do this later with /login)[/]")
console.print()
# Check if we have a known env file
env_path = Path("~/.secrets/hercules.env").expanduser()
if env_path.exists():
console.print(f" [success]Found:[/] {env_path}")
_try_load_env_file(str(env_path))
if _check_all_providers().get("bedrock"):
console.print(f" [success]AWS credentials loaded — Bedrock is ready![/]")
console.print()
return
# Show what's needed
providers = _check_all_providers()
for name, configured in providers.items():
if configured:
info = PROVIDER_CREDS[name]
console.print(f" [success]{info['display']}[/] — ready")
unconfigured = [n for n, c in providers.items() if not c]
if not unconfigured:
console.print(" [success]All providers ready![/]")
console.print()
return
console.print()
console.print(" [step]To get started, set up at least one provider:[/]")
console.print()
provider_choices = [
Choice(
title=PROVIDER_CREDS[name]["display"],
value=name,
description=f"Models: {', '.join(PROVIDER_CREDS[name]['models'])}",
)
for name in unconfigured
]
provider = await ask_select("Set up a provider", provider_choices, use_shortcuts=True)
if provider is None:
console.print(" [muted]Skipped. You can run /login anytime.[/]")
console.print()
return
await self._login_provider(provider)
async def _login_provider(self, provider: str) -> None:
"""Guide user through setting up a specific provider."""
info = PROVIDER_CREDS[provider]
console.print()
console.print(f" [step]Setting up {info['display']}[/]")
console.print()
creds: dict[str, str] = {}
for var in info["env_vars"]:
current = os.environ.get(var, "")
hint = f"current: ...{current[-8:]}" if current else None
val = await ask_text(f" {var}", default=current, instruction=hint)
if val is None:
console.print(" [muted]Cancelled.[/]")
return
val = val.strip()
if val:
creds[var] = val
elif current:
creds[var] = current
else:
console.print(f" [warning]Skipped {var}[/]")
if not creds:
return
# Apply to environment
for k, v in creds.items():
os.environ[k] = v
# Save to credentials file
creds_file = STATE_DIR / "credentials.env"
STATE_DIR.mkdir(parents=True, exist_ok=True)
# Append new vars (don't overwrite existing)
existing = {}
if creds_file.exists():
for line in creds_file.read_text().splitlines():
if "=" in line and not line.startswith("#"):
k, _, v = line.partition("=")
existing[k.strip()] = v.strip()
existing.update(creds)
lines = [f"{k}={v}" for k, v in existing.items()]
creds_file.write_text("\n".join(lines) + "\n")
creds_file.chmod(0o600)
# Verify
if _check_provider(provider):
console.print()
console.print(f" [success]{info['display']} is ready![/]")
models = ", ".join(info["models"])
console.print(f" [muted]Available models: {models}[/]")
# Auto-switch to first available model for this provider if current isn't working
active_prov = _provider_for_model(
next((a for a, fid in MODEL_ALIASES.items() if fid == self.model), "")
)
if not _check_provider(active_prov):
new_model = info["models"][0]
self.model = resolve_model(new_model)
self.config["default_model"] = new_model
_save_config(self.config)
console.print(f" [info]Switched to:[/] {new_model}")
else:
console.print(f" [warning]Credentials saved but verification failed.[/]")
console.print()
# ── Slash command router ─────────────────────────────────────────────
async def _handle_slash(self, raw: str) -> bool:
parts = raw.split(None, 1)
cmd = parts[0].lower()
arg = parts[1] if len(parts) > 1 else ""
match cmd:
case "/quit" | "/exit" | "/q":
self._goodbye()
return True
case "/help" | "/h" | "/?":
console.print(HELP_TEXT)
self._suggest_next_action()
case "/clear" | "/cls":
console.clear()
console.print(LOGO)
console.print(f" {_TAGLINE_TEXT}")
case "/pwd":
console.print(f" [info]Project:[/] {self.project_path}")
case "/cd":
self._cmd_cd(arg)
case "/resume":
await self._cmd_resume(arg)
case "/new":
await self._cmd_new(arg)
case "/plan":
if not arg:
console.print()
console.print(" [hint]What should Nova plan?[/]")
console.print(" [muted]Example: /plan Build a REST API for managing recipes[/]")
else:
await self._cmd_plan(arg)
case "/build":
await self._cmd_build(arg)
case "/status":
self._cmd_status()
case "/tasks":
self._cmd_tasks()
case "/model":
await self._cmd_model(arg)
case "/models":
self._cmd_models()
case "/config":
await self._cmd_config(arg)