ssh-agent-harness 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.
Files changed (102) hide show
  1. ssh_agent_harness/__init__.py +4 -0
  2. ssh_agent_harness/api/__init__.py +1 -0
  3. ssh_agent_harness/api/__main__.py +78 -0
  4. ssh_agent_harness/api/app.py +446 -0
  5. ssh_agent_harness/api/approvals.py +45 -0
  6. ssh_agent_harness/api/deployments.py +446 -0
  7. ssh_agent_harness/api/deps.py +98 -0
  8. ssh_agent_harness/api/hosts.py +146 -0
  9. ssh_agent_harness/api/knowledge.py +113 -0
  10. ssh_agent_harness/api/llm.py +208 -0
  11. ssh_agent_harness/api/package_inspect.py +120 -0
  12. ssh_agent_harness/api/packages.py +448 -0
  13. ssh_agent_harness/api/run_manager.py +571 -0
  14. ssh_agent_harness/api/runs.py +74 -0
  15. ssh_agent_harness/api/schemas.py +495 -0
  16. ssh_agent_harness/api/secrets.py +105 -0
  17. ssh_agent_harness/api/sessions.py +72 -0
  18. ssh_agent_harness/api/skill_schemas.py +96 -0
  19. ssh_agent_harness/api/skills.py +172 -0
  20. ssh_agent_harness/api/static/__init__.py +10 -0
  21. ssh_agent_harness/api/static/assets/index-C6jsNDMh.css +1 -0
  22. ssh_agent_harness/api/static/assets/index-CfCWLEGv.js +471 -0
  23. ssh_agent_harness/api/static/favicon-32.png +0 -0
  24. ssh_agent_harness/api/static/favicon.ico +0 -0
  25. ssh_agent_harness/api/static/icon-192.png +0 -0
  26. ssh_agent_harness/api/static/icon-512.png +0 -0
  27. ssh_agent_harness/api/static/index.html +14 -0
  28. ssh_agent_harness/api/synthetic_run.py +142 -0
  29. ssh_agent_harness/compat.py +79 -0
  30. ssh_agent_harness/config.py +317 -0
  31. ssh_agent_harness/core/__init__.py +76 -0
  32. ssh_agent_harness/core/artifact_catalog.py +175 -0
  33. ssh_agent_harness/core/deploy_definition.py +396 -0
  34. ssh_agent_harness/core/deploy_plan.py +198 -0
  35. ssh_agent_harness/core/deploy_primitives.py +625 -0
  36. ssh_agent_harness/core/deployer.py +754 -0
  37. ssh_agent_harness/core/fingerprint.py +541 -0
  38. ssh_agent_harness/core/gate_hooks.py +49 -0
  39. ssh_agent_harness/core/generation.py +91 -0
  40. ssh_agent_harness/core/host_loader.py +104 -0
  41. ssh_agent_harness/core/host_workspace.py +67 -0
  42. ssh_agent_harness/core/install_step.py +106 -0
  43. ssh_agent_harness/core/llm.py +232 -0
  44. ssh_agent_harness/core/llm_discovery.py +186 -0
  45. ssh_agent_harness/core/llm_logging.py +126 -0
  46. ssh_agent_harness/core/llm_presets.py +122 -0
  47. ssh_agent_harness/core/model_adapter.py +509 -0
  48. ssh_agent_harness/core/multi_turn.py +337 -0
  49. ssh_agent_harness/core/ollama_client.py +653 -0
  50. ssh_agent_harness/core/orchestrator.py +523 -0
  51. ssh_agent_harness/core/package_commands.py +166 -0
  52. ssh_agent_harness/core/package_installer.py +670 -0
  53. ssh_agent_harness/core/package_manager.py +343 -0
  54. ssh_agent_harness/core/path_policy.py +66 -0
  55. ssh_agent_harness/core/plan_runner.py +283 -0
  56. ssh_agent_harness/core/progress.py +87 -0
  57. ssh_agent_harness/core/prompt_context.py +43 -0
  58. ssh_agent_harness/core/reflection.py +302 -0
  59. ssh_agent_harness/core/run_persistence.py +55 -0
  60. ssh_agent_harness/core/skill_import.py +272 -0
  61. ssh_agent_harness/core/skill_runtime.py +155 -0
  62. ssh_agent_harness/core/skills.py +498 -0
  63. ssh_agent_harness/core/step_items.py +331 -0
  64. ssh_agent_harness/core/step_loop.py +535 -0
  65. ssh_agent_harness/core/step_observation.py +48 -0
  66. ssh_agent_harness/core/step_phases.py +189 -0
  67. ssh_agent_harness/core/step_state.py +66 -0
  68. ssh_agent_harness/core/transfer_directive.py +447 -0
  69. ssh_agent_harness/core/transfer_executor.py +180 -0
  70. ssh_agent_harness/core/two_phase.py +408 -0
  71. ssh_agent_harness/core/upload_guard.py +91 -0
  72. ssh_agent_harness/default_settings.yaml +99 -0
  73. ssh_agent_harness/harness/__init__.py +75 -0
  74. ssh_agent_harness/harness/confirmation.py +517 -0
  75. ssh_agent_harness/harness/note_policy.py +170 -0
  76. ssh_agent_harness/harness/prompts.py +449 -0
  77. ssh_agent_harness/harness/protocol.py +217 -0
  78. ssh_agent_harness/harness/safety.py +477 -0
  79. ssh_agent_harness/harness/transfer_policy.py +177 -0
  80. ssh_agent_harness/logging_setup.py +152 -0
  81. ssh_agent_harness/security/__init__.py +23 -0
  82. ssh_agent_harness/security/secrets.py +155 -0
  83. ssh_agent_harness/skills/deploy/SKILL.md +53 -0
  84. ssh_agent_harness/skills/install/SKILL.md +43 -0
  85. ssh_agent_harness/storage/__init__.py +25 -0
  86. ssh_agent_harness/storage/deploy_store.py +527 -0
  87. ssh_agent_harness/storage/host_store.py +186 -0
  88. ssh_agent_harness/storage/llm_store.py +106 -0
  89. ssh_agent_harness/storage/run_store.py +286 -0
  90. ssh_agent_harness/storage/secret_store.py +142 -0
  91. ssh_agent_harness/storage/secret_vault.py +319 -0
  92. ssh_agent_harness/storage/session_store.py +890 -0
  93. ssh_agent_harness/tests/__init__.py +0 -0
  94. ssh_agent_harness/tools/__init__.py +39 -0
  95. ssh_agent_harness/tools/command_executor.py +315 -0
  96. ssh_agent_harness/tools/ssh_pool.py +524 -0
  97. ssh_agent_harness-0.1.0.dist-info/METADATA +272 -0
  98. ssh_agent_harness-0.1.0.dist-info/RECORD +102 -0
  99. ssh_agent_harness-0.1.0.dist-info/WHEEL +5 -0
  100. ssh_agent_harness-0.1.0.dist-info/entry_points.txt +2 -0
  101. ssh_agent_harness-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. ssh_agent_harness-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,4 @@
