worker.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. """Private newline-delimited RPC worker for the embedded Yaovi kernel."""
  2. import json
  3. import os
  4. from pathlib import Path
  5. import queue
  6. import signal
  7. import re
  8. import sys
  9. import threading
  10. import uuid
  11. ROOT = Path(__file__).resolve().parent
  12. sys.path.insert(0, str(ROOT / "hermes"))
  13. WIRE = sys.stdout
  14. sys.stdout = sys.stderr
  15. lock = threading.Lock()
  16. pending = {}
  17. agent = None
  18. persistent_waits = False
  19. # Guards steer acceptance against the end of the turn: after the final drain nothing can deliver it.
  20. steer_lock = threading.Lock()
  21. turn_closed = False
  22. steer_ready = False
  23. startup_steers = []
  24. # Prefix of the per-turn application state Yaovi renders (src/server/workspacePrompt.ts).
  25. TURN_CONTEXT_SENTINEL = "[[YAOVI_TURN_CONTEXT_V1]]"
  26. # Control-plane RPCs whose replies are JSON values, never model-facing tool output.
  27. CONTROL_TOOLS = ("yaovi_clarify", "yaovi_native_authorize", "yaovi_native_check")
  28. def emit(kind, **payload):
  29. with lock:
  30. WIRE.write(json.dumps({"type": kind, **payload}, ensure_ascii=False, default=str) + "\n")
  31. WIRE.flush()
  32. def dispatch(name, args, **metadata):
  33. call_id = str(uuid.uuid4())
  34. from native_authorization import metadata as call_metadata
  35. metadata = call_metadata(**metadata)
  36. model_call_id = metadata.get("tool_call_id")
  37. reply = queue.Queue(maxsize=1)
  38. with lock:
  39. pending[call_id] = reply
  40. emit("tool.request", id=call_id, name=name, arguments=args,
  41. sessionId=metadata.get("session_id"), taskId=metadata.get("task_id"), modelCallId=model_call_id)
  42. try:
  43. value = reply.get() if persistent_waits else reply.get(timeout=600)
  44. if "error" in value:
  45. return json.dumps({"error": value["error"], "isError": True})
  46. result = value.get("result")
  47. if name not in CONTROL_TOOLS:
  48. # Yaoyao normalizes application tool results (text, or Hermes' native multimodal envelope).
  49. if isinstance(result, dict) and result.get("_multimodal") is True:
  50. return result
  51. if isinstance(result, str):
  52. return result
  53. from workspace_media import computer_result
  54. return computer_result(name, result)
  55. finally:
  56. with lock:
  57. pending.pop(call_id, None)
  58. def interrupt():
  59. global turn_closed
  60. with steer_lock:
  61. turn_closed = True
  62. if agent is not None:
  63. agent.interrupt()
  64. # Release root and child RPC waits so cancellation does not wait for the
  65. # 600-second tool timeout. Product receipts retain uncertain side effects.
  66. with lock:
  67. targets = list(pending.values())
  68. for target in targets:
  69. try:
  70. target.put_nowait({"error": "Task cancelled. Inspect effects before retrying."})
  71. except queue.Full:
  72. pass
  73. def read_replies():
  74. for line in sys.stdin:
  75. message = json.loads(line)
  76. if message.get("type") == "interrupt":
  77. interrupt()
  78. continue
  79. if message.get("type") == "steer":
  80. # Initialization is part of this turn too. Retain early input until
  81. # the agent exists; redirect owns admission through final reply commit.
  82. accepted = False
  83. phase = "closed"
  84. with steer_lock:
  85. text = str(message.get("text") or "").strip()
  86. if text and not turn_closed and not steer_ready:
  87. startup_steers.append(text)
  88. accepted, phase = True, "initializing"
  89. elif text and not turn_closed:
  90. phase = ("tools" if getattr(agent, "_executing_tools", False) else
  91. "model" if agent._model_request_active.is_set() else
  92. "preparing" if agent._turn_redirect_open else "finishing")
  93. try:
  94. deliver = agent.steer if getattr(agent, "_executing_tools", False) else agent.redirect
  95. accepted = bool(deliver(text))
  96. except Exception:
  97. phase = "delivery_error"
  98. accepted = False
  99. emit("kernel.event", name="steer.admission", value={"accepted": accepted, "phase": phase})
  100. emit("steer.result", id=message.get("id"), accepted=accepted)
  101. continue
  102. with lock:
  103. target = pending.get(message.get("id"))
  104. if target is not None:
  105. try:
  106. target.put_nowait(message)
  107. except queue.Full:
  108. pass
  109. interrupt()
  110. def strip_turn_context_sidecars(history):
  111. """Earlier turns replay their user content only, never the per-turn state sent with them."""
  112. for message in history:
  113. sidecar = message.get("api_content")
  114. if message.get("role") == "user" and isinstance(sidecar, str) and sidecar.startswith(TURN_CONTEXT_SENTINEL):
  115. message.pop("api_content", None)
  116. return history
  117. def compose_turn(text, turn_context):
  118. """``(model-facing message, persisted message)``; state reaches this turn's calls only."""
  119. if not turn_context:
  120. return text, None
  121. if not str(turn_context).startswith(TURN_CONTEXT_SENTINEL):
  122. raise ValueError("Turn context is missing its sentinel")
  123. if isinstance(text, list):
  124. return [{"type": "text", "text": turn_context}, *text], text
  125. return turn_context + "\n\n" + str(text), text
  126. def clarify(questions):
  127. answers = {}
  128. for question in questions:
  129. answer = json.loads(dispatch("yaovi_clarify", {"question": question["question"], "choices": question.get("choices")}))
  130. if not isinstance(answer, str):
  131. return {"answers": answers, "outcome": "cancelled"}
  132. answers[question["qid"]] = answer
  133. return {"answers": answers, "outcome": "submitted"}
  134. def load_hermes_env(home):
  135. """System-layer Hermes .env first, then the Bot's own .env (Bot keys win); process env stays authoritative."""
  136. from agent.secret_scope import load_env_file
  137. root = os.environ.get("YAOVI_HERMES_ROOT", "").strip()
  138. merged = {}
  139. for path in ([Path(root) / ".env"] if root else []) + [home / ".env"]:
  140. if path.exists():
  141. merged.update(load_env_file(path))
  142. for key, value in merged.items():
  143. os.environ.setdefault(key, value)
  144. def resolve_route(route, config):
  145. """Hermes owns provider resolution: config.yaml model/providers, .env keys, auth.json OAuth and pools."""
  146. from hermes_cli.runtime_provider import resolve_runtime_provider
  147. if route.get("baseURL"): # explicit endpoint (tests / Hermes `--base-url` rung)
  148. runtime = resolve_runtime_provider(requested=route.get("provider") or "custom", explicit_base_url=route["baseURL"],
  149. explicit_api_key=route.get("apiKey"), target_model=route.get("model") or None)
  150. runtime["api_mode"] = route.get("apiMode") or runtime.get("api_mode")
  151. return runtime
  152. runtime = resolve_runtime_provider(requested=route.get("provider") or None, target_model=route.get("model") or None)
  153. if not runtime.get("base_url") and runtime.get("provider") not in ("bedrock", "copilot-acp", "moa"):
  154. raise RuntimeError(f"Hermes could not resolve provider {route.get('provider')!r}; configure it in model services")
  155. return runtime
  156. def model_speed_options(route, runtime):
  157. """Translate the Bot's selected speed using Hermes' route-aware native fast gate."""
  158. from agent.fast_mode import parse_exact_service_tier
  159. from hermes_cli.models import resolve_fast_mode_overrides
  160. mode = route.get("fastMode") or "normal"
  161. if mode not in ("normal", "fast"):
  162. raise ValueError(f"Unsupported Bot fast mode: {mode}")
  163. tier = parse_exact_service_tier(mode)
  164. overrides = {}
  165. if tier:
  166. overrides = resolve_fast_mode_overrides(route["model"], provider=runtime.get("provider"), base_url=runtime.get("base_url"))
  167. if overrides is None:
  168. raise ValueError("The resolved provider route does not support fast mode")
  169. return {"service_tier": tier or None, "request_overrides": overrides}
  170. def register_vault_env():
  171. """Owner-authorized vault env credentials arrive in the process env only.
  172. Register each value for model-facing redaction before any tool runs, and allow
  173. the names through Hermes sandbox env scrubbing (owner decision: all subprocesses)."""
  174. names = [n for n in os.environ.pop("YAOVI_VAULT_ENV_NAMES", "").split(",") if re.fullmatch(r"[A-Z][A-Z0-9_]*", n or "")]
  175. if not names:
  176. return
  177. from agent.redact import register_vault_redaction_value
  178. from tools.env_passthrough import register_env_passthrough
  179. for name in names:
  180. register_vault_redaction_value(os.environ.get(name))
  181. register_env_passthrough(names)
  182. def compact_session(agent, db, history, saved, history_file):
  183. """Compress a settled session in place and report the new size; anything else is left untouched."""
  184. def done(status, **usage):
  185. emit("completed", text=status, usage=usage)
  186. # Only a turn that ended cleanly has a transcript without dangling tool calls.
  187. if not isinstance(saved, dict) or saved.get("status") != "complete" or not history:
  188. return done("skipped")
  189. from agent.conversation_compression import finalize_context_engine_compression_notification
  190. from agent.conversation_compression_manual import CompressRequest, compress_now
  191. # This process has no tools and no live prompt environment: keep the session's stored prompt
  192. # (and its saved tool list) instead of rebuilding them at the commit boundary.
  193. row = db.get_session(agent.session_id) or {}
  194. stored_prompt = row.get("system_prompt")
  195. agent._cached_system_prompt = stored_prompt if isinstance(stored_prompt, str) else ""
  196. agent._retain_seeded_system_prompt = True
  197. committed = False
  198. try:
  199. outcome = compress_now(agent, history, CompressRequest(), system_message="",
  200. skip_without_window=True, task_id=agent.session_id or "default")
  201. committed = outcome.status == "compressed"
  202. if committed and agent.session_id != saved.get("kernelSessionId"):
  203. # The kernel moved the conversation to a new session id: the next turn must follow it.
  204. temporary = history_file.with_suffix(".tmp")
  205. temporary.write_text(json.dumps({**saved, "kernelSessionId": agent.session_id}))
  206. temporary.chmod(0o600)
  207. temporary.replace(history_file)
  208. finally:
  209. finalize_context_engine_compression_notification(agent, committed=committed)
  210. if not committed:
  211. return done(outcome.status)
  212. compressor = getattr(agent, "context_compressor", None)
  213. done("compressed", context_used=int(outcome.after_tokens), before_tokens=int(outcome.before_tokens),
  214. context_max=int(getattr(compressor, "context_length", 0) or 0) or None, context_source="local_estimate")
  215. def main():
  216. global agent, persistent_waits, turn_closed, steer_ready
  217. request = json.loads(sys.stdin.readline())
  218. persistent_waits = request.get("botPolicy", {}).get("version") == 2
  219. # Native initialization and skill admission may issue RPCs before AIAgent
  220. # exists. Start the sole reply reader before any such authorization call.
  221. threading.Thread(target=read_replies, daemon=True).start()
  222. home = Path(request["dataRoot"]).resolve()
  223. home.mkdir(parents=True, exist_ok=True, mode=0o700)
  224. os.environ["HERMES_HOME"] = str(home)
  225. os.environ["HERMES_PYTHON_SRC_ROOT"] = str(ROOT / "hermes")
  226. os.environ["HERMES_SKIP_UPDATE_CHECK"] = "1"
  227. os.environ["YAOVI_KERNEL"] = "1"
  228. from agent.runtime_context import install, migrate_product_prompt
  229. # Session titles belong to the Yaovi workspace (server-side, via Hermes auxiliary.title_generation).
  230. aux = request.setdefault("config", {}).setdefault("auxiliary", {})
  231. aux.setdefault("title_generation", {})["enabled"] = False
  232. network_snapshot = request.pop("network", None)
  233. install(request, dispatch)
  234. import model_network
  235. model_network.install()
  236. network_scope = model_network.scope(network_snapshot, model_operation=False)
  237. network_scope.__enter__() # One turn owns this process; child threads inherit its snapshot.
  238. from run_agent import AIAgent
  239. if request.get('usageObservation'):
  240. import dialogue_usage
  241. dialogue_usage.install({**request['usageObservation'], 'provider': request.get('route', {}).get('provider', 'unknown')}, emit, AIAgent)
  242. import native_authorization
  243. native_authorization.install(request, dispatch, agent_class=AIAgent)
  244. load_hermes_env(home)
  245. register_vault_env()
  246. import host_runtime
  247. host_cwd = host_runtime.install(request)
  248. from hermes_state import SessionDB
  249. db = SessionDB(db_path=home / "state.db")
  250. session = request["sessionId"]
  251. if not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", session):
  252. raise ValueError("Invalid session identifier")
  253. route = request["route"]
  254. config = request["config"]
  255. history_file = home / "contexts" / (session + ".json")
  256. checkpoint = json.loads(history_file.read_text()) if history_file.exists() else {}
  257. if isinstance(checkpoint, list):
  258. history = checkpoint
  259. else:
  260. session = checkpoint.get("kernelSessionId", session)
  261. # Preserve dangling calls before repairing alternation: repair can drop them.
  262. history = db.get_messages_as_conversation(session, include_ancestors=True, repair_alternation=False)
  263. if checkpoint.get("status") == "running":
  264. # Missing tool receipts remain unknown; never invoke the old action again.
  265. pending_calls = {c["id"] for m in history for c in m.get("tool_calls", [])}
  266. pending_calls -= {m.get("tool_call_id") for m in history if m.get("role") == "tool"}
  267. for call in pending_calls:
  268. history.append({"role":"tool", "tool_call_id":call, "content":json.dumps({"error":"Interrupted before the result was confirmed. Inspect effects before retrying.","outcomeUnknown":True})})
  269. # A turn that crashed before its cleanup must not leak its state into this one,
  270. # including rows reloaded from the store after in-turn compaction.
  271. db.clear_user_api_content_with_prefix(session, TURN_CONTEXT_SENTINEL)
  272. strip_turn_context_sidecars(history)
  273. # Existing sessions retain their admitted tools and context. Only the known
  274. # application identity prefix changes, at a turn boundary before model use.
  275. row = db.get_session(session)
  276. if row:
  277. stored_prompt = row.get("system_prompt")
  278. product_prompt = migrate_product_prompt(stored_prompt)
  279. if product_prompt != stored_prompt:
  280. db.update_system_prompt(session, product_prompt)
  281. runtime = resolve_route(route, config)
  282. agent = AIAgent(
  283. **model_speed_options(route, runtime),
  284. model=route["model"], provider=runtime.get("provider"),
  285. base_url=runtime.get("base_url"), api_key=runtime.get("api_key"),
  286. api_mode=runtime.get("api_mode"), credential_pool=runtime.get("credential_pool"),
  287. fallback_model=config.get("fallback_model") or None,
  288. session_id=session, session_db=db, platform=str(request.get("platform") or "yaovi"),
  289. **({'cwd': host_cwd} if host_cwd else {}),
  290. max_iterations=config["agent"]["max_iterations"],
  291. reasoning_config=(None if route.get("reasoningEffort") in (None, "default")
  292. else {"enabled": False} if route["reasoningEffort"] == "none"
  293. else {"effort": route["reasoningEffort"]}),
  294. quiet_mode=True, skip_context_files=True, skip_memory=False,
  295. skip_background_review=not config.get("memory", {}).get("automatic", True),
  296. ephemeral_system_prompt=request.get("instructions", ""),
  297. stream_delta_callback=lambda text: emit("message.delta", text=text),
  298. reasoning_callback=lambda text, **kw: emit("reasoning.delta", text=text),
  299. event_callback=lambda name, value: emit("kernel.event", name=name, value=value),
  300. tool_progress_callback=lambda kind, name=None, preview=None, args=None, **kw: emit("kernel.event", name=kind, value={"tool":name,"preview":preview,"args":args,**kw}),
  301. clarify_callback=clarify,
  302. )
  303. # Tag tool progress with the model's call id so the host can pair started/completed events.
  304. agent._yaovi_embedded = True
  305. if request.get('reportOnlyReview') is True:
  306. # The Host admitted only the structured decision and session attachment
  307. # reader. Native skill,
  308. # clarification, delegation and discovery tools are not in this turn's
  309. # catalog; native_authorization remains a second fail-closed boundary.
  310. allowed = {'workspace_review_background_task', 'harness_result_read'}
  311. names = [entry.get('name') for entry in request.get('tools', [])]
  312. if request.get('botPolicy', {}).get('enabled') is not True or len(names) != len(allowed) or set(names) != allowed:
  313. raise RuntimeError('Report-only review contains an unsupported tool')
  314. agent.tools = [tool for tool in agent.tools if tool.get('function', {}).get('name') in allowed]
  315. agent.valid_tool_names = {tool['function']['name'] for tool in agent.tools}
  316. agent.enabled_toolsets = ['yaovi']
  317. agent.disabled_toolsets = []
  318. if request.get('nativeMemory') and not any(getattr(p, '_client', None) for p in getattr(agent._memory_manager, 'providers', [])):
  319. emit('memory.provider.degraded', message='Hermes 原生记忆暂不可用,本轮未接入远程记忆;不会改用 user 模式。')
  320. agent._iters_since_skill = checkpoint.get("skillIterations", 0) if isinstance(checkpoint, dict) else 0
  321. if request.get("compact") is not None:
  322. # specs/102: the Host compresses a settled session between turns. No conversation turn runs,
  323. # and the turn checkpoint keeps its status and run id.
  324. compact_session(agent, db, history, checkpoint, history_file)
  325. agent.close()
  326. db.close()
  327. return
  328. history_file.parent.mkdir(parents=True, exist_ok=True)
  329. def checkpoint(status):
  330. temporary = history_file.with_suffix(".tmp")
  331. temporary.write_text(json.dumps({"version":1,"status":status,"kernelSessionId":agent.session_id,"runId":request["runId"],"skillIterations":agent._iters_since_skill}))
  332. temporary.chmod(0o600)
  333. temporary.replace(history_file)
  334. checkpoint("running")
  335. with steer_lock:
  336. if turn_closed:
  337. raise RuntimeError("Task cancelled during initialization")
  338. # Opt this worker into whole-turn admission. Native redirect otherwise
  339. # retains its model-request-only contract for other Hermes surfaces.
  340. with agent._pending_redirect_lock:
  341. agent._turn_redirect_open = True
  342. for text in startup_steers:
  343. if not agent.redirect(text):
  344. # External runtimes can own their own turn admission. Preserve
  345. # accepted input for their existing leftover recovery contract.
  346. agent.steer(text)
  347. startup_steers.clear()
  348. steer_ready = True
  349. from tool_discovery import metadata as discovery_metadata
  350. emit("ready", sessionId=session, toolDiscovery=discovery_metadata(agent))
  351. if request.get("review"):
  352. from agent.background_review import _run_review_fork, _ReviewForkState, spawn_background_review_thread
  353. state = _ReviewForkState()
  354. _, prompt = spawn_background_review_thread(agent, request["review"]["messages"], review_skills=True, focus=request["review"].get("focus"))
  355. result = _run_review_fork(agent, request["review"]["messages"], prompt, {}, None, state)
  356. if not result:
  357. raise RuntimeError("Native skill review did not finish")
  358. else:
  359. message, persisted = compose_turn(request["text"], request.get("turnContext"))
  360. try:
  361. result = agent.run_conversation(message, conversation_history=history,
  362. **({"persist_user_message": persisted} if persisted is not None else {}))
  363. finally:
  364. if persisted is not None:
  365. for lineage in dict.fromkeys((session, agent.session_id)):
  366. db.clear_user_api_content_with_prefix(lineage, TURN_CONTEXT_SENTINEL)
  367. with steer_lock:
  368. turn_closed = True
  369. with agent._pending_redirect_lock:
  370. agent._turn_redirect_open = False
  371. unapplied_redirect = agent._pending_redirect
  372. agent._pending_redirect = None
  373. # Keep Hermes' recovery handoff for an unconsumed tool steer or redirect
  374. # restart limit. Normal model-time insertion is consumed in this turn.
  375. leftover_steer = (result.get("pending_steer") or "").strip()
  376. drain = getattr(agent, "_drain_pending_steer", None)
  377. late = (drain() or "").strip() if callable(drain) else ""
  378. leftover_steer = "\n".join(part for part in (leftover_steer, late, unapplied_redirect) if part)
  379. if leftover_steer and result.get("completed") is not False:
  380. emit("steer.leftover", text=leftover_steer)
  381. checkpoint("complete" if result.get("completed") else "interrupted")
  382. if result.get("completed") is False:
  383. raise RuntimeError(result.get("error") or "Agent did not complete the turn")
  384. # Hermes is the source of truth: session_* counters for billing, last_prompt_tokens /
  385. # context_usage_fields for occupancy (never use session sums as context %).
  386. compressor = getattr(agent, "context_compressor", None)
  387. context_fields = {}
  388. try:
  389. from agent.context_breakdown import context_usage_fields
  390. context_fields = context_usage_fields(compressor) if compressor else {}
  391. except Exception:
  392. context_fields = {}
  393. if not context_fields.get("context_used"):
  394. last_prompt = int(result.get("last_prompt_tokens") or 0)
  395. context_max = int(getattr(compressor, "context_length", 0) or 0) if compressor else 0
  396. if last_prompt > 0:
  397. context_fields = {
  398. "context_used": min(last_prompt, context_max) if context_max else last_prompt,
  399. "context_max": context_max or None,
  400. "context_source": "provider_usage" if last_prompt else "local_estimate",
  401. }
  402. breakdown = None
  403. try:
  404. from agent.context_breakdown import compute_session_context_breakdown
  405. breakdown = compute_session_context_breakdown(agent, history if isinstance(history, list) else [])
  406. except Exception:
  407. breakdown = None
  408. last_turn = getattr(agent, "_last_turn_usage", None)
  409. emit("completed", text=result.get("final_response", ""), usage={
  410. # Per-process turn totals (Yaovi spawns one worker per turn).
  411. "input_tokens": int(getattr(agent, "session_prompt_tokens", 0) or result.get("prompt_tokens") or 0),
  412. "output_tokens": int(getattr(agent, "session_completion_tokens", 0) or result.get("completion_tokens") or 0),
  413. "total_tokens": int(getattr(agent, "session_total_tokens", 0) or result.get("total_tokens") or 0),
  414. "prompt_tokens": int(getattr(agent, "session_prompt_tokens", 0) or 0),
  415. "completion_tokens": int(getattr(agent, "session_completion_tokens", 0) or 0),
  416. "cache_read_tokens": int(getattr(agent, "session_cache_read_tokens", 0) or 0),
  417. "cache_write_tokens": int(getattr(agent, "session_cache_write_tokens", 0) or 0),
  418. "reasoning_tokens": int(getattr(agent, "session_reasoning_tokens", 0) or 0),
  419. "last_prompt_tokens": int(result.get("last_prompt_tokens") or 0),
  420. "last_turn": last_turn if isinstance(last_turn, dict) else None,
  421. "model": result.get("model") or getattr(agent, "model", None),
  422. "provider": result.get("provider") or getattr(agent, "provider", None),
  423. "usage_mode": "turn",
  424. **{k: v for k, v in context_fields.items() if v is not None},
  425. **({"breakdown": breakdown} if breakdown else {}),
  426. })
  427. if request.get("nativeMemory") and agent._memory_manager:
  428. agent._memory_manager.flush_pending(timeout=15)
  429. agent.close()
  430. db.close()
  431. if __name__ == "__main__":
  432. try:
  433. main()
  434. except BaseException as error:
  435. emit("failed", message=str(error), code=type(error).__name__)
  436. import traceback
  437. traceback.print_exc(file=sys.stderr)
  438. sys.exit(1)
  439. finally:
  440. import native_skills
  441. native_skills.cleanup()