"""HTTP adapter to the same np command used by agents; no planner logic here.""" import json from pathlib import Path import subprocess import sys from np.planning import CONTRACTS, read_json, validate_schema class BatchCommands: def __init__(self, catalog=None, packages=None, result=None): self._schema_cache = None self.catalog = catalog self.packages = packages self.result_path = Path(result) if result else CONTRACTS / 'batch-result.example.json' def command(self, name, config=None): if not self.catalog or not self.packages: raise ValueError('未登记问法核心与证据层;启动服务时提供 --np-catalog 和 --np-evidence-packages') key = None if name == 'schema': key = tuple((str(path), path.stat().st_mtime_ns) for path in (Path(self.catalog), Path(self.packages), self.result_path)) if self._schema_cache is not None and self._schema_cache[0] == key: return self._schema_cache[1] argv = [sys.executable, '-m', 'np', name, '--catalog', str(self.catalog), '--evidence-packages', str(self.packages), '--result', str(self.result_path)] if config is not None: argv += ['--config', '/dev/stdin'] run = subprocess.run(argv, input=json.dumps(config) if config is not None else None, # schema is cached after the first call; a cold restart reads the catalog from shared NVMe. capture_output=True, text=True, timeout=20 if name == 'schema' else 2, cwd=Path(__file__).resolve().parents[3]) if run.returncode: try: message = json.loads(run.stderr)['error'] except (ValueError, KeyError): message = 'np 命令失败' raise ValueError(message) value = json.loads(run.stdout) if name == 'schema': self._schema_cache = (key, value) if name == 'plan': # the console's own last step, shown with np's commands from .np_generation import planned_convert value['commands']['convert'] = planned_convert() return value def result(self): result = read_json(self.result_path) validate_schema(result, read_json(CONTRACTS / 'batch-result.schema.json')) return result