xg-cli 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.
Files changed (130) hide show
  1. xg/__init__.py +3 -0
  2. xg/__main__.py +3 -0
  3. xg/adaptive/__init__.py +27 -0
  4. xg/adaptive/calibrate.py +191 -0
  5. xg/adaptive/feedback.py +170 -0
  6. xg/adaptive/learned_rules.py +284 -0
  7. xg/adaptive/signals.py +125 -0
  8. xg/adaptive/store.py +164 -0
  9. xg/agent/__init__.py +0 -0
  10. xg/agent/plan.py +631 -0
  11. xg/agent/react.py +268 -0
  12. xg/agent/team.py +1793 -0
  13. xg/assets/router.lgb +0 -0
  14. xg/assets/router_semantics.json +21278 -0
  15. xg/assets/router_semantics.onnx +0 -0
  16. xg/cli/__init__.py +0 -0
  17. xg/cli/app.py +1372 -0
  18. xg/cli/commands.py +921 -0
  19. xg/cli/completion.py +740 -0
  20. xg/cli/help.py +185 -0
  21. xg/cli/train.py +200 -0
  22. xg/config/__init__.py +0 -0
  23. xg/config/env_writer.py +121 -0
  24. xg/config/manager.py +446 -0
  25. xg/config/mcp.py +229 -0
  26. xg/config/provider_service.py +267 -0
  27. xg/config/providers.py +46 -0
  28. xg/config/settings.py +258 -0
  29. xg/config/skills.py +100 -0
  30. xg/config/smart_router_service.py +121 -0
  31. xg/config/web.py +140 -0
  32. xg/input_history/__init__.py +7 -0
  33. xg/input_history/models.py +28 -0
  34. xg/input_history/persistence.py +126 -0
  35. xg/input_history/policy.py +39 -0
  36. xg/input_history/prompt_toolkit.py +36 -0
  37. xg/input_history/store.py +118 -0
  38. xg/llm/__init__.py +0 -0
  39. xg/llm/client.py +49 -0
  40. xg/llm/factory.py +40 -0
  41. xg/llm/openai_compat.py +275 -0
  42. xg/llm/types.py +98 -0
  43. xg/mcp/__init__.py +4 -0
  44. xg/mcp/http.py +192 -0
  45. xg/mcp/manager.py +726 -0
  46. xg/mcp/models.py +86 -0
  47. xg/mcp/protocol.py +62 -0
  48. xg/mcp/resources.py +72 -0
  49. xg/mcp/schema.py +137 -0
  50. xg/mcp/stdio.py +210 -0
  51. xg/mcp/transport.py +66 -0
  52. xg/memory/__init__.py +15 -0
  53. xg/memory/context.py +327 -0
  54. xg/memory/manager.py +111 -0
  55. xg/memory/models.py +41 -0
  56. xg/memory/project.py +187 -0
  57. xg/memory/store.py +144 -0
  58. xg/router/__init__.py +124 -0
  59. xg/router/features.py +66 -0
  60. xg/router/keywords.py +50 -0
  61. xg/router/ml_router.py +178 -0
  62. xg/router/model_tiers.py +73 -0
  63. xg/router/postprocess.py +167 -0
  64. xg/router/rule_router.py +77 -0
  65. xg/router/semantic.py +138 -0
  66. xg/safety/__init__.py +0 -0
  67. xg/safety/audit.py +96 -0
  68. xg/safety/guards.py +106 -0
  69. xg/safety/hitl.py +73 -0
  70. xg/skill/__init__.py +9 -0
  71. xg/skill/errors.py +45 -0
  72. xg/skill/loader.py +42 -0
  73. xg/skill/models.py +57 -0
  74. xg/skill/parser.py +93 -0
  75. xg/skill/policy.py +40 -0
  76. xg/skill/prompt.py +45 -0
  77. xg/skill/registry.py +169 -0
  78. xg/tool/__init__.py +0 -0
  79. xg/tool/builtin.py +356 -0
  80. xg/tool/registry.py +228 -0
  81. xg/tui/__init__.py +34 -0
  82. xg/tui/app.py +612 -0
  83. xg/tui/controller.py +1296 -0
  84. xg/tui/diagrams/__init__.py +22 -0
  85. xg/tui/diagrams/layout.py +110 -0
  86. xg/tui/diagrams/markdown.py +39 -0
  87. xg/tui/diagrams/model.py +36 -0
  88. xg/tui/diagrams/parser.py +119 -0
  89. xg/tui/diagrams/renderer.py +551 -0
  90. xg/tui/i18n.py +169 -0
  91. xg/tui/messages.py +45 -0
  92. xg/tui/plan_renderables.py +147 -0
  93. xg/tui/reducer.py +1029 -0
  94. xg/tui/renderables.py +252 -0
  95. xg/tui/state.py +240 -0
  96. xg/tui/theme.tcss +208 -0
  97. xg/tui/widgets/__init__.py +1 -0
  98. xg/tui/widgets/action_card.py +94 -0
  99. xg/tui/widgets/agent_group_card.py +39 -0
  100. xg/tui/widgets/approval_modal.py +59 -0
  101. xg/tui/widgets/collapsible_card.py +40 -0
  102. xg/tui/widgets/command_suggestions.py +128 -0
  103. xg/tui/widgets/composer.py +151 -0
  104. xg/tui/widgets/config_panel.py +198 -0
  105. xg/tui/widgets/confirm_modal.py +31 -0
  106. xg/tui/widgets/footer.py +9 -0
  107. xg/tui/widgets/header.py +118 -0
  108. xg/tui/widgets/inspector.py +378 -0
  109. xg/tui/widgets/plan_modal.py +53 -0
  110. xg/tui/widgets/provider_form.py +141 -0
  111. xg/tui/widgets/queue_status.py +30 -0
  112. xg/tui/widgets/smart_router_form.py +95 -0
  113. xg/tui/widgets/transcript.py +354 -0
  114. xg/tui/workers.py +14 -0
  115. xg/web/__init__.py +21 -0
  116. xg/web/errors.py +57 -0
  117. xg/web/extract.py +127 -0
  118. xg/web/fetch.py +106 -0
  119. xg/web/markdown.py +77 -0
  120. xg/web/models.py +91 -0
  121. xg/web/providers.py +79 -0
  122. xg/web/search.py +118 -0
  123. xg/web/searxng.py +27 -0
  124. xg/web/serpapi.py +29 -0
  125. xg/web/url_policy.py +110 -0
  126. xg/web/zhipu.py +27 -0
  127. xg_cli-1.0.dist-info/METADATA +284 -0
  128. xg_cli-1.0.dist-info/RECORD +130 -0
  129. xg_cli-1.0.dist-info/WHEEL +4 -0
  130. xg_cli-1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,121 @@
