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.
- ssh_agent_harness/__init__.py +4 -0
- ssh_agent_harness/api/__init__.py +1 -0
- ssh_agent_harness/api/__main__.py +78 -0
- ssh_agent_harness/api/app.py +446 -0
- ssh_agent_harness/api/approvals.py +45 -0
- ssh_agent_harness/api/deployments.py +446 -0
- ssh_agent_harness/api/deps.py +98 -0
- ssh_agent_harness/api/hosts.py +146 -0
- ssh_agent_harness/api/knowledge.py +113 -0
- ssh_agent_harness/api/llm.py +208 -0
- ssh_agent_harness/api/package_inspect.py +120 -0
- ssh_agent_harness/api/packages.py +448 -0
- ssh_agent_harness/api/run_manager.py +571 -0
- ssh_agent_harness/api/runs.py +74 -0
- ssh_agent_harness/api/schemas.py +495 -0
- ssh_agent_harness/api/secrets.py +105 -0
- ssh_agent_harness/api/sessions.py +72 -0
- ssh_agent_harness/api/skill_schemas.py +96 -0
- ssh_agent_harness/api/skills.py +172 -0
- ssh_agent_harness/api/static/__init__.py +10 -0
- ssh_agent_harness/api/static/assets/index-C6jsNDMh.css +1 -0
- ssh_agent_harness/api/static/assets/index-CfCWLEGv.js +471 -0
- ssh_agent_harness/api/static/favicon-32.png +0 -0
- ssh_agent_harness/api/static/favicon.ico +0 -0
- ssh_agent_harness/api/static/icon-192.png +0 -0
- ssh_agent_harness/api/static/icon-512.png +0 -0
- ssh_agent_harness/api/static/index.html +14 -0
- ssh_agent_harness/api/synthetic_run.py +142 -0
- ssh_agent_harness/compat.py +79 -0
- ssh_agent_harness/config.py +317 -0
- ssh_agent_harness/core/__init__.py +76 -0
- ssh_agent_harness/core/artifact_catalog.py +175 -0
- ssh_agent_harness/core/deploy_definition.py +396 -0
- ssh_agent_harness/core/deploy_plan.py +198 -0
- ssh_agent_harness/core/deploy_primitives.py +625 -0
- ssh_agent_harness/core/deployer.py +754 -0
- ssh_agent_harness/core/fingerprint.py +541 -0
- ssh_agent_harness/core/gate_hooks.py +49 -0
- ssh_agent_harness/core/generation.py +91 -0
- ssh_agent_harness/core/host_loader.py +104 -0
- ssh_agent_harness/core/host_workspace.py +67 -0
- ssh_agent_harness/core/install_step.py +106 -0
- ssh_agent_harness/core/llm.py +232 -0
- ssh_agent_harness/core/llm_discovery.py +186 -0
- ssh_agent_harness/core/llm_logging.py +126 -0
- ssh_agent_harness/core/llm_presets.py +122 -0
- ssh_agent_harness/core/model_adapter.py +509 -0
- ssh_agent_harness/core/multi_turn.py +337 -0
- ssh_agent_harness/core/ollama_client.py +653 -0
- ssh_agent_harness/core/orchestrator.py +523 -0
- ssh_agent_harness/core/package_commands.py +166 -0
- ssh_agent_harness/core/package_installer.py +670 -0
- ssh_agent_harness/core/package_manager.py +343 -0
- ssh_agent_harness/core/path_policy.py +66 -0
- ssh_agent_harness/core/plan_runner.py +283 -0
- ssh_agent_harness/core/progress.py +87 -0
- ssh_agent_harness/core/prompt_context.py +43 -0
- ssh_agent_harness/core/reflection.py +302 -0
- ssh_agent_harness/core/run_persistence.py +55 -0
- ssh_agent_harness/core/skill_import.py +272 -0
- ssh_agent_harness/core/skill_runtime.py +155 -0
- ssh_agent_harness/core/skills.py +498 -0
- ssh_agent_harness/core/step_items.py +331 -0
- ssh_agent_harness/core/step_loop.py +535 -0
- ssh_agent_harness/core/step_observation.py +48 -0
- ssh_agent_harness/core/step_phases.py +189 -0
- ssh_agent_harness/core/step_state.py +66 -0
- ssh_agent_harness/core/transfer_directive.py +447 -0
- ssh_agent_harness/core/transfer_executor.py +180 -0
- ssh_agent_harness/core/two_phase.py +408 -0
- ssh_agent_harness/core/upload_guard.py +91 -0
- ssh_agent_harness/default_settings.yaml +99 -0
- ssh_agent_harness/harness/__init__.py +75 -0
- ssh_agent_harness/harness/confirmation.py +517 -0
- ssh_agent_harness/harness/note_policy.py +170 -0
- ssh_agent_harness/harness/prompts.py +449 -0
- ssh_agent_harness/harness/protocol.py +217 -0
- ssh_agent_harness/harness/safety.py +477 -0
- ssh_agent_harness/harness/transfer_policy.py +177 -0
- ssh_agent_harness/logging_setup.py +152 -0
- ssh_agent_harness/security/__init__.py +23 -0
- ssh_agent_harness/security/secrets.py +155 -0
- ssh_agent_harness/skills/deploy/SKILL.md +53 -0
- ssh_agent_harness/skills/install/SKILL.md +43 -0
- ssh_agent_harness/storage/__init__.py +25 -0
- ssh_agent_harness/storage/deploy_store.py +527 -0
- ssh_agent_harness/storage/host_store.py +186 -0
- ssh_agent_harness/storage/llm_store.py +106 -0
- ssh_agent_harness/storage/run_store.py +286 -0
- ssh_agent_harness/storage/secret_store.py +142 -0
- ssh_agent_harness/storage/secret_vault.py +319 -0
- ssh_agent_harness/storage/session_store.py +890 -0
- ssh_agent_harness/tests/__init__.py +0 -0
- ssh_agent_harness/tools/__init__.py +39 -0
- ssh_agent_harness/tools/command_executor.py +315 -0
- ssh_agent_harness/tools/ssh_pool.py +524 -0
- ssh_agent_harness-0.1.0.dist-info/METADATA +272 -0
- ssh_agent_harness-0.1.0.dist-info/RECORD +102 -0
- ssh_agent_harness-0.1.0.dist-info/WHEEL +5 -0
- ssh_agent_harness-0.1.0.dist-info/entry_points.txt +2 -0
- ssh_agent_harness-0.1.0.dist-info/licenses/LICENSE +21 -0
- ssh_agent_harness-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""Deployment routes: app definitions, deploy/rollback, release history.
|
|
2
|
+
|
|
3
|
+
One deploy = one approval for the whole mutation script (design D11). The
|
|
4
|
+
request stays open until the script finishes (stop + start + 60s health window),
|
|
5
|
+
so the console shows it as a synthetic ``dep-<uuid>`` run row exactly like an
|
|
6
|
+
install.
|
|
7
|
+
|
|
8
|
+
Boundary with install: this page owns artifacts that must keep running.
|
|
9
|
+
``kind=app`` entries are refused by the install channel (P0.5), and nothing here
|
|
10
|
+
calls the model - P1 is deliberately template-driven (design D10).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import logging
|
|
17
|
+
import time
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from fastapi import APIRouter, HTTPException, Request
|
|
21
|
+
|
|
22
|
+
from ssh_agent_harness.api.deps import AppState, get_state
|
|
23
|
+
from ssh_agent_harness.api.schemas import (
|
|
24
|
+
DeploymentDraftDeleted,
|
|
25
|
+
DeploymentDraftOut,
|
|
26
|
+
DeploymentIn,
|
|
27
|
+
DeploymentOut,
|
|
28
|
+
DeployResult,
|
|
29
|
+
ReleaseOut,
|
|
30
|
+
)
|
|
31
|
+
from ssh_agent_harness.api.synthetic_run import SyntheticRun
|
|
32
|
+
from ssh_agent_harness.config import PackagesSettings, get_settings
|
|
33
|
+
from ssh_agent_harness.core.deploy_definition import (
|
|
34
|
+
validate_app_dir,
|
|
35
|
+
validate_artifact_file,
|
|
36
|
+
validate_commands,
|
|
37
|
+
validate_name,
|
|
38
|
+
validate_probe,
|
|
39
|
+
)
|
|
40
|
+
from ssh_agent_harness.core.deployer import Deployer, DeployHooks, DeployOutcome
|
|
41
|
+
from ssh_agent_harness.core.host_loader import get_host_config
|
|
42
|
+
from ssh_agent_harness.tools.ssh_pool import HostConfig, get_pool
|
|
43
|
+
|
|
44
|
+
router = APIRouter(prefix="/api", tags=["deployments"])
|
|
45
|
+
logger = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
_BAD_GATEWAY = 502
|
|
48
|
+
_DEPLOY_REASON = "部署应用需要在远端服务器执行停止旧进程、切换版本、启动与探活,确认执行?"
|
|
49
|
+
_ROLLBACK_REASON = "回滚会把 current 切到上一次发布并重启应用,确认执行?"
|
|
50
|
+
#: Same host+app deploy requests are serialized; the second gets 409.
|
|
51
|
+
_LOCKS: dict[tuple[int, str], asyncio.Lock] = {}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _settings() -> PackagesSettings:
|
|
55
|
+
return get_settings().packages
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _host_or_404(host_id: int, state: AppState) -> HostConfig:
|
|
59
|
+
try:
|
|
60
|
+
return get_host_config(host_id, db_provider=state.hosts_provider)
|
|
61
|
+
except KeyError:
|
|
62
|
+
raise HTTPException(status_code=404, detail=f"host {host_id} not found") from None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _deployment_or_404(state: AppState, host_id: int, name: str) -> dict[str, Any]:
|
|
66
|
+
row = state.deployments.get(host_id, name)
|
|
67
|
+
if row is None:
|
|
68
|
+
raise HTTPException(status_code=404, detail=f"应用 {name!r} 未定义")
|
|
69
|
+
return row
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _lock(host_id: int, name: str) -> asyncio.Lock:
|
|
73
|
+
return _LOCKS.setdefault((host_id, name), asyncio.Lock())
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _DeployRun(SyntheticRun):
|
|
77
|
+
"""Synthetic run row for one deploy/rollback (same shape as install)."""
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self, state: AppState, host_cfg: HostConfig, app: str, action: str
|
|
81
|
+
) -> None:
|
|
82
|
+
super().__init__(
|
|
83
|
+
state,
|
|
84
|
+
host_cfg,
|
|
85
|
+
f"{action}应用 {app} → {host_cfg.name}",
|
|
86
|
+
reason=_DEPLOY_REASON if action == "部署" else _ROLLBACK_REASON,
|
|
87
|
+
prefix="dep",
|
|
88
|
+
note="该任务由控制台部署通道执行:未调用模型,命令由固定流程生成。",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---- validation -------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _bad(detail: str) -> HTTPException:
|
|
96
|
+
return HTTPException(status_code=400, detail=detail)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _validated_fields(name: str, body: DeploymentIn) -> dict[str, Any]:
|
|
100
|
+
"""Validate the definition and pin the artifact sha256 (server-side truth)."""
|
|
101
|
+
bad = validate_name(name)
|
|
102
|
+
if bad is not None:
|
|
103
|
+
raise _bad(bad)
|
|
104
|
+
artifact = body.artifact.strip()
|
|
105
|
+
sha, error = validate_artifact_file(artifact, body.form, _settings().dir)
|
|
106
|
+
if error is not None:
|
|
107
|
+
raise _bad(error)
|
|
108
|
+
start, stop, error = validate_commands(
|
|
109
|
+
body.runtime, body.start_command, body.stop_command
|
|
110
|
+
)
|
|
111
|
+
if error is not None:
|
|
112
|
+
raise _bad(error)
|
|
113
|
+
health_url, health_timeout, port, error = validate_probe(
|
|
114
|
+
body.health_url, body.health_timeout, body.port
|
|
115
|
+
)
|
|
116
|
+
if error is not None:
|
|
117
|
+
raise _bad(error)
|
|
118
|
+
app_dir, error = validate_app_dir(name, body.app_dir)
|
|
119
|
+
if error is not None:
|
|
120
|
+
raise _bad(error)
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
"runtime": body.runtime,
|
|
124
|
+
"artifact": artifact,
|
|
125
|
+
"artifact_sha256": sha,
|
|
126
|
+
"form": body.form,
|
|
127
|
+
"app_dir": app_dir,
|
|
128
|
+
"start_command": start,
|
|
129
|
+
"stop_command": stop or None,
|
|
130
|
+
"health_url": health_url or None,
|
|
131
|
+
"health_timeout": health_timeout,
|
|
132
|
+
"port": port,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ---- response mapping -------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _release_out(row: dict[str, Any] | None) -> ReleaseOut | None:
|
|
140
|
+
if row is None:
|
|
141
|
+
return None
|
|
142
|
+
return ReleaseOut(
|
|
143
|
+
id=int(row["id"]),
|
|
144
|
+
deployment_id=int(row["deployment_id"]),
|
|
145
|
+
artifact_sha256=str(row["artifact_sha256"]),
|
|
146
|
+
remote_dir=str(row["remote_dir"]),
|
|
147
|
+
status=str(row["status"]),
|
|
148
|
+
pid=row.get("pid"),
|
|
149
|
+
health_ok=None if row.get("health_ok") is None else bool(row["health_ok"]),
|
|
150
|
+
health_method=row.get("health_method"),
|
|
151
|
+
backup_path=row.get("backup_path"),
|
|
152
|
+
detail=row.get("detail"),
|
|
153
|
+
started_at=float(row["started_at"]),
|
|
154
|
+
finished_at=row.get("finished_at"),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _deployment_out(state: AppState, row: dict[str, Any]) -> DeploymentOut:
|
|
159
|
+
dep_id = int(row["id"])
|
|
160
|
+
active = state.deployments.active(dep_id)
|
|
161
|
+
failure = state.deployments.last_failure(dep_id)
|
|
162
|
+
# A failure older than the running release is history, not a current warning:
|
|
163
|
+
# the release history drawer still lists it, but the summary must not claim
|
|
164
|
+
# the app is broken right after a successful deploy.
|
|
165
|
+
if failure is not None and active is not None and int(failure["id"]) < int(active["id"]):
|
|
166
|
+
failure = None
|
|
167
|
+
return DeploymentOut(
|
|
168
|
+
host_id=int(row["host_id"]),
|
|
169
|
+
name=str(row["name"]),
|
|
170
|
+
runtime=str(row["runtime"]),
|
|
171
|
+
artifact=str(row["artifact"]),
|
|
172
|
+
artifact_sha256=str(row["artifact_sha256"]),
|
|
173
|
+
form=str(row["form"]),
|
|
174
|
+
app_dir=str(row["app_dir"]),
|
|
175
|
+
start_command=str(row["start_command"]),
|
|
176
|
+
stop_command=row.get("stop_command"),
|
|
177
|
+
health_url=row.get("health_url"),
|
|
178
|
+
health_timeout=int(row["health_timeout"]),
|
|
179
|
+
port=row.get("port"),
|
|
180
|
+
created_at=float(row["created_at"]),
|
|
181
|
+
updated_at=float(row["updated_at"]),
|
|
182
|
+
active_release=_release_out(active),
|
|
183
|
+
last_failure=_release_out(failure),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _to_result(outcome: DeployOutcome) -> DeployResult:
|
|
188
|
+
return DeployResult(
|
|
189
|
+
ok=outcome.ok,
|
|
190
|
+
status=outcome.status,
|
|
191
|
+
detail=outcome.detail,
|
|
192
|
+
release_id=outcome.release_id,
|
|
193
|
+
pid=outcome.pid,
|
|
194
|
+
backup_path=outcome.backup_path,
|
|
195
|
+
stdout=outcome.stdout,
|
|
196
|
+
stderr=outcome.stderr,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _run_status(outcome: DeployOutcome) -> str:
|
|
201
|
+
if outcome.status == "denied":
|
|
202
|
+
return "denied"
|
|
203
|
+
return "succeeded" if outcome.ok else "failed"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def _run_and_record(
|
|
207
|
+
state: AppState,
|
|
208
|
+
host_cfg: HostConfig,
|
|
209
|
+
definition: dict[str, Any],
|
|
210
|
+
*,
|
|
211
|
+
action: str,
|
|
212
|
+
) -> DeployResult:
|
|
213
|
+
"""Execute one deploy/rollback under the concurrency lock + synthetic row."""
|
|
214
|
+
lock = _lock(int(host_cfg.id or 0), str(definition["name"]))
|
|
215
|
+
if lock.locked():
|
|
216
|
+
raise HTTPException(
|
|
217
|
+
status_code=409,
|
|
218
|
+
detail="该应用正在部署中,请等待当前部署结束",
|
|
219
|
+
)
|
|
220
|
+
async with lock:
|
|
221
|
+
run = _DeployRun(state, host_cfg, str(definition["name"]), action)
|
|
222
|
+
deployer = Deployer(state.deployments, _settings())
|
|
223
|
+
hooks = DeployHooks(
|
|
224
|
+
confirm=run.confirm,
|
|
225
|
+
on_stage=run.note_stage,
|
|
226
|
+
on_result=run.note_result,
|
|
227
|
+
run_id=run.run_id,
|
|
228
|
+
)
|
|
229
|
+
outcome: DeployOutcome | None = None
|
|
230
|
+
started = time.time()
|
|
231
|
+
try:
|
|
232
|
+
pool = await get_pool()
|
|
233
|
+
async with pool.get_connection(host_cfg) as conn:
|
|
234
|
+
if action == "部署":
|
|
235
|
+
outcome = await deployer.deploy(
|
|
236
|
+
conn, definition, host_user=host_cfg.user, hooks=hooks
|
|
237
|
+
)
|
|
238
|
+
else:
|
|
239
|
+
outcome = await deployer.rollback(
|
|
240
|
+
conn, definition, host_user=host_cfg.user, hooks=hooks
|
|
241
|
+
)
|
|
242
|
+
except Exception as exc:
|
|
243
|
+
run.finish("failed", f"{type(exc).__name__}: {exc}")
|
|
244
|
+
logger.warning(
|
|
245
|
+
"deploy route error host=%s app=%s action=%s: %s",
|
|
246
|
+
host_cfg.name,
|
|
247
|
+
definition["name"],
|
|
248
|
+
action,
|
|
249
|
+
exc,
|
|
250
|
+
)
|
|
251
|
+
if isinstance(exc, HTTPException):
|
|
252
|
+
raise
|
|
253
|
+
raise HTTPException(
|
|
254
|
+
status_code=_BAD_GATEWAY,
|
|
255
|
+
detail=f"连接服务器 {host_cfg.name!r} 失败: {exc}",
|
|
256
|
+
) from exc
|
|
257
|
+
finally:
|
|
258
|
+
if outcome is not None:
|
|
259
|
+
run.finish(_run_status(outcome), None if outcome.ok else outcome.detail)
|
|
260
|
+
logger.info(
|
|
261
|
+
"deploy done host=%s app=%s action=%s status=%s release=%s"
|
|
262
|
+
" duration_ms=%d detail=%s",
|
|
263
|
+
host_cfg.name,
|
|
264
|
+
definition["name"],
|
|
265
|
+
action,
|
|
266
|
+
outcome.status,
|
|
267
|
+
outcome.release_id,
|
|
268
|
+
int((time.time() - started) * 1000),
|
|
269
|
+
outcome.detail,
|
|
270
|
+
)
|
|
271
|
+
if outcome is None: # pragma: no cover - every path sets one or raises
|
|
272
|
+
raise HTTPException(status_code=500, detail="部署未产生结果")
|
|
273
|
+
return _to_result(outcome)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# ---- routes -----------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
@router.get("/hosts/{host_id}/deployments", response_model=list[DeploymentOut])
|
|
280
|
+
async def list_deployments(host_id: int, request: Request) -> list[DeploymentOut]:
|
|
281
|
+
state = get_state(request)
|
|
282
|
+
_host_or_404(host_id, state)
|
|
283
|
+
return [
|
|
284
|
+
_deployment_out(state, row) for row in state.deployments.list_deployments(host_id)
|
|
285
|
+
]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@router.put("/hosts/{host_id}/deployments/{name}", response_model=DeploymentOut)
|
|
289
|
+
async def upsert_deployment(
|
|
290
|
+
host_id: int, name: str, body: DeploymentIn, request: Request
|
|
291
|
+
) -> DeploymentOut:
|
|
292
|
+
state = get_state(request)
|
|
293
|
+
_host_or_404(host_id, state)
|
|
294
|
+
fields = _validated_fields(name, body)
|
|
295
|
+
row = await asyncio.to_thread(state.deployments.upsert, host_id, name, fields)
|
|
296
|
+
return _deployment_out(state, row)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@router.post(
|
|
300
|
+
"/hosts/{host_id}/deployments/{name}/deploy", response_model=DeployResult
|
|
301
|
+
)
|
|
302
|
+
async def deploy_app(host_id: int, name: str, request: Request) -> DeployResult:
|
|
303
|
+
state = get_state(request)
|
|
304
|
+
host_cfg = _host_or_404(host_id, state)
|
|
305
|
+
definition = _deployment_or_404(state, host_id, name)
|
|
306
|
+
return await _run_and_record(state, host_cfg, definition, action="部署")
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
@router.post(
|
|
310
|
+
"/hosts/{host_id}/deployments/{name}/rollback", response_model=DeployResult
|
|
311
|
+
)
|
|
312
|
+
async def rollback_app(host_id: int, name: str, request: Request) -> DeployResult:
|
|
313
|
+
state = get_state(request)
|
|
314
|
+
host_cfg = _host_or_404(host_id, state)
|
|
315
|
+
definition = _deployment_or_404(state, host_id, name)
|
|
316
|
+
return await _run_and_record(state, host_cfg, definition, action="回滚")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@router.get(
|
|
320
|
+
"/hosts/{host_id}/deployments/{name}/releases", response_model=list[ReleaseOut]
|
|
321
|
+
)
|
|
322
|
+
async def list_releases(host_id: int, name: str, request: Request) -> list[ReleaseOut]:
|
|
323
|
+
state = get_state(request)
|
|
324
|
+
_host_or_404(host_id, state)
|
|
325
|
+
definition = _deployment_or_404(state, host_id, name)
|
|
326
|
+
rows = state.deployments.list_releases(int(definition["id"]))
|
|
327
|
+
return [out for out in (_release_out(row) for row in rows) if out is not None]
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# ---- drafts (model proposals; adopting is an explicit operator action) ------
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _draft_out(state: AppState, row: dict[str, Any]) -> DeploymentDraftOut:
|
|
334
|
+
return DeploymentDraftOut(
|
|
335
|
+
host_id=int(row["host_id"]),
|
|
336
|
+
name=str(row["name"]),
|
|
337
|
+
runtime=str(row["runtime"]),
|
|
338
|
+
artifact=str(row["artifact"]),
|
|
339
|
+
artifact_sha256=str(row["artifact_sha256"]),
|
|
340
|
+
form=str(row["form"]),
|
|
341
|
+
app_dir=str(row["app_dir"]),
|
|
342
|
+
start_command=str(row["start_command"]),
|
|
343
|
+
stop_command=row.get("stop_command"),
|
|
344
|
+
health_url=row.get("health_url"),
|
|
345
|
+
health_timeout=int(row["health_timeout"]),
|
|
346
|
+
port=row.get("port"),
|
|
347
|
+
reason=str(row.get("reason") or ""),
|
|
348
|
+
source_run_id=row.get("source_run_id"),
|
|
349
|
+
created_at=float(row["created_at"]),
|
|
350
|
+
updated_at=float(row["updated_at"]),
|
|
351
|
+
overwrites_existing=state.deployments.get(int(row["host_id"]), str(row["name"]))
|
|
352
|
+
is not None,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _adoptable_fields(draft: dict[str, Any]) -> dict[str, Any]:
|
|
357
|
+
"""Re-validate a stored draft against the CURRENT local artifact.
|
|
358
|
+
|
|
359
|
+
The draft pinned a sha256 when the model proposed it; if the artifact has
|
|
360
|
+
since been replaced, adopting silently would deploy different bytes than the
|
|
361
|
+
operator reviewed. Refuse and ask for a fresh draft instead.
|
|
362
|
+
"""
|
|
363
|
+
bad = validate_name(str(draft["name"]))
|
|
364
|
+
if bad is not None:
|
|
365
|
+
raise _bad(bad)
|
|
366
|
+
sha, error = validate_artifact_file(
|
|
367
|
+
str(draft["artifact"]), str(draft["form"]), _settings().dir
|
|
368
|
+
)
|
|
369
|
+
if error is not None:
|
|
370
|
+
raise _bad(error)
|
|
371
|
+
if sha != str(draft["artifact_sha256"]):
|
|
372
|
+
raise _bad(
|
|
373
|
+
"制品文件已变化(sha256 与草案记录不一致),草案已过期:"
|
|
374
|
+
"请让模型重新生成草案,或手工创建定义"
|
|
375
|
+
)
|
|
376
|
+
start, stop, error = validate_commands(
|
|
377
|
+
str(draft["runtime"]), draft.get("start_command"), draft.get("stop_command")
|
|
378
|
+
)
|
|
379
|
+
if error is not None:
|
|
380
|
+
raise _bad(error)
|
|
381
|
+
health_url, health_timeout, port, error = validate_probe(
|
|
382
|
+
draft.get("health_url"),
|
|
383
|
+
int(draft["health_timeout"]),
|
|
384
|
+
draft.get("port"),
|
|
385
|
+
)
|
|
386
|
+
if error is not None:
|
|
387
|
+
raise _bad(error)
|
|
388
|
+
app_dir, error = validate_app_dir(str(draft["name"]), draft.get("app_dir"))
|
|
389
|
+
if error is not None:
|
|
390
|
+
raise _bad(error)
|
|
391
|
+
return {
|
|
392
|
+
"runtime": str(draft["runtime"]),
|
|
393
|
+
"artifact": str(draft["artifact"]),
|
|
394
|
+
"artifact_sha256": sha,
|
|
395
|
+
"form": str(draft["form"]),
|
|
396
|
+
"app_dir": app_dir,
|
|
397
|
+
"start_command": start,
|
|
398
|
+
"stop_command": stop or None,
|
|
399
|
+
"health_url": health_url or None,
|
|
400
|
+
"health_timeout": health_timeout,
|
|
401
|
+
"port": port,
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
@router.get(
|
|
406
|
+
"/hosts/{host_id}/deployments/drafts", response_model=list[DeploymentDraftOut]
|
|
407
|
+
)
|
|
408
|
+
async def list_deployment_drafts(
|
|
409
|
+
host_id: int, request: Request
|
|
410
|
+
) -> list[DeploymentDraftOut]:
|
|
411
|
+
state = get_state(request)
|
|
412
|
+
_host_or_404(host_id, state)
|
|
413
|
+
return [_draft_out(state, row) for row in state.deployments.list_drafts(host_id)]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@router.post(
|
|
417
|
+
"/hosts/{host_id}/deployments/drafts/{name}/adopt", response_model=DeploymentOut
|
|
418
|
+
)
|
|
419
|
+
async def adopt_deployment_draft(
|
|
420
|
+
host_id: int, name: str, request: Request
|
|
421
|
+
) -> DeploymentOut:
|
|
422
|
+
"""Adopt a draft into a real definition; nothing is deployed by this call."""
|
|
423
|
+
state = get_state(request)
|
|
424
|
+
_host_or_404(host_id, state)
|
|
425
|
+
draft = state.deployments.get_draft(host_id, name)
|
|
426
|
+
if draft is None:
|
|
427
|
+
raise HTTPException(status_code=404, detail=f"草案 {name!r} 不存在")
|
|
428
|
+
fields = _adoptable_fields(draft)
|
|
429
|
+
row = await asyncio.to_thread(state.deployments.upsert, host_id, name, fields)
|
|
430
|
+
state.deployments.delete_draft(host_id, name)
|
|
431
|
+
logger.info("adopted deployment draft host=%s app=%s", host_id, name)
|
|
432
|
+
return _deployment_out(state, row)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@router.delete(
|
|
436
|
+
"/hosts/{host_id}/deployments/drafts/{name}",
|
|
437
|
+
response_model=DeploymentDraftDeleted,
|
|
438
|
+
)
|
|
439
|
+
async def discard_deployment_draft(
|
|
440
|
+
host_id: int, name: str, request: Request
|
|
441
|
+
) -> DeploymentDraftDeleted:
|
|
442
|
+
state = get_state(request)
|
|
443
|
+
_host_or_404(host_id, state)
|
|
444
|
+
if not state.deployments.delete_draft(host_id, name):
|
|
445
|
+
raise HTTPException(status_code=404, detail=f"草案 {name!r} 不存在")
|
|
446
|
+
return DeploymentDraftDeleted(name=name)
|
|
@@ -0,0 +1,98 @@
|
|
|
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.deploy_store import DeployStore
|
|
21
|
+
from ssh_agent_harness.storage.llm_store import LlmStore
|
|
22
|
+
from ssh_agent_harness.storage.run_store import ApprovalStore, RunStore
|
|
23
|
+
from ssh_agent_harness.storage.session_store import Storage
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@runtime_checkable
|
|
27
|
+
class SupportsAenterRun(Protocol):
|
|
28
|
+
"""Structural contract of an orchestrator usable by RunManager.
|
|
29
|
+
|
|
30
|
+
Runtime-checkable and signature-based so Task 9 fakes satisfy it
|
|
31
|
+
without inheriting from SingleTurnOrchestrator.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
async def __aenter__(self) -> SupportsAenterRun: ...
|
|
35
|
+
|
|
36
|
+
async def __aexit__(
|
|
37
|
+
self,
|
|
38
|
+
exc_type: type[BaseException] | None,
|
|
39
|
+
exc: BaseException | None,
|
|
40
|
+
tb: Any,
|
|
41
|
+
) -> None: ...
|
|
42
|
+
|
|
43
|
+
async def run(
|
|
44
|
+
self,
|
|
45
|
+
task: str,
|
|
46
|
+
host: HostConfig,
|
|
47
|
+
options: ExecutionOptions | None = None,
|
|
48
|
+
host_info: dict[str, Any] | None = None,
|
|
49
|
+
) -> OrchestratorResult: ...
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Kept as an alias: the design sketch referred to this protocol by this name.
|
|
53
|
+
SupportsRun = SupportsAenterRun
|
|
54
|
+
|
|
55
|
+
OrchestratorFactory = Callable[
|
|
56
|
+
[
|
|
57
|
+
bool,
|
|
58
|
+
ConfirmationGate | None,
|
|
59
|
+
ProgressCallback | None,
|
|
60
|
+
int,
|
|
61
|
+
bool,
|
|
62
|
+
str | None,
|
|
63
|
+
ShouldCancel | None,
|
|
64
|
+
],
|
|
65
|
+
SupportsAenterRun,
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# Connectivity probe seam: (host, command, timeout) → {"reachable","latency_ms","error"}.
|
|
70
|
+
CommandTester = Callable[[HostConfig, str, float], Awaitable[dict[str, Any]]]
|
|
71
|
+
|
|
72
|
+
# Fingerprint seam: host → host_info dict (raising degrades to None, like the CLI).
|
|
73
|
+
FingerprintFn = Callable[[HostConfig], Awaitable[dict[str, Any]]]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class AppState:
|
|
78
|
+
"""Per-app container, stored as ``app.state.harness`` (single namespace)."""
|
|
79
|
+
|
|
80
|
+
storage: Storage
|
|
81
|
+
runs: RunStore
|
|
82
|
+
approvals: ApprovalStore
|
|
83
|
+
coordinator: ApprovalCoordinator
|
|
84
|
+
manager: RunManager
|
|
85
|
+
command_tester: CommandTester
|
|
86
|
+
# DB host rows of *this app's own* storage (same db as --db); injected into
|
|
87
|
+
# host_loader so api reads never touch the global get_storage()/cache.
|
|
88
|
+
hosts_provider: Callable[[], list[dict[str, Any]]]
|
|
89
|
+
# UI-selected LLM config row store bound to *this app's own* db.
|
|
90
|
+
llm: LlmStore
|
|
91
|
+
# Deployment definitions + release history (P1), same db as everything else.
|
|
92
|
+
deployments: DeployStore
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def get_state(request: Request) -> AppState:
|
|
96
|
+
"""FastAPI dependency giving routes the whole wiring container."""
|
|
97
|
+
state: AppState = request.app.state.harness
|
|
98
|
+
return state
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Host inventory routes: DB-only (SQLite hosts table).
|
|
2
|
+
|
|
3
|
+
Never echo credentials: HostOut has no password field and no route returns
|
|
4
|
+
raw store rows (identity_file paths may appear, secret values never do).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import replace
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from fastapi import APIRouter, HTTPException, Request, Response
|
|
13
|
+
|
|
14
|
+
from ssh_agent_harness.api.deps import AppState, get_state
|
|
15
|
+
from ssh_agent_harness.api.schemas import HostCreate, HostOut, HostUpdate, TestConnectionOut
|
|
16
|
+
from ssh_agent_harness.core.host_loader import invalidate_hosts_cache, load_hosts
|
|
17
|
+
from ssh_agent_harness.tools.ssh_pool import HostConfig
|
|
18
|
+
|
|
19
|
+
router = APIRouter(prefix="/api/hosts", tags=["hosts"])
|
|
20
|
+
|
|
21
|
+
_TEST_COMMAND = "echo ok"
|
|
22
|
+
_TEST_TIMEOUT = 10.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _pick(key: str, default: Any, cfg: HostConfig | None,
|
|
26
|
+
row: dict[str, Any] | None) -> Any:
|
|
27
|
+
"""Effective value: DB row wins, then merged view (yaml∪db), then default."""
|
|
28
|
+
if row is not None and row.get(key) is not None:
|
|
29
|
+
return row[key]
|
|
30
|
+
if cfg is not None:
|
|
31
|
+
return getattr(cfg, key)
|
|
32
|
+
return default
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _host_out(
|
|
36
|
+
host_id: int, name: str, cfg: HostConfig | None, row: dict[str, Any] | None
|
|
37
|
+
) -> HostOut:
|
|
38
|
+
password = _pick("password", None, cfg, row)
|
|
39
|
+
identity = _pick("identity_file", None, cfg, row)
|
|
40
|
+
auth_type = "password" if password else "key" if identity else "none"
|
|
41
|
+
return HostOut(
|
|
42
|
+
id=host_id,
|
|
43
|
+
name=name,
|
|
44
|
+
hostname=_pick("hostname", name, cfg, row),
|
|
45
|
+
port=_pick("port", 22, cfg, row),
|
|
46
|
+
# "" 占位仅为类型兜底:视图经 db_provider 合并后 cfg 必存在,root 假值死兜底已删。
|
|
47
|
+
user=_pick("user", "", cfg, row),
|
|
48
|
+
auth_type=auth_type,
|
|
49
|
+
tags=_pick("tags", [], cfg, row) or [],
|
|
50
|
+
known_hosts_policy=_pick("known_hosts_policy", None, cfg, row),
|
|
51
|
+
sudo=bool(_pick("sudo", False, cfg, row)),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _view(state: AppState) -> dict[int, HostConfig]:
|
|
56
|
+
"""DB view computed against *this app's* db (bypasses global cache)."""
|
|
57
|
+
return load_hosts(db_provider=state.hosts_provider)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _one_out(host_id: int, state: AppState) -> HostOut:
|
|
61
|
+
row = state.storage.hosts.get_by_id(host_id)
|
|
62
|
+
if row is None:
|
|
63
|
+
raise HTTPException(status_code=404, detail=f"host {host_id} not found")
|
|
64
|
+
return _host_out(host_id, str(row["name"]), _view(state).get(host_id), row)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _resolve_host(host_id: int, state: AppState) -> HostConfig | None:
|
|
68
|
+
"""Effective HostConfig for the probe, or None if the host does not exist."""
|
|
69
|
+
cfg = _view(state).get(host_id)
|
|
70
|
+
row = state.storage.hosts.get_by_id(host_id)
|
|
71
|
+
if cfg is None and row is None:
|
|
72
|
+
return None
|
|
73
|
+
name = str(row["name"]) if row is not None else (cfg.name if cfg else "")
|
|
74
|
+
if cfg is None or row is None:
|
|
75
|
+
return cfg if row is None else HostConfig(
|
|
76
|
+
id=host_id, name=name, hostname=row.get("hostname") or name,
|
|
77
|
+
**{k: v for k, v in row.items()
|
|
78
|
+
if v is not None and k not in {"id", "name", "hostname"}},
|
|
79
|
+
)
|
|
80
|
+
overrides = {k: v for k, v in row.items() if v is not None and k not in {"id", "name"}}
|
|
81
|
+
return replace(cfg, **overrides)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@router.get("", response_model=list[HostOut])
|
|
85
|
+
async def list_hosts(
|
|
86
|
+
request: Request, response: Response, limit: int | None = None, offset: int = 0
|
|
87
|
+
) -> list[HostOut]:
|
|
88
|
+
"""Full DB inventory ordered by id, sources tagged.
|
|
89
|
+
|
|
90
|
+
``limit`` UNSET keeps the legacy full list on purpose: the submit form's host
|
|
91
|
+
dropdown and the session host filter need every host, never a single page.
|
|
92
|
+
Paging (limit + offset) is opt-in for the host management table, and
|
|
93
|
+
``X-Total-Count`` always reports the unpaged total.
|
|
94
|
+
"""
|
|
95
|
+
state = get_state(request)
|
|
96
|
+
db_rows = state.hosts_provider()
|
|
97
|
+
view = _view(state)
|
|
98
|
+
response.headers["X-Total-Count"] = str(len(db_rows))
|
|
99
|
+
if limit is not None:
|
|
100
|
+
db_rows = db_rows[offset : offset + limit]
|
|
101
|
+
return [
|
|
102
|
+
_host_out(int(r["id"]), str(r["name"]), view.get(int(r["id"])), r) for r in db_rows
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@router.post("", response_model=HostOut, status_code=201)
|
|
107
|
+
async def create_host(body: HostCreate, request: Request) -> HostOut:
|
|
108
|
+
"""Insert a new host row; the name is a label and may repeat."""
|
|
109
|
+
state = get_state(request)
|
|
110
|
+
new_id = state.storage.hosts.create(body.name, body.model_dump(exclude={"name"}))
|
|
111
|
+
invalidate_hosts_cache() # 见下方注释:对 api 视图不再关键
|
|
112
|
+
return _one_out(new_id, state)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@router.put("/{host_id}", response_model=HostOut)
|
|
116
|
+
async def update_host(host_id: int, body: HostUpdate, request: Request) -> HostOut:
|
|
117
|
+
"""Update an existing row by id; unset fields keep their values."""
|
|
118
|
+
state = get_state(request)
|
|
119
|
+
if state.storage.hosts.get_by_id(host_id) is None:
|
|
120
|
+
raise HTTPException(status_code=404, detail=f"host {host_id} not found")
|
|
121
|
+
payload = body.model_dump(exclude_unset=True, exclude={"name"})
|
|
122
|
+
state.storage.hosts.update(host_id, body.name, payload)
|
|
123
|
+
invalidate_hosts_cache() # 见 create_host 注释:对 api 视图不再关键
|
|
124
|
+
return _one_out(host_id, state)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@router.delete("/{host_id}")
|
|
128
|
+
async def delete_host(host_id: int, request: Request) -> dict[str, Any]:
|
|
129
|
+
"""Delete a DB row by id; unknown id 404s."""
|
|
130
|
+
state = get_state(request)
|
|
131
|
+
name = state.storage.hosts.name_by_id(host_id)
|
|
132
|
+
if state.storage.hosts.delete(host_id):
|
|
133
|
+
invalidate_hosts_cache() # 见 create_host 注释:对 api 视图不再关键
|
|
134
|
+
return {"status": "deleted", "id": host_id, "name": name}
|
|
135
|
+
raise HTTPException(status_code=404, detail=f"host {host_id} not found")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@router.post("/{host_id}/test", response_model=TestConnectionOut)
|
|
139
|
+
async def test_connection(host_id: int, request: Request) -> TestConnectionOut:
|
|
140
|
+
"""Probe reachability via the injectable tester; failures never 500."""
|
|
141
|
+
state = get_state(request)
|
|
142
|
+
host = _resolve_host(host_id, state)
|
|
143
|
+
if host is None:
|
|
144
|
+
raise HTTPException(status_code=404, detail=f"host {host_id} not found")
|
|
145
|
+
result = await state.command_tester(host, _TEST_COMMAND, _TEST_TIMEOUT)
|
|
146
|
+
return TestConnectionOut(**result)
|