feat: embed native Harness assistant and verify live task model
This commit is contained in:
1 parent
9c508333bb
commit
96227eed2e
29 files changed
+11110
-582
No files matched your search
@@ -0,0 +1,31 @@
|
||||
"""Command-line verification of the official embedded Harness installation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from .native_runtime import integration_root, node_executable
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(prog='python -m dx_productivity.dsh')
|
||||
parser.add_argument('--doctor', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if not args.doctor:
|
||||
parser.error('Use --doctor to verify the native Harness runtime.')
|
||||
try:
|
||||
result = subprocess.run([node_executable(), str(integration_root() / 'start.mjs'), '--doctor'],
|
||||
capture_output=True, text=True, encoding='utf8', timeout=45, check=False)
|
||||
if result.returncode:
|
||||
print(json.dumps({'status': 'unavailable', 'reason': 'Official runtime check failed'}))
|
||||
return result.returncode
|
||||
print(result.stdout.strip())
|
||||
return 0
|
||||
except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
|
||||
print(json.dumps({'status': 'unavailable', 'reason': str(error)}))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Locate and configure the application-owned official Harness runtime."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
from .snapshot import TaskSnapshot
|
||||
|
||||
HARNESS_VERSION = '0.2.1-rc.5'
|
||||
|
||||
|
||||
def integration_root() -> Path:
|
||||
if getattr(sys, 'frozen', False):
|
||||
return Path(sys._MEIPASS) / 'dsh-runtime'
|
||||
return Path(__file__).resolve().parents[3] / 'integration' / 'dsh'
|
||||
|
||||
|
||||
def node_executable() -> str:
|
||||
bundled = integration_root() / 'node.exe'
|
||||
value = str(bundled) if bundled.is_file() else shutil.which('node')
|
||||
if not value:
|
||||
raise RuntimeError('未找到 Node.js 24.9+,请先安装 DSH 运行时。')
|
||||
return value
|
||||
|
||||
|
||||
def launch_environment(data_root: Path) -> dict[str, str]:
|
||||
allowed = {'SystemRoot', 'WINDIR', 'ComSpec', 'PATHEXT', 'PATH', 'TEMP', 'TMP',
|
||||
'APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMFILES', 'PROGRAMFILES(X86)',
|
||||
'DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY'}
|
||||
env = {key: value for key, value in os.environ.items() if key.upper() in {s.upper() for s in allowed}}
|
||||
if not all(env.get(key) for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY')):
|
||||
from .provider_config import load_provider
|
||||
env.update(load_provider(data_root))
|
||||
env.update(DX_DSH_HOME=str(data_root / 'harness-home'),
|
||||
DX_DSH_CONTEXT_FILE=str(data_root / 'task-context.json'),
|
||||
DSH_TELEMETRY_DISABLED='1', DX_DSH_PARENT_PIPE='1', NO_COLOR='1')
|
||||
return env
|
||||
|
||||
|
||||
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='') -> dict:
|
||||
data_root.mkdir(parents=True, exist_ok=True)
|
||||
value = snapshot.safe_dict() | {'revision': uuid4().hex,
|
||||
'events': [str(e)[:300] for e in events][-20:], 'action_result': str(action_result)[:300],
|
||||
'task_name': str(task_name)[:128]}
|
||||
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
|
||||
os.replace(temporary, data_root / 'task-context.json')
|
||||
return value
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Machine-local API configuration; credentials are protected by Windows DPAPI."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def save_provider(directory: Path, *, base_url: str, models: list[str], default_model: str, api_key: str):
|
||||
import win32crypt
|
||||
if not base_url.startswith('https://') or not models or default_model not in models or not api_key:
|
||||
raise ValueError('invalid_provider_configuration')
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
encrypted = win32crypt.CryptProtectData(api_key.encode('utf8'), 'DxPartReplace DSH provider', None, None, None, 0)
|
||||
key_file = directory / 'provider-key.dpapi'
|
||||
temporary = directory / 'provider-key.tmp'
|
||||
temporary.write_bytes(encrypted)
|
||||
os.replace(temporary, key_file)
|
||||
metadata = {'base_url': base_url.rstrip('/'), 'models': models, 'default_model': default_model}
|
||||
(directory / 'provider.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf8')
|
||||
|
||||
|
||||
def load_provider(directory: Path) -> dict[str, str]:
|
||||
import win32crypt
|
||||
if not (directory / 'provider.json').is_file():
|
||||
return {}
|
||||
metadata = json.loads((directory / 'provider.json').read_text(encoding='utf8'))
|
||||
_, plain = win32crypt.CryptUnprotectData((directory / 'provider-key.dpapi').read_bytes(), None, None, None, 0)
|
||||
return {'DSH_API_BASE': metadata['base_url'], 'DSH_MODEL': metadata['default_model'],
|
||||
'DSH_API_KEY': plain.decode('utf8'), 'DX_DSH_MODELS': json.dumps(metadata['models'])}
|
||||
Reference in new issue
Block a user