frontieragent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
frontieragent/cli.py ADDED
@@ -0,0 +1,1347 @@
1
+ """Unified CLI and Interactive Antigravity-Grade Terminal REPL for FrontierAgent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import queue
8
+ import re
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ from searchharnes import SearchHarnes
15
+ from tuiharness import THEMES, style
16
+
17
+ from . import __version__
18
+ from .config import (
19
+ ALL_PROVIDERS,
20
+ ConfigManager,
21
+ DEFAULT_BASES,
22
+ DEFAULT_MODELS,
23
+ fetch_endpoint_models,
24
+ initialize_frontier_md,
25
+ list_ollama_models,
26
+ mask_secret,
27
+ probe_ollama,
28
+ )
29
+ from .core.agent import FrontierAgent
30
+ from .types import Attachment, AutonomyMode, EffortLevel, MEDIA_EXTENSIONS, format_attachments_summary
31
+ from .ui.cockpit import AgentCockpit, CockpitApprovalGate
32
+ from .ui.markdown_plus import MUTED_GREY, erase_terminal_rows
33
+ from .ui.prompt_bar import (
34
+ capture_clipboard_attachment,
35
+ copy_text_to_clipboard,
36
+ extract_media_attachments,
37
+ read_masked_secret,
38
+ resolve_media_path,
39
+ )
40
+
41
+
42
+ def _read_secret_or_line(prompt_text: str, allow_empty: bool = True) -> str:
43
+ """Prompt securely for API keys with masked bullets and Ctrl+V clipboard paste support."""
44
+ return read_masked_secret(prompt_text)
45
+
46
+
47
+ def _render_models_table(
48
+ cockpit: AgentCockpit,
49
+ provider: str,
50
+ base_url: str,
51
+ models: List[Dict[str, str]],
52
+ active_model: str = "",
53
+ filter_text: str = "",
54
+ ) -> None:
55
+ filtered = [
56
+ m for m in models
57
+ if not filter_text or filter_text.lower() in m["id"].lower() or filter_text.lower() in m.get("info", "").lower()
58
+ ]
59
+ title = f"### Available Models on `{provider}` (`{base_url or 'default'}`)"
60
+ if not filtered:
61
+ print(cockpit.md.render(f"{title}\n\nNo models matched filter `{filter_text}` ({len(models)} total fetched)."))
62
+ return
63
+
64
+ rows = ["| # | Model ID | Info | Active |", "| :--- | :--- | :--- | :--- |"]
65
+ for idx, m in enumerate(filtered, 1):
66
+ mark = "`ACTIVE`" if m["id"] == active_model else ""
67
+ info = m.get("info", "")[:45]
68
+ rows.append(f"| {idx} | `{m['id']}` | {info} | {mark} |")
69
+ print(cockpit.md.render(f"{title}\n\n" + "\n".join(rows)))
70
+
71
+
72
+ def _fetch_and_pick_model(
73
+ cfg_mgr: ConfigManager,
74
+ cockpit: AgentCockpit,
75
+ provider: str,
76
+ api_key: Optional[str] = None,
77
+ api_base: Optional[str] = None,
78
+ current_model: str = "",
79
+ filter_text: str = "",
80
+ ) -> Optional[str]:
81
+ """Query live endpoint models and present interactive selector (or custom fallback input)."""
82
+ key = api_key if api_key is not None else cfg_mgr.resolve_api_key(provider)
83
+ base = api_base or cfg_mgr.resolve_api_base(provider)
84
+
85
+ def _query_and_filter() -> List[Dict[str, Any]]:
86
+ print(style(f" Querying models from {provider} ({base or 'default'})...", fg=cockpit.theme.info))
87
+ models, err = fetch_endpoint_models(provider=provider, api_key=key, api_base=base)
88
+ if err:
89
+ print(style(f" ! Could not list models from endpoint: {err}", fg=cockpit.theme.warning))
90
+ elif not models:
91
+ print(style(" ! Endpoint returned zero models.", fg=cockpit.theme.warning))
92
+ return [
93
+ m for m in models
94
+ if not filter_text or filter_text.lower() in m["id"].lower()
95
+ ]
96
+
97
+ if sys.stdin.isatty():
98
+ with cockpit.alt_screen():
99
+ filtered = _query_and_filter()
100
+ if filtered:
101
+ if len(filtered) > 18:
102
+ _render_models_table(cockpit, provider, base or "", filtered, active_model=current_model)
103
+ sub_filter = cockpit.tui.input("Filter model name (or press Enter to browse top 18)")
104
+ if sub_filter:
105
+ narrowed = [m for m in filtered if sub_filter.lower() in m["id"].lower()]
106
+ if narrowed:
107
+ filtered = narrowed
108
+
109
+ display_opts = []
110
+ for m in filtered[:25]:
111
+ label = style(m["id"], fg=cockpit.theme.subheads)
112
+ if m.get("info"):
113
+ label += " " + style(f"({m['info']})", fg=MUTED_GREY)
114
+ if m["id"] == current_model:
115
+ label += " " + style("[active]", fg=cockpit.theme.success)
116
+ display_opts.append(label)
117
+ custom_opt = style("[Type a custom model ID manually]", fg=cockpit.theme.dim)
118
+ display_opts.append(custom_opt)
119
+ idx = cockpit.select_menu(f"Choose model ({len(filtered)} available)", display_opts, default_index=0)
120
+ if idx is None:
121
+ return None
122
+ if idx == len(display_opts) - 1:
123
+ manual = cockpit.tui.input("Enter Model ID", default=current_model or DEFAULT_MODELS.get(provider, ""))
124
+ return manual.strip() or None
125
+ return filtered[idx]["id"]
126
+
127
+ default_id = current_model or DEFAULT_MODELS.get(provider, "")
128
+ manual = cockpit.tui.input("Enter Model ID", default=default_id)
129
+ return manual.strip() or None
130
+
131
+ filtered = _query_and_filter()
132
+ default_id = current_model or (filtered[0]["id"] if filtered else DEFAULT_MODELS.get(provider, ""))
133
+ return default_id or None
134
+
135
+
136
+ def _run_provider_wizard(
137
+ cfg_mgr: ConfigManager,
138
+ cockpit: AgentCockpit,
139
+ agent: Optional[FrontierAgent] = None,
140
+ preset_provider: Optional[str] = None,
141
+ preset_base: Optional[str] = None,
142
+ ) -> bool:
143
+ """Interactive provider, custom endpoint URL, API key & live model selection wizard."""
144
+ provider_labels = [
145
+ "gemini Google Gemini API",
146
+ "openai OpenAI Platform",
147
+ "anthropic Anthropic Claude API",
148
+ "openrouter OpenRouter Multi-Model Gateway",
149
+ "deepseek DeepSeek API",
150
+ "groq Groq Fast Inference",
151
+ "nvidia NVIDIA NIM API (integrate.api.nvidia.com)",
152
+ "ollama Local Ollama (Offline / No Key)",
153
+ "custom Custom Endpoint URL (vLLM / LM Studio / Proxy / Mistral / Together)",
154
+ ]
155
+
156
+ with cockpit.alt_screen():
157
+ if preset_provider:
158
+ prov = preset_provider.strip().lower()
159
+ else:
160
+ default_idx = 0
161
+ if agent and agent.router.active_provider in ALL_PROVIDERS:
162
+ default_idx = ALL_PROVIDERS.index(agent.router.active_provider)
163
+ chosen = cockpit.select_menu("Choose LLM Provider", [style(p, fg=cockpit.theme.subheads) for p in provider_labels], default_index=default_idx)
164
+ if chosen is None:
165
+ print(style(" Cancelled provider setup.\n", fg=cockpit.theme.warning))
166
+ return False
167
+ prov = provider_labels[chosen].split()[0]
168
+
169
+ existing_base = preset_base or cfg_mgr.resolve_api_base(prov) or DEFAULT_BASES.get(prov, "")
170
+ new_base: Optional[str] = preset_base
171
+ if prov in ("custom", "ollama") and not preset_base:
172
+ hint_ex = "http://localhost:11434" if prov == "ollama" else "http://localhost:8000/v1"
173
+ while True:
174
+ url_in = cockpit.tui.input(f"Endpoint Base URL (e.g. {hint_ex})", default=existing_base)
175
+ candidate = url_in.strip() or existing_base
176
+ if candidate.startswith(("http://", "https://")):
177
+ new_base = candidate.rstrip("/")
178
+ break
179
+ print(style(" ! URL must start with http:// or https:// (use the next prompt for API keys).", fg=cockpit.theme.warning))
180
+ elif new_base and not new_base.startswith(("http://", "https://")):
181
+ print(style(f" ! Invalid endpoint URL '{new_base}' — must begin with http:// or https://.\n", fg=cockpit.theme.error))
182
+ return False
183
+
184
+ existing_key = cfg_mgr.resolve_api_key(prov)
185
+ new_key: Optional[str] = None
186
+ if prov != "ollama":
187
+ cur_hint = f" [current: {mask_secret(existing_key)} — Enter to keep]" if existing_key else (" [optional for local]" if prov == "custom" else " [Ctrl+V to paste]")
188
+ entered_key = _read_secret_or_line(f" {style('❯', fg=cockpit.theme.info, bold=True)} API Key for {prov}{cur_hint}: ")
189
+ if entered_key:
190
+ new_key = entered_key
191
+
192
+ chosen_model = _fetch_and_pick_model(
193
+ cfg_mgr=cfg_mgr,
194
+ cockpit=cockpit,
195
+ provider=prov,
196
+ api_key=new_key if new_key is not None else existing_key,
197
+ api_base=new_base or existing_base,
198
+ current_model=agent.router.active_model if (agent and agent.router.active_provider == prov) else "",
199
+ )
200
+
201
+ if not chosen_model:
202
+ print(style(" Cancelled provider setup.\n", fg=cockpit.theme.warning))
203
+ return False
204
+
205
+ cfg_mgr.set_provider_config(
206
+ provider=prov,
207
+ api_key=new_key,
208
+ api_base=new_base,
209
+ model=chosen_model,
210
+ set_default=True,
211
+ )
212
+ if agent is not None:
213
+ agent.router.switch_model(
214
+ provider=prov,
215
+ model=chosen_model,
216
+ api_base=new_base,
217
+ api_key=new_key,
218
+ persist=True,
219
+ )
220
+
221
+ eff_base = cfg_mgr.resolve_api_base(prov, new_base)
222
+ print(style(f"\n ✓ Active Provider: {prov} ({eff_base or 'default'})", fg=cockpit.theme.success, bold=True))
223
+ print(style(f" ✓ Active Model: {chosen_model}\n", fg=cockpit.theme.success, bold=True))
224
+ return True
225
+
226
+
227
+ def _resolve_media_path(raw_path: str, workspace: Path) -> Optional[Path]:
228
+ return resolve_media_path(raw_path, workspace)
229
+
230
+
231
+ def _parse_attachments_from_prompt(prompt: str, workspace: Path) -> tuple[str, List[Attachment]]:
232
+ """Extract @mentions and dragged/quoted local image, audio, video, PDF, or file paths."""
233
+ return extract_media_attachments(prompt, workspace, strip_media_tokens=False, keep_at_mentions=True)
234
+
235
+
236
+ def handle_slash_command(
237
+ raw_cmd: str,
238
+ agent: FrontierAgent,
239
+ cockpit: AgentCockpit,
240
+ staged_attachments: Optional[List[Attachment]] = None,
241
+ ) -> tuple[bool, Optional[str]]:
242
+ """
243
+ Execute interactive slash command cleanly.
244
+ Returns (should_continue_repl, optional_prompt_to_send_to_agent).
245
+ """
246
+ parts = raw_cmd.strip().split(maxsplit=1)
247
+ cmd = parts[0].lower()
248
+ arg = parts[1].strip() if len(parts) > 1 else ""
249
+
250
+ if cmd in ("/exit", "/quit", "/q"):
251
+ print(style("\nSaving session trace and exiting FrontierAgent. Goodbye!\n", fg=cockpit.theme.dim))
252
+ return False, None
253
+
254
+ if cmd in ("/help", "/?"):
255
+ cockpit.show_shortcuts_help()
256
+ return True, None
257
+
258
+ if cmd == "/paste":
259
+ if staged_attachments is None:
260
+ print(style(" ! Clipboard staging is only available in interactive mode.\n", fg=cockpit.theme.warning))
261
+ return True, None
262
+ atts, clip_txt = capture_clipboard_attachment(agent.workspace)
263
+ candidates = list(atts)
264
+ if not candidates and clip_txt:
265
+ _, candidates = extract_media_attachments(clip_txt, agent.workspace, strip_media_tokens=False)
266
+ seen_p = {a.path for a in staged_attachments if a.path}
267
+ added = 0
268
+ for att in candidates:
269
+ if not att.path or att.path not in seen_p:
270
+ staged_attachments.append(att)
271
+ added += 1
272
+ if att.path:
273
+ seen_p.add(att.path)
274
+ if not added:
275
+ if clip_txt:
276
+ print(style(" ! Clipboard contains text rather than an image/media file. Type your message directly or pass `/attach <path>`.\n", fg=cockpit.theme.dim))
277
+ else:
278
+ print(style(" ! Clipboard does not currently contain a screenshot or media file.\n", fg=cockpit.theme.dim))
279
+ return True, None
280
+
281
+ if cmd in ("/attach", "/media"):
282
+ if staged_attachments is None:
283
+ print(style(" ! Attachment staging is only available in interactive mode.\n", fg=cockpit.theme.warning))
284
+ return True, None
285
+ if not arg or arg.lower() == "list":
286
+ if not staged_attachments:
287
+ print(style(" Usage: /attach <file_or_media_path> [more files...] (supports images, audio, video, PDF, text)\n", fg=cockpit.theme.dim))
288
+ else:
289
+ print(style(f" Staged: {format_attachments_summary(staged_attachments)}", fg=cockpit.theme.info))
290
+ for att in staged_attachments:
291
+ print(f" • [{att.media_kind.upper()}] {att.label} ({att.mime_type}, {att.size_human})")
292
+ print()
293
+ return True, None
294
+ if arg.lower() == "clear":
295
+ staged_attachments.clear()
296
+ print(style(" ✓ Cleared staged attachments.\n", fg=cockpit.theme.success))
297
+ return True, None
298
+ import shlex
299
+ try:
300
+ tokens = shlex.split(arg, posix=False)
301
+ except ValueError:
302
+ tokens = arg.split()
303
+ seen_p = {a.path for a in staged_attachments if a.path}
304
+ for tok in tokens:
305
+ cand = _resolve_media_path(tok, agent.workspace)
306
+ if cand:
307
+ if str(cand) not in seen_p:
308
+ staged_attachments.append(Attachment.from_path(str(cand)))
309
+ seen_p.add(str(cand))
310
+ else:
311
+ print(style(f" ! File not found: {tok}", fg=cockpit.theme.warning))
312
+ return True, None
313
+
314
+ if cmd == "/clear":
315
+ agent.clear()
316
+ print(style(" ✓ Conversation context cleared (FRONTIER.md & episodic memory retained).\n", fg=cockpit.theme.success))
317
+ return True, None
318
+
319
+ if cmd == "/init":
320
+ fpath = initialize_frontier_md(agent.workspace)
321
+ agent.refresh_system_prompt()
322
+ print(style(f" ✓ Created {fpath.name} and updated agent context.\n", fg=cockpit.theme.success))
323
+ return True, None
324
+
325
+ if cmd == "/compact":
326
+ n = agent.compact()
327
+ print(style(f" ✓ Compacted {n} historical messages. Context usage: {int(agent.memory.context_usage_ratio * 100)}%\n", fg=cockpit.theme.success))
328
+ return True, None
329
+
330
+ if cmd == "/undo":
331
+ res = agent.undo()
332
+ if res.get("success"):
333
+ reverted = res.get("reverted_files", [])
334
+ deleted = res.get("deleted_files", [])
335
+ print(style(f" ✓ Reverted checkpoint {res.get('checkpoint_id')} ({len(reverted)} restored, {len(deleted)} removed).\n", fg=cockpit.theme.success))
336
+ else:
337
+ print(style(f" ! {res.get('error', 'No checkpoints to revert.')}\n", fg=cockpit.theme.warning))
338
+ return True, None
339
+
340
+ if cmd == "/checkpoints":
341
+ cps = agent.list_checkpoints()
342
+ if not cps:
343
+ print(style(" (No checkpoints saved yet in this session.)\n", fg=cockpit.theme.dim))
344
+ else:
345
+ print(cockpit.md.render("### Saved Session Checkpoints\n"))
346
+ for cp in cps[-10:]:
347
+ print(f" • {style(cp['checkpoint_id'], fg=cockpit.theme.info, bold=True)} — {cp['label']} ({cp['file_count']} files)")
348
+ print()
349
+ return True, None
350
+
351
+ if cmd == "/diff":
352
+ diff_txt = agent.tools.ws_tools.git_diff()
353
+ print(cockpit.md.render(f"```diff\n{diff_txt}\n```"))
354
+ return True, None
355
+
356
+ if cmd == "/verify":
357
+ test_cmd = arg or agent.tools.detect_test_command()
358
+ print(style(f" Running verification gate ({test_cmd or 'syntax check only'})...", fg=cockpit.theme.info))
359
+ report = agent.tools.verifier.verify_change(
360
+ modified_files=agent.memory.session.modified_files,
361
+ test_command=test_cmd,
362
+ cwd=str(agent.workspace),
363
+ )
364
+ badge = style("PASSED", fg=cockpit.theme.success, bold=True) if report.passed else style("FAILED", fg=cockpit.theme.error, bold=True)
365
+ print(f" Verification: {badge}")
366
+ if report.diagnostics:
367
+ print(style(report.diagnostics[:1000], fg=cockpit.theme.warning))
368
+ print()
369
+ return True, None
370
+
371
+ if cmd == "/search":
372
+ if not arg:
373
+ print(style(" Usage: /search <query>\n", fg=cockpit.theme.warning))
374
+ return True, None
375
+ print(style(f" Searching live web via SearchHarnes: {arg}...", fg=cockpit.theme.info))
376
+ results = agent.tools.search_engine.search(arg, max_results=4)
377
+ for i, r in enumerate(results, 1):
378
+ print(f" [{i}] {style(r.title, fg=cockpit.theme.subheads, bold=True)}")
379
+ print(f" {style(r.url, fg=cockpit.theme.info)}")
380
+ print(f" {style(r.snippet[:160], fg=cockpit.theme.dim)}")
381
+ if results:
382
+ summary_src = "\n".join(f"[{r.title}] {r.snippet} ({r.url})" for r in results)
383
+ agent.memory.add_evidence(f"search:{arg}", summary_src)
384
+ print()
385
+ return True, None
386
+
387
+ if cmd == "/ground":
388
+ if arg.lower() in ("on", "true", "1"):
389
+ agent.config.enable_grounding = True
390
+ elif arg.lower() in ("off", "false", "0"):
391
+ agent.config.enable_grounding = False
392
+ else:
393
+ agent.config.enable_grounding = not agent.config.enable_grounding
394
+ state = "ON" if agent.config.enable_grounding else "OFF"
395
+ print(style(f" ✓ GroundAnchor auto-verification: {state}\n", fg=cockpit.theme.success))
396
+ return True, None
397
+
398
+ if cmd == "/effort":
399
+ if arg:
400
+ try:
401
+ agent.config.effort = EffortLevel(arg.lower())
402
+ except ValueError:
403
+ print(style(" Valid effort tiers: low, medium, high, xhigh\n", fg=cockpit.theme.warning))
404
+ return True, None
405
+ else:
406
+ agent.config.effort = EffortLevel.cycle(agent.config.effort)
407
+ print(style(f" ✓ Reasoning effort set to: {agent.config.effort.value}\n", fg=cockpit.theme.success))
408
+ return True, None
409
+
410
+ if cmd in ("/provider", "/setup"):
411
+ _run_provider_wizard(agent.config_mgr, cockpit, agent=agent, preset_provider=arg or None)
412
+ return True, None
413
+
414
+ if cmd in ("/key", "/apikey"):
415
+ parts_k = arg.split(maxsplit=1) if arg else []
416
+ if len(parts_k) == 2:
417
+ prov_k, secret_k = parts_k[0].lower(), parts_k[1].strip()
418
+ agent.config_mgr.set_provider_config(provider=prov_k, api_key=secret_k, set_default=True)
419
+ agent.router.switch_model(prov_k, api_key=secret_k)
420
+ print(style(f" ✓ Saved API key ({mask_secret(secret_k)}) for '{prov_k}' -> model '{agent.router.active_model}'.\n", fg=cockpit.theme.success))
421
+ return True, None
422
+
423
+ if len(parts_k) == 1 and parts_k[0].lower() in ALL_PROVIDERS:
424
+ prov_k = parts_k[0].lower()
425
+ sec = _read_secret_or_line(f" 🔑 Enter API Key for {prov_k}: ")
426
+ if sec:
427
+ agent.config_mgr.set_provider_config(provider=prov_k, api_key=sec, set_default=True)
428
+ agent.router.switch_model(prov_k, api_key=sec)
429
+ print(style(f" ✓ Saved API key ({mask_secret(sec)}) for '{prov_k}'.\n", fg=cockpit.theme.success))
430
+ return True, None
431
+
432
+ # No valid args: run clean alternate-screen key manager so scrollback stays spotless
433
+ if sys.stdin.isatty():
434
+ updated_msg: Optional[str] = None
435
+ with cockpit.alt_screen():
436
+ rows = ["| Provider | API Key | Endpoint Base |", "| :--- | :--- | :--- |"]
437
+ for p_name in ALL_PROVIDERS:
438
+ k_val = agent.config_mgr.resolve_api_key(p_name)
439
+ b_val = agent.config_mgr.resolve_api_base(p_name) or "(not set)"
440
+ rows.append(f"| `{p_name}` | {mask_secret(k_val)} | {b_val} |")
441
+ print(cockpit.md.render("### Configured Providers & Keys\n\n" + "\n".join(rows)))
442
+ opts = [style(p, fg=cockpit.theme.subheads) for p in ALL_PROVIDERS] + [style("Cancel", fg=MUTED_GREY)]
443
+ pick = cockpit.select_menu("Select provider to enter/update API key", opts, default_index=0)
444
+ if pick is not None and pick < len(ALL_PROVIDERS):
445
+ prov_k = ALL_PROVIDERS[pick]
446
+ sec = _read_secret_or_line(f" 🔑 Enter API Key for {prov_k}: ")
447
+ if sec:
448
+ agent.config_mgr.set_provider_config(provider=prov_k, api_key=sec, set_default=True)
449
+ agent.router.switch_model(prov_k, api_key=sec)
450
+ updated_msg = f" ✓ Updated key for '{prov_k}' and activated {agent.router.active_model}.\n"
451
+ if updated_msg:
452
+ print(style(updated_msg, fg=cockpit.theme.success))
453
+ else:
454
+ rows = ["| Provider | API Key | Endpoint Base |", "| :--- | :--- | :--- |"]
455
+ for p_name in ALL_PROVIDERS:
456
+ k_val = agent.config_mgr.resolve_api_key(p_name)
457
+ b_val = agent.config_mgr.resolve_api_base(p_name) or "(not set)"
458
+ rows.append(f"| `{p_name}` | {mask_secret(k_val)} | {b_val} |")
459
+ print(cockpit.md.render("### Configured Providers & Keys\n\n" + "\n".join(rows)))
460
+ return True, None
461
+
462
+ if cmd in ("/endpoint", "/custom"):
463
+ ep_parts = arg.split(maxsplit=1) if arg else []
464
+ ep_url = ep_parts[0] if ep_parts else None
465
+ ep_key = ep_parts[1].strip() if len(ep_parts) == 2 else None
466
+ if ep_key:
467
+ agent.config_mgr.set_provider_config("custom", api_key=ep_key, api_base=ep_url, set_default=False)
468
+ _run_provider_wizard(agent.config_mgr, cockpit, agent=agent, preset_provider="custom", preset_base=ep_url)
469
+ return True, None
470
+
471
+ if cmd == "/models":
472
+ prov = agent.router.active_provider
473
+ if prov == "unconfigured":
474
+ print(style(" ! No active provider configured yet. Run `/provider` or `/endpoint` first.\n", fg=cockpit.theme.warning))
475
+ return True, None
476
+ key = agent.config_mgr.resolve_api_key(prov, agent.config.api_key)
477
+ base = agent.config_mgr.resolve_api_base(prov, agent.config.api_base)
478
+ print(style(f" Fetching live model catalog from {prov} ({base or 'default'})...", fg=cockpit.theme.info))
479
+ models, err = fetch_endpoint_models(prov, api_key=key, api_base=base)
480
+ if err:
481
+ print(style(f" ! {err}\n", fg=cockpit.theme.warning))
482
+ else:
483
+ _render_models_table(cockpit, prov, base or "", models, active_model=agent.router.active_model, filter_text=arg)
484
+ return True, None
485
+
486
+ if cmd == "/model":
487
+ if not arg:
488
+ prov = agent.router.active_provider
489
+ if prov == "unconfigured":
490
+ _run_provider_wizard(agent.config_mgr, cockpit, agent=agent)
491
+ return True, None
492
+ if prov not in ("ollama", "custom") and not agent.config_mgr.resolve_api_key(prov, agent.config.api_key) and sys.stdin.isatty():
493
+ sec = _read_secret_or_line(f" {style('❯', fg=cockpit.theme.info, bold=True)} API Key for {prov} [Ctrl+V to paste]: ")
494
+ if sec:
495
+ agent.config_mgr.set_provider_config(provider=prov, api_key=sec, set_default=False)
496
+ picked = _fetch_and_pick_model(
497
+ cfg_mgr=agent.config_mgr,
498
+ cockpit=cockpit,
499
+ provider=prov,
500
+ api_key=agent.config.api_key,
501
+ api_base=agent.config.api_base,
502
+ current_model=agent.router.active_model,
503
+ )
504
+ if picked:
505
+ agent.router.switch_model(prov, model=picked)
506
+ print(style(f" ✓ Switched to {agent.router.active_provider}:{agent.router.active_model}\n", fg=cockpit.theme.success))
507
+ elif ":" in arg:
508
+ # Handle both `provider:model` and Ollama tags like `qwen2.5:14b` when left half is a known provider
509
+ head, tail = arg.split(":", 1)
510
+ if head.lower() in ALL_PROVIDERS:
511
+ agent.router.switch_model(head.lower(), tail)
512
+ else:
513
+ agent.router.switch_model(agent.router.active_provider, arg)
514
+ print(style(f" ✓ Switched to {agent.router.active_provider}:{agent.router.active_model}\n", fg=cockpit.theme.success))
515
+ elif arg.lower() in ALL_PROVIDERS:
516
+ prov_t = arg.lower()
517
+ if prov_t not in ("ollama", "custom") and not agent.config_mgr.resolve_api_key(prov_t) and sys.stdin.isatty():
518
+ sec = _read_secret_or_line(f" {style('❯', fg=cockpit.theme.info, bold=True)} API Key for {prov_t} [Ctrl+V to paste]: ")
519
+ if sec:
520
+ agent.config_mgr.set_provider_config(provider=prov_t, api_key=sec, set_default=False)
521
+ picked = _fetch_and_pick_model(cfg_mgr=agent.config_mgr, cockpit=cockpit, provider=prov_t)
522
+ agent.router.switch_model(prov_t, model=picked)
523
+ print(style(f" ✓ Switched to {agent.router.active_provider}:{agent.router.active_model}\n", fg=cockpit.theme.success))
524
+ else:
525
+ prov = agent.router.active_provider
526
+ if prov == "unconfigured":
527
+ print(style(" ! Choose provider first with `/provider` or pass `/model provider:model_id`.\n", fg=cockpit.theme.warning))
528
+ return True, None
529
+ agent.router.switch_model(prov, model=arg)
530
+ print(style(f" ✓ Switched to {agent.router.active_provider}:{agent.router.active_model}\n", fg=cockpit.theme.success))
531
+ return True, None
532
+
533
+ if cmd == "/skills":
534
+ skills = agent.skills.list_skills()
535
+ if arg.startswith("pin "):
536
+ sk_name = arg[4:].strip()
537
+ if agent.skills.pin_skill(sk_name):
538
+ agent.refresh_system_prompt()
539
+ print(style(f" ✓ Pinned skill '{sk_name}' into active instructions.\n", fg=cockpit.theme.success))
540
+ else:
541
+ print(style(f" ! Skill '{sk_name}' not found.\n", fg=cockpit.theme.warning))
542
+ return True, None
543
+ if arg.startswith("unpin "):
544
+ sk_name = arg[6:].strip()
545
+ if agent.skills.unpin_skill(sk_name):
546
+ agent.refresh_system_prompt()
547
+ print(style(f" ✓ Unpinned skill '{sk_name}'.\n", fg=cockpit.theme.success))
548
+ else:
549
+ print(style(f" ! Skill '{sk_name}' is not pinned.\n", fg=cockpit.theme.warning))
550
+ return True, None
551
+ if arg.startswith("install "):
552
+ src_raw = arg[8:].strip().strip("\"'")
553
+ if not src_raw:
554
+ print(style(" Usage: /skills install <path-to-skill-dir>\n", fg=cockpit.theme.warning))
555
+ return True, None
556
+ try:
557
+ installed = agent.skills.install_skill(Path(src_raw).expanduser())
558
+ agent.refresh_system_prompt()
559
+ print(style(f" ✓ Installed skill '{installed.name}' into {agent.skills.frontier_skills_dir}\n", fg=cockpit.theme.success))
560
+ except Exception as exc:
561
+ print(style(f" ! Failed to install skill: {exc}\n", fg=cockpit.theme.error))
562
+ return True, None
563
+ if arg.startswith("show "):
564
+ sk_name = arg[5:].strip()
565
+ data = agent.skills.load_skill_content(sk_name)
566
+ if not data.get("success"):
567
+ print(style(f" ! {data.get('error', 'Skill not found.')}\n", fg=cockpit.theme.warning))
568
+ else:
569
+ print(cockpit.md.render(f"### Skill: `{data['name']}`\n\n`{data['path']}`\n\n{data['instructions'][:4000]}"))
570
+ return True, None
571
+ print(style(f" Skills root: {agent.skills.frontier_skills_dir}", fg=MUTED_GREY))
572
+ if not skills:
573
+ print(style(" (No SKILL.md modules found.)\n", fg=cockpit.theme.dim))
574
+ else:
575
+ rows = ["| Skill | Status | Scripts | Description |", "| :--- | :--- | :--- | :--- |"]
576
+ for sk in skills:
577
+ status_tag = "`PINNED`" if sk.name in agent.skills.pinned_skills else (
578
+ "auto-used" if sk.name in agent.skills.used_skills else "discovered"
579
+ )
580
+ scr = str(len(sk.scripts)) if sk.scripts else "-"
581
+ rows.append(f"| `{sk.name}` | {status_tag} | {scr} | {' '.join(sk.description.split())[:62]} |")
582
+ print(cockpit.md.render("\n".join(rows)))
583
+ return True, None
584
+
585
+ if cmd == "/theme":
586
+ if arg in THEMES:
587
+ cockpit.set_theme(arg)
588
+ print(style(f" ✓ Theme switched to '{arg}'.\n", fg=cockpit.theme.success))
589
+ else:
590
+ print(style(f" Available themes: {', '.join(THEMES.keys())}\n", fg=cockpit.theme.warning))
591
+ return True, None
592
+
593
+ if cmd == "/stats":
594
+ last_turn = agent.memory.completed_turns[-1] if agent.memory.completed_turns else None
595
+ ctx_pct = int(agent.memory.context_usage_ratio * 100)
596
+ card = cockpit.tui.metrics(
597
+ model=f"{agent.router.active_provider}:{agent.router.active_model}",
598
+ latency_s=last_turn.duration_s if last_turn else 0.0,
599
+ prompt_tokens=last_turn.prompt_tokens if last_turn else 0,
600
+ completion_tokens=last_turn.completion_tokens if last_turn else 0,
601
+ cost_usd=agent.total_cost_usd,
602
+ )
603
+ print(card)
604
+ from loopcircuit import CircuitState
605
+ c_label = "NORMAL" if agent.loop.circuit.state == CircuitState.CLOSED else agent.loop.circuit.state.value.upper()
606
+ print(
607
+ cockpit.tui.hud(
608
+ steps=str(len(agent.memory.completed_turns)),
609
+ cost=f"${agent.total_cost_usd:.4f}",
610
+ memory=f"{ctx_pct}%",
611
+ circuit=c_label,
612
+ grounded="ON" if agent.config.enable_grounding else "OFF",
613
+ )
614
+ )
615
+ print()
616
+ return True, None
617
+
618
+ if cmd == "/btw":
619
+ question = arg
620
+ if not question and sys.stdin.isatty():
621
+ question = cockpit.tui.input("Quick /btw side question").strip()
622
+ if sys.stdout.isatty():
623
+ erase_terminal_rows(1)
624
+ if not question:
625
+ print(style(" Usage: /btw <quick side question>\n", fg=cockpit.theme.warning))
626
+ return True, None
627
+ ans = agent.btw(question)
628
+ print(cockpit.md.render(f"### /btw Side Answer\n\n{ans}"))
629
+ return True, None
630
+
631
+ if cmd in ("/resume", "/sessions"):
632
+ sessions = agent.list_saved_sessions()
633
+ if not sessions:
634
+ print(style(" (No previous sessions saved yet. Complete at least one turn first.)\n", fg=MUTED_GREY))
635
+ return True, None
636
+
637
+ picked: Optional[Dict[str, Any]] = None
638
+ if arg:
639
+ # Allow `/resume <id_prefix>` or `/resume <1-based-index>`
640
+ if arg.isdigit() and 1 <= int(arg) <= len(sessions):
641
+ picked = sessions[int(arg) - 1]
642
+ else:
643
+ for s in sessions:
644
+ if s["session_id"].startswith(arg) or arg in s["session_id"]:
645
+ picked = s
646
+ break
647
+ if picked is None:
648
+ print(style(f" ! No saved session matching '{arg}'.\n", fg=cockpit.theme.warning))
649
+ return True, None
650
+ elif sys.stdin.isatty():
651
+ opts: List[str] = []
652
+ for idx_s, s in enumerate(sessions[:12], 1):
653
+ ts_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(s["updated_at"]))
654
+ prev = (s["preview"] or "").replace("\n", " ")[:44]
655
+ if len(s["preview"] or "") > 44:
656
+ prev += "..."
657
+ meta = f"{s['turn_count']} turns · {s['model'] or s['provider'] or 'model'}"
658
+ opts.append(
659
+ f"{style(f'{idx_s}.', fg=cockpit.theme.info, bold=True)} "
660
+ f"{style(ts_str, fg=MUTED_GREY)} {style(prev, fg=cockpit.theme.subheads)} "
661
+ f"{style(f'({meta})', fg=MUTED_GREY)}"
662
+ )
663
+ opts.append(style("Cancel", fg=MUTED_GREY))
664
+ sel = cockpit.select_menu(f"Resume Past Session ({len(sessions)} available)", opts, default_index=0)
665
+ if sel is None or sel >= min(len(sessions), 12):
666
+ return True, None
667
+ picked = sessions[sel]
668
+ else:
669
+ picked = sessions[0]
670
+
671
+ meta = agent.resume_session(Path(picked["path"]))
672
+ if meta.get("provider") in ALL_PROVIDERS and meta.get("model"):
673
+ try:
674
+ agent.router.switch_model(meta["provider"], model=meta["model"])
675
+ except Exception:
676
+ pass
677
+ print(
678
+ style(
679
+ f" ✓ Resumed session {agent.memory.session_id} "
680
+ f"({len(agent.memory.completed_turns)} turns, {len(agent.memory.messages) - 1} messages · \"{picked['preview'][:50]}\")\n",
681
+ fg=cockpit.theme.success,
682
+ )
683
+ )
684
+ return True, None
685
+
686
+ if cmd == "/rewind":
687
+ rps = agent.memory.rewind_points
688
+ if not rps:
689
+ print(style(" (No completed prompts in this session yet to rewind.)\n", fg=MUTED_GREY))
690
+ return True, None
691
+
692
+ recent = rps[-5:]
693
+ target_rp = None
694
+ if arg and arg.isdigit():
695
+ t_num = int(arg)
696
+ for rp in rps:
697
+ if rp.turn_number == t_num:
698
+ target_rp = rp
699
+ break
700
+ if target_rp is None and 1 <= t_num <= len(recent):
701
+ target_rp = recent[t_num - 1]
702
+ if target_rp is None:
703
+ print(style(f" ! Turn #{t_num} not found in recent prompts.\n", fg=cockpit.theme.warning))
704
+ return True, None
705
+ elif sys.stdin.isatty():
706
+ opts = []
707
+ for rp in recent:
708
+ preview = " ".join(rp.user_prompt.split())[:48]
709
+ if len(rp.user_prompt.strip()) > 48:
710
+ preview += "..."
711
+ if rp.lines_added or rp.lines_removed:
712
+ diff_badge = (
713
+ f"{style(f'+{rp.lines_added}', fg=cockpit.theme.success, bold=True)} "
714
+ f"{style(f'-{rp.lines_removed}', fg=cockpit.theme.error, bold=True)}"
715
+ )
716
+ if rp.files_touched:
717
+ diff_badge += f" {style(f'({len(rp.files_touched)} file)', fg=MUTED_GREY)}"
718
+ elif rp.commands_run:
719
+ diff_badge = style(f"({len(rp.commands_run)} cmd)", fg=cockpit.theme.warning)
720
+ else:
721
+ diff_badge = style("(no file changes)", fg=MUTED_GREY)
722
+
723
+ opts.append(
724
+ f"{style(f'#{rp.turn_number}', fg=cockpit.theme.info, bold=True)} "
725
+ f"{style(preview, fg=cockpit.theme.subheads)} {diff_badge}"
726
+ )
727
+ opts.append(style("Cancel (keep current state)", fg=MUTED_GREY))
728
+ sel = cockpit.select_menu(
729
+ "Rewind chat & workspace edits to BEFORE which prompt? (last 5 prompts)",
730
+ opts,
731
+ default_index=max(0, len(recent) - 1),
732
+ )
733
+ if sel is None or sel >= len(recent):
734
+ return True, None
735
+ target_rp = recent[sel]
736
+ else:
737
+ target_rp = recent[-1]
738
+
739
+ res = agent.rewind_to(target_rp.turn_number)
740
+ if not res.get("success"):
741
+ print(style(f" ! {res.get('error', 'Rewind failed.')}\n", fg=cockpit.theme.warning))
742
+ return True, None
743
+
744
+ rev_n = len(res.get("reverted_files", []))
745
+ del_n = len(res.get("deleted_files", []))
746
+ print(
747
+ style(
748
+ f" ✓ Rewound {res['rewound_turns']} prompt(s) back to before #{res['target_turn_number']} "
749
+ f"({rev_n} file(s) restored, {del_n} deleted · "
750
+ f"+{res['lines_reverted_added']}/-{res['lines_reverted_removed']} lines undone)\n",
751
+ fg=cockpit.theme.success,
752
+ )
753
+ )
754
+ cmds_ran = res.get("commands_that_ran") or []
755
+ if cmds_ran:
756
+ print(style(f" ! Note: {len(cmds_ran)} shell command(s) ran during rewound turns ({', '.join(cmds_ran[:3])}); external side effects outside tracked files are not auto-undone.\n", fg=cockpit.theme.warning))
757
+ return True, None
758
+
759
+ if cmd in ("/run-command", "/run", "/sh"):
760
+ shell_cmd = arg
761
+ if not shell_cmd and sys.stdin.isatty():
762
+ shell_cmd = cockpit.tui.input("Command to execute in workspace").strip()
763
+ if sys.stdout.isatty():
764
+ erase_terminal_rows(1)
765
+ if not shell_cmd:
766
+ print(style(" Usage: /run-command <shell command> (or `!command`)\n", fg=cockpit.theme.warning))
767
+ return True, None
768
+ ok, out, err, rec = agent.run_direct_command(shell_cmd)
769
+ badge = style("✓", fg=cockpit.theme.success, bold=True) if ok else style("✗", fg=cockpit.theme.error, bold=True)
770
+ print(f" {badge} {style('$ ' + shell_cmd, fg=cockpit.theme.subheads, bold=True)} {style(f'[{rec.duration_ms:.0f}ms]', fg=MUTED_GREY)}")
771
+ body = (out or err or "").strip()
772
+ if body:
773
+ print(body)
774
+ print()
775
+ return True, None
776
+
777
+ if cmd == "/mode":
778
+ if not arg:
779
+ print(style(f" Current autonomy mode: {agent.config.mode.value} — {agent.config.mode.description}\n", fg=cockpit.theme.info))
780
+ return True, None
781
+ try:
782
+ agent.config.mode = AutonomyMode(arg.lower())
783
+ print(style(f" ✓ Switched mode to: {agent.config.mode.value}\n", fg=cockpit.theme.success))
784
+ except ValueError:
785
+ print(style(" Valid modes: safe, auto, plan, yolo\n", fg=cockpit.theme.warning))
786
+ return True, None
787
+
788
+ if cmd == "/copy":
789
+ ans = next((t.final_answer for t in reversed(agent.memory.completed_turns) if t.final_answer), "")
790
+ if not ans:
791
+ print(style(" (No assistant response in this session yet to copy.)\n", fg=MUTED_GREY))
792
+ return True, None
793
+ if copy_text_to_clipboard(ans):
794
+ print(style(f" ✓ Copied latest response ({len(ans)} chars) to clipboard.\n", fg=cockpit.theme.success))
795
+ else:
796
+ print(style(" ! Could not access OS clipboard cleanly.\n", fg=cockpit.theme.warning))
797
+ return True, None
798
+
799
+ if cmd == "/export":
800
+ exp_dir = agent.workspace / ".frontier" / "exports"
801
+ exp_dir.mkdir(parents=True, exist_ok=True)
802
+ out_path = Path(arg) if arg else (exp_dir / f"{agent.memory.session_id}.md")
803
+ if not out_path.is_absolute():
804
+ out_path = (agent.workspace / out_path).resolve()
805
+ md_lines = [
806
+ f"# FrontierAgent Session `{agent.memory.session_id}`",
807
+ f"- Model: `{agent.router.active_provider}:{agent.router.active_model}`",
808
+ f"- Workspace: `{agent.workspace}`",
809
+ f"- Total Cost: `${agent.total_cost_usd:.4f}` | Turns: `{len(agent.memory.completed_turns)}`",
810
+ "",
811
+ ]
812
+ for idx_t, t in enumerate(agent.memory.completed_turns, 1):
813
+ md_lines.append(f"## Turn {idx_t}: {t.user_prompt}")
814
+ if t.actions:
815
+ md_lines.append("**Actions:** " + ", ".join(f"`{a.tool_name}` ({a.summary})" for a in t.actions))
816
+ if t.final_answer:
817
+ md_lines.append("\n" + t.final_answer + "\n")
818
+ out_path.write_text("\n".join(md_lines), encoding="utf-8")
819
+ print(style(f" ✓ Exported {len(agent.memory.completed_turns)} turn(s) to {out_path}\n", fg=cockpit.theme.success))
820
+ return True, None
821
+
822
+ if cmd == "/context":
823
+ from frontierharness import TokenBudget
824
+ sys_len = len(agent.memory.messages[0].content) if agent.memory.messages else 0
825
+ conv_len = sum(len(m.content) + len(m.thought or "") for m in agent.memory.messages[1:])
826
+ max_tok = max(1, agent.memory.session.budget.max_context_tokens)
827
+ est_sys = TokenBudget.estimate_tokens("x" * sys_len)
828
+ est_conv = TokenBudget.estimate_tokens("x" * conv_len)
829
+ pct = min(100, int(((est_sys + est_conv) / max_tok) * 100))
830
+ files = agent.memory.session.modified_files
831
+ rows = [
832
+ "| Segment | Count / Size | Est. Tokens |",
833
+ "| :--- | :--- | :--- |",
834
+ f"| System prompt + skills | {sys_len:,} chars | ~{est_sys:,} |",
835
+ f"| Conversation history | {max(0, len(agent.memory.messages) - 1)} messages | ~{est_conv:,} |",
836
+ f"| Total budget usage | {pct}% of {max_tok:,} | ~{est_sys + est_conv:,} |",
837
+ f"| Tracked modified files | {len(files)} file(s) | {', '.join(files[-4:]) or '-'} |",
838
+ ]
839
+ print(cockpit.md.render("### Context Window Breakdown\n\n" + "\n".join(rows)))
840
+ return True, None
841
+
842
+ if cmd == "/cost":
843
+ turns = agent.memory.completed_turns
844
+ if not turns:
845
+ print(style(" (No completed turns yet — cost is $0.0000.)\n", fg=MUTED_GREY))
846
+ return True, None
847
+ rows = ["| Turn | Prompt | Tokens | Duration | Cost |", "| :--- | :--- | :--- | :--- | :--- |"]
848
+ for i, t in enumerate(turns, 1):
849
+ p_prev = " ".join(t.user_prompt.split())[:34].replace("|", "/")
850
+ toks = t.prompt_tokens + t.completion_tokens
851
+ rows.append(f"| #{i} | {p_prev} | {toks:,} | {t.duration_s:.2f}s | ${t.cost_usd:.4f} |")
852
+ rows.append(f"| **Total** | **{len(turns)} turns** | **{agent.total_tokens:,}** | - | **${agent.total_cost_usd:.4f}** |")
853
+ print(cockpit.md.render("### Session Token & Cost Breakdown\n\n" + "\n".join(rows)))
854
+ return True, None
855
+
856
+ if cmd == "/history":
857
+ rps = agent.memory.rewind_points
858
+ if not rps:
859
+ print(style(" (No prompts recorded in this session yet.)\n", fg=MUTED_GREY))
860
+ return True, None
861
+ limit = int(arg) if arg.isdigit() and int(arg) > 0 else 15
862
+ rows = ["| # | Prompt | File Changes | Commands |", "| :--- | :--- | :--- | :--- |"]
863
+ for rp in rps[-limit:]:
864
+ prev = " ".join(rp.user_prompt.split())[:48].replace("|", "/")
865
+ chg = f"+{rp.lines_added} / -{rp.lines_removed}" if (rp.lines_added or rp.lines_removed) else "-"
866
+ cmds_s = ", ".join(rp.commands_run[:2]) or "-"
867
+ rows.append(f"| #{rp.turn_number} | {prev} | `{chg}` | `{cmds_s}` |")
868
+ print(cockpit.md.render("### Prompt & Edit History\n\n" + "\n".join(rows)))
869
+ return True, None
870
+
871
+ if cmd == "/status":
872
+ prov = agent.router.active_provider
873
+ mod = agent.router.active_model
874
+ base = agent.config_mgr.resolve_api_base(prov, agent.config.api_base) or "default"
875
+ rows = [
876
+ "| Setting | Active Value |",
877
+ "| :--- | :--- |",
878
+ f"| Session ID | `{agent.memory.session_id}` |",
879
+ f"| Provider / Model | `{prov}` : `{mod}` |",
880
+ f"| Endpoint Base | `{base}` |",
881
+ f"| Mode / Effort | `{agent.config.mode.value}` / `{agent.config.effort.value}` |",
882
+ f"| GroundAnchor | `{'ON' if agent.config.enable_grounding else 'OFF'}` |",
883
+ f"| Turns / Checkpoints | {len(agent.memory.completed_turns)} turn(s) / {len(agent.list_checkpoints())} checkpoint(s) |",
884
+ ]
885
+ print(cockpit.md.render("### Active Session Status\n\n" + "\n".join(rows)))
886
+ return True, None
887
+
888
+ if cmd == "/doctor":
889
+ ns = argparse.Namespace(workspace=str(agent.workspace))
890
+ cmd_doctor(ns)
891
+ return True, None
892
+
893
+ if cmd == "/plan":
894
+ agent.config.mode = AutonomyMode.PLAN
895
+ if arg:
896
+ return True, f"Create a read-only architectural execution plan for: {arg}"
897
+ print(style(" ✓ Switched to PLAN (read-only) mode. Enter your goal below.\n", fg=cockpit.theme.info))
898
+ return True, None
899
+
900
+ print(style(f" Unknown command: {cmd}. Type /help for available commands.\n", fg=cockpit.theme.warning))
901
+ return True, None
902
+
903
+
904
+ def _collect_cli_overrides(args: argparse.Namespace, default_mode: Optional[str] = None) -> Dict[str, Any]:
905
+ overrides: Dict[str, Any] = {}
906
+ if default_mode:
907
+ overrides["mode"] = default_mode
908
+ if getattr(args, "provider", None):
909
+ overrides["provider"] = args.provider
910
+ if getattr(args, "model", None):
911
+ overrides["model"] = args.model
912
+ if getattr(args, "base_url", None):
913
+ overrides["api_base"] = args.base_url
914
+ if getattr(args, "theme", None):
915
+ overrides["theme"] = args.theme
916
+ if getattr(args, "mode", None):
917
+ overrides["mode"] = args.mode
918
+ if getattr(args, "sandbox", None) == "docker":
919
+ overrides["use_docker"] = True
920
+ return overrides
921
+
922
+
923
+ def cmd_interactive(args: argparse.Namespace) -> int:
924
+ workspace = Path(args.workspace).resolve()
925
+ cfg_mgr = ConfigManager()
926
+ overrides = _collect_cli_overrides(args)
927
+
928
+ cfg = cfg_mgr.load_config(overrides=overrides)
929
+ cockpit = AgentCockpit(workspace=workspace, theme_name=cfg.theme)
930
+
931
+ # Workspace trust prompt on first run (Screenshot 2)
932
+ if not args.yes and not cfg_mgr.is_workspace_trusted(workspace):
933
+ if not cockpit.show_trust_gate():
934
+ print(style("\nExited without granting workspace access.", fg=cockpit.theme.dim))
935
+ return 1
936
+ cfg_mgr.trust_workspace(workspace)
937
+
938
+ ui_queue: queue.Queue = queue.Queue()
939
+ steering_queue: queue.Queue = queue.Queue()
940
+ agent_holder: Dict[str, Any] = {}
941
+
942
+ def _mode_getter() -> AutonomyMode:
943
+ return agent_holder["agent"].config.mode
944
+
945
+ def _mode_setter(new_m: AutonomyMode) -> None:
946
+ agent_holder["agent"].config.mode = new_m
947
+
948
+ gate = CockpitApprovalGate(
949
+ cockpit=cockpit,
950
+ mode_getter=_mode_getter,
951
+ mode_setter=_mode_setter,
952
+ ui_queue=ui_queue,
953
+ )
954
+ agent = FrontierAgent(workspace=workspace, config=cfg, config_mgr=cfg_mgr, approval_gate=gate)
955
+ agent_holder["agent"] = agent
956
+
957
+ cockpit.show_welcome(
958
+ version=__version__,
959
+ provider=agent.router.active_provider,
960
+ model=agent.router.active_model,
961
+ effort=agent.config.effort,
962
+ grounding_enabled=agent.config.enable_grounding,
963
+ )
964
+
965
+ queued_prompts: List[str] = []
966
+ staged_attachments: List[Attachment] = []
967
+ for fpath in getattr(args, "attach", None) or []:
968
+ cand = _resolve_media_path(fpath, workspace)
969
+ if cand:
970
+ staged_attachments.append(Attachment.from_path(str(cand)))
971
+
972
+ while True:
973
+ try:
974
+ if queued_prompts:
975
+ raw_input_text = queued_prompts.pop(0)
976
+ display_prompt: Optional[str] = None
977
+ attachments: List[Attachment] = []
978
+ else:
979
+ def _cycle_mode() -> AutonomyMode:
980
+ agent.config.mode = AutonomyMode.cycle(agent.config.mode)
981
+ return agent.config.mode
982
+
983
+ def _dismiss_tip() -> None:
984
+ cockpit.tip_dismissed = True
985
+
986
+ raw_input_text, prompt_atts = cockpit.prompt_bar.read_prompt(
987
+ mode=agent.config.mode,
988
+ model=agent.router.active_model,
989
+ effort=agent.config.effort,
990
+ on_cycle_mode=_cycle_mode,
991
+ on_toggle_expand=cockpit.toggle_expand_and_redraw,
992
+ on_dismiss_tip=_dismiss_tip,
993
+ on_show_shortcuts=cockpit.show_shortcuts_help,
994
+ initial_attachments=staged_attachments,
995
+ )
996
+ display_prompt = cockpit.prompt_bar.last_display_prompt or None
997
+ cockpit.prompt_bar.last_display_prompt = ""
998
+ attachments = list(prompt_atts)
999
+ staged_attachments.clear()
1000
+
1001
+ if not raw_input_text:
1002
+ staged_attachments.extend(attachments)
1003
+ continue
1004
+
1005
+ if raw_input_text.startswith("!"):
1006
+ raw_input_text = f"/run-command {raw_input_text[1:].strip()}"
1007
+ display_prompt = None
1008
+
1009
+ if raw_input_text.startswith("/"):
1010
+ staged_attachments.extend(attachments)
1011
+ cont, injected = handle_slash_command(
1012
+ raw_input_text, agent, cockpit, staged_attachments=staged_attachments
1013
+ )
1014
+ if not cont:
1015
+ break
1016
+ if not injected:
1017
+ continue
1018
+ raw_input_text = injected
1019
+ display_prompt = None
1020
+ attachments = list(staged_attachments)
1021
+ staged_attachments.clear()
1022
+
1023
+ clean_prompt, extra_atts = _parse_attachments_from_prompt(raw_input_text, workspace)
1024
+ seen_ids = {a.path for a in attachments if a.path}
1025
+ all_atts = list(attachments) + [a for a in extra_atts if a.path not in seen_ids]
1026
+
1027
+ _, leftover = cockpit.execute_turn_interactive(
1028
+ agent=agent,
1029
+ user_prompt=clean_prompt,
1030
+ attachments=all_atts,
1031
+ ui_queue=ui_queue,
1032
+ steering_queue=steering_queue,
1033
+ btw_handler=agent.btw,
1034
+ display_prompt=display_prompt,
1035
+ )
1036
+ if leftover:
1037
+ queued_prompts.extend(leftover)
1038
+ except KeyboardInterrupt:
1039
+ _reset_terminal_modes()
1040
+ print(style("\n Interrupted cleanly — press Esc twice or type /exit to quit.\n", fg=MUTED_GREY))
1041
+ except Exception as exc:
1042
+ _reset_terminal_modes()
1043
+ _print_clean_error(exc, theme=cockpit.theme)
1044
+
1045
+ return 0
1046
+
1047
+
1048
+ def cmd_run(args: argparse.Namespace) -> int:
1049
+ workspace = Path(args.workspace).resolve()
1050
+ cfg_mgr = ConfigManager()
1051
+ overrides = _collect_cli_overrides(args, default_mode="yolo")
1052
+
1053
+ cfg = cfg_mgr.load_config(overrides=overrides)
1054
+ cockpit = AgentCockpit(workspace=workspace, theme_name=cfg.theme)
1055
+ agent = FrontierAgent(workspace=workspace, config=cfg, config_mgr=cfg_mgr)
1056
+
1057
+ _, extra_atts = _parse_attachments_from_prompt(args.task, workspace)
1058
+ cli_atts: List[Attachment] = []
1059
+ for fp in getattr(args, "attach", None) or []:
1060
+ cand = _resolve_media_path(fp, workspace)
1061
+ if cand:
1062
+ cli_atts.append(Attachment.from_path(str(cand)))
1063
+ all_atts = cli_atts + [a for a in extra_atts if a.path not in {c.path for c in cli_atts if c.path}]
1064
+
1065
+ turn = agent.run(prompt=args.task, attachments=all_atts)
1066
+ cockpit._print_turn_completion(args.task, all_atts, turn)
1067
+
1068
+ if args.trace:
1069
+ Path(args.trace).write_text(
1070
+ json.dumps(
1071
+ {
1072
+ "session_id": agent.memory.session_id,
1073
+ "provider": agent.router.active_provider,
1074
+ "model": agent.router.active_model,
1075
+ "modified_files": turn.modified_files,
1076
+ "grounding": turn.grounding.__dict__,
1077
+ "cost_usd": turn.cost_usd,
1078
+ "duration_s": turn.duration_s,
1079
+ "final_answer": turn.final_answer,
1080
+ },
1081
+ indent=2,
1082
+ ),
1083
+ encoding="utf-8",
1084
+ )
1085
+ return 0 if not turn.error else 1
1086
+
1087
+
1088
+ def cmd_ask(args: argparse.Namespace) -> int:
1089
+ search = SearchHarnes()
1090
+ cockpit = AgentCockpit(workspace=Path(args.workspace).resolve())
1091
+ results = search.search(args.query, max_results=args.max_results)
1092
+ lines = [f"### SearchHarnes Results for: `{args.query}`\n"]
1093
+ for i, r in enumerate(results, 1):
1094
+ lines.append(f"{i}. **[{r.title}]({r.url})** (`{r.source_engine}`)\n {r.snippet}")
1095
+ md_out = "\n".join(lines)
1096
+ print(cockpit.md.render(md_out))
1097
+ return 0
1098
+
1099
+
1100
+ def cmd_config(args: argparse.Namespace) -> int:
1101
+ cfg_mgr = ConfigManager()
1102
+ cockpit = AgentCockpit(workspace=Path(args.workspace).resolve())
1103
+
1104
+ if getattr(args, "show", False):
1105
+ cfg = cfg_mgr.load_config()
1106
+ prov, mod = cfg_mgr.detect_active_provider(cfg)
1107
+ rows = ["| Provider | Key | Custom Base URL | Saved Model |", "| :--- | :--- | :--- | :--- |"]
1108
+ for p in ALL_PROVIDERS:
1109
+ k = mask_secret(cfg_mgr.resolve_api_key(p))
1110
+ b = cfg_mgr.resolve_api_base(p) or "-"
1111
+ m = cfg_mgr.resolve_provider_model(p)
1112
+ mark = " **" if p == prov else ""
1113
+ rows.append(f"| `{p}`{mark} | {k} | {b} | `{m}` |")
1114
+ print(cockpit.md.render(f"### FrontierAgent Configuration (`active: {prov}:{mod}`)\n\n" + "\n".join(rows)))
1115
+ return 0
1116
+
1117
+ if getattr(args, "provider", None) or getattr(args, "key", None) or getattr(args, "base_url", None) or getattr(args, "model", None):
1118
+ prov = getattr(args, "provider", "").lower()
1119
+ if not prov:
1120
+ cfg = cfg_mgr.load_config()
1121
+ prov, _ = cfg_mgr.detect_active_provider(cfg)
1122
+ if prov == "unconfigured":
1123
+ prov = "custom" if getattr(args, "base_url", None) else "openai"
1124
+ cfg_mgr.set_provider_config(
1125
+ provider=prov,
1126
+ api_key=getattr(args, "key", None),
1127
+ api_base=getattr(args, "base_url", None),
1128
+ model=getattr(args, "model", None),
1129
+ set_default=True,
1130
+ )
1131
+ eff_base = cfg_mgr.resolve_api_base(prov, getattr(args, "base_url", None))
1132
+ eff_mod = cfg_mgr.resolve_provider_model(prov, getattr(args, "model", None))
1133
+ print(f"Configured provider '{prov}' (base: {eff_base or 'default'}, model: {eff_mod}).")
1134
+ return 0
1135
+
1136
+ if sys.stdin.isatty():
1137
+ ok = _run_provider_wizard(cfg_mgr, cockpit)
1138
+ return 0 if ok else 1
1139
+
1140
+ print("Configure FrontierAgent providers & custom endpoints (~/.frontier/config.json):")
1141
+ print(" Interactive wizard: frontier config")
1142
+ print(" Set provider key: frontier config --provider gemini --key AIza...")
1143
+ print(" Custom endpoint: frontier config --provider custom --base-url http://localhost:8000/v1 --key sk-... --model qwen2.5")
1144
+ print(" List live models: frontier models --provider gemini")
1145
+ return 0
1146
+
1147
+
1148
+ def cmd_models(args: argparse.Namespace) -> int:
1149
+ cfg_mgr = ConfigManager()
1150
+ cfg = cfg_mgr.load_config()
1151
+ cockpit = AgentCockpit(workspace=Path(args.workspace).resolve(), theme_name=cfg.theme)
1152
+
1153
+ prov = (args.provider or "").lower()
1154
+ if not prov:
1155
+ prov, active_mod = cfg_mgr.detect_active_provider(cfg)
1156
+ else:
1157
+ active_mod = cfg_mgr.resolve_provider_model(prov)
1158
+
1159
+ if prov == "unconfigured":
1160
+ print(style("No active provider configured. Pass `--provider` / `--base-url` / `--key`, or run `frontier config`.", fg=cockpit.theme.warning))
1161
+ return 1
1162
+
1163
+ key = cfg_mgr.resolve_api_key(prov, getattr(args, "key", None))
1164
+ base = cfg_mgr.resolve_api_base(prov, getattr(args, "base_url", None))
1165
+ models, err = fetch_endpoint_models(provider=prov, api_key=key, api_base=base)
1166
+ if err:
1167
+ print(style(f"Error listing models from {prov}: {err}", fg=cockpit.theme.error))
1168
+ return 1
1169
+
1170
+ _render_models_table(cockpit, prov, base or "", models, active_model=active_mod, filter_text=getattr(args, "filter", "") or "")
1171
+ return 0
1172
+
1173
+
1174
+ def cmd_doctor(args: argparse.Namespace) -> int:
1175
+ import importlib
1176
+ cockpit = AgentCockpit(workspace=Path(args.workspace).resolve())
1177
+ rows = ["| Component | Status | Details |", "| :--- | :--- | :--- |"]
1178
+ for pkg in ("frontierharness", "loopcircuit", "groundanchor", "searchharnes", "tuiharness"):
1179
+ try:
1180
+ m = importlib.import_module(pkg)
1181
+ rows.append(f"| `{pkg}` | OK | v{getattr(m, '__version__', '?')} |")
1182
+ except ImportError as e:
1183
+ rows.append(f"| `{pkg}` | MISSING | {e} |")
1184
+
1185
+ cfg_mgr = ConfigManager()
1186
+ for prov in ("gemini", "anthropic", "openai", "openrouter", "deepseek", "groq", "nvidia"):
1187
+ has_k = bool(cfg_mgr.resolve_api_key(prov))
1188
+ rows.append(f"| API `{prov}` | {'Configured' if has_k else 'Not set'} | Key resolved cleanly |")
1189
+
1190
+ ollama_up = probe_ollama()
1191
+ ollama_models = list_ollama_models() if ollama_up else []
1192
+ rows.append(f"| Local `ollama` | {'ONLINE' if ollama_up else 'Offline'} | {len(ollama_models)} model(s) |")
1193
+
1194
+ print(cockpit.md.render("### FrontierAgent System Health (`doctor`)\n\n" + "\n".join(rows)))
1195
+ return 0
1196
+
1197
+
1198
+ def cmd_benchmark(args: argparse.Namespace) -> int:
1199
+ from groundanchor import Verifier
1200
+ from loopcircuit import CircuitBreaker
1201
+ from searchharnes.scraper import FastScraper
1202
+ from .ui.markdown_plus import MarkdownPlusRenderer
1203
+
1204
+ iterations = args.iterations
1205
+ html = "<html><body><h1>Test</h1><script>bad()</script><p>FastAPI lifespan v0.93.0 latency is 12ms.</p></body></html>"
1206
+ src = "FastAPI lifespan handler was introduced in version 0.93.0 with 12ms boot latency."
1207
+ claim = "FastAPI lifespan was added in 0.93.0."
1208
+
1209
+ t0 = time.perf_counter()
1210
+ for _ in range(iterations):
1211
+ FastScraper.scrape_html(html)
1212
+ scrape_ms = ((time.perf_counter() - t0) * 1000.0) / iterations
1213
+
1214
+ cb = CircuitBreaker(on_trip="silent")
1215
+ t0 = time.perf_counter()
1216
+ for i in range(iterations):
1217
+ cb.record("read_file", {"path": f"file_{i % 50}.py"})
1218
+ loop_us = ((time.perf_counter() - t0) * 1_000_000.0) / iterations
1219
+
1220
+ v = Verifier()
1221
+ t0 = time.perf_counter()
1222
+ for _ in range(min(200, iterations)):
1223
+ v.verify(sources=src, response=claim)
1224
+ ground_ms = ((time.perf_counter() - t0) * 1000.0) / min(200, iterations)
1225
+
1226
+ md = MarkdownPlusRenderer()
1227
+ t0 = time.perf_counter()
1228
+ for _ in range(iterations):
1229
+ md.render("### Result\n\n| A | B |\n| :--- | :--- |\n| `ok` | `fast` |\n")
1230
+ render_ms = ((time.perf_counter() - t0) * 1000.0) / iterations
1231
+
1232
+ print(
1233
+ md.render(
1234
+ "### FrontierAgent Full-Stack Empirical Benchmark\n\n"
1235
+ "| Subsystem | Metric | Latency |\n"
1236
+ "| :--- | :--- | :--- |\n"
1237
+ f"| `searchharnes` Scraper | HTML to Markdown | `{scrape_ms:.3f} ms` |\n"
1238
+ f"| `loopcircuit` Governor | Step check overhead | `{loop_us:.1f} us` |\n"
1239
+ f"| `groundanchor` Verifier | Claim audit | `{ground_ms:.2f} ms` |\n"
1240
+ f"| `MarkdownPlusRenderer` | Table & pill render | `{render_ms:.3f} ms` |\n"
1241
+ )
1242
+ )
1243
+ return 0
1244
+
1245
+
1246
+ def build_parser() -> argparse.ArgumentParser:
1247
+ parser = argparse.ArgumentParser(
1248
+ prog="frontier",
1249
+ description="FrontierAgent — Sovereign, Hallucination-Verified Autonomous Coding & Research CLI",
1250
+ )
1251
+ parser.add_argument("-v", "--version", action="version", version=f"frontieragent {__version__}")
1252
+ parser.add_argument("-w", "--workspace", default=".", help="Workspace root directory (default: current directory)")
1253
+ parser.add_argument("--provider", help="LLM provider: gemini, anthropic, openai, openrouter, deepseek, groq, nvidia, ollama, custom")
1254
+ parser.add_argument("--model", help="Explicit model identifier")
1255
+ parser.add_argument("--base-url", help="Custom API base URL override")
1256
+ parser.add_argument("--mode", choices=["safe", "auto", "plan", "yolo"], help="Autonomy mode")
1257
+ parser.add_argument("--theme", choices=list(THEMES.keys()), help="Cockpit color theme")
1258
+ parser.add_argument("--sandbox", choices=["local", "docker"], default="local", help="Shell sandbox target")
1259
+ parser.add_argument("--attach", nargs="+", default=argparse.SUPPRESS, help="Attach image, audio, video, or PDF files")
1260
+ parser.add_argument("-y", "--yes", action="store_true", help="Auto-trust workspace directory without prompt")
1261
+
1262
+ sub = parser.add_subparsers(dest="subcommand")
1263
+
1264
+ p_run = sub.add_parser("run", help="Execute a one-shot autonomous agent task")
1265
+ p_run.add_argument("task", help="Task prompt string")
1266
+ p_run.add_argument("--attach", nargs="+", default=argparse.SUPPRESS, help="Attach image, audio, video, or PDF files")
1267
+ p_run.add_argument("--trace", help="Write structured JSON execution trace to path")
1268
+
1269
+ p_ask = sub.add_parser("ask", help="Run live free web search via SearchHarnes")
1270
+ p_ask.add_argument("query", help="Search query")
1271
+ p_ask.add_argument("--max-results", type=int, default=5)
1272
+ p_ask.add_argument("--grounded", action="store_true", help="Enable strict GroundAnchor audit")
1273
+
1274
+ p_cfg = sub.add_parser("config", help="Configure provider, API key, custom endpoint & default model (interactive wizard if empty)")
1275
+ p_cfg.add_argument("--provider", default=argparse.SUPPRESS, help="Provider name (gemini, openai, anthropic, openrouter, deepseek, groq, nvidia, ollama, custom)")
1276
+ p_cfg.add_argument("--key", default=argparse.SUPPRESS, help="API key")
1277
+ p_cfg.add_argument("--base-url", default=argparse.SUPPRESS, help="Custom OpenAI-compatible or proxy base URL")
1278
+ p_cfg.add_argument("--model", default=argparse.SUPPRESS, help="Default model name")
1279
+ p_cfg.add_argument("--show", action="store_true", help="Show sanitized provider configuration summary")
1280
+
1281
+ p_mods = sub.add_parser("models", help="List all models live from configured or target endpoint")
1282
+ p_mods.add_argument("--provider", default=argparse.SUPPRESS, help="Target provider to query")
1283
+ p_mods.add_argument("--base-url", default=argparse.SUPPRESS, help="Custom endpoint base URL to query")
1284
+ p_mods.add_argument("--key", default=argparse.SUPPRESS, help="API key override")
1285
+ p_mods.add_argument("--filter", help="Substring filter for model IDs")
1286
+
1287
+ sub.add_parser("doctor", help="Inspect stack health, API keys, Ollama, and package versions")
1288
+
1289
+ p_bench = sub.add_parser("benchmark", help="Run full-stack micro-benchmarks")
1290
+ p_bench.add_argument("--iterations", type=int, default=200)
1291
+
1292
+ return parser
1293
+
1294
+
1295
+ def _reset_terminal_modes() -> None:
1296
+ """Restore terminal mouse/paste tracking and reset styles if interrupted mid-UI."""
1297
+ try:
1298
+ if sys.stdout.isatty():
1299
+ sys.stdout.write("\033[?1000l\033[?1006l\033[?2004l\033[0m")
1300
+ sys.stdout.flush()
1301
+ except Exception:
1302
+ pass
1303
+
1304
+
1305
+ def _print_clean_error(exc: BaseException, theme: Optional[Any] = None) -> None:
1306
+ """Format exceptions cleanly without dumping raw Python tracebacks to users."""
1307
+ import os
1308
+ err_fg = getattr(theme, "error", "#f43f5e")
1309
+ detail = " ".join(str(exc).split()) or type(exc).__name__
1310
+ msg = f"\n ! {type(exc).__name__}: {detail}\n"
1311
+ try:
1312
+ print(style(msg, fg=err_fg))
1313
+ except Exception:
1314
+ sys.stderr.write(msg)
1315
+ if os.environ.get("FRONTIER_DEBUG") == "1":
1316
+ import traceback
1317
+ traceback.print_exc()
1318
+
1319
+
1320
+ def main(argv: Optional[List[str]] = None) -> int:
1321
+ parser = build_parser()
1322
+ try:
1323
+ args = parser.parse_args(argv)
1324
+ if args.subcommand == "run":
1325
+ return cmd_run(args)
1326
+ if args.subcommand == "ask":
1327
+ return cmd_ask(args)
1328
+ if args.subcommand == "config":
1329
+ return cmd_config(args)
1330
+ if args.subcommand == "models":
1331
+ return cmd_models(args)
1332
+ if args.subcommand == "doctor":
1333
+ return cmd_doctor(args)
1334
+ if args.subcommand == "benchmark":
1335
+ return cmd_benchmark(args)
1336
+ return cmd_interactive(args)
1337
+ except KeyboardInterrupt:
1338
+ _reset_terminal_modes()
1339
+ print(style("\nCancelled cleanly. Goodbye!\n", fg=MUTED_GREY))
1340
+ return 130
1341
+ except SystemExit as e:
1342
+ _reset_terminal_modes()
1343
+ return int(e.code) if isinstance(e.code, int) else (0 if e.code is None else 1)
1344
+ except Exception as exc:
1345
+ _reset_terminal_modes()
1346
+ _print_clean_error(exc)
1347
+ return 1