from __future__ import annotations from copy import copy, deepcopy from dataclasses import asdict, replace from functools import wraps import json import os from pathlib import Path import threading import time import uuid from types import SimpleNamespace from .model import Action, Catalog, Planner, Policy, Snapshot, seconds from .daily import DailyLedger, DailyPolicy, selected_entries from .sweeping import SweepPolicy, SweepRunner from .quests import QuestPolicy, TaskPlanner, commission_priority, commission_reason_kind from .procurement import resource_kind from .commission_history import CommissionHistory from .market import PurchaseBudget from .management import expansion_quote, manual_monster_actions from .gifts import GiftPlanner from .master_sync import MasterSync from .stage_cache import StageCache from .drop_statistics import reward_text from .cultivation import CultivationSelector from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch, digest, gameplay_response, public_data, value from .resource_stages import resource_entry_reason from .resource_stages import with_resource_data from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy from .battle_messages import battle_message from .maps import stages from .exploration import ExplorePlanner, ExplorePolicy from .breakthrough import BreakthroughPlanner, primary_target_reason def account_serial(method): """Serialize whole operations, not just individual Client.call requests.""" @wraps(method) def invoke(self, *args, **kwargs): with self.battle_journal.lock: return method(self, *args, **kwargs) return invoke def single_flight(method): @wraps(method) def invoke(self, *args, **kwargs): generation = self._progression_cancel_generation if not self.battle_journal.lock.acquire(blocking=False): return self.snapshot, [], "同账号已有任务 / 战斗正在执行" try: with self._progression_cancel_lock: if self.auto and generation == self._progression_cancel_generation and self._progression_cancel.is_set(): self._progression_cancel = threading.Event() return method(self, *args, **kwargs) finally: self.battle_journal.lock.release() return invoke class Engine: def __init__(self, catalog, client=None, budget_path=None, *, game_data=None, battle_runtime=None, experimental_runtime=None): self.catalog, self.client = catalog, client self.resource_catalog = None folder = Path(budget_path).parent if budget_path else None self.cultivation = CultivationSelector(catalog, folder / "cultivation_choices.json" if folder else None) self.planner = Planner(catalog, self.cultivation) self.hatch_planner = Planner(catalog, self.cultivation) self.pending_hatches = [] self.gift_planner = GiftPlanner(catalog, self.cultivation) self.policy = Policy() self.quest_policy = QuestPolicy() self.tasks = TaskPlanner(catalog) self.snapshot = None self.demo = client is None self.auto = False self.last_heartbeat = 0 self.last_pending_check = 0 self.heartbeat_enabled = True self.purchase_budget = PurchaseBudget(budget_path) self.last_draw = "" self.growth_cache = {} self.growth_attempts = {} self.master_sync = MasterSync(catalog) self.last_executed = False self.stage_cache = StageCache(catalog, folder / "maps.json" if folder else None) self.daily_policy = DailyPolicy() self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None) self.sweep_policy = SweepPolicy() self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None) self.explore_planner = ExplorePlanner(catalog) self.explore_policy = ExplorePolicy() self.breakthrough_planner = BreakthroughPlanner(catalog, self.cultivation) self.automation_state_path = folder / "automation_state.json" if folder else None self._explore_pending_last_check = 0 self._explore_pending_confirmed = False self._breakthrough_pending = None self._breakthrough_pending_last_check = 0 self._breakthrough_pending_confirmed = False self._automation_load_error = "" self._load_automation_state() self.progression_policy = ProgressionPolicy() self.progression_view_active = False self.progression_planner = None self.game_data = game_data self._progression_namespace = str(folder.resolve()) if folder else "" self._progression_state_loaded = False self._battle_catalog_ready = False self.battle_journal = BattleJournal(folder / "progression" / "journal.json" if folder else None) self._commission_history = CommissionHistory(folder / "progression" / "commission_history.json" if folder else None) self._commission_history_roles = set() self._commission_offer_diagnostics = [] self._commission_diagnostics_key = None self.battles = BattleOrchestrator(catalog, self.battle_journal, battle_runtime, self.sweeper, request_builder=self._battle_request, observer=self._battle_observer) self._progression_cancel = threading.Event() self._progression_cancel_lock = threading.Lock() self._progression_cancel_generation = 0 self._progression_cache_key = None self._progression_rows = [] self._progression_intents = [] self._commission_planner_available = False self._commission_offer_reason = "" self._commission_offer_checks = {} self._map_challenge_reasons = {} self._map_reason_snapshot = None self._map_reason_team = "" self._progression_records = [] self._progression_error = "" self._planner_pending = False self._capability_cache = {} self._battle_snapshot_source = None self._battle_snapshot_digest = "" self._battle_roster_digest = None self._battle_roster = None self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime} self._selected_battle_mode = "original" self._sweep_recovery_cache = {} self._sweep_recovery_message = "" def _map_catalog(self): if self.resource_catalog is None: self.resource_catalog = with_resource_data(self.catalog) return self.resource_catalog def _load_automation_state(self): if not self.automation_state_path: return if not self.automation_state_path.exists(): self._automation_state = {"version": 1, "exploration": self.explore_planner.export_state(), "breakthrough": None} self._save_automation_state() return try: state = json.loads(self.automation_state_path.read_text(encoding="utf-8")) if not isinstance(state, dict) or state.get("version") != 1 or set(state) != {"version", "exploration", "breakthrough"}: raise ValueError("自动操作策略状态版本或结构无效") if not isinstance(state["exploration"], dict): raise ValueError("探险持久化状态无效") self.explore_planner.restore_state(state["exploration"]) self._automation_state = deepcopy(state) pending = state.get("breakthrough") if pending is not None: required = {"kind", "monster_id", "type_id", "attribute", "before", "item_type_ids", "path", "payload", "uncertain", "message", "role_id"} if (not isinstance(pending, dict) or set(pending) != required or pending["kind"] not in ("potential", "breakthrough") or type(pending["monster_id"]) is not int or pending["monster_id"] <= 0 or not isinstance(pending["role_id"], str) or not pending["role_id"] or not isinstance(pending["payload"], dict) or not isinstance(pending["item_type_ids"], list)): raise ValueError("突破待核对状态无效,保留文件并禁止重发") if pending["kind"] == "potential": if pending["attribute"] not in ("atk", "def", "hp", "dex") or type(pending["before"]) not in (int, float): raise ValueError("补潜能待核对状态无效") elif type(pending["before"]) is not int: raise ValueError("潜能阶段待核对状态无效") pending = deepcopy(pending) pending.update(uncertain=True, message="上次进程突破请求结果未知,需由快照核对,禁止重放") self._breakthrough_pending = pending except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: # A failed restore stays fail-closed in memory; do not overwrite the evidence. self._breakthrough_pending = {"kind": "invalid", "role_id": "", "message": "自动操作策略状态无法读取,禁止重发", "uncertain": True} self._explore_pending_confirmed = False self._automation_load_error = str(error) def _save_automation_state(self): if not self.automation_state_path: return if self._automation_load_error: self.auto = False raise ValueError("自动操作策略状态无法读取;保留原文件,禁止覆盖或重发") value = {"version": 1, "exploration": self.explore_planner.export_state(), "breakthrough": self._breakthrough_pending} if self._automation_state == value: return self.automation_state_path.parent.mkdir(parents=True, exist_ok=True) temporary = self.automation_state_path.with_name(self.automation_state_path.name + "." + uuid.uuid4().hex + ".tmp") try: with temporary.open("w", encoding="utf-8") as stream: json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False) stream.flush() os.fsync(stream.fileno()) temporary.replace(self.automation_state_path) self._automation_state = deepcopy(value) except OSError: self.auto = False raise finally: temporary.unlink(missing_ok=True) @staticmethod def _automation_pending_message(planner, snapshot): pending = planner.pending(snapshot) return pending.get("message") if pending else "" def _reconcile_exploration(self): if self._automation_load_error: return pending = self.explore_planner.pending(self.snapshot) if not pending: return if pending.get("uncertain"): self.explore_planner.reconcile(self.snapshot) else: # A transport reply is not proof of server state; use the same fresh # team fingerprint validation as an unknown-result recovery. pending["uncertain"] = True self.explore_planner.reconcile(self.snapshot) self._save_automation_state() def _discard_unsent_automation(self, *, explore=False, before=None): """Rollback is valid only before the host has invoked Client.call.""" if explore: if before is not None: self.explore_planner.restore_state(before) else: self._breakthrough_pending = None self._save_automation_state() def _reconcile_breakthrough(self): pending = self._breakthrough_pending if not pending: return if pending.get("kind") == "invalid": return if str(self.snapshot.raw.get("master", {}).get("id")) != pending.get("role_id"): return mon = self.snapshot.monsters.get(int(pending.get("monster_id", 0))) if not mon or str(mon.get("typeId")) != str(pending.get("type_id")): return if pending["kind"] == "potential": current, previous = mon.get("p" + pending["attribute"].capitalize()), pending.get("before") if current is None or previous is None: return try: confirmed = float(current) > float(previous) except (TypeError, ValueError, OverflowError): return else: try: confirmed = int(mon.get("potentialLevel") or 0) > int(pending.get("before")) except (TypeError, ValueError, OverflowError): return if confirmed: self._breakthrough_pending = None self._save_automation_state() def _execute_explore(self, action): before = self.explore_planner.export_state() try: self.explore_planner.mark_started(self.snapshot, action) try: self._save_automation_state() except Exception: # No wire call occurred: only this pre-dispatch failure may roll back. self.explore_planner.restore_state(before) self.auto = False raise if not self.auto or self._progression_cancel.is_set(): self._discard_unsent_automation(explore=True, before=before) return self.snapshot, self.plans(), "探险请求尚未发送,已取消" try: response = self.client.call(action.path, deepcopy(action.payload)) self.explore_planner.acknowledge(self.snapshot, action, response) self._save_automation_state() except Exception as error: self.explore_planner.mark_uncertain(self.snapshot, action, "探险请求结果未知:" + str(error)) self._save_automation_state() self.auto = False raise self._explore_pending_last_check = time.monotonic() self._explore_pending_confirmed = False self.read_snapshot(sync_master=False) return self.snapshot, self.plans(), action.description + ";已读取新快照核对" except Exception: self.auto = False raise def cultivation_target_reason(self, monster_id, *, primaries=None): return primary_target_reason(self.catalog, self.cultivation, self.snapshot, monster_id, primaries=primaries) def _automatic_cultivation_reason(self, action, *, primaries=None): recipient_key = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"}.get(action.kind) return self.cultivation_target_reason(action.payload.get(recipient_key), primaries=primaries) if recipient_key else "" def _admit_automatic_cultivation(self, actions): primaries = self.cultivation.select(self.snapshot) admitted = [] for action in actions: reason = self._automatic_cultivation_reason(action, primaries=primaries) if reason: self.planner.notes.append("跳过自动操作:" + reason) else: admitted.append(action) return admitted def _skip_automatic_cultivation(self, reason): self.last_executed = False plans = self.plans() self.planner.notes.append("跳过自动操作:" + reason) return self.snapshot, plans, "跳过自动操作:" + reason def _execute_breakthrough(self, action): self.last_executed = False if self._breakthrough_pending: return self.snapshot, [], "突破请求待核对,禁止重发" reason = self._automatic_cultivation_reason(action) if reason: return self._skip_automatic_cultivation(reason) mon = self.snapshot.monsters[int(action.payload["monId"])] attribute = action.payload.get("monsterAttr", "") before = mon.get("p" + attribute.capitalize()) if action.kind == "potential" else mon.get("potentialLevel") item_ids = ([int(action.payload["traceInfo"]["itemTypeId"])] if action.kind == "potential" else [int(item_id) for item_id in action.payload["itemIds"]]) self._breakthrough_pending = {"kind": action.kind, "monster_id": int(mon["id"]), "type_id": str(mon.get("typeId")), "attribute": attribute, "before": before, "item_type_ids": item_ids, "path": action.path, "payload": deepcopy(action.payload), "uncertain": False, "role_id": str(self.snapshot.raw.get("master", {}).get("id") or ""), "message": action.description + ":请求进行中"} try: self._save_automation_state() # Must persist before any material request. except Exception: self._breakthrough_pending = None self.auto = False raise if not self.auto or self._progression_cancel.is_set(): self._discard_unsent_automation() return self.snapshot, self.plans(), "突破请求尚未发送,已取消" reason = self._automatic_cultivation_reason(action) if reason: # Only this newly journaled, unsent request may be discarded. An # older pending request returned above and must retain its evidence. self._discard_unsent_automation() return self._skip_automatic_cultivation(reason) try: self.last_executed = True response = self.client.call(action.path, deepcopy(action.payload)) if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"): raise ValueError("突破请求尚未确认成功") self._breakthrough_pending["message"] = action.description + ":请求已确认,等待新快照核对" self._save_automation_state() except Exception as error: self._breakthrough_pending.update(uncertain=True, message="突破请求结果未知,禁止自动重发:" + str(error)) self._save_automation_state() self.auto = False raise self._breakthrough_pending_last_check = time.monotonic() self._breakthrough_pending_confirmed = False self.read_snapshot(sync_master=False) return self.snapshot, self.plans(), action.description + ";已读取新快照核对" def cancel_progression(self): """Safe on Qt's thread while a worker is running; never waits or calls APIs.""" with self._progression_cancel_lock: self.auto = False self._progression_cancel_generation += 1 self._progression_cancel.set() def progression_rows(self): """A cached view only. Full-table planning always runs in an account worker.""" return deepcopy(self._progression_rows) def progression_records(self): return deepcopy(self._progression_records) def _progression_pending(self): return self.snapshot is not None and (self.battle_journal.pending(self.snapshot) or self.sweeper.state.get("pending") or self._planner_pending) def _require_no_battle(self): if self._progression_pending(): raise ValueError("有待核对的任务 / 战斗,已暂停冲突写操作;后台每2分钟自动核对") def _ensure_progression(self): if self.game_data is None: from .game_data import load_progression_data self.game_data = load_progression_data() if self.progression_planner is None: self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace) self.progression_planner.guard.cultivation = self.cultivation self.progression_planner.procurement_daily_left = self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money) if self.snapshot else 0 # This is a read-only preflight; the same check must precede navigation # and dialogue, not just the battle action they lead to. self.progression_planner.battle_capability = self._battle_capability if not self._progression_state_loaded and self.snapshot is not None: stored = deepcopy(self.battle_journal.role(self.snapshot).get("planner_state")) if stored: for account in stored.get("accounts", {}).values(): pending = account.get("pending") if pending: pending["token"] = pending.pop("intent_id", "") pending["intent"]["token"] = pending["intent"].pop("intent_id", "") self.progression_planner.restore_state(stored) self._progression_state_loaded = True # A separate view preserves the commission-only legacy catalog. if not self._battle_catalog_ready: battle_catalog = self._map_catalog() positions = dict(self.catalog.data.get("stage_task_positions", {})) for key, task in self.game_data.tasks.items(): positions[str(key)] = [step.get("position", "") for step in task.get("steps", [])] battle_catalog.data = battle_catalog.data | {"stage_info": self.game_data.stages | battle_catalog.data.get("stage_info", {}), "stage_sp": self.game_data.stage_sp | battle_catalog.data.get("stage_sp", {}), "stage_task_positions": positions, "game_setting": self.game_data.game_setting | battle_catalog.data.get("game_setting", {})} self.battles.catalog = battle_catalog self._battle_catalog_ready = True self._select_battle_runtime(self.progression_policy.battle_mode) def _select_battle_runtime(self, mode): if mode not in ("original", "experimental"): raise ValueError("未知战斗模式,未开始战斗") if self.battles.runtime is not None: self._battle_runtimes[self._selected_battle_mode] = self.battles.runtime self._selected_battle_mode = mode runtime = self._battle_runtimes.get(mode) if runtime is None: try: if mode == "experimental": from .battle_simulator import ExperimentalBattleRuntime as Runtime else: from .battle_runtime import BattleRuntime as Runtime except ImportError: pass else: runtime = self._battle_runtimes[mode] = Runtime() self.battles.runtime = runtime def _persist_progression(self, *, save=True): state = self.progression_planner.export_state() self._planner_pending = any(account.get("pending") for account in state.get("accounts", {}).values()) for account in state.get("accounts", {}).values(): account["applied"] = account["applied"][-1000:] account["received"] = {key: {field: task[field] for field in ("id", "typeId", "curStep", "stepValue") if field in task} for key, task in account["received"].items()} pending = account.get("pending") if pending: # These are planner-issued hashes, not authentication tokens. # Store them under an unambiguous local name on disk. pending["intent_id"] = pending.pop("token") pending["intent"]["intent_id"] = pending["intent"].pop("token") for task in account["tasks"].values(): cutoff = min(task.get("cursor", 0), task.get("server_step", 0)) for field in ("before", "after", "acknowledged"): task[field] = [number for number in task.get(field, []) if number >= cutoff] state = public_data(state) target = self.battle_journal.role(self.snapshot) if target.get("planner_state") != state: target["planner_state"] = state if save: self.battle_journal.save() def _battle_observer(self, event, intent, response): if event == "started" and self._is_commission(intent): record = self.battle_journal.pending(self.snapshot) if record is not None: self._journal_commission(record, intent) if value(intent, "kind") == "map_battle": stage = SimpleNamespace(stage_id=str(value(intent, "stage_id")), level=str(value(intent, "difficulty"))) key = self.sweeper.key(self.snapshot, stage) if event == "started": record = self.battle_journal.pending(self.snapshot) if record is not None: record["map_roster_signature"] = self._map_roster_signature(self.snapshot, value(intent, "team", self.sweep_policy.team)) self.sweeper.state["counts"][key] = self.sweeper.used(self.snapshot, stage) + 1 self.sweeper.save() elif event == "cancelled_before_start": self.sweeper.state["counts"][key] = max(0, self.sweeper.used(self.snapshot, stage) - 1) self.sweeper.save() elif event == "loss": record = self.battle_journal.pending(self.snapshot) or {} self.sweeper.state.setdefault("challenge_failures", {})[key] = record.get("map_roster_signature") or self._map_roster_signature(self.snapshot, value(intent, "team", self.sweep_policy.team)) self.sweeper.save() elif event in ("settled", "event"): self.sweeper.state.setdefault("challenge_failures", {}).pop(key, None) if value(intent, "stage_category") in ("mine", "ticket"): completed = self.battle_journal.pending(self.snapshot) or {} self.sweeper.remember_map_reward(self.snapshot, completed, response, event=event == "event") self.sweeper.save() return None farming = self._is_farm(intent) if value(intent, "kind") != "progression_battle" and not farming: return None planner = self.progression_planner if event == "cancelled_before_start": self._cancel_unsent_progression(intent) return None if farming: if event == "started": planner.mark_started(self.snapshot, intent) # validates the issued ordinary intent only elif event in ("settled", "event"): record = self.battle_journal.pending(self.snapshot) if record is not None: self.battle_journal.update(record, record["phase"], commission_action_response=gameplay_response(response), commission_action_confirmed=True) # Farming is a normal map action. Its journal and fresh server # snapshot govern the result; it never acknowledges a task step. return None if event == "validate": account = planner.export_state().get("accounts", {}).get(intent.account_key, {}) task = account.get("tasks", {}).get(f"{intent.task_id}:{intent.task_type_id}", {}) return task.get("cursor") == intent.step_number if event == "started": planner.mark_started(self.snapshot, intent) elif event in ("settled", "event"): if not planner.acknowledge(self.snapshot, intent, gameplay_response(response)): raise ValueError("任务战斗结算已返回,但任务步骤确认未完成") elif event == "loss": planner.battle_lost(self.snapshot, intent) self._persist_progression() def _cancel_unsent_progression(self, intent): """Rollback only the matching planner send marker, before dispatch.""" state = self.progression_planner.export_state() account = state.get("accounts", {}).get(value(intent, "account_key"), {}) pending = account.get("pending") if pending: if pending.get("token") != value(intent, "token") or pending.get("intent") != intent.to_dict(): raise ValueError("取消的未发送请求与任务检查点不匹配") account["pending"] = None self.progression_planner.restore_state(state) self._persist_progression(save=False) def _recover_confirmed_progression(self): """Replay only local acknowledgement of a durably received success.""" self._reconcile_procurement() record = self.battle_journal.pending(self.snapshot) if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id")) or not str(record.get("kind", "")).startswith("progression_")): return battle = record["kind"] == "progression_battle" confirmed = record.get("phase") == ("settlement_acknowledged" if battle else "acknowledged") confirmed = confirmed or record.get("settlement_confirmed" if battle else "response_confirmed") is True response = record.get("response") if not confirmed or not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"): return path = record.get("path") or "" if battle and path != "taskService/taskCompleteStep": return if not battle and path not in {"taskService/taskReceive", "taskService/taskLoopReceive", "taskService/taskLoopFlush", "taskService/taskCompleteStep", "taskService/taskComplete", "taskService/taskUpdate"}: return state = self.progression_planner.export_state() account = state.get("accounts", {}).get(record.get("account_key"), {}) intent_id = record.get("intent_id") applied = bool(intent_id and intent_id in account.get("applied", [])) if not applied: pending = self.progression_planner.pending(self.snapshot) if not pending or not isinstance(pending.get("intent"), dict): return intent = ProgressionIntent(**pending["intent"]) if (pending.get("token") != intent.token or intent.blocked or intent_id and intent.token != intent_id or record.get("account_key") and intent.account_key != record["account_key"]): return if any(str(value(intent, field)) != str(record.get(field)) for field in ("kind", "task_id", "task_type_id", "step_number")): return # The current restore_state API restores durable accounts but not # its transient issued-token registry. Rehydrate only this exact # saved pending intent after validating the successful receipt. # Cursor/story effects still belong exclusively to acknowledge. issued = self.progression_planner._issued if intent.token in issued and issued[intent.token] != intent.to_dict(): raise ValueError("持久化确认与已签发任务意图不匹配") issued[intent.token] = intent.to_dict() if not self.progression_planner.acknowledge(self.snapshot, intent, response): return self._persist_progression(save=False) self.battle_journal.finish(self.snapshot, record, "win" if battle else "task", "已从持久化成功回包恢复本地任务检查点;未重发请求") def pending_recovery_due(self): now = time.monotonic() automation = bool(self.snapshot and ( self.explore_planner.pending(self.snapshot) and now - self._explore_pending_last_check >= 120 or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120)) return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120) def pending_battle_recovery(self): """Read-only recovery contract for desktop/Web pending guards.""" record = self.battle_journal.pending(self.snapshot) if self.snapshot is not None else None status = self.battles.recovery_status(record, snapshot=self.snapshot) if status["resumable"]: if self.game_data is None and (record.get("source_task_type_id") or record.get("task_type_id")): from .game_data import load_progression_data self.game_data = load_progression_data() if not self._intent_policy(record).enabled: origin = ("自动扫荡" if record.get("kind") in ("map_battle", "map_sweep") else "自动委托" if self._is_commission(record) else "自动主线") return {"state": "blocked_policy", "resumable": False, "message": "等待启用" + origin + "来源策略;已保留待核对战斗"} return status def _resume_pending_task_clock(self, *, running=None, generation=None): record = self.battle_journal.pending(self.snapshot) if not self.pending_battle_recovery()["resumable"]: return "" with self._progression_cancel_lock: if (not (self.auto if running is None else running is True) or generation is not None and generation != self._progression_cancel_generation): return "" # Web deliberately keeps auto=False. Only its current running intent # may rearm an older cancellation; a newer Stop always wins. if running is True and self._progression_cancel.is_set(): self._progression_cancel = threading.Event() cancel = self._progression_cancel if cancel.is_set(): return "" if not record.get("task_id"): intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number", "stage_category", "stage_id", "difficulty", "battle_kind", "team", "path", "source_task_id", "source_task_type_id", "source_step_number")} policy = self._intent_policy(intent) if record.get("sweep_sample_id"): self._select_battle_runtime(record["battle_mode"]) return self.battles.continue_sweep(self.client, self.snapshot, policy, cancel=cancel) if self.pending_battle_recovery()["state"] == "retry_local_runtime": self._select_battle_runtime(record["battle_mode"]) return self.battles.resume_task_clock(self.client, self.snapshot, intent, policy, cancel=cancel) pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None if not pending or not isinstance(pending.get("intent"), dict): return "" intent = ProgressionIntent(**pending["intent"]) if (pending.get("token") != intent.token or intent.token != record.get("intent_id") or intent.account_key != record.get("account_key")): return "" issued = self.progression_planner._issued if intent.token in issued and issued[intent.token] != intent.to_dict(): return "" issued[intent.token] = intent.to_dict() if self.pending_battle_recovery()["state"] == "retry_local_runtime": self._select_battle_runtime(record["battle_mode"]) return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._intent_policy(intent), cancel=cancel) def _battle_capability(self, intent): try: from .battle_simulator import DEFAULT_DAMAGE_PROFILE, DESKTOP_DAMAGE_PROFILE if self._is_commission(intent) and not self.quest_policy.battle_tasks: return False, "战斗委托未启用;未开始战斗" if self.battles.runtime is None: return False, ("实验模型" if self.progression_policy.battle_mode == "experimental" else "原始战斗运行时") + "尚未提供,未开始战斗" policy = self._intent_policy(intent) preview = bool(value(intent, "task_type_id")) and not value(intent, "task_id") and not self._is_farm(intent) if not preview: reason = self.battles.resource_reason(self.snapshot, intent, policy, self.policy) if reason: return False, reason damage_profile = DESKTOP_DAMAGE_PROFILE if policy.battle_mode == "experimental" else DEFAULT_DAMAGE_PROFILE key = digest({"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime), "team": policy.team, "mode": policy.battle_mode, "damage_profile": damage_profile, **{name: value(intent, name) for name in ("task_type_id", "step_number", "stage_id", "difficulty", "battle_kind")}}) if key not in self._capability_cache: request = self.battles.request(self.snapshot, intent, policy) self._capability_cache[key] = self.battles.inspect(request) while len(self._capability_cache) > 64: self._capability_cache.pop(next(iter(self._capability_cache))) return self._capability_cache[key] except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error: return False, "战斗输入或运行时未就绪:" + str(error) def _overlay_battle_capabilities(self, rows, intents): battle_kinds = {"task", "battle", "passStage", "task_battle", "task_pass_stage", "ordinary_stage", "stage", "map_battle", "hidden"} reasons = {} adjusted = [] for intent in intents: if value(intent, "kind") == "progression_loop_accept": key = str(value(intent, "task_type_id")) if key not in self._commission_offer_checks: self._check_commission_offer(key) supported, reason = self._commission_offer_checks[key] if not supported: intent = replace(intent, block_reason=reason) # Local battle preludes share the planner's cached input preflight. prelude = value(intent, "task_id") and value(intent, "battle_kind") in battle_kinds and ( value(intent, "kind") == "progression_navigate" or value(intent, "kind") == "progression_dialogue" and value(intent, "phase") == "before") if (prelude or value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle") or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"): supported, reason = self._battle_capability(intent) reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason) if not supported: intent = replace(intent, block_reason=reason) if not isinstance(intent, dict) else intent | {"block_reason": reason} adjusted.append(intent) commissions = {str(value(intent, "task_type_id")): intent for intent in adjusted if self._is_commission(intent)} farms = {str(value(intent, "source_task_type_id")): intent for intent in adjusted if self._is_farm(intent)} for row in rows: source_supported = row.get("supported") is not False check = self._commission_offer_checks.get(str(row.get("task_type_id"))) if row.get("category") == "commission" and row.get("state") == "offered" and check is not None: if not check[0]: row.update(block_reason=check[1], next_action="暂不接取:" + check[1]) commission = commissions.get(str(row.get("task_type_id"))) if commission is not None: row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", "")) farm = farms.get(str(row.get("task_type_id"))) if farm is not None: row.update(next_action=value(farm, "description"), block_reason=value(farm, "block_reason", ""), battle_kind="sweep" if self._is_sweep_intent(farm) else "ordinary_stage", stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty")) reason = row.get("block_reason") or row.get("blocked_reason") or "" if row.get("battle_kind") in battle_kinds: supported, runtime_reason = reasons.get(str(row.get("task_type_id")), (None, "")) reason = reason or runtime_reason row["supported"] = False if not source_supported or reason else supported else: row["supported"] = bool(source_supported and not reason) row["block_reason"] = row["blocked_reason"] = reason row["reason_kind"] = "unchecked" if row["supported"] is None else commission_reason_kind(reason) if row["supported"] is None and row.get("category") == "mainline" and not self.progression_policy.enabled: row.setdefault("status", "自动主线策略未启用") return rows, adjusted def _battle_request(self, snapshot, intent, policy, request): from .battle_simulator import DEFAULT_DAMAGE_PROFILE, DESKTOP_DAMAGE_PROFILE self._ensure_progression() self._select_battle_runtime(policy.battle_mode) if self._battle_snapshot_source is not snapshot: self._battle_snapshot_source = snapshot self._battle_snapshot_digest = digest(snapshot.raw) if self._battle_roster_digest != self._battle_snapshot_digest: self._battle_roster = deepcopy(snapshot.raw) self._battle_roster_digest = self._battle_snapshot_digest task = bool(value(intent, "task_type_id")) and value(intent, "battle_kind") in ("task", "battle", "passStage", "task_battle", "task_pass_stage") kind = value(intent, "battle_kind") battle = self.game_data.task_battle(value(intent, "task_type_id"), value(intent, "step_number")) if task else \ self.game_data.stage_battle(value(intent, "stage_id"), value(intent, "difficulty", "1")) prepared = request | {"snapshot": self._battle_roster, "battle_mode": policy.battle_mode, "damage_profile": DESKTOP_DAMAGE_PROFILE if policy.battle_mode == "experimental" else DEFAULT_DAMAGE_PROFILE, "context": "task_pass_stage" if task and kind == "passStage" else "task_battle" if task else "ordinary_stage", "original_data": {"battle": battle, "manifest": self.game_data.manifest}, "roster": self._battle_roster, "task_id": value(intent, "task_id"), "step_index": int(value(intent, "step_number", 1) or 1) - 1 if task else None} if policy.battle_mode == "original": from .battle_runtime import BattleRuntime if isinstance(self.battles.runtime, BattleRuntime): source = self.game_data.manifest.get("source", {}) prepared["runtime_request"] = {name: prepared[name] for name in ( "context", "roster", "stage_id", "task_id", "step_index")} prepared["runtime_request"].update(difficulty=int(value(intent, "difficulty", 1) or 1), purpose="settlement", original_data={"source": "original_apk", "resource_identity": { "apk_sha256": source.get("apk_sha256"), "main_swf_sha256": source.get("main_swf_sha256")}}) return prepared def _is_commission(self, intent): if value(intent, "kind") in ("progression_loop_accept", "progression_loop_reset"): return True info = self.game_data.task(value(intent, "source_task_type_id") or value(intent, "task_type_id")) if self.game_data else None return bool(info and info.get("type") == 4) def _commission_info(self, type_id): info = self.game_data.task(type_id) if self.game_data and type_id else None return info or self.catalog.data.get("task_info", {}).get(str(type_id)) or {} def _sync_commission_history(self): """Use the already loaded, bounded journal; ledger failures never retry a game write.""" if self.snapshot is None or self.snapshot.raw.get("master", {}).get("id") is None: return role = str(self.snapshot.raw["master"]["id"]) try: records = self.battle_journal.role(self.snapshot)["records"] self._commission_history.ingest(role, records, self._commission_info, self.snapshot) self._commission_history_roles.add(role) except (OSError, ValueError, TypeError, KeyError, AttributeError): self._commission_history.warning = "委托历史暂未写入磁盘;任务回包仍保存在原日志,稍后核对导入,请勿重发" @account_serial def commission_history(self, day=None): """Independent plain DTO; day is YYYY-MM-DD in Beijing, default wall-clock today. summary: accepted_count/completed_count/pending_count/expected_ke/ confirmed_ke/unknown_reward_count. Unknown row rewards are None. Only events on the selected day contribute to daily counts and rewards. """ role = str(self.snapshot.raw.get("master", {}).get("id", "")) if self.snapshot else "" if role and (role not in self._commission_history_roles or self._commission_history._dirty): self._sync_commission_history() return self._commission_history.query(role, day) @account_serial def commission_offer_diagnostics(self): """Cached offline eligibility; no journal reload, game calls or runtime inspection.""" if self.snapshot is None: return [] self._ensure_commission_diagnostics() return deepcopy(self._commission_offer_diagnostics) def _ensure_commission_diagnostics(self): key = (id(self.snapshot), digest({"quest": vars(self.quest_policy), "ranch": vars(self.policy), "progression": vars(self.progression_policy), "checks": self._commission_offer_checks, "budget": self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money), "state": self.progression_planner.state_signature(self.snapshot) if self.progression_planner else ""})) if key == self._commission_diagnostics_key: return if self.progression_planner is None: self._ensure_progression() # Reuse model checks from the worker's last planning pass. A missing # check remains explicitly unverified until that worker runs. self._commission_offer_diagnostics = self.progression_planner.commission_offers( self.snapshot, self.quest_policy, self.policy, battle_policy=self.progression_policy, accept_supported=lambda key: self._commission_offer_checks.get(str(key), (False, "后续步骤或战斗能力尚未验证,等待后台检查"))) self._commission_diagnostics_key = key def _journal_commission(self, record, intent, *, legacy=False): type_id = str(value(intent, "source_task_type_id") or value(intent, "task_type_id") or "") info = self._commission_info(type_id) if info.get("type", 4 if legacy else None) != 4 and value(intent, "kind") not in ("progression_loop_reset", "quest_reset"): return selected = getattr(self.tasks if legacy else self.progression_planner, "commission_selection", {}) or {} accepting = (record.get("path") or "").endswith("taskLoopReceive") meta = {"name": info.get("name", type_id or "每日委托"), "expected_ke": -commission_priority(info), "city": (record.get("payload") or {}).get("city")} number = value(intent, "source_step_number") or value(intent, "step_number") or 0 steps = info.get("steps") or [] if 1 <= number <= len(steps): step = steps[number - 1] kind, required = step.get("statusType"), step.get("statusValue") or {} remove = required.get("remove") is True prefix = "提交" if remove else "核对持有" type_key, count = str(required.get("type", "")), required.get("num", 0) if kind == "getMoney": detail = f"{prefix}金币×{required.get('money', 0)}" elif kind == "getItem" or kind == "getMonster" and required.get("mode") == 0: name = self.catalog.monster(type_key).get("name", type_key) + "蛋" if type_key in self.catalog.monsters else self.catalog.data.get("item_names", {}).get(type_key, f"道具#{type_key}") detail = f"{prefix}{name}×{count}" elif kind == "getMonster": detail = f"{prefix}{self.catalog.monster(type_key).get('name', '魔物#' + type_key)}×{count}" elif kind == "passStage": stage = self.game_data.stage(required.get("stage")) if self.game_data else None detail = f"通关{(stage or {}).get('name', required.get('stage', '指定关卡'))},难度{required.get('level', 1)}" elif kind == "battle": detail = "完成委托专用战斗" elif kind == "none": detail = "完成对话条件" elif kind == "killMonster": detail = f"核对{self.catalog.monster(type_key).get('name', '魔物#' + type_key)}累计击杀数量" elif kind == "passLevel": detail = f"核对角色等级达到{required.get('level', 0)}级" else: detail = str(value(intent, "description", "")) meta["operation_detail"] = detail if accepting and selected.get("task_type_id") == type_id: meta.update(deepcopy(selected)) self.battle_journal.update(record, record["phase"], commission=meta) def _commission_message(self, record, default): self._sync_commission_history() role = str(self.snapshot.raw["master"].get("id", "")) event = self._commission_history.state["roles"].get(role, {}).get(str(record.get("attempt_id"))) return event["description"] if event else default @staticmethod def _is_farm(intent): return bool(value(intent, "source_task_type_id")) and not value(intent, "task_id") and bool(value(intent, "stage_id")) @staticmethod def _is_sweep_intent(intent): return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep" def _intent_policy(self, intent): if value(intent, "kind") == "map_sweep": return SimpleNamespace(**(vars(self._map_policy()) | {"enabled": self.sweep_policy.enabled})) if value(intent, "kind") == "map_battle": return self._map_policy() if not self._is_commission(intent): return self.progression_policy quest = self.quest_policy return replace(self.progression_policy, enabled=quest.enabled, mainline=False, sidequests=False, commissions=True, accept=quest.accept, auto_farm=True, allow_items=quest.allow_items, allow_monsters=quest.allow_monsters, max_money=quest.max_money, item_reserves=dict(quest.item_reserves)) def _check_commission_offer(self, type_id): supported = self._commission_offer_supported(type_id) self._commission_offer_checks[str(type_id)] = (supported, "" if supported else self._commission_offer_reason or "委托后续步骤当前无法自动完成") return supported def _commission_offer_eligibility(self, type_id): self._check_commission_offer(type_id) return self._commission_offer_checks[str(type_id)] def _commission_offer_supported(self, type_id): self._commission_offer_reason = "委托后续条件、剧情或战斗未验证支持,未消耗接取次数" info = self.game_data.task(type_id) if not info or info.get("type") != 4: self._commission_offer_reason = "委托配置缺失或类型不符" return False for number, step in enumerate(info.get("steps", []), 1): for name in (step.get("story"), step.get("afterStory")): if name and (self.game_data.script(name) or {}).get("supported") is not True: script = self.game_data.script(name) or {} self._commission_offer_reason = f"第{number}步剧情 {name} 未验证支持" + (":" + ";".join(script.get("block_reasons") or []) if script.get("block_reasons") else "") return False kind = step.get("statusType") if kind in ("battle", "passStage"): if not self.quest_policy.battle_tasks: self._commission_offer_reason = "委托战斗开关未启用" return False intent = {"kind": "progression_battle", "task_type_id": str(type_id), "task_id": 0, "step_number": number, "battle_kind": "passStage" if kind == "passStage" else "task", "stage_id": (step.get("statusValue") or {}).get("stage"), "difficulty": (step.get("statusValue") or {}).get("level", 1)} supported, reason = self._battle_capability(intent) if not supported: self._commission_offer_reason = reason return False else: policy = self._intent_policy({"task_type_id": str(type_id)}) ready, _, requirement_reason = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy) if not ready: if resource_kind(step) and isinstance(self.progression_planner, ProgressionPlanner): supply = self.progression_planner.resource_plan(self.snapshot, info.get("steps") or [], {"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy) if supply.feasible: continue self._commission_offer_reason = supply.reason return False sources = self.progression_planner.farming_intents(self.snapshot, step, {"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy) source_reasons = [] feasible = False for source in sources: supported, reason = (True, "") if self._is_sweep_intent(source) else self._battle_capability(source) if supported: feasible = True break if reason: source_reasons.append(reason) if not feasible: self._commission_offer_reason = f"第{number}步:{requirement_reason}" + (";材料来源:" + ";".join(source_reasons) if source_reasons else ";没有当前可用的自动收集来源") return False if not info.get("steps"): self._commission_offer_reason = "委托没有有效步骤" return bool(info.get("steps")) def _refresh_progression_cache(self, *, force=False): if self.snapshot is None: return if not (force or self.progression_view_active or self.progression_policy.enabled or self.quest_policy.enabled): return try: self._ensure_progression() self._recover_confirmed_progression() retry_reason = self.progression_planner.battle_retry_reason(self.snapshot, self.progression_policy) journal_retry_reason = self.battle_journal.loss_reason(self.snapshot, self.progression_policy) self._battle_snapshot_source = self.snapshot self._battle_snapshot_digest = digest(self.snapshot.raw) self.progression_planner.battle_capability_key = digest({ "snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)}) key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy), "quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot), "purchase_left": self.progression_planner.procurement_daily_left, "loss_retry": (retry_reason, journal_retry_reason), "pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)}) if force or key != self._progression_cache_key: self._commission_offer_checks = {} self._commission_diagnostics_key = None rows = self.progression_planner.rows(self.snapshot, self.progression_policy, self.policy, quest_policy=self.quest_policy) intents = self.progression_planner.plan(self.snapshot, self.progression_policy, self.policy) commission_plan = getattr(self.progression_planner, "commission_plan", None) self._commission_planner_available = callable(commission_plan) if self._commission_planner_available: intents += commission_plan(self.snapshot, self.quest_policy, self.policy, battle_policy=self.progression_policy, accept_supported=self._commission_offer_eligibility) self._commission_offer_diagnostics = deepcopy(self.progression_planner.commission_offer_rows) intents.sort(key=lambda intent: not self._is_commission(intent)) self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents) for row in self._progression_rows: if row.get("category") == "commission" and row.get("state") == "offered": offer = next((r for r in self._commission_offer_diagnostics if r["task_type_id"] == row["task_type_id"]), None) if offer: row.update(reason_kind=offer["reason_kind"], resources=offer["resources"], progress_plan=offer["progress_plan"], next_action=offer["next_step"], block_reason="" if offer["eligible"] else offer["reason"], blocked_reason="" if offer["eligible"] else offer["reason"], supported=offer["eligible"]) self._persist_progression() self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy), "quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot), "purchase_left": self.progression_planner.procurement_daily_left, "loss_retry": (retry_reason, journal_retry_reason), "pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)}) self._progression_error = "" except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error: self._progression_error = "任务规划暂不可用:" + str(error) self._progression_rows = [{"state": "unsupported", "supported": False, "blocked_reason": self._progression_error}] self._progression_intents = [] self._progression_records = self.battle_journal.records(self.snapshot) self._sync_commission_history() @account_serial def refresh_progression(self): if not self.demo: self.read_snapshot(sync_master=False) elif self.snapshot is None: self.snapshot = demo_snapshot(self.catalog) self._refresh_progression_cache(force=True) pending = self.battle_journal.pending(self.snapshot) message = self._progression_error or (pending.get("message") or "存在待核对的任务 / 战斗") if pending else self._progression_error or "已刷新任务与战斗记录" return self.snapshot, self.plans(), message @single_flight @account_serial def run_progression_once(self): self.last_executed = False if not self.demo: self.read_snapshot(sync_master=False) elif self.snapshot is None: self.snapshot = demo_snapshot(self.catalog) self._refresh_progression_cache() return self._run_progression_intent() def _run_progression_intent(self, intent=None): if not self.progression_policy.enabled and not self.quest_policy.enabled: return self.snapshot, self.plans(), "自动主线策略未启用" if self._progression_pending(): return self.snapshot, [], "有待核对的任务 / 战斗;未重复提交" if self._progression_cancel.is_set(): return self.snapshot, self.plans(), "任务推进已取消" intents = self._progression_intents if intent is None: intent = next((i for i in intents if not value(i, "block_reason")), None) if intent is None: reasons = [str(value(i, "block_reason")) for i in intents if value(i, "block_reason")] return self.snapshot, self.plans(), self._progression_error or (";".join(dict.fromkeys(reasons)) if reasons else "当前没有可执行的任务步骤") if self.demo: return self.snapshot, self.plans(), "演示只展示任务;不会伪造战斗、任务进度或奖励" if value(intent, "block_reason"): return self.snapshot, self.plans(), str(value(intent, "block_reason")) effective_policy = self._intent_policy(intent) if not effective_policy.enabled: return self.snapshot, self.plans(), "对应任务策略未启用" try: self.last_executed = True kind = value(intent, "kind") self._sync_commission_history() if kind in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle", "sweep") or self._is_farm(intent): previous_attempts = {record["attempt_id"] for record in self.battle_journal.role(self.snapshot)["records"]} message = self.battles.run(self.client, self.snapshot, intent, effective_policy, cancel=self._progression_cancel, ranch=self.policy) records = [record for record in self.battle_journal.role(self.snapshot)["records"] if record["attempt_id"] not in previous_attempts] if records: message = self._commission_message(records[-1], message) elif kind == "progression_procure": message = self._execute_procurement(intent) else: message = self._execute_task_intent(intent) if self.battle_journal.pending(self.snapshot) and kind == "progression_battle": record = self.battle_journal.pending(self.snapshot) reason = ("战果已保存;后台每2分钟核对,开启策略后自动续交" if self.battles.resumable_task_clock(record) else "战斗待核对;后台每2分钟查询服务器状态,禁止重复提交") self.progression_planner.mark_uncertain(self.snapshot, intent, reason) self._persist_progression() if not self._progression_cancel.is_set(): self.read_snapshot(sync_master=False) return self.snapshot, self.plans(), message except Exception: if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind") != "progression_procure" and value(intent, "kind", "").startswith("progression_"): self.progression_planner.mark_uncertain(self.snapshot, intent, "任务 / 战斗结果待核对,禁止重放") self._persist_progression() raise finally: self._sync_commission_history() self._refresh_progression_cache(force=True) def _execute_procurement(self, intent): """Journal resource writes separately; never advance a task cursor.""" if self._progression_cancel.is_set() or self._progression_pending(): return "补资源已取消或有待核对请求;未发送" planner = self.progression_planner planner.mark_started(self.snapshot, intent) # validates account and issued payload only key = str(value(intent, "source_task_type_id")) policy = self._intent_policy(intent) source_id = int(value(intent, "source_task_id", 0) or 0) info = self._commission_info(key) if source_id: source = next((t for t in self.snapshot.raw.get("currentTasks", []) if int(t.get("id", 0)) == source_id and str(t.get("typeId")) == key), None) if source is None: return "资源来源任务已变化,等待重新规划;未发送" else: offers = planner.commission_offers(self.snapshot, self.quest_policy, self.policy, battle_policy=self.progression_policy, accept_supported=self._commission_offer_eligibility) if not any(row["task_type_id"] == key and row.get("preparable") for row in offers): return "委托额度、城市或资源条件已变化,未采购、未消耗接取次数" source = {"id": 0, "typeId": key} planner.procurement_daily_left = self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money) supply = planner.remaining_resource_plan(self.snapshot, info, source, policy, self.policy) action = supply.action if not supply.feasible or action is None or action.path != value(intent, "path") or action.payload != value(intent, "payload"): return "资源缺口或保护状态已变化,等待重新规划;未发送" allowed = {"gachaService/gachaGetEggs": {"id", "num", "voucherNum", "traceInfo"}, "stackService/stackAddMonster": {"eggs"}, "stackService/stackTransferMonster": {"datas"}} if action.path not in allowed or set(action.payload) != allowed[action.path]: return "补资源请求未验证,未发送" def admission_signature(): return digest({"snapshot": self.snapshot.raw, "quest": vars(self.quest_policy), "ranch": vars(self.policy), "progression": vars(self.progression_policy), "task": self._commission_info(key), "day": planner._loop_day(self.snapshot, self.snapshot.now - 10)}) admitted = admission_signature() self._sync_commission_history() record = self.battle_journal.begin(self.snapshot, intent) self._journal_commission(record, intent) baseline = {str(i["typeId"]): 0 for i in self.snapshot.raw["items"]} for item in self.snapshot.raw["items"]: baseline[str(item["typeId"])] += max(0, int(item.get("num", 0))) self.battle_journal.update(record, "prepared", procurement_baseline=baseline) dispatched = False try: if self._progression_cancel.is_set() or admission_signature() != admitted: raise CancelledBeforeDispatch() if action.kind == "buy": self.purchase_budget.record(self.snapshot.now, supply.purchase_cost, self.policy.daily_buy_money) self.battle_journal.update(record, "request_pending") if admission_signature() != admitted: raise CancelledBeforeDispatch() dispatched = True response = self.battles._call(self.client, action.path, deepcopy(action.payload), cancel=self._progression_cancel) receipt = gameplay_response(response) if action.kind == "buy" and isinstance(response.get("eggs"), list): receipt["eggs"] = [{k: egg[k] for k in ("typeId", "num") if k in egg} for egg in response["eggs"] if isinstance(egg, dict)] self.battle_journal.update(record, "acknowledged", response=receipt, response_confirmed=True, message="补资源请求已返回,等待权威背包/孵化位核对;不重复发送") if action.kind == "buy": self.record_draw(response.get("eggs") or []) return record["message"] except CancelledBeforeDispatch: self.battle_journal.finish(self.snapshot, record, "cancelled", "补资源请求尚未发送,已取消") return record["message"] except Exception as error: if dispatched: self.battle_journal.update(record, "unknown", message="补资源请求结果未知,禁止重购或重复装填", error_type=type(error).__name__) else: self.battle_journal.finish(self.snapshot, record, "cancelled", "补资源准备未完成,未发送") raise finally: self._sync_commission_history() def _reconcile_procurement(self): if self.snapshot is None: return record = self.battle_journal.pending(self.snapshot) if not record or record.get("kind") != "progression_procure" or record.get("response_confirmed") is not True: return payload, response = record.get("payload") or {}, record.get("response") or {} if str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id")) or response.get("resCode", 0) not in (0, "0"): return path, confirmed = record.get("path"), False if path == "gachaService/gachaGetEggs": eggs, expected = response.get("eggs"), {} if isinstance(eggs, list): for egg in eggs: if isinstance(egg, dict) and str(egg.get("typeId")) in self.catalog.monsters and int(egg.get("num", 0)) > 0: key = str(egg["typeId"]) expected[key] = expected.get(key, 0) + int(egg["num"]) totals = {} for item in self.snapshot.raw["items"]: key = str(item.get("typeId")) totals[key] = totals.get(key, 0) + int(item.get("num", 0)) baseline = record.get("procurement_baseline") or {} confirmed = bool(expected) and sum(expected.values()) >= int(payload.get("num", 0)) and all( totals.get(k, 0) >= baseline.get(k, 0) + n for k, n in expected.items()) elif path == "stackService/stackAddMonster": confirmed = bool(payload.get("eggs")) and all(any(int(s["id"]) == int(egg["stackId"]) and int(s.get("monsterId") or 0) in self.snapshot.monsters for s in self.snapshot.raw["stacks"]) for egg in payload["eggs"]) elif path == "stackService/stackTransferMonster": confirmed = bool(payload.get("datas")) and all( (self.snapshot.monsters.get(int(mid)) or {}).get("process") == 3 and int((self.snapshot.monsters.get(int(mid)) or {}).get("roomId") or 0) == int(data["roomId"]) for data in payload["datas"] for mid in data["monsterId"]) if confirmed: self.battle_journal.finish(self.snapshot, record, "task", "已按服务器背包/孵化位确认补资源;任务步骤仍需独立核对提交") self._sync_commission_history() def _execute_task_intent(self, intent): path, kind = value(intent, "path", "") or "", value(intent, "kind") payload = deepcopy(value(intent, "payload", {}) or {}) allowed = {"taskService/taskReceive": {"taskTypeId"}, "taskService/taskLoopReceive": {"taskTypeId", "city"}, "taskService/taskCompleteStep": {"taskId", "taskTypeId", "removeIds"}, "taskService/taskComplete": {"taskId", "taskTypeId"}, "taskService/taskLoopFlush": set(), "taskService/taskUpdate": {"unlockTasks", "receiveTasks", "removeTasks"}} local = kind in ("progression_navigate", "progression_dialogue", "progression_local_step") and not path if not local and (path not in allowed or set(payload) != allowed[path]): return "任务请求字段或本地剧情类型未受支持,未执行" if path.endswith("taskUpdate") and (not all(isinstance(payload[k], list) for k in allowed[path]) or not any(payload.values())): return "任务补链必须提供计算后的三个数组;未发送查询或空补链" if self._progression_cancel.is_set(): return "任务推进已取消" self._sync_commission_history() record = self.battle_journal.begin(self.snapshot, intent) self._journal_commission(record, intent) if local: self.progression_planner.acknowledge(self.snapshot, intent) self._persist_progression(save=False) self.battle_journal.finish(self.snapshot, record, "local", "已保存普通剧情的本地检查点") return self._commission_message(record, "已推进普通剧情并保存本地检查点") try: self.progression_planner.mark_started(self.snapshot, intent) self._persist_progression(save=False) self.battle_journal.update(record, "request_pending") try: response = self.battles._call(self.client, path, payload, cancel=self._progression_cancel) except CancelledBeforeDispatch: self._cancel_unsent_progression(intent) self.battle_journal.finish(self.snapshot, record, "cancelled", "任务请求尚未发送,已取消") return self._commission_message(record, record["message"]) self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True) acknowledged = self.progression_planner.acknowledge(self.snapshot, intent, gameplay_response(response)) self._persist_progression(save=False) if acknowledged: self.battle_journal.finish(self.snapshot, record, "task", "服务器已确认任务请求,已保存本地检查点") else: self.battle_journal.update(record, "unknown", message="任务成功回包缺少有效状态,等待核对") return self._commission_message(record, value(intent, "description", "任务请求已确认") if acknowledged else "任务成功回包缺少有效状态,等待核对,禁止重发") except Exception as error: self.battle_journal.update(record, "unknown", message="任务请求结果未确认,禁止自动重试", error_type=type(error).__name__) raise finally: self._sync_commission_history() def _recover_sweep_entry(self): """Worker-only local migration, immediately after a successful read.""" pending = self.sweeper.state.get("pending") if not isinstance(pending, dict): return message = self.battles.archive_cancelled_sweep(self.snapshot) if message: self._sweep_recovery_message = message return if self.battles.handoff_sweep(self.snapshot): return phases = ("遭遇隐藏关卡,请在游戏内手动战斗", "遇到事件或响应缺少事件状态,请在游戏内处理", "开始请求待确认") if pending.get("phase") not in phases or pending.get("start_response"): return from .sweep_recovery import scan_trace, role_path_matches owner = str(self.snapshot.raw["master"]["id"]) path = getattr(getattr(self.client, "trace", None), "path", None) key = owner + ":" + digest(pending) if key not in self._sweep_recovery_cache: evidence = scan_trace(path, owner) recovered = (evidence["valid"] and (pending.get("role_id") is not None or role_path_matches(self.sweeper.path, getattr(self.client, "session", None), owner, path)) and self.sweeper.recover_hidden_start(self.snapshot, path, events=evidence["events"])) # Keep only bounded evidence after the one scan. Presentation and # subsequent snapshots never rescan the 16 MB rotated logs. evidence.pop("events", None) self._sweep_recovery_cache[key] = evidence if recovered: self.battles.handoff_sweep(self.snapshot) return else: # An unsuccessful legacy proof is not retried on every refresh. # A completed archive still repairs a crash before sweep.save. if not any(row.get("sweep_sample_id") == pending.get("sampleId") and (row.get("outcome") == "abandoned_missing_hidden_id" or row.get("phase") == "legacy_hidden_archived") and row.get("sweep_entry") == pending for row in self.battle_journal.role(self.snapshot)["records"]): return evidence = self._sweep_recovery_cache[key] if (pending.get("phase") != phases[0] or set(pending) != {"stage", "level", "phase", "sampleId"} or not all(isinstance(pending.get(field), str) and pending[field] for field in ("stage", "level", "sampleId")) or not evidence["valid"] or not evidence["owner_read"] or not evidence["no_consumption"] or self.snapshot.raw.get("masterCurrentEvent") or not role_path_matches(self.sweeper.path, getattr(self.client, "session", None), owner, path) or any(state.get("pending") and not any(row.get("attempt_id") == state["pending"] and row.get("phase") == "legacy_hidden_archived" and row.get("sweep_entry") == pending and row.get("sweep_sample_id") == pending["sampleId"] and str(row.get("role_id")) == owner for row in state.get("records", [])) for state in self.battle_journal.state["roles"].values())): return reservations = [str(key).split(":") for key, count in self.sweeper.state.get("counts", {}).items() if type(count) is int and count > 0 and str(key).split(":")[-2:] == [pending["stage"], pending["level"]]] if not reservations or any(len(parts) != 4 or parts[0] != owner for parts in reservations): return # Archive before releasing the guard. A crash between these two atomic # saves is repaired by the sample ID on the next trusted read. existing = next((row for row in self.battle_journal.role(self.snapshot)["records"] if row.get("sweep_sample_id") == pending["sampleId"] and row.get("outcome") == "abandoned_missing_hidden_id" and row.get("sweep_entry") == pending), None) message = "旧版未保存隐藏关卡编号,本次未完成已放弃;未结算奖励" if existing is None: record = self.battle_journal.pending(self.snapshot) or self.battle_journal.begin(self.snapshot, {"kind": "map_sweep", "stage_id": pending["stage"], "difficulty": pending["level"], "battle_kind": "sweep"}, sweep_entry=pending, sweep_phase="legacy_hidden_archived") self.battle_journal.update(record, "legacy_hidden_archived", sweep_sample_id=pending["sampleId"], sweep_entry=deepcopy(pending), archival_evidence={"role_id": owner, "snapshot_read_at": time.time(), "role_path_bound": True, "trace_files": evidence["files"], "no_later_consumption": True}) self.battle_journal.finish(self.snapshot, record, "abandoned_missing_hidden_id", message) self.sweeper.state["pending"] = None self.sweeper.save() self._sweep_recovery_message = message @account_serial def read_snapshot(self, *, sync_master=True): if self._progression_pending(): self.last_pending_check = time.monotonic() self.snapshot = self.client.snapshot() self._recover_sweep_entry() self._reconcile_procurement() pending = self.battle_journal.pending(self.snapshot) pending_id = pending.get("attempt_id") if pending else None if self.battle_journal.reconcile(self.snapshot, trusted=True) and pending_id: record = next((row for row in self.battle_journal.role(self.snapshot)["records"] if row["attempt_id"] == pending_id), None) if record and (record.get("path") or "").endswith("taskLoopReceive"): old = {str(task.get("id")) for task in record.get("baseline", {}).get("tasks", [])} task = next((task for task in self.snapshot.raw.get("currentTasks", []) if str(task.get("typeId")) == str(record.get("task_type_id")) and str(task.get("id")) not in old), None) if task: record["commission_task"] = {key: task[key] for key in ("id", "typeId", "curStep") if key in task} self._sync_commission_history() self.master_sync.apply(self.snapshot) if sync_master and not self._progression_pending(): self.master_sync.settle(self.client, self.snapshot) present = self.snapshot.monsters self.growth_cache = {mid: entry for mid, entry in self.growth_cache.items() if mid in present} self.growth_attempts = {key: stamp for key, stamp in self.growth_attempts.items() if key[0] in present} rows = [] fields = ("gAtk", "gDef", "gHp", "gDex") for mon in self.snapshot.raw["monsters"]: mid = int(mon["id"]) entry = self.growth_cache.get(mid) if entry: start = seconds(mon.get("timeStart")) if str(mon.get("typeId")) != entry["type"] or start > 0 and entry["start"] > 0 and start != entry["start"]: self.growth_cache.pop(mid, None) else: confirmed = int(mon.get("mode") or 0) >= entry.get("mode", 0) if entry.get("mode") == 2: confirmed = confirmed and all(q is not None for q in self.catalog.quality(mon)) for field in fields: if field in entry and mon.get(field) != entry[field]: confirmed = False if confirmed: self.growth_cache.pop(mid, None) else: mon = dict(mon) mon["mode"] = max(int(mon.get("mode") or 0), entry.get("mode", 0)) mon.update({field: entry[field] for field in fields if field in entry}) rows.append(mon) self.snapshot.raw["monsters"] = rows self.gift_planner.apply_confirmed(self.snapshot) self._reconcile_exploration() self._reconcile_breakthrough() self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None)) self._refresh_progression_cache() return self.snapshot def master_sync_due(self): return not self.demo and not self._progression_pending() and bool(self.master_sync.pending(self.snapshot)) @account_serial def sync_master(self): self.read_snapshot() return self.snapshot, self.plans(), "已同步等级 / 体力" @account_serial def refresh_stages(self): self.auto = False if not self.demo: self.read_snapshot() elif self.snapshot is None: self.snapshot = demo_snapshot(self.catalog) self.stage_cache.get(self.snapshot, refresh=True) return self.snapshot, self.plans(), "已刷新关卡并保存当前账号的地图缓存" def remember_growth(self, response): # MonsterCenter.checkGrowUpHandler treats these two arrays as the # authoritative stage and growth values, including after a stale read. if not isinstance(response, dict): return current = self.snapshot.monsters for key in ("datas", "stackMonsterInfos"): for row in response.get(key) or []: if not isinstance(row, dict) or row.get("monsterId") is None: continue mid = int(row["monsterId"]) mon = current.get(mid) if mon is None: continue entry = self.growth_cache.setdefault(mid, {"type": str(mon.get("typeId")), "start": seconds(mon.get("timeStart"))}) if key == "datas" and row.get("mode") in (0, 1, 2): entry["mode"] = max(entry.get("mode", 0), int(row["mode"])) else: entry.update({field: row[field] for field in ("gAtk", "gDef", "gHp", "gDex") if row.get(field) is not None}) def settle_pending_growth(self, force=False): if self._progression_pending(): return False pending = self.snapshot.growth_pending(self.catalog) now = time.monotonic() if not pending or not force and all(now - self.growth_attempts.get(key, -1e12) < 60 for key in pending): return False for key in pending: self.growth_attempts[key] = now response = self.client.settle_growth() self.remember_growth(response) self.read_snapshot() return True def growth_sync_due(self): if self.snapshot is None or self._progression_pending(): return False now = time.monotonic() return any(now - self.growth_attempts.get(key, -1e12) >= 60 for key in self.snapshot.growth_pending(self.catalog)) @account_serial def sync_growth(self): if self.demo: if self.snapshot is None: self.snapshot = demo_snapshot(self.catalog) for mon in self.snapshot.raw["monsters"]: if mon.get("process") == 2: mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog) else: self.read_snapshot() self.settle_pending_growth() pending = self.snapshot.growth_pending(self.catalog) message = "已自动同步孵化 / 成长状态" if pending: message += f";仍有 {len(pending)} 只等待服务器确认阶段或资质" return self.snapshot, self.plans(), message @account_serial def keep_alive(self): if self.demo: return "离线演示无需心跳" self.client.call("heartBeatService/keepAlive") self.last_heartbeat = time.monotonic() return "会话心跳已更新" @single_flight @account_serial def poll(self, *, hatch_only=False, defer_hatch=False, resume_pending=None): if resume_pending is not None and type(resume_pending) is not bool: raise ValueError("resume_pending must be a boolean or None") recovery_generation = self._progression_cancel_generation self.last_executed = False settled = False if self.demo: if self.snapshot is None: self.snapshot = demo_snapshot(self.catalog) for mon in self.snapshot.raw["monsters"]: if mon.get("process") == 2: mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog) else: self.read_snapshot(sync_master=not hatch_only) if not hatch_only: settled = self.settle_pending_growth() message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "") if self._sweep_recovery_message: message += ";" + self._sweep_recovery_message self._sweep_recovery_message = "" if self.sweeper.recovered_event: message += ";已解除旧版对已结算奖励事件的误阻塞" self.sweeper.recovered_event = False if self.snapshot.growth_pending(self.catalog): message += ";成长状态等待服务器确认,将自动检查" if self.demo: self._refresh_progression_cache() if self._progression_pending(): self.pending_hatches = [] pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle" recovered = self._resume_pending_task_clock(running=resume_pending, generation=recovery_generation) if not self.demo else "" if recovered: self.last_executed = True if not self.battle_journal.pending(self.snapshot): self.read_snapshot(sync_master=False) if pending_map: self.stage_cache.get(self.snapshot, refresh=True) return self.snapshot, self.plans(), recovered pending = self.battle_journal.pending(self.snapshot) or {} recovery = self.pending_battle_recovery() detail = recovery["message"] or pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作" return self.snapshot, [], message + ";" + detail explore_pending = self.explore_planner.pending(self.snapshot) if explore_pending or self._breakthrough_pending: self.pending_hatches = [] if explore_pending: message += ";" + explore_pending.get("message", "探险请求待核对") + ";后台每2分钟自动核对" if self._breakthrough_pending: message += ";" + self._breakthrough_pending.get("message", "突破请求待核对") + ";后台每2分钟自动核对" return self.snapshot, [], message try: plans = self.plans() except (ValueError, TypeError, KeyError, AttributeError) as error: self.auto = False return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error) actions = self.pending_hatches if hatch_only else plans action = actions[0] if actions else None if action and defer_hatch and action.kind == "hatch": action = None if self.auto and action and action.kind.startswith("explore_"): if action.kind == "explore_blocked" or not action.path: blocked = next((candidate for candidate in plans if candidate.path and not candidate.kind.startswith("explore_")), None) if blocked is None: return self.snapshot, plans, action.description self.planner.notes.append(action.description) action = blocked else: self.last_executed = True return self._execute_explore(action) if self.auto and action and action.kind in ("potential", "breakthrough"): self.last_executed = True return self._execute_breakthrough(action) if self.auto and action is not None: reason = self._automatic_cultivation_reason(action) if reason: return self._skip_automatic_cultivation(reason) self.last_executed = True if action.kind == "progression": return self._run_progression_intent(action.payload["intent"]) if action.kind == "daily": entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action) self.claim_daily_entry(entry) return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + action.description if action.kind == "sweep": stage = self.sweeper.next(self.snapshot, self.sweep_policy) if self.demo: return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗" origin = {"kind": "map_sweep", "stage_id": stage.stage_id, "difficulty": stage.level, "battle_kind": "sweep", "battle_mode": "experimental"} try: result = self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy, cancel=self._progression_cancel, origin=origin) except CancelledBeforeDispatch: return self.snapshot, [], "扫荡已停止,未确认的入场已保留" if self.sweeper.last_outcome == "hidden": self.battles.handoff_sweep(self.snapshot) self._select_battle_runtime("experimental") message = self.battles.continue_sweep(self.client, self.snapshot, self._intent_policy(origin), cancel=self._progression_cancel) if not self._progression_cancel.is_set(): self.read_snapshot(sync_master=False) return self.snapshot, self.plans(), "扫荡遭遇隐藏关卡;" + (message or "隐藏入场已保存,等待来源策略开启后继续") self.read_snapshot() label = "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡完成" message = f"{label}:{stage.number} {stage.name} / 难度{stage.level};" + reward_text(self.sweeper.last_reward) if self.sweeper.statistics_error: message += ";" + self.sweeper.statistics_error return self.snapshot, self.plans(), message if action.kind == "map_challenge": return self._run_map_challenge(action.payload["intent"]) if action.kind == "buy": price = int(self.catalog.data["markets"][action.payload["id"]]["money"]) self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money) if self.demo: self.apply_demo(action) else: response = self._execute_legacy_task(action) if action.kind.startswith("quest_") else self.client.call(action.path, action.payload) if action.kind == "buy": self.record_draw(response.get("eggs") or []) if action.kind == "gift": try: self.gift_planner.remember_success(self.snapshot, action, response) except ValueError: self.auto = False raise self.read_snapshot(sync_master=not hatch_only) if action.kind == "hatch": stack_id = action.payload["eggs"][0]["stackId"] slot = next((slot for slot in self.snapshot.raw["stacks"] if int(slot["id"]) == stack_id), None) if slot is None or int(slot.get("monsterId") or 0) <= 0: self.auto = False raise ValueError("装填已返回,但坑位状态尚未同步;已停止,请刷新核对后再继续") if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]): self.auto = False raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续") message = ("[演示] " if self.demo else "") + action.description if action.kind == "buy" and self.last_draw: message += ";" + self.last_draw try: plans = self.plans() except (ValueError, TypeError, KeyError, AttributeError) as error: self.auto = False plans = [] message += ";状态已读取,策略暂不可用:" + str(error) if not plans and self.planner.notes: message += ";" + ";".join(dict.fromkeys(self.planner.notes)) return self.snapshot, plans, message @single_flight @account_serial def poll_automation(self, kind): """Execute one fast-scheduler kind without dispatching other strategies.""" if kind not in {"explore", "breakthrough", "gift", "hatch"}: raise ValueError("快速自动操作类型无效") self.last_executed = False if self.demo: if self.snapshot is None: self.snapshot = demo_snapshot(self.catalog) else: self.read_snapshot(sync_master=False) if self._progression_pending(): pending = self.battle_journal.pending(self.snapshot) or {} return self.snapshot, [], pending.get("message") or "有待核对的任务 / 战斗,快速操作未执行" explore_pending = self.explore_planner.pending(self.snapshot) if explore_pending or self._breakthrough_pending: message = (explore_pending or self._breakthrough_pending).get("message", "自动操作待核对") return self.snapshot, [], message plans = self.plans() allowed = {"explore": {"explore_start", "explore_finish"}, "breakthrough": {"potential", "breakthrough"}, "gift": {"gift"}, "hatch": {"hatch"}}[kind] candidates = self.pending_hatches if kind == "hatch" else plans action = next((action for action in candidates if action.kind in allowed and action.path), None) if not self.auto or self._progression_cancel.is_set(): return self.snapshot, plans, "策略已停止,快速操作未执行" if action is None: message = {"explore": "探险", "breakthrough": "突破", "gift": "赠礼", "hatch": "孵化"}[kind] + "当前无可执行动作" if self.planner.notes: message += ";" + ";".join(dict.fromkeys(self.planner.notes)) return self.snapshot, plans, message reason = self._automatic_cultivation_reason(action) if reason: return self._skip_automatic_cultivation(reason) self.last_executed = True if kind == "explore": return self._execute_explore(action) if kind == "breakthrough": return self._execute_breakthrough(action) if self.demo: self.apply_demo(action) else: response = self.client.call(action.path, action.payload) if kind == "gift": try: self.gift_planner.remember_success(self.snapshot, action, response) except ValueError: self.auto = False raise self.read_snapshot(sync_master=False) if kind == "hatch": stack_id = action.payload["eggs"][0]["stackId"] slot = next((slot for slot in self.snapshot.raw["stacks"] if int(slot["id"]) == stack_id), None) if slot is None or int(slot.get("monsterId") or 0) <= 0: self.auto = False raise ValueError("装填已返回,但坑位状态尚未同步;已停止,请刷新核对后再继续") return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + action.description def _execute_legacy_task(self, action): """Keep the commission scheduler, with the same durable replay barrier.""" payload = action.payload task = next((task for task in self.snapshot.raw.get("currentTasks", []) if str(task.get("id")) == str(payload.get("taskId"))), {}) intent = {"kind": action.kind, "description": action.description, "path": action.path, "payload": payload, "task_id": payload.get("taskId"), "task_type_id": payload.get("taskTypeId"), "step_number": task.get("curStep")} self._sync_commission_history() record = self.battle_journal.begin(self.snapshot, intent) self._journal_commission(record, intent, legacy=True) try: self.battle_journal.update(record, "request_pending") response = self.battles._call(self.client, action.path, payload) self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True) action.description = self._commission_message(record, action.description) return response except Exception as error: self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__) raise finally: self._sync_commission_history() def _map_policy(self): return SimpleNamespace(enabled=self.sweep_policy.enabled and (self.sweep_policy.allow_challenge or self.sweep_policy.allow_special), team=self.sweep_policy.team, reserve_ti=self.sweep_policy.keep_stamina, keep_stamina=self.sweep_policy.keep_stamina, allow_challenge=self.sweep_policy.allow_challenge, rules=self.sweep_policy.rules, allow_special=self.sweep_policy.allow_special, keep_tickets=self.sweep_policy.keep_tickets, max_money=max(0, int(self.snapshot.raw["master"].get("money") or 0)) if self.snapshot else 0, allow_items=True, item_reserves=dict(self.quest_policy.item_reserves), stop_after_loss=0, battle_mode="experimental") def _map_roster_signature(self, snapshot, team): from .battle_simulator import DESKTOP_DAMAGE_PROFILE selected = next((row for row in snapshot.raw.get("teams", []) if row.get("teamName") == team and row.get("teamType") == "battleTeam"), {}) ids = {int(mid) for mid in selected.get("monsters", []) if mid and int(mid) > 0} transient = {"exp", "timeStart", "nicName", "roomId"} return digest({"team": selected, "damage_profile": DESKTOP_DAMAGE_PROFILE, "master": {key: val for key, val in snapshot.raw["master"].items() if key == "level" or key.startswith("global")}, "monsters": sorted([{key: val for key, val in mon.items() if key not in transient} for mon in snapshot.raw.get("monsters", []) if int(mon["id"]) in ids], key=lambda mon: int(mon["id"])), "attributes": sorted([row for row in snapshot.raw.get("monsterAttributes", []) or [] if int(row.get("monsterId") or 0) in ids], key=lambda row: int(row["monsterId"]))}) def map_stage_reason(self, snapshot, stage, policy, *, team_ids=None): """Lightweight page status; runtime inspection belongs to the account worker.""" if self._progression_pending(): return "有待核对的任务 / 战斗,后台会自动检查" reason = self.sweeper.reason(snapshot, stage, policy, team_ids=team_ids, challenge=not stage.sweep) if reason: return battle_message(reason) rule = policy.rules.get(stage.stage_id) or {} if rule.get("enabled") and self.sweeper.used(snapshot, stage) >= max(0, int(rule.get("limit") or 0)): return "已达本日次数上限" if stage.sweep: return "" if stage.category in ("mine", "ticket"): failed = self.sweeper.state.get("challenge_failures", {}).get(self.sweeper.key(snapshot, stage)) if failed and failed == self._map_roster_signature(snapshot, policy.team): return "打不过;调整战队或提升魔物属性后自动重试" if self._map_reason_snapshot is snapshot and self._map_reason_team == policy.team: return self._map_challenge_reasons.get((stage.stage_id, stage.level), "") return "" if not policy.allow_challenge: return "未开启未满星时自动挑战" failed = self.sweeper.state.get("challenge_failures", {}).get(self.sweeper.key(snapshot, stage)) if failed and failed == self._map_roster_signature(snapshot, policy.team): return "打不过;调整战队或提升魔物属性后自动重试" if self._map_reason_snapshot is snapshot and self._map_reason_team == policy.team: return self._map_challenge_reasons.get((stage.stage_id, stage.level), "") return "" def _next_map_action(self): if not self.sweep_policy.enabled or self.demo: return None self._map_challenge_reasons = {} self._map_reason_snapshot, self._map_reason_team = self.snapshot, self.sweep_policy.team for stage in sorted(stages(self._map_catalog(), self.snapshot), key=lambda row: (row.city, row.number, row.stage_id, row.level)): rule = self.sweep_policy.rules.get(stage.stage_id) or {} if not rule.get("enabled") or str(rule.get("level", "3")) != stage.level: continue if self.map_stage_reason(self.snapshot, stage, self.sweep_policy): continue if stage.sweep: return Action("sweep", f"扫荡 {stage.number} {stage.name} / 难度{stage.level}", "", {}) self._ensure_progression() if self.progression_planner.pending(self.snapshot): self._planner_pending = True return None self._select_battle_runtime("experimental") self._battle_snapshot_digest = digest(self.snapshot.raw) intent = {"kind": "map_battle", "description": f"挑战 {stage.number} {stage.name} / 难度{stage.level}", "path": "stageService/stageStart", "task_id": 0, "task_type_id": "", "step_number": 0, "stage_id": stage.stage_id, "difficulty": int(stage.level), "battle_kind": "ordinary_stage", "position": f"city{stage.city}_wild_stage{stage.stage_id}_level{stage.level}", "team": self.sweep_policy.team, "battle_mode": "experimental"} if stage.category in ("mine", "ticket"): intent.update(description=f"资源关卡 {stage.number} {stage.name}", battle_kind="resource_stage", stage_category=stage.category) supported, reason = self._battle_capability(intent) self._map_challenge_reasons[(stage.stage_id, stage.level)] = battle_message(reason) if supported: return Action("map_challenge", intent["description"], "", {"intent": intent}) return None def _run_map_challenge(self, intent): stage = next((row for row in stages(self._map_catalog(), self.snapshot) if row.stage_id == str(value(intent, "stage_id")) and row.level == str(value(intent, "difficulty"))), None) resource = stage is not None and stage.category in ("mine", "ticket") if stage is None or not self.sweep_policy.enabled or not (self.sweep_policy.allow_special if resource else self.sweep_policy.allow_challenge): return self.snapshot, self.plans(), "自动挑战已关闭或关卡状态已改变" if resource: if str(value(intent, "stage_category")) != stage.category or str(value(intent, "battle_kind")) != "resource_stage": return self.snapshot, self.plans(), "资源关卡类型或入口已改变,禁止入场" reason = self.map_stage_reason(self.snapshot, stage, self.sweep_policy) if reason: return self.snapshot, self.plans(), reason self._ensure_progression() self._select_battle_runtime("experimental") message = self.battles.run(self.client, self.snapshot, intent, self._map_policy(), cancel=self._progression_cancel, ranch=self.policy) if not self._progression_cancel.is_set(): self.read_snapshot(sync_master=False) if not self._progression_pending(): self.stage_cache.get(self.snapshot, refresh=True) return self.snapshot, self.plans(), battle_message(message) def plans(self): if self.snapshot is None or self._progression_pending(): self.pending_hatches = [] return [] primaries = self.cultivation.select(self.snapshot) # One owner for commission writes; never accept the same offer through # both the legacy planner and the full progression planner. quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy) preparing = [] for intent in self._progression_intents: key = str(value(intent, "source_task_type_id") or value(intent, "task_type_id") or "") if self._is_commission(intent) and key and not value(intent, "source_task_id") and not value(intent, "task_id"): info = self._commission_info(key) if any(r.get("task_type_id") == key and r.get("preparable") for r in self._commission_offer_diagnostics): preparing.append({"typeId": key, "curStep": 1, "info": info}) types, eggs = self.tasks.reservations(self.snapshot, extra_tasks=preparing) reserved = dict(self.policy.reserved_eggs) for key, count in eggs.items(): reserved[key] = max(reserved.get(key, 0), count) # The task supply planner owns these eggs, including when it is waiting # for one already growing. Generic hatch/refill must not overproduce. for type_id in types: key = str(type_id) reserved[key] = max(reserved.get(key, 0), sum(int(i.get("num", 0)) for i in self.snapshot.raw["items"] if str(i.get("typeId")) == key)) policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved) self.hatch_planner.notes = [] self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy) left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money) daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else [] map_action = self._next_map_action() sweep_actions = [map_action] if map_action else [] gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy) ranch = self.planner.plan(self.snapshot, replace(policy, buy=False) if types or eggs else policy, left) explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy) breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)})) self.breakthrough_planner.notes = [] breakthrough = self.breakthrough_planner.plan(self.snapshot, breakthrough_policy, targets=policy.breakthrough_targets, enabled=not self._breakthrough_pending) if policy.breakthrough_targets else None self.planner.notes.extend(self.gift_planner.notes) self.planner.notes.extend(self.breakthrough_planner.notes) feed_targets = policy.feed_targets or ({str(policy.feed_target): 1} if policy.feed_target else {}) for enabled, targets in ( (policy.enabled and policy.feed, feed_targets), (policy.gift_enabled and not policy.gift_auto_representative, policy.gift_targets), (policy.enabled, policy.breakthrough_targets)): if enabled: for mid in targets: reason = self.cultivation_target_reason(mid, primaries=primaries) if reason: self.planner.notes.append("跳过自动目标:" + reason) breakthroughs = [breakthrough] if breakthrough else [] progression = [Action("progression", value(intent, "description", "推进任务"), "", {"intent": intent}) for intent in self._progression_intents if not value(intent, "block_reason") and self._intent_policy(intent).enabled] commission = [action for action in progression if self._is_commission(action.payload["intent"])] progression = [action for action in progression if not self._is_commission(action.payload["intent"])] if quests and quests[0].kind == "quest_reset": return self._admit_automatic_cultivation(quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions) return self._admit_automatic_cultivation(commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions) @account_serial def claim_daily_entry(self, entry): self._require_no_battle() self.daily_ledger.record(self.snapshot, entry.key) if not self.demo: self.client.call(entry.action.path, entry.action.payload) self.read_snapshot() @account_serial def claim_daily(self): self.auto = False if not self.demo: self.read_snapshot() self._require_no_battle() # Fresh status after every claim, bounded by the initially available IDs. keys = [row.key for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] done = 0 for key in keys: row = next((r for r in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if r.key == key), None) if row: self.claim_daily_entry(row) done += 1 return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + f"已处理 {done} 项勾选奖励;自动执行已暂停" def record_draw(self, eggs): totals = {} for egg in eggs: if isinstance(egg, dict) and egg.get("typeId") is not None: key = str(egg["typeId"]) totals[key] = totals.get(key, 0) + int(egg.get("num") or 0) parts = [f"{self.catalog.monster(key).get('name', key)} ×{count}" for key, count in totals.items()] self.last_draw = f"抽蛋完成,共 {sum(totals.values())} 枚:" + "、".join(parts[:8]) + ("…" if len(parts) > 8 else "") @account_serial def set_monster_lock(self, monster_ids, locked): self.auto = False ids = list(dict.fromkeys(int(mid) for mid in monster_ids)) if not ids or any(mid <= 0 for mid in ids): raise ValueError("请先选择需要锁定 / 解锁的魔物") if not self.demo: self.read_snapshot() self._require_no_battle() monsters = self.snapshot.monsters if any(mid not in monsters for mid in ids): raise ValueError("选中的魔物已不存在,请刷新后重新选择") if not locked and any(monsters[mid].get("sysLock") for mid in ids): raise ValueError("选中包含系统锁定魔物,普通解锁不能解除系统锁,请重新选择") changed = 0 for mid in ids: if bool(monsters[mid].get("lock")) == bool(locked): continue if self.demo: monsters[mid]["lock"] = int(locked) else: self.client.call("monsterService/monsterLock", {"monsterId": mid, "lock": int(locked)}) self.read_snapshot() if bool(self.snapshot.monsters.get(mid, {}).get("lock")) != bool(locked): raise ValueError("服务器返回的锁定状态未更新,已停止后续操作") changed += 1 message = ("[演示] " if self.demo else "") + f"已{'锁定' if locked else '解锁'} {changed} 只魔物;自动执行已暂停" return self.snapshot, self.plans(), message @account_serial def manage_monsters(self, kind, monster_ids, target_id=0): self.auto = False if not self.demo: self.read_snapshot() self._require_no_battle() actions = manual_monster_actions(self.catalog, self.snapshot, kind, monster_ids, target_id) for action in actions: if self.demo: field = "foods" if kind == "feed" else "monsterId" if "monsterId" in action.payload else "monsterIds" for mid in action.payload[field]: self.apply_demo(replace(action, payload=action.payload | {field: [mid]})) else: self.client.call(action.path, action.payload) self.read_snapshot() consumed = action.payload.get("foods") or action.payload.get("monsterId") or action.payload.get("monsterIds") or [] if any(int(mid) in self.snapshot.monsters for mid in consumed): raise ValueError("操作已返回,但魔物记录尚未更新;请刷新核对,不会重复提交") return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + ";".join(a.description for a in actions) + ";自动执行已暂停" @account_serial def expand(self, quote): self.auto = False if not self.demo: self.read_snapshot() self._require_no_battle() fresh = expansion_quote(self.catalog, self.snapshot, quote.kind, quote.currency, quote.position) if fresh != quote: raise ValueError("扩建费用或次数已变化,请刷新后重新确认") old_rooms = {int(r["id"]) for r in self.snapshot.raw["rooms"]} if self.demo: raw = self.snapshot.raw raw["master"][quote.currency] -= quote.cost counter = ("numAdd" if quote.currency == "money" else "numKeAdd") + ("Stack" if quote.kind == "stack" else "Room") raw["history"][counter] += 1 if quote.kind == "stack": raw["stacks"].append({"id": max([int(s["id"]) for s in raw["stacks"]] + [0]) + 1, "position": quote.position, "monsterId": -1, "openType": quote.payload["openType"]}) else: type_id = 1000 if "1000" in self.catalog.data["room_info"] else int(raw["rooms"][0]["typeId"]) raw["rooms"].append({"id": max(old_rooms or {0}) + 1, "typeId": type_id, "openType": 1 if quote.currency == "money" else 2}) else: self.client.call(quote.path, quote.payload) self.read_snapshot() verified = (any(int(s.get("position", -1)) == quote.position for s in self.snapshot.raw["stacks"]) if quote.kind == "stack" else bool({int(r["id"]) for r in self.snapshot.raw["rooms"]} - old_rooms)) if not verified: raise ValueError("扩建请求已返回,但尚未读取到新增记录;请刷新核对,不会自动重复提交") return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + quote.description + ",已完成" def apply_demo(self, action): if action.kind == "collect" and sum(len(d["monsterId"]) for d in action.payload["datas"]) > 1: for data in action.payload["datas"]: for mid in data["monsterId"]: self.apply_demo(replace(action, payload={"datas": [{"monsterId": [mid], "roomId": data["roomId"]}]})) return if action.kind == "feed" and len(action.payload["foods"]) > 1: for mid in action.payload["foods"]: self.apply_demo(replace(action, payload=action.payload | {"foods": [mid]})) return raw = self.snapshot.raw if action.kind.startswith("quest_"): self.apply_demo_quest(action) return if action.kind == "buy": market = self.catalog.data["markets"][action.payload["id"]] count = action.payload["num"] gift_every = int(market.get("freegift") or 0) received = count + (count // gift_every if gift_every > 0 else 0) # Deterministic offline example, not a prediction of the server draw. type_id = int(next(iter(market["eggs"].values()))[0]) item = next((i for i in raw["items"] if int(i["typeId"]) == type_id), None) if item: item["num"] += received else: raw["items"].append({"id": max([int(i["id"]) for i in raw["items"]] + [500]) + 1, "typeId": type_id, "num": received}) raw["master"]["money"] -= int(market["money"]) * count self.record_draw([{"typeId": type_id, "num": received}]) return if action.kind == "collect": data = action.payload["datas"][0] mid = data["monsterId"][0] self.snapshot.monsters[mid].update(process=3, roomId=data["roomId"]) elif action.kind in ("sell", "feed"): mid = (action.payload.get("monsterId") or action.payload.get("monsterIds") or action.payload.get("foods"))[0] mon = self.snapshot.monsters[mid] if action.kind == "sell": raw["master"]["money"] += self.catalog.monster(mon["typeId"])["sell_money"] else: target = self.snapshot.monsters[action.payload["targetId"]] target["exp"] = target.get("exp", 0) + self.catalog.feed_exp(mon) raw["monsters"] = [m for m in raw["monsters"] if m["id"] != mid] elif action.kind == "gift": target = self.snapshot.monsters[action.payload["monsterId"]] item = next(i for i in raw["items"] if int(i["id"]) == action.payload["itemId"]) gain = int(self.catalog.monster(target.get("typeId")).get("like", {}).get(str(item["typeId"]), 0)) target["feel"] = max(0, min(self.catalog.max_feel(target), int(target.get("feel") or 0) + gain)) target["giftTime"] = int(time.time()) item["num"] -= 1 return else: egg = action.payload["eggs"][0] item = next(i for i in raw["items"] if i["id"] == egg["itemId"]) item["num"] -= 1 mid = max([m["id"] for m in raw["monsters"]] + [100]) + 1 row = self.catalog.monster(item["typeId"]) mon = {"id": mid, "typeId": item["typeId"], "process": 2, "mode": 0, "level": 1, "exp": 0, "timeStart": int(time.time() * 1000), "roomId": 0} mon.update({"g" + s.capitalize(): row[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")}) raw["monsters"].append(mon) next(s for s in raw["stacks"] if s["id"] == egg["stackId"])["monsterId"] = mid return for slot in raw["stacks"]: if slot.get("monsterId") == mid: slot["monsterId"] = 0 def apply_demo_quest(self, action): raw = self.snapshot.raw history = raw.setdefault("history", {}) tasks = raw.setdefault("currentTasks", []) if action.kind == "quest_reset": history["loopTaskTime"] = int(time.time()) history["loopTaskNum"] = self.catalog.data["game_setting"].get("loopTaskMaxNum", 6) elif action.kind == "quest_accept": type_id = action.payload["taskTypeId"] tasks.append({"id": max([t["id"] for t in tasks] + [1000]) + 1, "typeId": type_id, "curStep": 1, "stepValue": 0}) history["loopTaskNum"] -= 1 offers = history["loopTask"][str(action.payload["city"])] offers[:] = [t for t in offers if str(t) != type_id] else: task = next(t for t in tasks if int(t["id"]) == action.payload["taskId"]) info = self.catalog.data["task_info"][str(task["typeId"])] if action.kind == "quest_complete": raw["master"]["money"] += int(info.get("reward", {}).get("money", 0)) raw["master"]["ke"] = raw["master"].get("ke", 0) + int(info.get("reward", {}).get("ke", 0)) tasks.remove(task) else: step = info["steps"][task["curStep"] - 1] value = step.get("statusValue") or {} if value.get("remove"): ids = action.payload.get("removeIds") or [] if step["statusType"] == "getMoney": raw["master"]["money"] -= int(value["money"]) elif step["statusType"] == "getItem" or int(value.get("mode", 2)) == 0: left = int(value["num"]) for item in raw["items"]: if int(item["id"]) in ids: used = min(left, int(item["num"])) item["num"] -= used left -= used else: raw["monsters"] = [m for m in raw["monsters"] if int(m["id"]) not in ids] for slot in raw["stacks"]: if slot.get("monsterId") in ids: slot["monsterId"] = 0 task["curStep"] += 1 def demo_snapshot(catalog): types = [int(k) for k, row in catalog.monsters.items() if row.get("star") == 1 and not row.get("npc")][:4] monsters = [] for i, type_id in enumerate(types): row = catalog.monster(type_id) mon = {"id": 101 + i, "typeId": type_id, "level": 1, "exp": 0, "process": 2, "mode": 2 if i < 2 else 0, "timeStart": int((time.time() - catalog.total_time(type_id) + (0 if i < 2 else 200)) * 1000), "roomId": 0, "lock": 0} mon.update({"g" + s.capitalize(): row[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")}) monsters.append(mon) target = dict(monsters[0]) | {"id": 900, "process": 3, "mode": 2, "level": 20, "potentialLevel": 7, "roomId": 1, "lock": 1} room_type = next(k for k, row in catalog.data["room_info"].items() if row.get("maxNum", 0) >= 10) return Snapshot({"master": {"id": 1, "roleName": "离线演示", "level": 62, "exp": 456789, "money": 12345, "ke": 2000, "ti": 100}, "stacks": [{"id": i + 1, "position": i, "monsterId": 101 + i if i < 4 else 0, "openType": 3} for i in range(6)], "monsters": monsters + [target], "items": [{"id": 501 + i, "typeId": t, "num": 8} for i, t in enumerate(types)] + [{"id": 600, "typeId": 20047, "num": 3}], "rooms": [{"id": 1, "typeId": int(room_type), "openType": 3, "name": "主牧场"}], "teams": [{"monsters": [900]}], "activityHistory": {}, "history": {"unlockCity": {"1": True}, "openFarmBuild": True, "numAddStack": 0, "numKeAddStack": 0, "numAddRoom": 0, "numKeAddRoom": 0}})