1
+ """SSH Agent Harness - Local LLM powered SSH automation."""
2
+
3
+ __version__ = "0.1.0"
4
+ __author__ = "SSH Agent Harness Contributors"
@@ -0,0 +1 @@
1
+ """Web API package (FastAPI)."""
@@ -0,0 +1,78 @@
1
+ """ssh-agent-web console entry (independent of the typer CLI on purpose)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+
9
+ import uvicorn
10
+
11
+ from ssh_agent_harness.config import set_config_override
12
+ from ssh_agent_harness.logging_setup import setup_logging
13
+
14
+
15
+ def _parse_args(argv: Sequence[str] | None) -> argparse.Namespace:
16
+ parser = argparse.ArgumentParser(
17
+ prog="ssh-agent-web",
18
+ description="Local web console (binds 127.0.0.1 by default)",
19
+ )
20
+ parser.add_argument("--host", default="127.0.0.1")
21
+ parser.add_argument("--port", type=int, default=8000)
22
+ parser.add_argument(
23
+ "--db",
24
+ default=None,
25
+ help="SQLite path (default: settings.storage.db_path)",
26
+ )
27
+ parser.add_argument("--approval-timeout", type=float, default=900.0)
28
+ parser.add_argument(
29
+ "--config",
30
+ default=None,
31
+ help=(
32
+ "settings.yaml to read (default: ~/.ssh-agent-harness/settings.yaml,"
33
+ " else the defaults bundled in the package)"
34
+ ),
35
+ )
36
+ parser.add_argument(
37
+ "--static",
38
+ default=None,
39
+ help=(
40
+ "serve this SPA build dir instead of the one shipped inside the"
41
+ " package (default: ssh_agent_harness/api/static; point it at"
42
+ " web/dist for a source checkout)"
43
+ ),
44
+ )
45
+ return parser.parse_args(argv)
46
+
47
+
48
+ def _default_static_dir() -> str | None:
49
+ """The SPA build that ships inside the wheel, or None when absent.
50
+
51
+ The wheel bundles the console (``package-data``), so an installed copy needs
52
+ no flag at all. A source checkout has an empty ``static/`` unless
53
+ ``scripts/build_frontend.py`` was run - returning None then keeps the old
54
+ behaviour (API only; the dev workflow is vite on 5173).
55
+ """
56
+ candidate = Path(__file__).resolve().parent / "static"
57
+ if (candidate / "index.html").is_file():
58
+ return str(candidate)
59
+ return None
60
+
61
+
62
+ def main(argv: Sequence[str] | None = None) -> None:
63
+ args = _parse_args(argv)
64
+ # Resolve config BEFORE setup_logging()/create_app(): both read get_settings(),
65
+ # which is an lru_cache singleton and would otherwise already hold the
66
+ # default (non---config) instance.
67
+ set_config_override(args.config)
68
+ setup_logging() # wires settings.logging (console + rotating file) before serving
69
+ from ssh_agent_harness.api.app import create_app # noqa: PLC0415 - lazy
70
+ static_dir = args.static if args.static is not None else _default_static_dir()
71
+ app = create_app(
72
+ db_path=args.db, approval_timeout=args.approval_timeout, static_dir=static_dir
73
+ )
74
+ uvicorn.run(app, host=args.host, port=args.port)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
@@ -0,0 +1,446 @@
1
+ """FastAPI application factory for the web console."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from collections.abc import AsyncIterator, Awaitable, Callable
8
+ from contextlib import asynccontextmanager
9
+ from dataclasses import asdict
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from fastapi import FastAPI, Request
14
+ from fastapi.responses import JSONResponse
15
+ from fastapi.staticfiles import StaticFiles
16
+ from starlette.exceptions import HTTPException as StarletteHTTPException
17
+ from starlette.responses import Response
18
+ from starlette.types import Scope
19
+
20
+ from ssh_agent_harness import __version__
21
+ from ssh_agent_harness.api.approvals import router as approvals_router
22
+ from ssh_agent_harness.api.deployments import router as deployments_router
23
+ from ssh_agent_harness.api.deps import (
24
+ AppState,
25
+ CommandTester,
26
+ FingerprintFn,
27
+ OrchestratorFactory,
28
+ SupportsAenterRun,
29
+ )
30
+ from ssh_agent_harness.api.hosts import router as hosts_router
31
+ from ssh_agent_harness.api.knowledge import router as knowledge_router
32
+ from ssh_agent_harness.api.llm import router as llm_router
33
+ from ssh_agent_harness.api.packages import router as packages_router
34
+ from ssh_agent_harness.api.run_manager import (
35
+ RunManager,
36
+ make_cached_fingerprint,
37
+ )
38
+ from ssh_agent_harness.api.runs import router as runs_router
39
+ from ssh_agent_harness.api.secrets import router as secrets_router
40
+ from ssh_agent_harness.api.sessions import router as sessions_router
41
+ from ssh_agent_harness.api.skills import router as skills_router
42
+ from ssh_agent_harness.config import OllamaSettings, PackagesSettings, get_settings
43
+ from ssh_agent_harness.core.artifact_catalog import build_catalog
44
+ from ssh_agent_harness.core.deploy_definition import (
45
+ DraftSaveResult,
46
+ build_draft_spec,
47
+ validate_payload,
48
+ )
49
+ from ssh_agent_harness.core.host_loader import get_host_config
50
+ from ssh_agent_harness.core.llm import LlmSelection, create_llm_client
51
+ from ssh_agent_harness.core.multi_turn import MultiTurnOrchestrator
52
+ from ssh_agent_harness.core.orchestrator import ProgressCallback, SingleTurnOrchestrator
53
+ from ssh_agent_harness.core.package_manager import PackageError, PackageManager
54
+ from ssh_agent_harness.core.plan_runner import PlanRunner
55
+ from ssh_agent_harness.core.progress import ShouldCancel
56
+ from ssh_agent_harness.core.step_loop import StepOrchestrator
57
+ from ssh_agent_harness.core.transfer_directive import DeployDraftOp
58
+ from ssh_agent_harness.harness.confirmation import ApprovalCoordinator, ConfirmationGate
59
+ from ssh_agent_harness.harness.note_policy import NoteSaveResult, save_note_with_lru
60
+ from ssh_agent_harness.storage.deploy_store import DeployStore
61
+ from ssh_agent_harness.storage.llm_store import LlmStore
62
+ from ssh_agent_harness.storage.run_store import ApprovalStore, RunStore
63
+ from ssh_agent_harness.storage.secret_vault import SecretState
64
+ from ssh_agent_harness.storage.session_store import KnowledgeStore, Storage
65
+ from ssh_agent_harness.tools.command_executor import CommandExecutor, ExecutionOptions
66
+ from ssh_agent_harness.tools.ssh_pool import HostConfig, close_pool, get_pool
67
+
68
+ logger = logging.getLogger(__name__)
69
+
70
+ _NOT_FOUND = 404
71
+ #: 423 Locked: the vault is not unlocked, so business endpoints are unavailable.
72
+ _HTTP_LOCKED = 423
73
+ #: The only prefix allowed through while locked (see ``secrets_guard``).
74
+ _SECRETS_PATH_PREFIX = "/api/secrets"
75
+
76
+
77
+ class SPAStaticFiles(StaticFiles):
78
+ """StaticFiles + HTML5 history fallback: 未命中的非 /api 路径回 index.html。
79
+
80
+ Starlette 0.52.1 实测:``get_response`` 对缺失文件 raise HTTPException(404)
81
+ (而非返回 404 Response),故覆写点为 try/except。回退只使用字面量
82
+ ``"index.html"``,经 StaticFiles 自身路径校验,不引入目录穿越。
83
+ """
84
+
85
+ async def get_response(self, path: str, scope: Scope) -> Response:
86
+ try:
87
+ return await super().get_response(path, scope)
88
+ except StarletteHTTPException as exc:
89
+ if exc.status_code == _NOT_FOUND:
90
+ return await super().get_response("index.html", scope)
91
+ raise
92
+
93
+
94
+ async def default_command_tester(host: HostConfig, command: str, timeout: float) -> dict[str, Any]:
95
+ """Real probe: run one trivial command through the shared SSH pool."""
96
+ start = time.perf_counter()
97
+ try:
98
+ result = await CommandExecutor(await get_pool()).execute(
99
+ host, command, ExecutionOptions(timeout=timeout)
100
+ )
101
+ except Exception as exc: # noqa: BLE001 - probe failure must never 500 the endpoint
102
+ return {"reachable": False, "latency_ms": None, "error": str(exc)}
103
+ latency_ms = (time.perf_counter() - start) * 1000.0
104
+ if result.success:
105
+ return {"reachable": True, "latency_ms": latency_ms, "error": None}
106
+ return {
107
+ "reachable": False,
108
+ "latency_ms": latency_ms,
109
+ "error": result.stderr.strip() or f"exit code {result.exit_code}",
110
+ }
111
+
112
+
113
+ def _resolve_host_id(storage: Storage, host: str | int) -> int | None:
114
+ """Accept an id or a legacy name and return the id, or None if unknown.
115
+
116
+ Core hands us whatever it has (step loop passes the id; older paths passed the
117
+ name). Normalising here keeps the storage layer strictly id-based.
118
+ """
119
+ if isinstance(host, int):
120
+ return host
121
+ return storage.hosts.id_for_name(host)
122
+
123
+
124
+ def _load_knowledge(
125
+ knowledge: KnowledgeStore, storage: Storage | None, host: str | int
126
+ ) -> dict[str, Any]:
127
+ """Facts for this host, keyed by fact id."""
128
+ if storage is None:
129
+ return {}
130
+ host_id = _resolve_host_id(storage, host)
131
+ if host_id is None:
132
+ return {}
133
+ return dict(knowledge.get_all(host_id))
134
+
135
+
136
+ def _make_knowledge_saver(
137
+ knowledge: KnowledgeStore,
138
+ storage: Storage,
139
+ run_id: str | None = None,
140
+ ) -> Callable[[str, str], NoteSaveResult]:
141
+ """Single shared save policy: blacklist gate + content dedupe + provenance.
142
+
143
+ Orchestrators still hand us the host *name* (core stays identity-agnostic);
144
+ the name is resolved to an id here, at the storage boundary.
145
+ """
146
+
147
+ def saver(host: str | int, value: str) -> NoteSaveResult:
148
+ host_id = _resolve_host_id(storage, host)
149
+ if host_id is None:
150
+ # Unknown host: nothing to attach knowledge to. Report it as rejected
151
+ # rather than silently dropping the model's fact.
152
+ return NoteSaveResult(saved=False, detail=f"unknown host {host!r}")
153
+ return save_note_with_lru(knowledge, host_id, value, run_id)
154
+
155
+ return saver
156
+
157
+
158
+ def _make_knowledge_toucher(
159
+ knowledge: KnowledgeStore,
160
+ storage: Storage,
161
+ ) -> Callable[[str, list[str]], None]:
162
+ """Refresh last_used for facts that made it into an injected block."""
163
+
164
+ def toucher(host: str | int, keys: list[str]) -> None:
165
+ host_id = _resolve_host_id(storage, host)
166
+ if host_id is not None:
167
+ knowledge.touch(host_id, keys)
168
+
169
+ return toucher
170
+
171
+
172
+ def _make_draft_saver(
173
+ deploy_store: DeployStore,
174
+ packages: PackagesSettings,
175
+ storage: Storage,
176
+ run_id: str | None,
177
+ ) -> Callable[[str, DeployDraftOp], DraftSaveResult]:
178
+ """Validate a model-proposed deployment definition and store it for review.
179
+
180
+ Drafts never execute anything: adopting one is an explicit console action on
181
+ the 应用部署 page. Field validation lives here (not in the fence parser)
182
+ because artifact/form/sha256 must be resolved from the manifest + local file,
183
+ which the parser has no access to.
184
+ """
185
+
186
+ def saver(host: str | int, op: DeployDraftOp) -> DraftSaveResult:
187
+ host_id = _resolve_host_id(storage, host)
188
+ if host_id is None:
189
+ return DraftSaveResult(saved=False, detail=f"unknown host {host!r}")
190
+ payload, error = validate_payload(op.payload)
191
+ if payload is None:
192
+ return DraftSaveResult(saved=False, detail=error or "draft payload invalid")
193
+ try:
194
+ manifest = PackageManager(packages).load_manifest()
195
+ except PackageError as exc:
196
+ return DraftSaveResult(saved=False, detail=f"清单读取失败: {exc}")
197
+ spec, error = build_draft_spec(op.name, payload, manifest, packages.dir)
198
+ if spec is None:
199
+ return DraftSaveResult(saved=False, detail=error or "draft invalid")
200
+ deploy_store.upsert_draft(host_id, op.name, asdict(spec), source_run_id=run_id)
201
+ return DraftSaveResult(
202
+ saved=True,
203
+ detail=(
204
+ f"部署草案已保存({op.name})。它不会自动部署:"
205
+ "请在控制台「应用部署」页确认后采纳"
206
+ ),
207
+ )
208
+
209
+ return saver
210
+
211
+
212
+ def make_default_orchestrator_factory(
213
+ llm_store: LlmStore,
214
+ ollama: OllamaSettings,
215
+ knowledge: KnowledgeStore | None = None,
216
+ storage: Storage | None = None,
217
+ deploy_store: DeployStore | None = None,
218
+ ) -> OrchestratorFactory:
219
+ """Per-app real factory: SingleTurnOrchestrator per run, MultiTurn when
220
+ ``rounds > 1``, or StepOrchestrator when ``step`` (rounds = step budget).
221
+
222
+ Reads the UI LLM selection from *this app's own* db (never the global
223
+ get_storage()), so ``--db``-isolated instances honor their own llm_config;
224
+ selection=None explicitly skips the global default-store hook. ``knowledge``
225
+ feeds the per-host workspace injection on the step path.
226
+ """
227
+
228
+ def factory( # noqa: PLR0913, PLR0917 - OrchestratorFactory protocol arity
229
+ dry_run: bool,
230
+ gate: ConfirmationGate | None,
231
+ progress_cb: ProgressCallback | None,
232
+ rounds: int,
233
+ step: bool = False,
234
+ run_id: str | None = None,
235
+ should_cancel: ShouldCancel | None = None,
236
+ ) -> SupportsAenterRun:
237
+ row = llm_store.get()
238
+ selection: LlmSelection | None = None
239
+ if row:
240
+ selection = LlmSelection(
241
+ provider=row["provider"],
242
+ model=row["model"],
243
+ api_key=row.get("api_key"),
244
+ base_url=row.get("base_url"),
245
+ adapter_type=row.get("adapter_type"),
246
+ )
247
+ client = create_llm_client(ollama, selection=selection)
248
+ if step:
249
+ # 双阶段循环:rounds 直通规划圈数(去哨兵,填几就几);Web 默认 2 由前端显式给。
250
+ return StepOrchestrator(
251
+ ollama_client=client,
252
+ dry_run=dry_run,
253
+ confirmation_gate=gate,
254
+ progress_callback=progress_cb,
255
+ plan_rounds=rounds,
256
+ should_cancel=should_cancel,
257
+ knowledge_loader=(
258
+ lambda host: _load_knowledge(knowledge, storage, host)
259
+ if knowledge
260
+ else {}
261
+ ),
262
+ knowledge_saver=(
263
+ _make_knowledge_saver(knowledge, storage, run_id)
264
+ if knowledge and storage
265
+ else None
266
+ ),
267
+ knowledge_toucher=(
268
+ _make_knowledge_toucher(knowledge, storage)
269
+ if knowledge and storage
270
+ else None
271
+ ),
272
+ draft_saver=(
273
+ _make_draft_saver(deploy_store, get_settings().packages, storage, run_id)
274
+ if deploy_store and storage
275
+ else None
276
+ ),
277
+ plan_runner=(
278
+ PlanRunner(deploy_store, get_settings().packages, run_id=run_id)
279
+ if deploy_store
280
+ else None
281
+ ),
282
+ )
283
+ if rounds > 1:
284
+ # 同一 selection client;池/执行器由 MultiTurn.__aenter__ 自行解析。
285
+ return MultiTurnOrchestrator(
286
+ ollama_client=client,
287
+ dry_run=dry_run,
288
+ confirmation_gate=gate,
289
+ progress_callback=progress_cb,
290
+ max_rounds=rounds,
291
+ should_cancel=should_cancel,
292
+ )
293
+ return SingleTurnOrchestrator(
294
+ ollama_client=client,
295
+ dry_run=dry_run,
296
+ confirmation_gate=gate,
297
+ progress_callback=progress_cb,
298
+ should_cancel=should_cancel,
299
+ )
300
+
301
+ return factory
302
+
303
+
304
+ def create_app( # noqa: PLR0913, PLR0917
305
+ db_path: str | None = None,
306
+ approval_timeout: float = 900.0,
307
+ orchestrator_factory: OrchestratorFactory | None = None,
308
+ static_dir: str | None = None,
309
+ command_tester: CommandTester | None = None,
310
+ fingerprint: FingerprintFn | None = None,
311
+ ) -> FastAPI:
312
+ """Assemble stores/coordinator/manager into ``app.state.harness`` and build routes.
313
+
314
+ Hosts come from the SQLite ``hosts`` table only (no YAML inventory).
315
+ """
316
+ settings = get_settings()
317
+ storage = Storage(db_path or settings.storage.db_path)
318
+ runs = RunStore(storage.db_manager)
319
+ approvals = ApprovalStore(storage.db_manager)
320
+ llm_store = LlmStore(storage.db_manager, storage.secrets_codec)
321
+ deploy_store = DeployStore(storage.db_manager)
322
+ coordinator = ApprovalCoordinator(approvals, timeout=approval_timeout)
323
+ manager = RunManager(
324
+ runs=runs,
325
+ approvals=approvals,
326
+ coordinator=coordinator,
327
+ orchestrator_factory=orchestrator_factory
328
+ or make_default_orchestrator_factory(
329
+ llm_store, settings.ollama, storage.knowledge, storage, deploy_store
330
+ ),
331
+ storage=storage,
332
+ # 显式绑定 app 自己的库(前置修复 D):未知 host 抛 KeyError→404 语义,绝不静默伪造。
333
+ # 按 id 解析:name 是可改且可重复的显示标签,不能用来定位。
334
+ host_resolver=lambda host_id: get_host_config(
335
+ int(host_id), db_provider=storage.hosts.list_all
336
+ ),
337
+ fingerprint=fingerprint
338
+ or make_cached_fingerprint(storage.db_manager.db_path),
339
+ # 制品目录:清单里既可能是工具链也可能是应用,模型需要知道有哪些、
340
+ # 各自是什么,否则只能靠猜包名(真实 run:把 jar 当可执行文件去找)。
341
+ # 延迟读取,每次 run 都用最新清单;读失败只降级为无目录。
342
+ # 按服务器注入:`[app]` 条目要带该服务器上的定义与 active 发布,
343
+ # 模型才能判断"同 sha 已发布"(D7)。
344
+ catalog=lambda host_id: build_catalog(
345
+ settings.packages, host_id, deploy_store
346
+ ),
347
+ )
348
+ state = AppState(
349
+ storage=storage,
350
+ runs=runs,
351
+ approvals=approvals,
352
+ coordinator=coordinator,
353
+ manager=manager,
354
+ command_tester=command_tester or default_command_tester,
355
+ hosts_provider=storage.hosts.list_all,
356
+ llm=llm_store,
357
+ deployments=deploy_store,
358
+ )
359
+
360
+ @asynccontextmanager
361
+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
362
+ recovered = runs.cleanup_interrupted(approvals)
363
+ if recovered:
364
+ logger.warning("marked %d interrupted run(s) failed on startup", recovered)
365
+ try:
366
+ yield
367
+ finally:
368
+ # Without this the pool's cleanup task and every pooled asyncssh
369
+ # connection outlive the app and only die with the interpreter.
370
+ await manager.shutdown()
371
+ await close_pool()
372
+
373
+ app = FastAPI(
374
+ title="ssh-agent-harness web console",
375
+ version=__version__,
376
+ lifespan=lifespan,
377
+ )
378
+ app.state.harness = state
379
+
380
+ @app.middleware("http")
381
+ async def secrets_guard(
382
+ request: Request, call_next: Callable[[Request], Awaitable[Response]]
383
+ ) -> Response:
384
+ """Refuse business endpoints while the credential vault is locked.
385
+
386
+ Implemented as middleware rather than a per-route dependency so a newly
387
+ added route cannot forget to opt in. Non-``/api`` paths always pass:
388
+ the SPA has to load, otherwise the unlock screen can never render.
389
+ """
390
+ path = request.url.path
391
+ if path.startswith(_SECRETS_PATH_PREFIX) or not path.startswith("/api/"):
392
+ return await call_next(request)
393
+ if app.state.harness.storage.vault.state is not SecretState.UNLOCKED:
394
+ return JSONResponse(
395
+ status_code=_HTTP_LOCKED,
396
+ content={
397
+ "detail": "凭据未解锁:请先在控制台输入加密密钥",
398
+ "state": app.state.harness.storage.vault.state.value,
399
+ },
400
+ )
401
+ return await call_next(request)
402
+
403
+ @app.get("/api/version")
404
+ async def api_version() -> dict[str, str]:
405
+ return {"version": __version__}
406
+
407
+ @app.exception_handler(Exception)
408
+ async def unhandled_error(request: Request, exc: Exception) -> JSONResponse:
409
+ logger.exception("unhandled error on %s %s", request.method, request.url.path)
410
+ return JSONResponse(status_code=500, content={"detail": str(exc)})
411
+
412
+ app.include_router(secrets_router)
413
+ app.include_router(hosts_router)
414
+ app.include_router(knowledge_router)
415
+ app.include_router(llm_router)
416
+ app.include_router(packages_router)
417
+ app.include_router(deployments_router)
418
+ app.include_router(sessions_router)
419
+ app.include_router(skills_router)
420
+ app.include_router(runs_router)
421
+ app.include_router(approvals_router)
422
+
423
+ # Registered after the real routers (Starlette matches in order → they win)
424
+ # and before the SPA mount, so unmatched /api/* answer JSON 404 instead of
425
+ # ever falling into the SPA's HTML responses.
426
+ # 裸 /api 不匹配 {rest:path}(无尾斜杠),需精确路由才有同样的 JSON 404。
427
+ @app.api_route("/api", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
428
+ async def api_bare_root() -> JSONResponse:
429
+ return JSONResponse(
430
+ status_code=_NOT_FOUND,
431
+ content={"detail": "No API route: /api"},
432
+ )
433
+
434
+ @app.api_route(
435
+ "/api/{rest:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"]
436
+ )
437
+ async def api_no_such_route(rest: str) -> JSONResponse:
438
+ return JSONResponse(
439
+ status_code=_NOT_FOUND,
440
+ content={"detail": f"No API route: /api/{rest}"},
441
+ )
442
+
443
+ # SPA mount last so /api/* routes always win.
444
+ if static_dir and Path(static_dir).is_dir():
445
+ app.mount("/", SPAStaticFiles(directory=static_dir, html=True), name="spa")
446
+ return app
@@ -0,0 +1,45 @@
1
+ """Approval inbox routes: list pending, submit approve/deny decisions.
2
+
3
+ The suspended run itself is woken by ApprovalCoordinator.decide (in-process
4
+ Event); this layer only persists via the coordinator and mirrors the row back.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from fastapi import APIRouter, HTTPException, Request
10
+
11
+ from ssh_agent_harness.api.deps import get_state
12
+ from ssh_agent_harness.api.schemas import ApprovalDecision, ApprovalOut
13
+
14
+ router = APIRouter(prefix="/api/approvals", tags=["approvals"])
15
+
16
+ _PENDING = "pending"
17
+
18
+
19
+ @router.get("", response_model=list[ApprovalOut])
20
+ async def list_approvals(
21
+ request: Request, run_id: str | None = None, status: str | None = None
22
+ ) -> list[ApprovalOut]:
23
+ """Pending approvals (optionally per run); decided rows leave the inbox."""
24
+ state = get_state(request)
25
+ if status is not None and status != _PENDING:
26
+ raise HTTPException(
27
+ status_code=422, detail=f"unsupported status '{status}'; only 'pending' is available"
28
+ )
29
+ return [ApprovalOut(**r) for r in state.approvals.list_pending(run_id)]
30
+
31
+
32
+ @router.post("/{approval_id}/decide", response_model=ApprovalOut)
33
+ async def decide_approval(
34
+ approval_id: int, body: ApprovalDecision, request: Request
35
+ ) -> ApprovalOut:
36
+ """First decision wins and wakes the waiter; a second decide gets 409."""
37
+ state = get_state(request)
38
+ if state.approvals.get(approval_id) is None:
39
+ raise HTTPException(status_code=404, detail=f"approval '{approval_id}' not found")
40
+ if not state.coordinator.decide(approval_id, body.decision == "approve"):
41
+ raise HTTPException(status_code=409, detail="already decided or not found")
42
+ row = state.approvals.get(approval_id)
43
+ if row is None: # pragma: no cover - decide just wrote this row
44
+ raise HTTPException(status_code=500, detail="approval row vanished")
45
+ return ApprovalOut(**row)