amv-component-sdk 0.1.3__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.
@@ -0,0 +1,128 @@
1
+ """
2
+ ameva_component
3
+ AMEVA Component Protocol v1 공개 API
4
+
5
+ 사용 예:
6
+ from ameva_component import ComponentControl, ComponentInfo
7
+ from ameva_component import ComponentStateFile, ModelRegistry, InstanceRegistry
8
+ from ameva_component import render_ok, render_error, log_stderr, ExitCode
9
+ from ameva_component.exceptions import OperationNotSupported, ModelNotFound
10
+ """
11
+ from ameva_component.control import ComponentControl
12
+ from ameva_component.exceptions import (
13
+ AmevaError,
14
+ ActivationConflict,
15
+ ComponentError,
16
+ DrainTimeout,
17
+ HashMismatch,
18
+ InsufficientDisk,
19
+ InstanceNotFound,
20
+ InvalidManifest,
21
+ InvalidProtocol,
22
+ LockTimeout,
23
+ ModelLoadFailed,
24
+ ModelNotFound,
25
+ OperationNotSupported,
26
+ RollbackFailed,
27
+ redact_details,
28
+ redact_text,
29
+ )
30
+ from ameva_component.identity import (
31
+ ComponentInfo,
32
+ ALLOWED_CAPABILITIES,
33
+ PROTOCOL_COMPONENT,
34
+ PROTOCOL_STATUS,
35
+ PROTOCOL_MANIFEST,
36
+ PROTOCOL_INSTANCE,
37
+ )
38
+ from ameva_component.instance import ControlMode, InstanceState, InstanceStatus
39
+ from ameva_component.installer import ModelInstaller
40
+ from ameva_component.locks import ActivationLock, ArtifactLock, InstanceLock, ModelLock
41
+ from ameva_component.manifest import ModelFile, ModelManifest, ModelState
42
+ from ameva_component.output import (
43
+ ExitCode,
44
+ exit_for_result,
45
+ log_progress,
46
+ log_stderr,
47
+ render_error,
48
+ render_from_exception,
49
+ render_ok,
50
+ )
51
+ from ameva_component.registry import InstanceRegistry, ModelRegistry
52
+ from ameva_component.state import ComponentStateFile, resolve_state_dir
53
+ from ameva_component.timestamps import is_stale, now_timestamps, process_start_timestamps
54
+
55
+ __version__ = "0.1.2"
56
+
57
+ __all__ = [
58
+ # 핵심 추상 클래스
59
+ "ComponentControl",
60
+ # 예외
61
+ "AmevaError",
62
+ "ActivationConflict",
63
+ "ComponentError",
64
+ "DrainTimeout",
65
+ "HashMismatch",
66
+ "InsufficientDisk",
67
+ "InstanceNotFound",
68
+ "InvalidManifest",
69
+ "InvalidProtocol",
70
+ "LockTimeout",
71
+ "ModelLoadFailed",
72
+ "ModelNotFound",
73
+ "OperationNotSupported",
74
+ "RollbackFailed",
75
+ "redact_details",
76
+ "redact_text",
77
+ # 신원
78
+ "ComponentInfo",
79
+ "ALLOWED_CAPABILITIES",
80
+ "PROTOCOL_COMPONENT",
81
+ "PROTOCOL_STATUS",
82
+ "PROTOCOL_MANIFEST",
83
+ "PROTOCOL_INSTANCE",
84
+ # Instance
85
+ "ControlMode",
86
+ "InstanceState",
87
+ "InstanceStatus",
88
+ # 설치
89
+ "ModelInstaller",
90
+ # Lock
91
+ "ActivationLock",
92
+ "ArtifactLock",
93
+ "InstanceLock",
94
+ "ModelLock",
95
+ # Manifest
96
+ "ModelFile",
97
+ "ModelManifest",
98
+ "ModelState",
99
+ # 출력
100
+ "ExitCode",
101
+ "exit_for_result",
102
+ "log_progress",
103
+ "log_stderr",
104
+ "render_error",
105
+ "render_from_exception",
106
+ "render_ok",
107
+ # Registry
108
+ "InstanceRegistry",
109
+ "ModelRegistry",
110
+ # 상태 파일
111
+ "ComponentStateFile",
112
+ "resolve_state_dir",
113
+ # 타임스탬프
114
+ "is_stale",
115
+ "now_timestamps",
116
+ "process_start_timestamps",
117
+ # CLI 지원
118
+ "build_protocol_subcommands",
119
+ "dispatch_protocol",
120
+ # Heartbeat
121
+ "HeartbeatWriter",
122
+ ]
123
+
124
+ from ameva_component.cli_support import build_protocol_subcommands, dispatch_protocol # noqa: E402
125
+ from ameva_component.heartbeat import HeartbeatWriter # noqa: E402
126
+ from ameva_component.adapter_base import BaseOrchestratorAdapter # noqa: E402
127
+
128
+ __all__ += ["BaseOrchestratorAdapter"]
@@ -0,0 +1,138 @@
1
+ """
2
+ ameva_component.adapter_base
3
+ ============================
4
+ BaseOrchestratorAdapter — v0.8.1 Orchestrator Adapter 공통 베이스 클래스.
5
+
6
+ 사용법:
7
+ from ameva_component.adapter_base import BaseOrchestratorAdapter
8
+
9
+ class MyAdapter(BaseOrchestratorAdapter):
10
+ COMPONENT_ID = "termux-mypackage"
11
+ ...
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, AsyncIterator
16
+
17
+ from ameva_component.exceptions import InstanceNotFound, OperationNotSupported
18
+
19
+
20
+ _INFER_NOT_SUPPORTED_COMPONENTS = frozenset({
21
+ # streaming LLM inference를 지원하지 않는 컴포넌트는 서브클래스에서 오버라이드
22
+ })
23
+
24
+
25
+ class BaseOrchestratorAdapter:
26
+ """AMEVA Component Orchestrator Adapter 공통 베이스.
27
+
28
+ 오케스트레이터 v0.8.1 ComponentAdapter Protocol 전체 표면을 구현합니다.
29
+ 서브클래스는 `_control` 속성을 통해 ComponentControl에 접근합니다.
30
+
31
+ 메서드 계약:
32
+ - info / health / models / instances: dict 반환 (동기)
33
+ - activate / deactivate / start_instance / stop_instance: async dict 반환
34
+ - drain_instance / resume_instance: async dict 반환
35
+ - infer: AsyncIterator[dict] — 미지원 시 OPERATION_NOT_SUPPORTED 구조화 오류 반환
36
+ """
37
+
38
+ COMPONENT_ID: str = "" # 서브클래스에서 반드시 선언
39
+
40
+ # ──────────────────────────────────────────────────────────────
41
+ # 동기 표면
42
+ # ──────────────────────────────────────────────────────────────
43
+
44
+ def info(self) -> dict[str, Any]:
45
+ return self._control.component_info()
46
+
47
+ def health(self) -> dict[str, Any]:
48
+ return self._control.doctor_lite()
49
+
50
+ def models(self) -> dict[str, Any]:
51
+ return self._control.list_models()
52
+
53
+ def instances(self) -> dict[str, Any]:
54
+ return self._control.list_instances()
55
+
56
+ # ──────────────────────────────────────────────────────────────
57
+ # 비동기 표면 — 모델 Lifecycle
58
+ # ──────────────────────────────────────────────────────────────
59
+
60
+ async def activate(self, request: dict[str, Any]) -> dict[str, Any]:
61
+ return await self._control.activate_model(request)
62
+
63
+ async def deactivate(self, request: dict[str, Any]) -> dict[str, Any]:
64
+ return await self._control.deactivate_model(request)
65
+
66
+ # ──────────────────────────────────────────────────────────────
67
+ # 비동기 표면 — 인스턴스 Lifecycle
68
+ # ──────────────────────────────────────────────────────────────
69
+
70
+ async def start_instance(self, request: dict[str, Any]) -> dict[str, Any]:
71
+ return await self._control.start_instance(request)
72
+
73
+ async def drain_instance(self, instance_id: str) -> dict[str, Any]:
74
+ """인스턴스를 Draining 상태로 전환합니다.
75
+
76
+ 현재 처리 중인 요청이 완료되길 기다리되, 신규 요청은 거부합니다.
77
+ ComponentControl에 drain_instance가 없으면 DRAINING 상태로 전환 후 stop_instance 위임.
78
+ """
79
+ try:
80
+ if hasattr(self._control, "drain_instance"):
81
+ return await self._control.drain_instance(instance_id)
82
+ # Fallback: DRAINING 전환 후 stop_instance
83
+ return await self._control.stop_instance(instance_id)
84
+ except InstanceNotFound:
85
+ return {
86
+ "ok": False,
87
+ "error": {
88
+ "code": "INSTANCE_NOT_FOUND",
89
+ "message": f"instance {instance_id!r} not found",
90
+ "operation": "drain_instance",
91
+ "component_id": self.COMPONENT_ID,
92
+ "retryable": False,
93
+ },
94
+ }
95
+
96
+ async def resume_instance(self, instance_id: str) -> dict[str, Any]:
97
+ """Draining 상태의 인스턴스를 ACTIVE로 복귀합니다.
98
+
99
+ ComponentControl에 resume_instance가 없으면 OPERATION_NOT_SUPPORTED 반환.
100
+ """
101
+ if hasattr(self._control, "resume_instance"):
102
+ return await self._control.resume_instance(instance_id)
103
+ return self._not_supported("resume_instance")
104
+
105
+ async def stop_instance(self, instance_id: str) -> dict[str, Any]:
106
+ return await self._control.stop_instance(instance_id)
107
+
108
+ # ──────────────────────────────────────────────────────────────
109
+ # Inference 표면
110
+ # ──────────────────────────────────────────────────────────────
111
+
112
+ async def infer(self, request: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:
113
+ """Streaming inference. 미지원 컴포넌트는 OperationNotSupported를 발생시킵니다.
114
+
115
+ 서브클래스에서 오버라이드하여 실제 스트리밍을 구현합니다.
116
+ """
117
+ raise OperationNotSupported(operation="infer", component_id=self.COMPONENT_ID)
118
+ if False:
119
+ yield {}
120
+
121
+ # ──────────────────────────────────────────────────────────────
122
+ # 내부 유틸리티
123
+ # ──────────────────────────────────────────────────────────────
124
+
125
+ def _not_supported(self, operation: str) -> dict[str, Any]:
126
+ """OPERATION_NOT_SUPPORTED 구조화 오류 딕셔너리 반환."""
127
+ return {
128
+ "ok": False,
129
+ "error": {
130
+ "code": "OPERATION_NOT_SUPPORTED",
131
+ "operation": operation,
132
+ "component_id": self.COMPONENT_ID,
133
+ "message": (
134
+ f"{self.COMPONENT_ID} does not support {operation}"
135
+ ),
136
+ "retryable": False,
137
+ },
138
+ }
@@ -0,0 +1,243 @@
1
+ """
2
+ ameva_component.cli_support
3
+ AMEVA Component Protocol v1 — 공통 CLI 지원 함수
4
+
5
+ 모든 패키지 CLI에서 재사용하는 공통 명령 구현.
6
+ 사용법:
7
+ from ameva_component.cli_support import build_protocol_parser, dispatch_protocol
8
+
9
+ # 기존 subparsers에 추가
10
+ build_protocol_parser(subparsers)
11
+
12
+ # dispatch에 추가
13
+ "component": lambda args: dispatch_protocol(args, control),
14
+ "instance": lambda args: dispatch_protocol(args, control),
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import asyncio
19
+ import json
20
+ import sys
21
+ from typing import Any
22
+
23
+
24
+ def build_protocol_subcommands(subparsers: Any) -> None:
25
+ """기존 argparse subparsers에 component/instance 명령을 추가합니다."""
26
+ # ------------------------------------------------------------------ component
27
+ p_comp = subparsers.add_parser(
28
+ "component",
29
+ help="[AMEVA Protocol v1] Component identity and health"
30
+ )
31
+ comp_sub = p_comp.add_subparsers(dest="comp_action", required=True)
32
+
33
+ # component info
34
+ p_info = comp_sub.add_parser("info", help="Print component identity (protocol, id, capabilities)")
35
+ p_info.add_argument("--json", action="store_true", dest="json_output", help="Output as JSON to stdout")
36
+
37
+ # component doctor-lite
38
+ p_dlite = comp_sub.add_parser("doctor-lite", help="Lightweight health check (no inference, <500ms)")
39
+ p_dlite.add_argument("--json", action="store_true", dest="json_output")
40
+
41
+ # component doctor-full
42
+ p_dfull = comp_sub.add_parser("doctor-full", help="Full diagnostic including hardware/Vulkan checks")
43
+ p_dfull.add_argument("--json", action="store_true", dest="json_output")
44
+
45
+ # ------------------------------------------------------------------ model
46
+ p_mod = subparsers.add_parser(
47
+ "model",
48
+ help="[AMEVA Protocol v1] Model lifecycle management"
49
+ )
50
+ mod_sub = p_mod.add_subparsers(dest="model_action", required=True)
51
+
52
+ # model list
53
+ p_mlist = mod_sub.add_parser("list", help="List installed models from AMEVA ModelRegistry")
54
+ p_mlist.add_argument("--json", action="store_true", dest="json_output")
55
+
56
+ # model status
57
+ p_mstat = mod_sub.add_parser("status", help="Show model status (state, hash, timestamps)")
58
+ p_mstat.add_argument("model_id", nargs="?", default=None, help="Model ID (omit for all)")
59
+ p_mstat.add_argument("--json", action="store_true", dest="json_output")
60
+
61
+ # model install
62
+ p_minst = mod_sub.add_parser("install", help="Download and verify model (SHA-256 + format check)")
63
+ p_minst.add_argument("--url", required=True, help="Download URL")
64
+ p_minst.add_argument("--filename", required=True, help="Target filename")
65
+ p_minst.add_argument("--sha256", default="", help="Expected SHA-256 hex digest")
66
+ p_minst.add_argument("--expected-bytes", type=int, default=0, help="Expected file size")
67
+ p_minst.add_argument("--model-id", default=None, help="Model ID (default: stem of filename)")
68
+ p_minst.add_argument("--json", action="store_true", dest="json_output")
69
+
70
+ # model activate
71
+ p_mact = mod_sub.add_parser("activate", help="Activate model (safe-switch with rollback)")
72
+ p_mact.add_argument("--model-id", required=True, help="Model ID to activate")
73
+ p_mact.add_argument("--voice-id", default=None, help="[TTS only] Voice ID")
74
+ p_mact.add_argument("--json", action="store_true", dest="json_output")
75
+
76
+ # model deactivate
77
+ p_mdeact = mod_sub.add_parser("deactivate", help="Deactivate model")
78
+ p_mdeact.add_argument("--model-id", required=True, help="Model ID to deactivate")
79
+ p_mdeact.add_argument("--json", action="store_true", dest="json_output")
80
+
81
+ # ------------------------------------------------------------------ instance
82
+ p_inst = subparsers.add_parser(
83
+ "instance",
84
+ help="[AMEVA Protocol v1] Instance (worker) management"
85
+ )
86
+ inst_sub = p_inst.add_subparsers(dest="inst_action", required=True)
87
+
88
+ # instance list
89
+ p_ilist = inst_sub.add_parser("list", help="List running instances / workers")
90
+ p_ilist.add_argument("--json", action="store_true", dest="json_output")
91
+
92
+ # instance start
93
+ p_istart = inst_sub.add_parser("start", help="Start a new instance/worker")
94
+ p_istart.add_argument("--model-id", default="", help="Model ID to load in the instance")
95
+ p_istart.add_argument("--instance-id", default=None, help="Custom instance ID")
96
+ p_istart.add_argument("--backend", default=None, help="Backend override (e.g. dsp, onnx, cpu, vulkan)")
97
+ p_istart.add_argument("--json", action="store_true", dest="json_output")
98
+
99
+ # instance drain
100
+ p_idrain = inst_sub.add_parser("drain", help="Signal instance to stop accepting new jobs")
101
+ p_idrain.add_argument("instance_id", help="Instance ID")
102
+ p_idrain.add_argument("--json", action="store_true", dest="json_output")
103
+
104
+ # instance stop
105
+ p_istop = inst_sub.add_parser("stop", help="Terminate instance")
106
+ p_istop.add_argument("instance_id", help="Instance ID")
107
+ p_istop.add_argument("--json", action="store_true", dest="json_output")
108
+
109
+
110
+ def dispatch_protocol(args: Any, control: Any) -> None:
111
+ """
112
+ args.command ('component' | 'model' | 'instance') 에 따라
113
+ ComponentControl 메서드를 호출하고 결과를 stdout에 JSON으로 출력합니다.
114
+
115
+ 로그/오류는 stderr로만 출력.
116
+ EXIT CODE:
117
+ 0 = OK
118
+ 1 = ERROR (ameva 오류 또는 OPERATION_NOT_SUPPORTED)
119
+ 2 = DEGRADED (component ready=False)
120
+ """
121
+ from ameva_component.output import render_ok, render_error, render_from_exception, log_stderr
122
+ from ameva_component.exceptions import AmevaError, OperationNotSupported
123
+
124
+ cmd = args.command
125
+ json_out = getattr(args, "json_output", False)
126
+ component_id: str = getattr(control, "COMPONENT_ID", "unknown")
127
+
128
+ def _emit_json(json_str: str) -> None:
129
+ """render_ok/render_error 반환값(JSON 문자열)을 stdout으로 출력."""
130
+ print(json_str)
131
+
132
+ def _print_result(result: dict) -> None:
133
+ """결과 dict를 JSON 문자열로 변환해 출력."""
134
+ if json_out:
135
+ _emit_json(render_ok(component_id, result))
136
+ else:
137
+ _pretty_result(result)
138
+
139
+ def _pretty_result(data: dict) -> None:
140
+ """--json 없을 때 가독성 있는 출력."""
141
+ ok = data.get("ready", True)
142
+ prefix = "[OK]" if ok else "[WARN]"
143
+ print(f"{prefix} {data.get('component_id', component_id)} {data.get('component_type', '')}")
144
+ for k, v in data.items():
145
+ if k in ("protocol",):
146
+ continue
147
+ if isinstance(v, (dict, list)):
148
+ print(f" {k}: {json.dumps(v, ensure_ascii=False)}")
149
+ else:
150
+ print(f" {k}: {v}")
151
+
152
+ def _emit_error(code: str, message: str) -> None:
153
+ if json_out:
154
+ _emit_json(render_error(component_id, code, message))
155
+ else:
156
+ print(f"[ERROR] {code}: {message}", file=sys.stderr)
157
+
158
+ try:
159
+ # ---------------------------------------------------------------- component
160
+ if cmd == "component":
161
+ action = args.comp_action
162
+ if action == "info":
163
+ result = control.component_info()
164
+ _print_result(result)
165
+ elif action == "doctor-lite":
166
+ result = control.doctor_lite()
167
+ _print_result(result)
168
+ if not result.get("ready", True):
169
+ sys.exit(2)
170
+ elif action == "doctor-full":
171
+ if hasattr(control, "doctor_full"):
172
+ result = control.doctor_full()
173
+ else:
174
+ result = control.doctor_lite()
175
+ _print_result(result)
176
+
177
+ # ---------------------------------------------------------------- model
178
+ elif cmd == "model":
179
+ action = args.model_action
180
+ if action == "list":
181
+ result = control.list_models()
182
+ _print_result(result)
183
+ elif action == "status":
184
+ result = control.model_status(getattr(args, "model_id", None))
185
+ _print_result(result)
186
+ elif action == "install":
187
+ request = {
188
+ "url": args.url,
189
+ "filename": args.filename,
190
+ "sha256": args.sha256,
191
+ "expected_bytes": args.expected_bytes,
192
+ "model_id": args.model_id,
193
+ }
194
+ result = control.install_model(request)
195
+ _print_result(result)
196
+ elif action == "activate":
197
+ request = {"model_id": args.model_id, "voice_id": getattr(args, "voice_id", None)}
198
+ result = asyncio.run(control.activate_model(request))
199
+ if result.get("activated", False):
200
+ _print_result(result)
201
+ else:
202
+ _emit_error("MODEL_ACTIVATION_FAILED", str(result))
203
+ sys.exit(1)
204
+ elif action == "deactivate":
205
+ request = {"model_id": args.model_id}
206
+ result = asyncio.run(control.deactivate_model(request))
207
+ _print_result(result)
208
+
209
+ # ---------------------------------------------------------------- instance
210
+ elif cmd == "instance":
211
+ action = args.inst_action
212
+ if action == "list":
213
+ result = control.list_instances()
214
+ _print_result(result)
215
+ elif action == "start":
216
+ request = {
217
+ "model_id": getattr(args, "model_id", ""),
218
+ "instance_id": getattr(args, "instance_id", None),
219
+ "backend": getattr(args, "backend", None),
220
+ }
221
+ result = asyncio.run(control.start_instance(request))
222
+ _print_result(result)
223
+ elif action == "drain":
224
+ result = asyncio.run(control.drain_instance(args.instance_id))
225
+ _print_result(result)
226
+ elif action == "stop":
227
+ result = asyncio.run(control.stop_instance(args.instance_id))
228
+ _print_result(result)
229
+
230
+ except OperationNotSupported as e:
231
+ _emit_error("OPERATION_NOT_SUPPORTED", str(e))
232
+ sys.exit(1)
233
+ except AmevaError as e:
234
+ json_str, exit_code = render_from_exception(component_id, e)
235
+ if json_out:
236
+ print(json_str)
237
+ else:
238
+ print(f"[ERROR] {e}", file=sys.stderr)
239
+ sys.exit(exit_code)
240
+ except Exception as e:
241
+ _emit_error("INTERNAL_ERROR", str(e))
242
+ sys.exit(1)
243
+
@@ -0,0 +1,173 @@
1
+ """
2
+ ameva_component.control
3
+ AMEVA Component Protocol v1 — ComponentControl 추상 베이스 클래스
4
+
5
+ 진실의 원천은 반드시 하나여야 합니다.
6
+ CLI / 상태 파일 Writer / Orchestrator Adapter 모두 이 클래스를 통해 상태를 조회합니다.
7
+
8
+ 구현 의무:
9
+ - 모든 상태값은 실제 상태 파일, PID, Worker, Registry에서 계산
10
+ - 측정 실패를 0, 빈 배열, 정상 상태로 변환 금지
11
+ - 지원하지 않는 기능은 OperationNotSupported 예외 발생 (빈 성공 금지)
12
+ - doctor_lite 실행 시간 목표: 500ms 이내
13
+ - doctor_lite 금지 항목: 모델 전체 Load, Vulkan 전체 Doctor,
14
+ 대형 Hash 재계산, 샘플 추론, ONNX Session 생성,
15
+ Audio Device 초기화, 모델 다운로드 서버 접속
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from abc import ABC, abstractmethod
20
+
21
+
22
+ class ComponentControl(ABC):
23
+ """
24
+ AMEVA Component Protocol v1 공통 컨트롤 인터페이스.
25
+
26
+ 각 패키지는 이 클래스를 상속하고 모든 abstractmethod를 구현해야 합니다.
27
+ 기존 엔진 코드를 Adapter 방식으로 감싸서 연결하세요.
28
+ 기존 기능을 가짜 Stub로 대체하지 마세요.
29
+ """
30
+
31
+ # 서브클래스가 반드시 선언해야 하는 클래스 변수
32
+ COMPONENT_ID: str # e.g. "termux-llamacpp"
33
+ COMPONENT_TYPE: str # "llm", "stt", "tts", "vision", "diffusion", "train", "browser"
34
+ CAPABILITIES: tuple[str, ...] # 실제 지원하는 Capability만
35
+
36
+ @abstractmethod
37
+ def component_info(self) -> dict:
38
+ """
39
+ 컴포넌트 자기 신원 정보를 반환합니다.
40
+ protocol: "ameva-component/1" 포함.
41
+ 실패 시 예외 발생 — ok:false 응답을 직접 반환하지 않습니다.
42
+ """
43
+
44
+ @abstractmethod
45
+ def doctor_lite(self) -> dict:
46
+ """
47
+ 경량 상태 확인. 실행 시간 목표 500ms 이내.
48
+
49
+ 필수 포함:
50
+ - 버전, 상태 파일 경로 및 updated_at
51
+ - 활성 모델 ID
52
+ - Worker PID 존재 여부 및 실제 생존 여부 (os.kill(pid, 0))
53
+ - 최근 Heartbeat 시간
54
+ - Listening Socket 또는 Worker 연결 상태
55
+ - 현재 Instance 수
56
+ - 현재 Active Job 수
57
+ - 마지막 오류
58
+ - Backend와 Device의 이미 확인된 상태
59
+
60
+ 포함 금지:
61
+ - 모델 전체 Load
62
+ - Vulkan 전체 Doctor
63
+ - 대형 모델 Hash 재계산
64
+ - 샘플 추론
65
+ - ONNX Session 생성
66
+ - Audio Device 전체 초기화
67
+ - 모델 다운로드 서버 접속
68
+ """
69
+
70
+ @abstractmethod
71
+ def doctor_full(self) -> dict:
72
+ """
73
+ 상세 진단. 수 분 소요 가능.
74
+ Vulkan 전체 Doctor, 샘플 추론 등 포함 가능.
75
+ """
76
+
77
+ @abstractmethod
78
+ def list_models(self) -> dict:
79
+ """
80
+ 설치된 모델 목록을 반환합니다.
81
+ 각 모델의 state (missing/installed/active 등)를 포함합니다.
82
+ failed 모델을 installed로 반환하지 않습니다.
83
+
84
+ 미지원 패키지 (termux-playwright, termux-train): OperationNotSupported 발생.
85
+ """
86
+
87
+ @abstractmethod
88
+ def model_status(self, model_id: str | None = None) -> dict:
89
+ """
90
+ 특정 모델 또는 전체 모델 상태를 반환합니다.
91
+ failed를 installed로 변환하지 않습니다.
92
+
93
+ 미지원 패키지: OperationNotSupported 발생.
94
+ """
95
+
96
+ @abstractmethod
97
+ def install_model(self, request: dict) -> dict:
98
+ """
99
+ 모델을 설치합니다.
100
+
101
+ 공통 순서:
102
+ 1. URL 검사
103
+ 2. 디스크 여유 공간 검사
104
+ 3. 임시 파일 다운로드 (진행 상황 → stderr)
105
+ 4. 최대 크기 검사
106
+ 5. 예상 크기 검사
107
+ 6. SHA-256 검사
108
+ 7. 형식 검사 (패키지별 after_download hook)
109
+ 8. Package 호환성 검사
110
+ 9. Manifest 저장
111
+ 10. installed 상태 기록
112
+
113
+ 미지원 패키지: OperationNotSupported 발생.
114
+ """
115
+
116
+ @abstractmethod
117
+ async def activate_model(self, request: dict) -> dict:
118
+ """
119
+ 모델을 활성화합니다 (safe-switch 기본 전략).
120
+
121
+ 순서:
122
+ 1. 모델이 verified 상태인지 확인
123
+ 2. 대상 Instance 확인
124
+ 3. RAM 및 Accelerator 예산 확인
125
+ 4. 신규 Job 접수 일시 중단
126
+ 5. 기존 Job Drain
127
+ 6. 새 모델 준비
128
+ 7. 새 모델 Load
129
+ 8. 최소 Health Probe (실제 추론 없이 메타데이터만)
130
+ 9. 성공 시에만 Active Pointer 변경
131
+ 10. 기존 모델 자원 해제
132
+
133
+ 실패 시:
134
+ - Active Pointer 변경 금지
135
+ - 기존 모델 유지
136
+ - rollback.succeeded를 정직하게 반환
137
+ - 성공으로 위장 금지
138
+
139
+ 미지원 패키지 (termux-playwright): OperationNotSupported 발생.
140
+ """
141
+
142
+ @abstractmethod
143
+ async def deactivate_model(self, request: dict) -> dict:
144
+ """
145
+ 활성 모델을 비활성화합니다.
146
+ 미지원 패키지: OperationNotSupported 발생.
147
+ """
148
+
149
+ @abstractmethod
150
+ def list_instances(self) -> dict:
151
+ """
152
+ 현재 등록된 Instance 목록을 반환합니다.
153
+ termux-playwright는 Browser Context 또는 Worker 목록.
154
+ termux-train은 Training Worker 목록.
155
+ """
156
+
157
+ @abstractmethod
158
+ async def start_instance(self, request: dict) -> dict:
159
+ """
160
+ 새 Instance를 시작합니다.
161
+ termux-train: Training Worker.
162
+ """
163
+
164
+ @abstractmethod
165
+ async def drain_instance(self, instance_id: str) -> dict:
166
+ """
167
+ Instance를 Drain 상태로 전환합니다 (신규 Job 접수 중단, 기존 Job 완료 대기).
168
+ termux-train: Checkpoint 저장 후 중단 또는 새 작업 접수 중단.
169
+ """
170
+
171
+ @abstractmethod
172
+ async def stop_instance(self, instance_id: str) -> dict:
173
+ """Instance를 중지합니다."""