1
+ """SmartRouter 配置服务(config.json 介质,供 /tier 命令与 TUI 面板使用)。
2
+
3
+ 仅读写 config.json 的 ``smart_router`` 节点;不再依赖 XG_SMART_ROUTER* 环境变量。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ from xg.config.manager import ConfigManager, _SMART_ROUTER_TIERS
12
+ from xg.config.provider_service import validate_model
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class OpResult:
17
+ ok: bool
18
+ message: str
19
+
20
+
21
+ class SmartRouterConfigService:
22
+ def __init__(self, manager: ConfigManager, settings: Any = None) -> None:
23
+ self.manager = manager
24
+ # 运行的 Settings 对象(可选);用于配置档位时同步运行态开关,
25
+ # 使“自动开启”在当前会话立即生效,而非仅持久化到 config.json。
26
+ self._settings = settings
27
+
28
+ # ---------- 读取 ----------
29
+
30
+ def get(self) -> dict:
31
+ """返回 {enabled, tiers};tiers 为 {档位: {provider, model}}。"""
32
+ return self.manager.smart_router_config()
33
+
34
+ def skip_config_relies_on_active(self, raw: dict) -> str:
35
+ """未显式配置某档时的回落标记用(见 list_tiers)。"""
36
+ configured = raw.get("provider") and raw.get("model")
37
+ return "已配置" if configured else "回落到手动 active"
38
+
39
+ def list_tiers(self) -> list[dict]:
40
+ """按固定四档顺序返回每档 {name, provider, model, configured}。"""
41
+ cfg = self.get()
42
+ tiers = cfg.get("tiers") or {}
43
+ rows: list[dict] = []
44
+ for name in _SMART_ROUTER_TIERS:
45
+ entry = tiers.get(name) or {}
46
+ provider = str(entry.get("provider", "") or "")
47
+ model = str(entry.get("model", "") or "")
48
+ rows.append({
49
+ "name": name,
50
+ "provider": provider,
51
+ "model": model,
52
+ "configured": bool(provider and model),
53
+ })
54
+ return rows
55
+
56
+ def get_tier(self, tier: str) -> tuple[OpResult, dict | None]:
57
+ """查看单个档位。"""
58
+ err = self._validate_tier(tier)
59
+ if err:
60
+ return OpResult(False, err), None
61
+ cfg = self.get()
62
+ entry = (cfg.get("tiers") or {}).get(tier) or {}
63
+ return OpResult(True, ""), {
64
+ "name": tier,
65
+ "provider": str(entry.get("provider", "") or ""),
66
+ "model": str(entry.get("model", "") or ""),
67
+ }
68
+
69
+ # ---------- 写入 ----------
70
+
71
+ def set_tier(self, tier: str, provider: str, model: str | None = None) -> OpResult:
72
+ """设置档位 provider/model。宽松校验:provider 必须存在;model 任意非空合法串。"""
73
+ err = self._validate_tier(tier)
74
+ if err:
75
+ return OpResult(False, err)
76
+
77
+ p = provider.strip()
78
+ prov = self.manager.resolve_provider(p) if p else None
79
+ if p is None or prov is None:
80
+ return OpResult(False, f"未知 provider: {p}")
81
+
82
+ resolved_model: str
83
+ if model is None or model.strip() == "":
84
+ resolved_model = prov.default_model or "default"
85
+ else:
86
+ resolved_model = model.strip()
87
+ merr = validate_model(resolved_model)
88
+ if merr:
89
+ return OpResult(False, merr)
90
+
91
+ was_enabled = bool(self.get().get("enabled", False))
92
+ self.manager.set_smart_router_tier(tier, prov.name, resolved_model)
93
+ msg = f"档位 {tier} → {prov.name}/{resolved_model}"
94
+ if not was_enabled:
95
+ # 配置/修改档位后自动生效:开启开关并同步运行态。
96
+ self.manager.set_smart_router_enabled(True)
97
+ if self._settings is not None:
98
+ self._settings.smart_router_enabled = True
99
+ msg += "(SmartRouter 已自动开启)"
100
+ return OpResult(True, msg)
101
+
102
+ def clear_tier(self, tier: str) -> OpResult:
103
+ err = self._validate_tier(tier)
104
+ if err:
105
+ return OpResult(False, err)
106
+ removed = self.manager.remove_smart_router_tier(tier)
107
+ if not removed:
108
+ return OpResult(True, f"档位 {tier} 未配置,无需清空")
109
+ return OpResult(True, f"档位 {tier} 已清空,回落到手动 active")
110
+
111
+ def set_enabled(self, enabled: bool) -> OpResult:
112
+ self.manager.set_smart_router_enabled(bool(enabled))
113
+ return OpResult(True, f"SmartRouter 已{'开启' if enabled else '关闭'}")
114
+
115
+ @staticmethod
116
+ def _validate_tier(tier: str) -> str | None:
117
+ if tier not in _SMART_ROUTER_TIERS:
118
+ return (
119
+ f"未知档位: {tier}。可用: {'/'.join(_SMART_ROUTER_TIERS)}"
120
+ )
121
+ return None
xg/config/web.py ADDED
@@ -0,0 +1,140 @@
1
+ """Web configuration loading with user/project layering and env expansion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from xg.web.models import WebConfig, WebFetchConfig, WebSearchConfig
12
+
13
+ WEB_CONFIG_FILE = "web.json"
14
+ _ENV_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
15
+
16
+
17
+ def _merge(base: dict, override: dict) -> dict:
18
+ out = dict(base)
19
+ for key, value in override.items():
20
+ if isinstance(value, dict) and isinstance(out.get(key), dict):
21
+ out[key] = _merge(out[key], value)
22
+ else:
23
+ out[key] = value
24
+ return out
25
+
26
+
27
+ class WebConfigManager:
28
+ def __init__(self, *, user_dir: str | Path | None = None,
29
+ project_root: str | Path | None = None,
30
+ env: dict[str, str] | None = None) -> None:
31
+ self.user_dir = Path(user_dir) if user_dir else Path.home() / ".xg"
32
+ self.project_root = (Path(project_root) if project_root else Path.cwd()).resolve()
33
+ self.user_config_path = self.user_dir / WEB_CONFIG_FILE
34
+ self.project_config_path = self.project_root / ".xg" / WEB_CONFIG_FILE
35
+ self.env = env if env is not None else os.environ
36
+ self.errors: list[str] = []
37
+
38
+ def _read(self, path: Path) -> dict:
39
+ if not path.is_file():
40
+ return {}
41
+ try:
42
+ value = json.loads(path.read_text(encoding="utf-8"))
43
+ except (OSError, json.JSONDecodeError) as exc:
44
+ self.errors.append(f"{path}: 配置读取失败")
45
+ return {}
46
+ if not isinstance(value, dict):
47
+ self.errors.append(f"{path}: 顶层必须是 JSON 对象")
48
+ return {}
49
+ return value
50
+
51
+ def _expand(self, value: Any) -> Any:
52
+ if isinstance(value, str):
53
+ return _ENV_RE.sub(lambda m: str(self.env.get(m.group(1), "")), value)
54
+ if isinstance(value, list):
55
+ return [self._expand(item) for item in value]
56
+ if isinstance(value, dict):
57
+ return {str(k): self._expand(v) for k, v in value.items()}
58
+ return value
59
+
60
+ @staticmethod
61
+ def _float(value: Any, default: float, minimum: float = 0.1) -> float:
62
+ try:
63
+ return max(minimum, float(value))
64
+ except (TypeError, ValueError):
65
+ return default
66
+
67
+ @staticmethod
68
+ def _int(value: Any, default: int, minimum: int = 1) -> int:
69
+ try:
70
+ return max(minimum, int(value))
71
+ except (TypeError, ValueError):
72
+ return default
73
+
74
+ def load(self) -> WebConfig:
75
+ self.errors.clear()
76
+ raw = self._expand(_merge(self._read(self.user_config_path), self._read(self.project_config_path)))
77
+ search_raw = raw.get("search") if isinstance(raw.get("search"), dict) else {}
78
+ fetch_raw = raw.get("fetch") if isinstance(raw.get("fetch"), dict) else {}
79
+ env = self.env
80
+ provider = str(env.get("XG_WEB_SEARCH_PROVIDER", search_raw.get("provider", "none")) or "none").lower()
81
+ providers = raw.get("providers") if isinstance(raw.get("providers"), dict) else {}
82
+ providers = {str(k): dict(v) for k, v in providers.items() if isinstance(v, dict)}
83
+ selected = providers.get(provider, {})
84
+ api_key_env = str(selected.get("api_key_env") or {
85
+ "zhipu": "XG_ZHIPU_SEARCH_API_KEY",
86
+ "serpapi": "XG_SERPAPI_API_KEY",
87
+ }.get(provider, ""))
88
+ api_key = selected.get("api_key") or env.get(api_key_env, "")
89
+ api_base = selected.get("api_base") or env.get({
90
+ "zhipu": "XG_ZHIPU_SEARCH_API_BASE",
91
+ "serpapi": "XG_SERPAPI_API_BASE",
92
+ }.get(provider, ""), "") or None
93
+ if not api_base and provider == "zhipu":
94
+ api_base = "https://open.bigmodel.cn/api/paas/v4"
95
+ if not api_base and provider == "serpapi":
96
+ api_base = "https://serpapi.com"
97
+ if provider == "searxng":
98
+ api_base = selected.get("url") or env.get("XG_SEARXNG_URL", "") or None
99
+ search = WebSearchConfig(
100
+ provider=provider,
101
+ api_base=str(api_base) if api_base else None,
102
+ api_key_env=api_key_env or None,
103
+ api_key=str(api_key) if api_key else None,
104
+ timeout=self._float(env.get("XG_WEB_TIMEOUT", search_raw.get("timeout", 15)), 15.0),
105
+ max_results=min(10, self._int(env.get("XG_WEB_MAX_RESULTS", search_raw.get("max_results", 5)), 5)),
106
+ rate_limit_per_minute=self._int(env.get("XG_WEB_RATE_LIMIT_PER_MINUTE", search_raw.get("rate_limit_per_minute", 30)), 30),
107
+ enabled=provider != "none" and bool(raw.get("enabled", True)),
108
+ )
109
+ allowed = fetch_raw.get("allowed_ports", (80, 443))
110
+ if not isinstance(allowed, (list, tuple)):
111
+ allowed = (80, 443)
112
+ ports = tuple(self._int(p, 80) for p in allowed)
113
+ fetch = WebFetchConfig(
114
+ timeout=self._float(env.get("XG_WEB_TIMEOUT", fetch_raw.get("timeout", 15)), 15.0),
115
+ max_response_bytes=self._int(env.get("XG_WEB_MAX_RESPONSE_BYTES", fetch_raw.get("max_response_bytes", 2 * 1024 * 1024)), 2 * 1024 * 1024, 1024),
116
+ max_chars=self._int(env.get("XG_WEB_FETCH_MAX_CHARS", fetch_raw.get("max_chars", 32_000)), 32_000, 256),
117
+ max_redirects=self._int(env.get("XG_WEB_MAX_REDIRECTS", fetch_raw.get("max_redirects", 5)), 5, 0),
118
+ allowed_ports=ports,
119
+ )
120
+ enabled = env.get("XG_WEB_ENABLED", "on").lower() not in ("off", "0", "false") and bool(raw.get("enabled", True))
121
+ rate_limit = self._int(env.get("XG_WEB_RATE_LIMIT_PER_MINUTE", search_raw.get("rate_limit_per_minute", 30)), 30)
122
+ return WebConfig(enabled=enabled, search=search, fetch=fetch, providers=providers,
123
+ rate_limit_per_minute=rate_limit)
124
+
125
+ def snapshot(self) -> dict[str, Any]:
126
+ config = self.load()
127
+ return {
128
+ "enabled": config.enabled,
129
+ "search_provider": config.search.provider,
130
+ "search_configured": bool(config.search.api_base and (config.search.api_key or config.search.provider == "searxng")),
131
+ "fetch": {"timeout": config.fetch.timeout, "max_response_bytes": config.fetch.max_response_bytes,
132
+ "max_chars": config.fetch.max_chars, "max_redirects": config.fetch.max_redirects},
133
+ }
134
+
135
+
136
+ def load_web_config(*, user_dir=None, project_root=None, env=None) -> WebConfig:
137
+ return WebConfigManager(user_dir=user_dir, project_root=project_root, env=env).load()
138
+
139
+
140
+ load_web_settings = load_web_config
@@ -0,0 +1,7 @@
1
+ """Bounded, local input history for the TUI and inline CLI."""
2
+
3
+ from xg.input_history.models import HistoryConfig, HistoryCursor, HistoryEntry
4
+ from xg.input_history.prompt_toolkit import PromptToolkitHistory
5
+ from xg.input_history.store import InputHistory
6
+
7
+ __all__ = ["HistoryConfig", "HistoryCursor", "HistoryEntry", "InputHistory", "PromptToolkitHistory"]
@@ -0,0 +1,28 @@
1
+ """Public models for user input history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class HistoryConfig:
10
+ enabled: bool = True
11
+ persist: bool = True
12
+ max_entries: int = 100
13
+ max_entry_chars: int = 8_000
14
+ max_file_bytes: int = 1_048_576
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class HistoryEntry:
19
+ text: str
20
+ created_at: str
21
+ scope: str
22
+ persisted: bool = False
23
+
24
+
25
+ @dataclass
26
+ class HistoryCursor:
27
+ index: int | None = None
28
+ draft: str = ""
@@ -0,0 +1,126 @@
1
+ """Small, bounded JSONL persistence for input history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import tempfile
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+
12
+ from xg.input_history.models import HistoryConfig, HistoryEntry
13
+
14
+
15
+ def project_scope(project_root: str | Path | None) -> str:
16
+ if project_root is None:
17
+ return "global"
18
+ resolved = str(Path(project_root).resolve()).casefold()
19
+ return hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:16]
20
+
21
+
22
+ def history_path(user_dir: str | Path, scope: str) -> Path:
23
+ return Path(user_dir).resolve() / "input-history" / f"{scope}.jsonl"
24
+
25
+
26
+ class HistoryPersistence:
27
+ def __init__(self, path: str | Path, scope: str, config: HistoryConfig) -> None:
28
+ self.path = Path(path)
29
+ self.scope = scope
30
+ self.config = config
31
+
32
+ def load(self) -> list[HistoryEntry]:
33
+ try:
34
+ if not self.path.is_file():
35
+ return []
36
+ data = self.path.read_bytes()
37
+ except OSError:
38
+ return []
39
+ if len(data) > self.config.max_file_bytes:
40
+ data = data[-self.config.max_file_bytes:]
41
+ entries: list[HistoryEntry] = []
42
+ for raw_line in data.splitlines():
43
+ try:
44
+ item = json.loads(raw_line.decode("utf-8"))
45
+ text = item.get("text")
46
+ created_at = item.get("created_at")
47
+ if (
48
+ not isinstance(text, str)
49
+ or not isinstance(created_at, str)
50
+ or not text.strip()
51
+ or len(text) > self.config.max_entry_chars
52
+ or item.get("scope") != self.scope
53
+ ):
54
+ continue
55
+ entries.append(HistoryEntry(text, created_at, self.scope, persisted=True))
56
+ except (UnicodeError, AttributeError, TypeError, ValueError):
57
+ continue
58
+ return entries[-self.config.max_entries:]
59
+
60
+ def append(self, entry: HistoryEntry, entries: list[HistoryEntry]) -> bool:
61
+ try:
62
+ self.path.parent.mkdir(parents=True, exist_ok=True)
63
+ self._restrict_permissions(self.path.parent, directory=True)
64
+ line = self._encode(entry)
65
+ current_size = self.path.stat().st_size if self.path.exists() else 0
66
+ if current_size + len(line) <= self.config.max_file_bytes:
67
+ with self.path.open("ab") as handle:
68
+ handle.write(line)
69
+ self._restrict_permissions(self.path)
70
+ return True
71
+ self.rewrite(entries)
72
+ return True
73
+ except OSError:
74
+ return False
75
+
76
+ def clear(self) -> bool:
77
+ try:
78
+ if self.path.exists():
79
+ self.path.unlink()
80
+ return True
81
+ except OSError:
82
+ return False
83
+
84
+ def rewrite(self, entries: list[HistoryEntry]) -> bool:
85
+ self.path.parent.mkdir(parents=True, exist_ok=True)
86
+ self._restrict_permissions(self.path.parent, directory=True)
87
+ fd, raw_path = tempfile.mkstemp(prefix=".history-", suffix=".tmp", dir=self.path.parent)
88
+ temp_path = Path(raw_path)
89
+ try:
90
+ with os.fdopen(fd, "wb") as handle:
91
+ for entry in entries[-self.config.max_entries:]:
92
+ line = self._encode(entry)
93
+ if handle.tell() + len(line) > self.config.max_file_bytes:
94
+ continue
95
+ handle.write(line)
96
+ handle.flush()
97
+ os.fsync(handle.fileno())
98
+ temp_path.replace(self.path)
99
+ self._restrict_permissions(self.path)
100
+ return True
101
+ finally:
102
+ if temp_path.exists():
103
+ temp_path.unlink(missing_ok=True)
104
+
105
+ @staticmethod
106
+ def _encode(entry: HistoryEntry) -> bytes:
107
+ return (
108
+ json.dumps(
109
+ {"text": entry.text, "created_at": entry.created_at, "scope": entry.scope},
110
+ ensure_ascii=False,
111
+ separators=(",", ":"),
112
+ )
113
+ + "\n"
114
+ ).encode("utf-8")
115
+
116
+ @staticmethod
117
+ def _restrict_permissions(path: Path, *, directory: bool = False) -> None:
118
+ if os.name != "nt":
119
+ try:
120
+ path.chmod(0o700 if directory else 0o600)
121
+ except OSError:
122
+ pass
123
+
124
+
125
+ def now_iso() -> str:
126
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
@@ -0,0 +1,39 @@
1
+ """Privacy and bounded-input policy for local history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+
8
+ _SENSITIVE_ASSIGNMENT = re.compile(
9
+ r"\b(?:api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret|cookie)\b"
10
+ r"\s*[:=]\s*\S+",
11
+ re.IGNORECASE,
12
+ )
13
+ _BEARER = re.compile(r"\bBearer\s+\S+", re.IGNORECASE)
14
+ _SECRET_PREFIX = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{12,})\b")
15
+
16
+
17
+ def normalize_text(text: str) -> str:
18
+ """Normalize the same whitespace that the CLI submits to the agent."""
19
+ return str(text).strip()
20
+
21
+
22
+ def is_sensitive(text: str) -> bool:
23
+ """Best-effort detection; callers must still offer a persistence switch."""
24
+ value = normalize_text(text)
25
+ if not value:
26
+ return False
27
+ command = value.lower().split(maxsplit=1)[0]
28
+ if command in {"/save", "/config"} and value.lower().startswith(("/save", "/config set")):
29
+ return True
30
+ return bool(_SENSITIVE_ASSIGNMENT.search(value) or _BEARER.search(value) or _SECRET_PREFIX.search(value))
31
+
32
+
33
+ def should_record(text: str) -> bool:
34
+ """Exclude control commands which are not ordinary user tasks."""
35
+ value = normalize_text(text)
36
+ if not value:
37
+ return False
38
+ command = value.lower().split(maxsplit=1)[0]
39
+ return command not in {"/cancel", "/c", "/exit", "/quit", "/history"}
@@ -0,0 +1,36 @@
1
+ """Prompt Toolkit adapter backed by the shared XG input history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+
7
+ from prompt_toolkit.history import History
8
+
9
+ from xg.input_history.store import InputHistory
10
+
11
+
12
+ class PromptToolkitHistory(History):
13
+ """Use ``InputHistory`` without creating a second persistence file.
14
+
15
+ The inline loop toggles ``recording_enabled`` only around its top-level
16
+ prompt. Approval and plan prompts share the PromptSession but therefore
17
+ cannot accidentally enter ordinary task history.
18
+ """
19
+
20
+ def __init__(self, store: InputHistory) -> None:
21
+ super().__init__()
22
+ self.store = store
23
+ self.recording_enabled = False
24
+
25
+ def load_history_strings(self) -> Iterable[str]:
26
+ yield from (entry.text for entry in reversed(self.store.entries()))
27
+
28
+ def append_string(self, string: str) -> None:
29
+ if self.recording_enabled:
30
+ self.store.add(string)
31
+ self._loaded = True
32
+ self._loaded_strings = [entry.text for entry in reversed(self.store.entries())]
33
+
34
+ def store_string(self, string: str) -> None:
35
+ # ``append_string`` owns storage and applies the XG privacy policy.
36
+ return None
@@ -0,0 +1,118 @@
1
+ """In-memory history, cursor navigation and optional persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from xg.input_history.models import HistoryConfig, HistoryCursor, HistoryEntry
8
+ from xg.input_history.persistence import HistoryPersistence, history_path, now_iso, project_scope
9
+ from xg.input_history.policy import is_sensitive, normalize_text, should_record
10
+
11
+
12
+ class InputHistory:
13
+ def __init__(
14
+ self,
15
+ *,
16
+ project_root: str | Path | None = None,
17
+ user_dir: str | Path | None = None,
18
+ config: HistoryConfig | None = None,
19
+ persistence: HistoryPersistence | None = None,
20
+ ) -> None:
21
+ self.config = config or HistoryConfig()
22
+ self.scope = project_scope(project_root)
23
+ self.persistence = persistence
24
+ if self.persistence is None and user_dir is not None and self.config.persist:
25
+ self.persistence = HistoryPersistence(
26
+ history_path(user_dir, self.scope), self.scope, self.config
27
+ )
28
+ self._entries: list[HistoryEntry] = []
29
+ self._cursor = HistoryCursor()
30
+ if self.config.enabled and self.config.persist and self.persistence is not None:
31
+ self._entries = self._dedupe(self.persistence.load())[-self.config.max_entries:]
32
+
33
+ @property
34
+ def cursor(self) -> HistoryCursor:
35
+ return self._cursor
36
+
37
+ def add(self, text: str) -> bool:
38
+ value = normalize_text(text)
39
+ if not self.config.enabled or not should_record(value):
40
+ return False
41
+ if len(value) > self.config.max_entry_chars:
42
+ return False
43
+ if self._entries and self._entries[-1].text == value:
44
+ self.reset_cursor()
45
+ return False
46
+ was_full = len(self._entries) >= self.config.max_entries
47
+ entry = HistoryEntry(value, now_iso(), self.scope, persisted=False)
48
+ self._entries.append(entry)
49
+ self._entries = self._dedupe(self._entries)[-self.config.max_entries:]
50
+ if self.config.persist and self.persistence is not None and not is_sensitive(value):
51
+ try:
52
+ saved = (
53
+ self.persistence.rewrite(self._entries)
54
+ if was_full
55
+ else self.persistence.append(entry, self._entries)
56
+ )
57
+ except OSError:
58
+ saved = False
59
+ if saved:
60
+ self._entries[-1] = HistoryEntry(
61
+ entry.text, entry.created_at, entry.scope, persisted=True
62
+ )
63
+ self.reset_cursor()
64
+ return True
65
+
66
+ def previous(self, draft: str = "") -> str:
67
+ if not self.config.enabled or not self._entries:
68
+ return draft
69
+ if self._cursor.index is None:
70
+ self._cursor.draft = draft
71
+ self._cursor.index = len(self._entries) - 1
72
+ else:
73
+ self._cursor.index = max(0, self._cursor.index - 1)
74
+ return self._entries[self._cursor.index].text
75
+
76
+ def next(self) -> str:
77
+ if not self.config.enabled or self._cursor.index is None:
78
+ return self._cursor.draft if self._cursor.index is None else ""
79
+ if self._cursor.index >= len(self._entries) - 1:
80
+ draft = self._cursor.draft
81
+ # Keep the draft while sitting at the end. A repeated Down key
82
+ # should remain stable instead of replacing it with an empty
83
+ # value; the next Up call will capture the current Composer value
84
+ # again if the user starts a new navigation pass.
85
+ self._cursor.index = None
86
+ return draft
87
+ self._cursor.index += 1
88
+ return self._entries[self._cursor.index].text
89
+
90
+ def reset_cursor(self) -> None:
91
+ self._cursor = HistoryCursor()
92
+
93
+ def clear(self, *, persistent: bool = True) -> int:
94
+ count = len(self._entries)
95
+ self._entries.clear()
96
+ self.reset_cursor()
97
+ if persistent and self.persistence is not None:
98
+ self.persistence.clear()
99
+ return count
100
+
101
+ def entries(self) -> tuple[HistoryEntry, ...]:
102
+ return tuple(self._entries)
103
+
104
+ def status(self) -> str:
105
+ if not self.config.enabled:
106
+ return "输入历史:关闭"
107
+ persistence = "开启" if self.config.persist and self.persistence is not None else "关闭"
108
+ return f"输入历史:开启\n当前项目记录:{len(self._entries)} 条\n持久化:{persistence}"
109
+
110
+ @staticmethod
111
+ def _dedupe(entries: list[HistoryEntry]) -> list[HistoryEntry]:
112
+ result: list[HistoryEntry] = []
113
+ for entry in entries:
114
+ if result and result[-1].text == entry.text:
115
+ result[-1] = entry
116
+ else:
117
+ result.append(entry)
118
+ return result
xg/llm/__init__.py ADDED
File without changes
xg/llm/client.py ADDED
@@ -0,0 +1,49 @@
1
+ """LlmClient 抽象基类。所有 provider 实现统一的流式对话接口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import AsyncIterator
7
+
8
+ from xg.llm.types import Message, StreamEvent
9
+
10
+
11
+ class LlmError(Exception):
12
+ def __init__(
13
+ self,
14
+ message: str,
15
+ *,
16
+ status_code: int | None = None,
17
+ category: str = "llm_error",
18
+ retryable: bool = False,
19
+ retry_after: float | None = None,
20
+ response_started: bool = False,
21
+ attempt: int = 1,
22
+ max_attempts: int = 1,
23
+ request_id: str = "",
24
+ ) -> None:
25
+ super().__init__(message)
26
+ self.message = message
27
+ self.status_code = status_code
28
+ self.category = category
29
+ self.retryable = retryable
30
+ self.retry_after = retry_after
31
+ self.response_started = response_started
32
+ self.attempt = attempt
33
+ self.max_attempts = max_attempts
34
+ self.request_id = request_id
35
+ """LLM 请求失败(网络 / 鉴权 / 超时 / 协议错误)。"""
36
+
37
+
38
+ class LlmClient(ABC):
39
+ """流式 Chat Completions 客户端抽象。"""
40
+
41
+ @abstractmethod
42
+ def stream_chat(
43
+ self, messages: list[Message], tools: list[dict] | None = None
44
+ ) -> AsyncIterator[StreamEvent]:
45
+ """流式对话。
46
+
47
+ 产出事件序列:content* → tool_call* → done。
48
+ 失败时抛出 LlmError,消息面向用户可直接展示。
49
+ """