ssh-agent-harness 0.1.0rc1__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 (75) 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 +339 -0
  5. ssh_agent_harness/api/approvals.py +45 -0
  6. ssh_agent_harness/api/deps.py +95 -0
  7. ssh_agent_harness/api/hosts.py +146 -0
  8. ssh_agent_harness/api/knowledge.py +113 -0
  9. ssh_agent_harness/api/llm.py +136 -0
  10. ssh_agent_harness/api/package_inspect.py +120 -0
  11. ssh_agent_harness/api/packages.py +387 -0
  12. ssh_agent_harness/api/run_manager.py +528 -0
  13. ssh_agent_harness/api/runs.py +74 -0
  14. ssh_agent_harness/api/schemas.py +307 -0
  15. ssh_agent_harness/api/sessions.py +72 -0
  16. ssh_agent_harness/api/static/__init__.py +10 -0
  17. ssh_agent_harness/api/static/assets/index-C6jsNDMh.css +1 -0
  18. ssh_agent_harness/api/static/assets/index-D31rM0uZ.js +461 -0
  19. ssh_agent_harness/api/static/favicon-32.png +0 -0
  20. ssh_agent_harness/api/static/favicon.ico +0 -0
  21. ssh_agent_harness/api/static/icon-192.png +0 -0
  22. ssh_agent_harness/api/static/icon-512.png +0 -0
  23. ssh_agent_harness/api/static/index.html +14 -0
  24. ssh_agent_harness/config.py +256 -0
  25. ssh_agent_harness/core/__init__.py +76 -0
  26. ssh_agent_harness/core/fingerprint.py +541 -0
  27. ssh_agent_harness/core/generation.py +91 -0
  28. ssh_agent_harness/core/host_loader.py +104 -0
  29. ssh_agent_harness/core/host_workspace.py +67 -0
  30. ssh_agent_harness/core/install_step.py +117 -0
  31. ssh_agent_harness/core/llm.py +232 -0
  32. ssh_agent_harness/core/llm_logging.py +67 -0
  33. ssh_agent_harness/core/llm_presets.py +107 -0
  34. ssh_agent_harness/core/model_adapter.py +487 -0
  35. ssh_agent_harness/core/multi_turn.py +336 -0
  36. ssh_agent_harness/core/ollama_client.py +653 -0
  37. ssh_agent_harness/core/orchestrator.py +523 -0
  38. ssh_agent_harness/core/package_commands.py +156 -0
  39. ssh_agent_harness/core/package_installer.py +531 -0
  40. ssh_agent_harness/core/package_manager.py +245 -0
  41. ssh_agent_harness/core/progress.py +87 -0
  42. ssh_agent_harness/core/prompt_context.py +43 -0
  43. ssh_agent_harness/core/reflection.py +205 -0
  44. ssh_agent_harness/core/run_persistence.py +55 -0
  45. ssh_agent_harness/core/step_items.py +237 -0
  46. ssh_agent_harness/core/step_loop.py +481 -0
  47. ssh_agent_harness/core/step_observation.py +46 -0
  48. ssh_agent_harness/core/step_phases.py +134 -0
  49. ssh_agent_harness/core/step_state.py +60 -0
  50. ssh_agent_harness/core/transfer_directive.py +324 -0
  51. ssh_agent_harness/core/transfer_executor.py +180 -0
  52. ssh_agent_harness/core/two_phase.py +365 -0
  53. ssh_agent_harness/default_settings.yaml +77 -0
  54. ssh_agent_harness/harness/__init__.py +75 -0
  55. ssh_agent_harness/harness/confirmation.py +517 -0
  56. ssh_agent_harness/harness/note_policy.py +170 -0
  57. ssh_agent_harness/harness/prompts.py +436 -0
  58. ssh_agent_harness/harness/protocol.py +216 -0
  59. ssh_agent_harness/harness/safety.py +477 -0
  60. ssh_agent_harness/harness/transfer_policy.py +177 -0
  61. ssh_agent_harness/logging_setup.py +141 -0
  62. ssh_agent_harness/storage/__init__.py +25 -0
  63. ssh_agent_harness/storage/host_store.py +153 -0
  64. ssh_agent_harness/storage/llm_store.py +80 -0
  65. ssh_agent_harness/storage/run_store.py +282 -0
  66. ssh_agent_harness/storage/session_store.py +865 -0
  67. ssh_agent_harness/tests/__init__.py +0 -0
  68. ssh_agent_harness/tools/__init__.py +39 -0
  69. ssh_agent_harness/tools/command_executor.py +314 -0
  70. ssh_agent_harness/tools/ssh_pool.py +446 -0
  71. ssh_agent_harness-0.1.0rc1.dist-info/METADATA +239 -0
  72. ssh_agent_harness-0.1.0rc1.dist-info/RECORD +75 -0
  73. ssh_agent_harness-0.1.0rc1.dist-info/WHEEL +5 -0
  74. ssh_agent_harness-0.1.0rc1.dist-info/entry_points.txt +2 -0
  75. ssh_agent_harness-0.1.0rc1.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,339 @@
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, Callable
8
+ from contextlib import asynccontextmanager
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from fastapi import FastAPI, Request
13
+ from fastapi.responses import JSONResponse
14
+ from fastapi.staticfiles import StaticFiles
15
+ from starlette.exceptions import HTTPException as StarletteHTTPException
16
+ from starlette.responses import Response
17
+ from starlette.types import Scope
18
+
19
+ from ssh_agent_harness import __version__
20
+ from ssh_agent_harness.api.approvals import router as approvals_router
21
+ from ssh_agent_harness.api.deps import (
22
+ AppState,
23
+ CommandTester,
24
+ FingerprintFn,
25
+ OrchestratorFactory,
26
+ SupportsAenterRun,
27
+ )
28
+ from ssh_agent_harness.api.hosts import router as hosts_router
29
+ from ssh_agent_harness.api.knowledge import router as knowledge_router
30
+ from ssh_agent_harness.api.llm import router as llm_router
31
+ from ssh_agent_harness.api.packages import router as packages_router
32
+ from ssh_agent_harness.api.run_manager import (
33
+ RunManager,
34
+ make_cached_fingerprint,
35
+ )
36
+ from ssh_agent_harness.api.runs import router as runs_router
37
+ from ssh_agent_harness.api.sessions import router as sessions_router
38
+ from ssh_agent_harness.config import OllamaSettings, get_settings
39
+ from ssh_agent_harness.core.host_loader import get_host_config
40
+ from ssh_agent_harness.core.llm import LlmSelection, create_llm_client
41
+ from ssh_agent_harness.core.multi_turn import MultiTurnOrchestrator
42
+ from ssh_agent_harness.core.orchestrator import ProgressCallback, SingleTurnOrchestrator
43
+ from ssh_agent_harness.core.progress import ShouldCancel
44
+ from ssh_agent_harness.core.step_loop import StepOrchestrator
45
+ from ssh_agent_harness.harness.confirmation import ApprovalCoordinator, ConfirmationGate
46
+ from ssh_agent_harness.harness.note_policy import NoteSaveResult, save_note_with_lru
47
+ from ssh_agent_harness.storage.llm_store import LlmStore
48
+ from ssh_agent_harness.storage.run_store import ApprovalStore, RunStore
49
+ from ssh_agent_harness.storage.session_store import KnowledgeStore, Storage
50
+ from ssh_agent_harness.tools.command_executor import CommandExecutor, ExecutionOptions
51
+ from ssh_agent_harness.tools.ssh_pool import HostConfig, close_pool, get_pool
52
+
53
+ logger = logging.getLogger(__name__)
54
+
55
+ _NOT_FOUND = 404
56
+
57
+
58
+ class SPAStaticFiles(StaticFiles):
59
+ """StaticFiles + HTML5 history fallback: 未命中的非 /api 路径回 index.html。
60
+
61
+ Starlette 0.52.1 实测:``get_response`` 对缺失文件 raise HTTPException(404)
62
+ (而非返回 404 Response),故覆写点为 try/except。回退只使用字面量
63
+ ``"index.html"``,经 StaticFiles 自身路径校验,不引入目录穿越。
64
+ """
65
+
66
+ async def get_response(self, path: str, scope: Scope) -> Response:
67
+ try:
68
+ return await super().get_response(path, scope)
69
+ except StarletteHTTPException as exc:
70
+ if exc.status_code == _NOT_FOUND:
71
+ return await super().get_response("index.html", scope)
72
+ raise
73
+
74
+
75
+ async def default_command_tester(host: HostConfig, command: str, timeout: float) -> dict[str, Any]:
76
+ """Real probe: run one trivial command through the shared SSH pool."""
77
+ start = time.perf_counter()
78
+ try:
79
+ result = await CommandExecutor(await get_pool()).execute(
80
+ host, command, ExecutionOptions(timeout=timeout)
81
+ )
82
+ except Exception as exc: # noqa: BLE001 - probe failure must never 500 the endpoint
83
+ return {"reachable": False, "latency_ms": None, "error": str(exc)}
84
+ latency_ms = (time.perf_counter() - start) * 1000.0
85
+ if result.success:
86
+ return {"reachable": True, "latency_ms": latency_ms, "error": None}
87
+ return {
88
+ "reachable": False,
89
+ "latency_ms": latency_ms,
90
+ "error": result.stderr.strip() or f"exit code {result.exit_code}",
91
+ }
92
+
93
+
94
+ def _resolve_host_id(storage: Storage, host: str | int) -> int | None:
95
+ """Accept an id or a legacy name and return the id, or None if unknown.
96
+
97
+ Core hands us whatever it has (step loop passes the id; older paths passed the
98
+ name). Normalising here keeps the storage layer strictly id-based.
99
+ """
100
+ if isinstance(host, int):
101
+ return host
102
+ return storage.hosts.id_for_name(host)
103
+
104
+
105
+ def _load_knowledge(
106
+ knowledge: KnowledgeStore, storage: Storage | None, host: str | int
107
+ ) -> dict[str, Any]:
108
+ """Facts for this host, keyed by fact id."""
109
+ if storage is None:
110
+ return {}
111
+ host_id = _resolve_host_id(storage, host)
112
+ if host_id is None:
113
+ return {}
114
+ return dict(knowledge.get_all(host_id))
115
+
116
+
117
+ def _make_knowledge_saver(
118
+ knowledge: KnowledgeStore,
119
+ storage: Storage,
120
+ run_id: str | None = None,
121
+ ) -> Callable[[str, str], NoteSaveResult]:
122
+ """Single shared save policy: blacklist gate + content dedupe + provenance.
123
+
124
+ Orchestrators still hand us the host *name* (core stays identity-agnostic);
125
+ the name is resolved to an id here, at the storage boundary.
126
+ """
127
+
128
+ def saver(host: str | int, value: str) -> NoteSaveResult:
129
+ host_id = _resolve_host_id(storage, host)
130
+ if host_id is None:
131
+ # Unknown host: nothing to attach knowledge to. Report it as rejected
132
+ # rather than silently dropping the model's fact.
133
+ return NoteSaveResult(saved=False, detail=f"unknown host {host!r}")
134
+ return save_note_with_lru(knowledge, host_id, value, run_id)
135
+
136
+ return saver
137
+
138
+
139
+ def _make_knowledge_toucher(
140
+ knowledge: KnowledgeStore,
141
+ storage: Storage,
142
+ ) -> Callable[[str, list[str]], None]:
143
+ """Refresh last_used for facts that made it into an injected block."""
144
+
145
+ def toucher(host: str | int, keys: list[str]) -> None:
146
+ host_id = _resolve_host_id(storage, host)
147
+ if host_id is not None:
148
+ knowledge.touch(host_id, keys)
149
+
150
+ return toucher
151
+
152
+
153
+ def make_default_orchestrator_factory(
154
+ llm_store: LlmStore,
155
+ ollama: OllamaSettings,
156
+ knowledge: KnowledgeStore | None = None,
157
+ storage: Storage | None = None,
158
+ ) -> OrchestratorFactory:
159
+ """Per-app real factory: SingleTurnOrchestrator per run, MultiTurn when
160
+ ``rounds > 1``, or StepOrchestrator when ``step`` (rounds = step budget).
161
+
162
+ Reads the UI LLM selection from *this app's own* db (never the global
163
+ get_storage()), so ``--db``-isolated instances honor their own llm_config;
164
+ selection=None explicitly skips the global default-store hook. ``knowledge``
165
+ feeds the per-host workspace injection on the step path.
166
+ """
167
+
168
+ def factory( # noqa: PLR0913, PLR0917 - OrchestratorFactory protocol arity
169
+ dry_run: bool,
170
+ gate: ConfirmationGate | None,
171
+ progress_cb: ProgressCallback | None,
172
+ rounds: int,
173
+ step: bool = False,
174
+ run_id: str | None = None,
175
+ should_cancel: ShouldCancel | None = None,
176
+ ) -> SupportsAenterRun:
177
+ row = llm_store.get()
178
+ selection: LlmSelection | None = None
179
+ if row:
180
+ selection = LlmSelection(
181
+ provider=row["provider"],
182
+ model=row["model"],
183
+ api_key=row.get("api_key"),
184
+ base_url=row.get("base_url"),
185
+ adapter_type=row.get("adapter_type"),
186
+ )
187
+ client = create_llm_client(ollama, selection=selection)
188
+ if step:
189
+ # 双阶段循环:rounds 直通规划圈数(去哨兵,填几就几);Web 默认 2 由前端显式给。
190
+ return StepOrchestrator(
191
+ ollama_client=client,
192
+ dry_run=dry_run,
193
+ confirmation_gate=gate,
194
+ progress_callback=progress_cb,
195
+ plan_rounds=rounds,
196
+ should_cancel=should_cancel,
197
+ knowledge_loader=(
198
+ lambda host: _load_knowledge(knowledge, storage, host)
199
+ if knowledge
200
+ else {}
201
+ ),
202
+ knowledge_saver=(
203
+ _make_knowledge_saver(knowledge, storage, run_id)
204
+ if knowledge and storage
205
+ else None
206
+ ),
207
+ knowledge_toucher=(
208
+ _make_knowledge_toucher(knowledge, storage)
209
+ if knowledge and storage
210
+ else None
211
+ ),
212
+ )
213
+ if rounds > 1:
214
+ # 同一 selection client;池/执行器由 MultiTurn.__aenter__ 自行解析。
215
+ return MultiTurnOrchestrator(
216
+ ollama_client=client,
217
+ dry_run=dry_run,
218
+ confirmation_gate=gate,
219
+ progress_callback=progress_cb,
220
+ max_rounds=rounds,
221
+ should_cancel=should_cancel,
222
+ )
223
+ return SingleTurnOrchestrator(
224
+ ollama_client=client,
225
+ dry_run=dry_run,
226
+ confirmation_gate=gate,
227
+ progress_callback=progress_cb,
228
+ should_cancel=should_cancel,
229
+ )
230
+
231
+ return factory
232
+
233
+
234
+ def create_app( # noqa: PLR0913, PLR0917
235
+ db_path: str | None = None,
236
+ approval_timeout: float = 900.0,
237
+ orchestrator_factory: OrchestratorFactory | None = None,
238
+ static_dir: str | None = None,
239
+ command_tester: CommandTester | None = None,
240
+ fingerprint: FingerprintFn | None = None,
241
+ ) -> FastAPI:
242
+ """Assemble stores/coordinator/manager into ``app.state.harness`` and build routes.
243
+
244
+ Hosts come from the SQLite ``hosts`` table only (no YAML inventory).
245
+ """
246
+ settings = get_settings()
247
+ storage = Storage(db_path or settings.storage.db_path)
248
+ runs = RunStore(storage.db_manager)
249
+ approvals = ApprovalStore(storage.db_manager)
250
+ llm_store = LlmStore(storage.db_manager)
251
+ coordinator = ApprovalCoordinator(approvals, timeout=approval_timeout)
252
+ manager = RunManager(
253
+ runs=runs,
254
+ approvals=approvals,
255
+ coordinator=coordinator,
256
+ orchestrator_factory=orchestrator_factory
257
+ or make_default_orchestrator_factory(
258
+ llm_store, settings.ollama, storage.knowledge, storage),
259
+ storage=storage,
260
+ # 显式绑定 app 自己的库(前置修复 D):未知 host 抛 KeyError→404 语义,绝不静默伪造。
261
+ # 按 id 解析:name 是可改且可重复的显示标签,不能用来定位。
262
+ host_resolver=lambda host_id: get_host_config(
263
+ int(host_id), db_provider=storage.hosts.list_all
264
+ ),
265
+ fingerprint=fingerprint
266
+ or make_cached_fingerprint(storage.db_manager.db_path),
267
+ )
268
+ state = AppState(
269
+ storage=storage,
270
+ runs=runs,
271
+ approvals=approvals,
272
+ coordinator=coordinator,
273
+ manager=manager,
274
+ command_tester=command_tester or default_command_tester,
275
+ hosts_provider=storage.hosts.list_all,
276
+ llm=llm_store,
277
+ )
278
+
279
+ @asynccontextmanager
280
+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
281
+ recovered = runs.cleanup_interrupted(approvals)
282
+ if recovered:
283
+ logger.warning("marked %d interrupted run(s) failed on startup", recovered)
284
+ try:
285
+ yield
286
+ finally:
287
+ # Without this the pool's cleanup task and every pooled asyncssh
288
+ # connection outlive the app and only die with the interpreter.
289
+ await manager.shutdown()
290
+ await close_pool()
291
+
292
+ app = FastAPI(
293
+ title="ssh-agent-harness web console",
294
+ version=__version__,
295
+ lifespan=lifespan,
296
+ )
297
+ app.state.harness = state
298
+
299
+ @app.get("/api/version")
300
+ async def api_version() -> dict[str, str]:
301
+ return {"version": __version__}
302
+
303
+ @app.exception_handler(Exception)
304
+ async def unhandled_error(request: Request, exc: Exception) -> JSONResponse:
305
+ logger.exception("unhandled error on %s %s", request.method, request.url.path)
306
+ return JSONResponse(status_code=500, content={"detail": str(exc)})
307
+
308
+ app.include_router(hosts_router)
309
+ app.include_router(knowledge_router)
310
+ app.include_router(llm_router)
311
+ app.include_router(packages_router)
312
+ app.include_router(sessions_router)
313
+ app.include_router(runs_router)
314
+ app.include_router(approvals_router)
315
+
316
+ # Registered after the real routers (Starlette matches in order → they win)
317
+ # and before the SPA mount, so unmatched /api/* answer JSON 404 instead of
318
+ # ever falling into the SPA's HTML responses.
319
+ # 裸 /api 不匹配 {rest:path}(无尾斜杠),需精确路由才有同样的 JSON 404。
320
+ @app.api_route("/api", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
321
+ async def api_bare_root() -> JSONResponse:
322
+ return JSONResponse(
323
+ status_code=_NOT_FOUND,
324
+ content={"detail": "No API route: /api"},
325
+ )
326
+
327
+ @app.api_route(
328
+ "/api/{rest:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"]
329
+ )
330
+ async def api_no_such_route(rest: str) -> JSONResponse:
331
+ return JSONResponse(
332
+ status_code=_NOT_FOUND,
333
+ content={"detail": f"No API route: /api/{rest}"},
334
+ )
335
+
336
+ # SPA mount last so /api/* routes always win.
337
+ if static_dir and Path(static_dir).is_dir():
338
+ app.mount("/", SPAStaticFiles(directory=static_dir, html=True), name="spa")
339
+ 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)
@@ -0,0 +1,95 @@
1
+ """Dependency container: app state, orchestrator protocol, route deps."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
8
+
9
+ from fastapi import Request
10
+
11
+ from ssh_agent_harness.core.orchestrator import OrchestratorResult, ProgressCallback
12
+ from ssh_agent_harness.core.progress import ShouldCancel
13
+ from ssh_agent_harness.harness.confirmation import ConfirmationGate
14
+ from ssh_agent_harness.tools.command_executor import ExecutionOptions
15
+ from ssh_agent_harness.tools.ssh_pool import HostConfig
16
+
17
+ if TYPE_CHECKING:
18
+ from ssh_agent_harness.api.run_manager import RunManager
19
+ from ssh_agent_harness.harness.confirmation import ApprovalCoordinator
20
+ from ssh_agent_harness.storage.llm_store import LlmStore
21
+ from ssh_agent_harness.storage.run_store import ApprovalStore, RunStore
22
+ from ssh_agent_harness.storage.session_store import Storage
23
+
24
+
25
+ @runtime_checkable
26
+ class SupportsAenterRun(Protocol):
27
+ """Structural contract of an orchestrator usable by RunManager.
28
+
29
+ Runtime-checkable and signature-based so Task 9 fakes satisfy it
30
+ without inheriting from SingleTurnOrchestrator.
31
+ """
32
+
33
+ async def __aenter__(self) -> SupportsAenterRun: ...
34
+
35
+ async def __aexit__(
36
+ self,
37
+ exc_type: type[BaseException] | None,
38
+ exc: BaseException | None,
39
+ tb: Any,
40
+ ) -> None: ...
41
+
42
+ async def run(
43
+ self,
44
+ task: str,
45
+ host: HostConfig,
46
+ options: ExecutionOptions | None = None,
47
+ host_info: dict[str, Any] | None = None,
48
+ ) -> OrchestratorResult: ...
49
+
50
+
51
+ # Kept as an alias: the design sketch referred to this protocol by this name.
52
+ SupportsRun = SupportsAenterRun
53
+
54
+ OrchestratorFactory = Callable[
55
+ [
56
+ bool,
57
+ ConfirmationGate | None,
58
+ ProgressCallback | None,
59
+ int,
60
+ bool,
61
+ str | None,
62
+ ShouldCancel | None,
63
+ ],
64
+ SupportsAenterRun,
65
+ ]
66
+
67
+
68
+ # Connectivity probe seam: (host, command, timeout) → {"reachable","latency_ms","error"}.
69
+ CommandTester = Callable[[HostConfig, str, float], Awaitable[dict[str, Any]]]
70
+
71
+ # Fingerprint seam: host → host_info dict (raising degrades to None, like the CLI).
72
+ FingerprintFn = Callable[[HostConfig], Awaitable[dict[str, Any]]]
73
+
74
+
75
+ @dataclass
76
+ class AppState:
77
+ """Per-app container, stored as ``app.state.harness`` (single namespace)."""
78
+
79
+ storage: Storage
80
+ runs: RunStore
81
+ approvals: ApprovalStore
82
+ coordinator: ApprovalCoordinator
83
+ manager: RunManager
84
+ command_tester: CommandTester
85
+ # DB host rows of *this app's own* storage (same db as --db); injected into
86
+ # host_loader so api reads never touch the global get_storage()/cache.
87
+ hosts_provider: Callable[[], list[dict[str, Any]]]
88
+ # UI-selected LLM config row store bound to *this app's own* db.
89
+ llm: LlmStore
90
+
91
+
92
+ def get_state(request: Request) -> AppState:
93
+ """FastAPI dependency giving routes the whole wiring container."""
94
+ state: AppState = request.app.state.harness
95
+ return state