1543 lines
95 KiB
Python
1543 lines
95 KiB
Python
"""Offline task planning and account-local client progression.
|
||
|
||
Runner contract (all wire names/payloads come from NetTask/TaskStartPanel):
|
||
|
||
* ``plan`` returns one task transition, ranked farming alternatives (up to 12),
|
||
or explicit blocked intents.
|
||
``rows`` is read-only diagnostic data for every recovered task category.
|
||
* ``progression_navigate``, ``progression_dialogue``, ``progression_local_step``
|
||
have an empty path. They are logical client actions, not phone UI or APIs.
|
||
* For a wire intent call ``mark_started`` BEFORE sending, then
|
||
``acknowledge(snapshot, intent, response)`` ONLY after confirmed success.
|
||
On an ambiguous failure call ``mark_uncertain``; never replay that request.
|
||
* A dialogue before submission does not complete a step. Every nonbattle step,
|
||
including ``none``, needs taskCompleteStep acknowledgement before afterStory
|
||
and completeLocalStep can advance the local one-based cursor.
|
||
* ``progression_battle`` uses task battleStart for BOTH battle/passStage. It is
|
||
a request for the battle orchestrator, never an executable battle shortcut.
|
||
Only the orchestrator may attach real battleData to taskCompleteStep. Call
|
||
acknowledge for this intent only with its successful STEP settlement reply,
|
||
not its battleStart reply or a locally predicted victory.
|
||
* Resource farming emits ``stage_battle`` or ``sweep`` with task_id=0 and
|
||
source_task_* metadata. Only refreshed inventory/kill counters can satisfy
|
||
its source task. Sweeps never receive kill credit.
|
||
* Persist ``export_state()`` per account if desired; ``restore_state`` retains
|
||
unresolved submissions. Supply account_key when role IDs can overlap shards.
|
||
No raw snapshots, tokens, resources, or simulated progress are persisted.
|
||
|
||
Policy additions: repair_chain=True controls verified taskUpdate graph repair.
|
||
``commission_plan(snapshot, quest_policy, ranch_policy, battle_policy=None)``
|
||
is the single full-data commission execution path, explicitly driven by the
|
||
existing QuestPolicy. It replaces legacy commission planning in the runner;
|
||
never run both planners for commissions. Events/bond/unknown types are shown
|
||
and explicitly unsupported by this automation policy.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from copy import deepcopy
|
||
from dataclasses import asdict, dataclass, field, replace
|
||
from datetime import datetime, timedelta, timezone
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import re
|
||
import uuid
|
||
|
||
from .game_data import ProgressionData, load_progression_data
|
||
from .model import Planner, seconds
|
||
from .quests import commission_priority, commission_selection, commission_reason_kind, commission_quota_reason, indexed, stage_has_level
|
||
from .procurement import ResourceProcurement, resource_kind
|
||
from .battle_retry import loss_retry_reason
|
||
|
||
|
||
CATEGORIES = {1: ("mainline", "主线"), 2: ("sidequest", "支线"),
|
||
3: ("event", "活动"), 4: ("commission", "委托"), 5: ("bond", "羁绊")}
|
||
KNOWN_CONDITIONS = {"minLevel", "maxLevel", "close", "platform", "channel", "lang",
|
||
"finishTask", "unfinishTask", "passStage", "unlockStage", "week",
|
||
"startTime", "endTime", "startTimestamp", "endTimestamp"}
|
||
WIRE_KINDS = {"progression_accept", "progression_step", "progression_complete", "progression_update", "progression_battle", "progression_loop_accept", "progression_loop_reset"}
|
||
|
||
|
||
def _integer(value, default=0):
|
||
try:
|
||
number = float(value)
|
||
return int(number) if math.isfinite(number) and number.is_integer() else default
|
||
except (ValueError, TypeError, OverflowError):
|
||
return default
|
||
|
||
|
||
def _values(value):
|
||
"""The retained AMF decoder represents empty arrays as empty mappings."""
|
||
return value if isinstance(value, (list, tuple)) else []
|
||
|
||
|
||
def _flags(value):
|
||
if isinstance(value, dict):
|
||
return {str(key) for key, enabled in value.items() if enabled is True}
|
||
if isinstance(value, list):
|
||
if all(item is None or isinstance(item, bool) for item in value):
|
||
return {str(index) for index, item in enumerate(value) if item is True}
|
||
return {str(item) for item in value if isinstance(item, (str, int)) and not isinstance(item, bool)}
|
||
return set()
|
||
|
||
|
||
@dataclass
|
||
class ProgressionPolicy:
|
||
enabled: bool = False
|
||
mainline: bool = True
|
||
sidequests: bool = False
|
||
commissions: bool = False
|
||
accept: bool = True
|
||
auto_dialogue: bool = True
|
||
team: str = "teamA"
|
||
reserve_ti: int = 0
|
||
allow_sweep: bool = True
|
||
max_money: int = 0
|
||
allow_items: bool = False
|
||
allow_monsters: bool = False
|
||
item_reserves: dict[str, int] = field(default_factory=dict)
|
||
stop_after_loss: int = 1
|
||
loss_retry_hours: int = 3
|
||
repair_chain: bool = True
|
||
battle_mode: str = "original"
|
||
auto_farm: bool = True
|
||
|
||
def __post_init__(self):
|
||
for name in ("enabled", "mainline", "sidequests", "commissions", "accept", "auto_dialogue",
|
||
"allow_sweep", "allow_items", "allow_monsters", "repair_chain", "auto_farm"):
|
||
if not isinstance(getattr(self, name), bool):
|
||
raise ValueError(f"{name} must be a boolean")
|
||
for name in ("reserve_ti", "max_money", "stop_after_loss", "loss_retry_hours"):
|
||
value = getattr(self, name)
|
||
if type(value) is not int or value < 0:
|
||
raise ValueError(f"{name} must be a nonnegative integer")
|
||
setattr(self, name, _integer(value))
|
||
if self.stop_after_loss < 1:
|
||
raise ValueError("stop_after_loss must be at least 1")
|
||
if not 1 <= self.loss_retry_hours <= 168:
|
||
raise ValueError("loss_retry_hours must be between 1 and 168")
|
||
if (not isinstance(self.team, str) or not 1 <= len(self.team) <= 64
|
||
or self.team.strip() != self.team or not self.team.isprintable()):
|
||
raise ValueError("team must be a nonempty printable name of at most 64 characters")
|
||
if self.battle_mode not in ("original", "experimental"):
|
||
raise ValueError("battle_mode must be original or experimental")
|
||
if not isinstance(self.item_reserves, dict):
|
||
raise ValueError("item_reserves must be a mapping")
|
||
reserves = {}
|
||
for key, value in self.item_reserves.items():
|
||
if not str(key).isdigit() or int(key) <= 0 or type(value) is not int or value < 0:
|
||
raise ValueError("Item reserves require numeric IDs and nonnegative integer quantities")
|
||
canonical = str(int(key))
|
||
reserves[canonical] = max(reserves.get(canonical, 0), value)
|
||
self.item_reserves = reserves
|
||
|
||
def to_dict(self):
|
||
return asdict(self)
|
||
|
||
@classmethod
|
||
def from_dict(cls, value):
|
||
if not isinstance(value, dict):
|
||
raise ValueError("Progression policy must be an object")
|
||
unknown = set(value) - set(cls.__dataclass_fields__)
|
||
if unknown:
|
||
raise ValueError("Unknown progression policy fields: " + ", ".join(sorted(unknown)))
|
||
return cls(**value)
|
||
|
||
|
||
@dataclass
|
||
class ProgressionIntent:
|
||
kind: str
|
||
description: str
|
||
path: str = ""
|
||
payload: dict = field(default_factory=dict)
|
||
task_id: int = 0
|
||
task_type_id: str = ""
|
||
step_number: int = 0
|
||
position: str = ""
|
||
stage_id: str = ""
|
||
difficulty: int = 1
|
||
battle_kind: str = ""
|
||
block_reason: str = ""
|
||
npc: str = ""
|
||
npc_name: str = ""
|
||
location: str = ""
|
||
story: str = ""
|
||
phase: str = ""
|
||
team: str = "teamA"
|
||
battle_mode: str = "original"
|
||
account_key: str = ""
|
||
token: str = ""
|
||
source_task_id: int = 0
|
||
source_task_type_id: str = ""
|
||
source_step_number: int = 0
|
||
farming_target: str = ""
|
||
|
||
@property
|
||
def blocked(self):
|
||
return bool(self.block_reason)
|
||
|
||
def to_dict(self):
|
||
return asdict(self)
|
||
|
||
|
||
class ProgressionPlanner:
|
||
def __init__(self, catalog, data=None, *, account_key=None):
|
||
self.catalog = catalog
|
||
self.data = data if isinstance(data, ProgressionData) else ProgressionData(data) if data is not None else load_progression_data()
|
||
self.guard = Planner(catalog)
|
||
self.procurement = ResourceProcurement(catalog, self.guard)
|
||
self.procurement_daily_left = None
|
||
self._namespace = str(account_key) if account_key is not None else ""
|
||
self._anonymous = uuid.uuid4().hex
|
||
self._accounts = {}
|
||
self._issued = {}
|
||
self.commission_selection = {}
|
||
self.commission_offer_rows = []
|
||
|
||
def _scope(self, snapshot):
|
||
raw, master = snapshot.raw, snapshot.raw.get("master") or {}
|
||
role = master.get("id", master.get("userId"))
|
||
parts = [self._namespace, str(role) if role is not None else "" if self._namespace else self._anonymous,
|
||
str(raw.get("serverId", "")), str(raw.get("areaId", ""))]
|
||
return hashlib.sha256(json.dumps(parts, ensure_ascii=True).encode()).hexdigest()
|
||
|
||
def _account(self, snapshot):
|
||
scope = self._scope(snapshot)
|
||
account = self._accounts.setdefault(scope, {
|
||
"position": str(snapshot.raw.get("position") or ""), "tasks": {}, "received": {},
|
||
"unlocked": [], "finished": [], "stage_unlocks": [], "city_unlocks": [],
|
||
"stage_passes": [], "stage_levels": [], "stage_locks": [],
|
||
"pending": None, "losses": 0, "last_loss_at": None, "applied": [],
|
||
"commissions": {"day": None, "remaining": None, "offers": None, "accepted": [], "expired_ids": [], "finished": []},
|
||
})
|
||
return scope, account
|
||
|
||
def battle_retry_reason(self, snapshot, policy):
|
||
_, account = self._account(snapshot)
|
||
return loss_retry_reason(account, snapshot.now, policy)
|
||
|
||
def _tasks(self, snapshot, account):
|
||
received = {key: task for key, task in account["received"].items()
|
||
if not account["tasks"].get(f"{_integer(task.get('id'))}:{key}", {}).get("removed")}
|
||
for task in snapshot.raw.get("currentTasks") or []:
|
||
if isinstance(task, dict) and task.get("typeId") is not None:
|
||
if account["tasks"].get(f"{_integer(task.get('id'))}:{task['typeId']}", {}).get("removed"):
|
||
continue
|
||
if str(task.get("id")) in account["commissions"]["expired_ids"] and (self.data.task(task["typeId"]) or {}).get("type") == 4:
|
||
continue
|
||
received[str(task["typeId"])] = task
|
||
finished = _flags((snapshot.raw.get("history") or {}).get("passTask")) | set(account["finished"])
|
||
finished = {key for key in finished if (self.data.task(key) or {}).get("type") != 4}
|
||
finished.update(account["commissions"]["finished"])
|
||
unlocked = _flags((snapshot.raw.get("history") or {}).get("unlockTask")) | set(account["unlocked"])
|
||
# A reward reply can contain a received nextTasks instance while the
|
||
# previous snapshot still lists it as unlocked. Received always wins.
|
||
return received, unlocked, finished
|
||
|
||
def _record(self, task, account):
|
||
type_id, task_id = str(task["typeId"]), _integer(task.get("id"))
|
||
key = f"{task_id}:{type_id}"
|
||
server = _integer(task.get("curStep"), -1)
|
||
record = account["tasks"].setdefault(key, {
|
||
"cursor": server, "server_step": server, "before": [], "after": [],
|
||
"acknowledged": [], "next_value": None,
|
||
})
|
||
if server > record["cursor"] and record["cursor"] not in record["acknowledged"]:
|
||
record["cursor"] = server
|
||
record["server_step"] = max(server, record["server_step"])
|
||
return record
|
||
|
||
def _passed_stage(self, snapshot, account, field, stage_id, level=1):
|
||
key = f"{stage_id}:{level}"
|
||
if field == "unlockStage" and str(stage_id) in account["stage_locks"]:
|
||
return False
|
||
return (field == "unlockStage" and (key in account["stage_levels"] or int(level) == 1 and str(stage_id) in account["stage_unlocks"])
|
||
or field == "passStage" and key in account["stage_passes"]
|
||
or stage_has_level(snapshot.raw.get("history") or {}, field, str(stage_id), str(level)))
|
||
|
||
@staticmethod
|
||
def _unlock_local_stage(account, stage):
|
||
stage = str(stage)
|
||
if stage:
|
||
if stage not in account["stage_unlocks"]:
|
||
account["stage_unlocks"].append(stage)
|
||
if stage in account["stage_locks"]:
|
||
account["stage_locks"].remove(stage)
|
||
|
||
def condition(self, condition, snapshot):
|
||
"""Conservative declared conditions; do not exploit AS3 loader anomalies.
|
||
|
||
Nonempty passStage and lang are checked as declared, despite retained
|
||
ConditionVo.ondata dropping those fields. This can only restrict
|
||
automation, never silently bypass an unresolved prerequisite.
|
||
"""
|
||
if not condition:
|
||
return True, ""
|
||
if not isinstance(condition, dict):
|
||
return False, "前置条件格式未知"
|
||
unknown = set(condition) - KNOWN_CONDITIONS
|
||
if unknown:
|
||
return False, "未知前置条件:" + ", ".join(sorted(unknown))
|
||
for key in ("finishTask", "unfinishTask", "passStage", "unlockStage", "week"):
|
||
value = condition.get(key)
|
||
if value is not None and value != {} and not isinstance(value, (list, tuple)):
|
||
return False, "前置条件列表格式未知:" + key
|
||
scope, account = self._account(snapshot)
|
||
active, _, finished = self._tasks(snapshot, account)
|
||
level = _integer(snapshot.raw["master"].get("level"))
|
||
if condition.get("close") is True:
|
||
return False, "前置条件已关闭"
|
||
if not _integer(condition.get("minLevel", 0)) <= level <= _integer(condition.get("maxLevel", 2147483647)):
|
||
return False, "角色等级不满足前置条件"
|
||
context = snapshot.raw.get("client_context") or {}
|
||
for field in ("platform", "channel", "lang"):
|
||
expected = condition.get(field)
|
||
if expected not in (None, "", "all") and context.get(field) != expected:
|
||
return False, f"{field} 前置条件不满足或客户端上下文未确认"
|
||
if any(str(key) not in finished for key in _values(condition.get("finishTask"))):
|
||
return False, "前置任务尚未完成"
|
||
if any(str(key) in finished or str(key) in active for key in _values(condition.get("unfinishTask"))):
|
||
return False, "互斥任务已接取或已完成"
|
||
for field in ("passStage", "unlockStage"):
|
||
if any(not self._passed_stage(snapshot, account, field, key) for key in _values(condition.get(field))):
|
||
return False, "前置关卡尚未通关" if field == "passStage" else "前置关卡尚未解锁"
|
||
# The baseline client uses CN UTC+8, JP UTC+9. An explicit context can
|
||
# identify JP; no local workstation timezone participates in checks.
|
||
offset = 9 if context.get("lang") == "JP" else 8
|
||
now = datetime.fromtimestamp(snapshot.now, timezone(timedelta(hours=offset)))
|
||
week = condition.get("week")
|
||
if week is not None and (now.weekday() + 1) % 7 not in _values(week):
|
||
return False, "不在任务开放星期"
|
||
hhmm = now.hour * 100 + now.minute
|
||
if not _integer(condition.get("startTime", 0)) <= hhmm <= _integer(condition.get("endTime", 2147483647)):
|
||
return False, "不在任务开放时段"
|
||
if not _integer(condition.get("startTimestamp", 0)) <= snapshot.now <= _integer(condition.get("endTimestamp", 2147483647)):
|
||
return False, "不在任务开放日期"
|
||
return True, ""
|
||
|
||
def location_text(self, position):
|
||
local = {"farm": "牧场", "stackGround": "孵化场", "": "无指定位置"}
|
||
if position in local:
|
||
return local[position]
|
||
match = re.fullmatch(r"city(\d+)(?:_(.*))?", str(position))
|
||
if not match:
|
||
return str(position)
|
||
city, tail = match.groups()
|
||
city_name = (self.data.game_setting.get("cityInfo") or {}).get(city, {}).get("name") or f"地区 {city}"
|
||
stage = re.fullmatch(r"wild_stage([^_]+)(?:_level(\d+))?", tail or "")
|
||
if stage:
|
||
stage_id, level = stage.groups()
|
||
name = (self.data.stage(stage_id) or {}).get("name") or stage_id
|
||
return f"{city_name} · 野外 · {name}" + (f" · 难度 {level}" if level else "")
|
||
area = self.data.areas.get((tail or "").removeprefix("wild_")) if (tail or "").startswith("wild_") else None
|
||
if area:
|
||
return f"{city_name} · {area.get('name') or tail}"
|
||
mine = next((mine for mine in self.data.mines.values() if mine.get("pos") == position), None)
|
||
if mine:
|
||
return f"{city_name} · {mine.get('name') or tail}"
|
||
labels = {"market": "市场", "xiehui": "驯养师协会", "alchemy": "炼金工坊",
|
||
"bar": "酒馆", "shop": "商店", "wild": "野外", "mine": "矿洞", "pve": "挑战"}
|
||
return city_name + (" · " + labels.get(tail, tail) if tail else "")
|
||
|
||
def city_diagnostic(self, city, snapshot):
|
||
info = (self.data.game_setting.get("cityInfo") or {}).get(str(city), {})
|
||
name = info.get("name") or f"城市 {city}"
|
||
key = str(info.get("openTask") or "")
|
||
task = self.data.task(key) or {}
|
||
_, account = self._account(snapshot)
|
||
unlocked = snapshot.city_unlocked(city) or str(city) in account["city_unlocks"]
|
||
condition = f"完成{CATEGORIES.get(task.get('type'), ('', '任务'))[1]}《{task.get('name') or key}》({key})" if key else "等待服务器确认城市解锁"
|
||
reason = "" if unlocked else f"{name}(城市{city})城市尚未解锁;解锁条件:{condition}" if info else "城市尚未解锁"
|
||
return {"city_name": name, "unlock_task_id": key, "unlock_condition": condition,
|
||
"city_unlocked": unlocked, "city_reason": reason}
|
||
|
||
def _location_gate(self, position, snapshot, account):
|
||
if not position or position in ("farm", "stackGround"):
|
||
return ""
|
||
match = re.fullmatch(r"city(\d+)(?:_(.*))?", str(position))
|
||
if not match:
|
||
return "未验证的位置导航:" + str(position)
|
||
city, tail = match.groups()
|
||
city_info = (self.data.game_setting.get("cityInfo") or {}).get(city)
|
||
if city_info is None:
|
||
return "城市配置缺失"
|
||
if city_info.get("hide") is True:
|
||
return "城市已隐藏"
|
||
if not (snapshot.city_unlocked(int(city)) or city in account["city_unlocks"]):
|
||
return self.city_diagnostic(int(city), snapshot)["city_reason"]
|
||
if tail is None or tail in {"market", "xiehui", "alchemy", "bar", "shop", "wild", "mine", "pve"}:
|
||
if tail == "mine" and (snapshot.raw.get("history") or {}).get("openMine") is not True:
|
||
return "矿洞功能尚未开放"
|
||
return ""
|
||
entrances = self.data.positions.get(position, [])
|
||
if entrances:
|
||
reasons = []
|
||
for entry in entrances:
|
||
ok, reason = self.condition(entry.get("condition"), snapshot)
|
||
if not ok:
|
||
reasons.append(reason)
|
||
continue
|
||
parent = self.data.areas.get(str(entry.get("parent_area")))
|
||
if parent and not self._area_icon_open(snapshot, account, parent):
|
||
reasons.append("入口所在区域尚未解锁")
|
||
continue
|
||
parameters = entry.get("actionPara") or {}
|
||
if entry.get("action") == "area":
|
||
area = self.data.areas.get(str(parameters.get("area")))
|
||
if not area or str(area.get("city")) != city:
|
||
reasons.append("区域与城市配置不匹配")
|
||
continue
|
||
open_stage = area.get("openStage")
|
||
if open_stage and not self._passed_stage(snapshot, account, "unlockStage", open_stage, 1):
|
||
reasons.append("区域入口关卡尚未解锁")
|
||
continue
|
||
return ""
|
||
if entry.get("action") == "dungeon":
|
||
mine = self.data.mines.get(str(parameters.get("dungeon")))
|
||
if mine and mine.get("pos") == position:
|
||
return ""
|
||
reasons.append("地牢面板位置与入口配置不匹配")
|
||
else:
|
||
reasons.append("区域入口含未验证的特殊操作")
|
||
return ";".join(dict.fromkeys(reasons))
|
||
if tail.startswith("wild_") and tail[5:] in self.data.areas:
|
||
area = self.data.areas[tail[5:]]
|
||
if str(area.get("city")) != city:
|
||
return "区域与城市配置不匹配"
|
||
return "" if self._area_icon_open(snapshot, account, area) else "区域入口关卡尚未解锁"
|
||
match = re.fullmatch(r"wild_stage([^_]+)(?:_level(\d+))?", tail)
|
||
if not match:
|
||
return "未验证的位置导航:" + position
|
||
stage_id, difficulty = match.groups()
|
||
if str((self.data.stage(stage_id) or {}).get("city")) != city:
|
||
return "任务位置与关卡城市不匹配"
|
||
return self._stage_gate(snapshot, account, stage_id, _integer(difficulty, 1))
|
||
|
||
def _area_icon_open(self, snapshot, account, area):
|
||
# AreaVo.isOpen uses object existence; table-based position icons
|
||
# additionally check difficulty 1 and allow an empty openStage.
|
||
stage_id = area.get("openStage")
|
||
return (stage_id in account["stage_unlocks"] or bool(stage_id)
|
||
and indexed((snapshot.raw.get("history") or {}).get("unlockStage"), stage_id) is not None)
|
||
|
||
def _stage_gate(self, snapshot, account, stage_id, difficulty):
|
||
stage = self.data.stage(stage_id)
|
||
if not stage or stage.get("closed") is True:
|
||
return "关卡配置缺失或已关闭"
|
||
city = str(stage.get("city"))
|
||
city_info = (self.data.game_setting.get("cityInfo") or {}).get(city)
|
||
if not city_info or city_info.get("hide") is True or not (snapshot.city_unlocked(_integer(city)) or city in account["city_unlocks"]):
|
||
return "关卡所属城市尚未解锁或已隐藏"
|
||
if not self._passed_stage(snapshot, account, "unlockStage", stage_id, 1):
|
||
return "普通难度尚未解锁"
|
||
if not self._passed_stage(snapshot, account, "unlockStage", stage_id, difficulty):
|
||
return "目标关卡难度尚未解锁"
|
||
level = (stage.get("level") or {}).get(str(difficulty))
|
||
if not level or level.get("levelLock") is True:
|
||
return "关卡难度未开放"
|
||
ok, reason = self.condition((self.data.stage_sp.get(str(stage_id)) or {}).get("condition"), snapshot)
|
||
if not ok:
|
||
return reason
|
||
city = str(stage.get("city"))
|
||
city_info = (self.data.game_setting.get("cityInfo") or {}).get(city, {})
|
||
gate = city_info.get({2: "openHardModeStage", 3: "openExtraModeStage"}.get(difficulty, ""))
|
||
if difficulty > 1 and (snapshot.raw.get("history") or {}).get("openHardMode") is not True:
|
||
return "高难度模式已关闭"
|
||
if gate and not self._passed_stage(snapshot, account, "passStage", gate):
|
||
return "城市难度前置关卡未完成"
|
||
return ""
|
||
|
||
def _script_gate(self, name):
|
||
if not name:
|
||
return ""
|
||
script = self.data.script(name)
|
||
if script is None:
|
||
return "剧情脚本配置缺失:" + name
|
||
if script.get("supported") is not True:
|
||
return "剧情含未支持的分支或特殊操作:" + name + "(" + ", ".join(script.get("block_reasons") or ["unknown"]) + ")"
|
||
return ""
|
||
|
||
def requirement(self, snapshot, step, task, policy, ranch_policy):
|
||
"""Return ready, exact removeIds, description. No resource mutation."""
|
||
ok, reason = self.condition(step.get("condition"), snapshot)
|
||
if not ok:
|
||
return False, None, reason
|
||
guide = step.get("passGuide")
|
||
history = snapshot.raw.get("history") or {}
|
||
if guide and indexed(history.get("guide_record"), guide) is not True:
|
||
return False, None, "等待已验证的引导记录:" + str(guide)
|
||
kind, value = step.get("statusType"), step.get("statusValue") or {}
|
||
if kind in ("battle", "passStage"):
|
||
return False, None, "需要进行任务战斗" if kind == "battle" else "需要通过指定关卡的任务战斗"
|
||
if kind == "none":
|
||
return True, None, "对话步骤"
|
||
if kind == "getMoney":
|
||
amount = _integer(value.get("money"), -1)
|
||
if amount < 0:
|
||
return False, None, "金币条件缺少有效数量"
|
||
money = _integer(snapshot.raw["master"].get("money"))
|
||
if value.get("remove") is True:
|
||
if amount > policy.max_money:
|
||
return False, None, "提交金币超过设置上限"
|
||
if money - amount < ranch_policy.keep_money:
|
||
return False, None, "提交后低于牧场金币保留量"
|
||
return money >= amount, None, f"金币 {money}/{amount}"
|
||
if resource_kind(step):
|
||
row = self.procurement.inventory(snapshot, step, policy, ranch_policy)
|
||
return row["ready"], row["ids"] if row["ready"] else None, row["reason"]
|
||
if kind == "killMonster":
|
||
target = task.get("stepValue")
|
||
kills = indexed(history.get("numKillMonsters"), value.get("type"))
|
||
if target is None or kills is None:
|
||
return False, None, "击杀目标或累计击杀记录未同步"
|
||
return _integer(kills, -1) >= _integer(target, 2147483647), None, f"累计击杀 {kills}/{target}"
|
||
if kind == "passLevel":
|
||
level = _integer(value.get("level"), -1)
|
||
return level >= 0 and _integer(snapshot.raw["master"].get("level")) >= level, None, f"需要角色等级 {level}"
|
||
if kind == "unlockMonster":
|
||
return str(value.get("type")) in _flags(history.get("monLib")), None, "需要解锁目标魔物图鉴"
|
||
if kind == "sysLock":
|
||
return indexed(history.get("guide_record"), value.get("key")) is True, None, "等待系统条件:" + str(value.get("key"))
|
||
return False, None, "未支持的任务状态:" + str(kind)
|
||
|
||
def _intent(self, scope, task, step_number, step, kind, description, policy, **extra):
|
||
value = step.get("statusValue") or {}
|
||
position, npc = str(step.get("position") or ""), str(step.get("npc") or "")
|
||
intent = ProgressionIntent(
|
||
kind=kind, description=description, task_id=_integer(task.get("id")), task_type_id=str(task.get("typeId", "")),
|
||
step_number=step_number, position=position, stage_id=str(value.get("stage") or ""),
|
||
difficulty=_integer(value.get("level"), 1), battle_kind=extra.pop("battle_kind", "task" if step.get("statusType") == "battle" else "passStage" if step.get("statusType") == "passStage" else ""),
|
||
npc=npc, npc_name=self.data.npc_name(npc), location=self.location_text(position), team=policy.team,
|
||
battle_mode=policy.battle_mode, account_key=scope, **extra)
|
||
signature = [scope, intent.task_id, intent.task_type_id, step_number, kind, intent.phase, intent.story, position, intent.payload, intent.team, intent.battle_mode,
|
||
intent.source_task_id, intent.source_task_type_id, intent.source_step_number, intent.farming_target]
|
||
if kind == "progression_navigate":
|
||
signature.append(len(self._accounts[scope]["applied"]))
|
||
intent.token = hashlib.sha256(json.dumps(signature, sort_keys=True, ensure_ascii=True).encode()).hexdigest()
|
||
return intent
|
||
|
||
def _next(self, snapshot, policy, ranch, scope, account, task, info, unlocked=False):
|
||
steps = info.get("steps") or []
|
||
record = self._record(task, account) if not unlocked else account["tasks"].setdefault("0:" + str(task["typeId"]), {"before": []})
|
||
number = 0 if unlocked else record["cursor"]
|
||
step = info.get("startStep") or {} if unlocked else steps[number - 1] if 1 <= number <= len(steps) else {}
|
||
make = lambda kind, text, **kw: self._intent(scope, task, number, step, kind, text, policy, **kw)
|
||
block = lambda text: make("progression_blocked", text, block_reason=text)
|
||
if info.get("closed") is True:
|
||
return block("任务已关闭")
|
||
if unlocked and not policy.accept:
|
||
return block("自动接取未启用")
|
||
if not unlocked and (_integer(task.get("id")) <= 0 or number < 1 or number > len(steps) + 1):
|
||
return block("任务实例或一基步骤无效,需重新同步")
|
||
if not unlocked and number == len(steps) + 1:
|
||
if not steps:
|
||
return block("任务没有可核实的步骤")
|
||
return make("progression_complete", "领取任务奖励:" + info.get("name", ""),
|
||
path="taskService/taskComplete", payload={"taskId": _integer(task["id"]), "taskTypeId": str(task["typeId"])})
|
||
ok, reason = self.condition(step.get("condition"), snapshot)
|
||
if not ok:
|
||
return block(reason)
|
||
if step.get("passGuide") and indexed((snapshot.raw.get("history") or {}).get("guide_record"), step["passGuide"]) is not True:
|
||
return block("等待引导记录:" + step["passGuide"])
|
||
reason = self._location_gate(str(step.get("position") or ""), snapshot, account)
|
||
if reason:
|
||
return block(reason)
|
||
# This exact completeLocalStep hook opens a special task gacha. The
|
||
# generic dialogue planner must not consume or manufacture its result.
|
||
if str(task["typeId"]) == "1001006" and number == 4:
|
||
return block("任务1001006第4步含 task1 特殊抽蛋流程,需专门执行器")
|
||
if not unlocked and number in record["acknowledged"]:
|
||
after = step.get("afterStory") or ""
|
||
if after and number not in record["after"]:
|
||
reason = self._script_gate(after)
|
||
if reason or not policy.auto_dialogue:
|
||
return block(reason or "自动后续对话未启用")
|
||
return make("progression_dialogue", "完成后续对话:" + after, story=after, phase="after")
|
||
return make("progression_local_step", "完成已确认步骤的本地收尾", phase="completeLocalStep")
|
||
if unlocked:
|
||
story = step.get("story") or ""
|
||
# Normal unlocked tasks with a start dialogue need a deterministic
|
||
# GAoEvent true; default startStepAnswer is false.
|
||
if story:
|
||
reason = self._script_gate(story)
|
||
if reason:
|
||
return block(reason)
|
||
if self.data.script(story).get("answer") is not True:
|
||
return block("接取剧情没有已验证的肯定答案事件")
|
||
if not policy.auto_dialogue:
|
||
return block("自动接取对话未启用")
|
||
if 0 not in record["before"]:
|
||
if step.get("position") and account["position"] != step["position"]:
|
||
return make("progression_navigate", "前往接取位置:" + self.location_text(step["position"]))
|
||
return make("progression_dialogue", "接取对话:" + story, story=story, phase="start")
|
||
elif step.get("position") and step.get("npc"):
|
||
return block("接取步骤需要特殊入口的默认答案,尚未验证")
|
||
return make("progression_accept", "接取任务:" + info.get("name", ""),
|
||
path="taskService/taskReceive", payload={"taskTypeId": str(task["typeId"])})
|
||
effective_task = dict(task)
|
||
if number != _integer(task.get("curStep")):
|
||
effective_task["stepValue"] = record["next_value"]
|
||
effective_task["curStep"] = number
|
||
ready, ids, requirement = self.requirement(snapshot, step, effective_task, policy, ranch)
|
||
kind = step.get("statusType")
|
||
has_battle = kind in ("battle", "passStage")
|
||
if not ready and not has_battle:
|
||
reason = self._script_gate(step.get("afterStory"))
|
||
if reason or step.get("afterStory") and not policy.auto_dialogue:
|
||
return block(reason or "自动后续对话未启用")
|
||
if resource_kind(step):
|
||
supply = self.remaining_resource_plan(snapshot, info, task, policy, ranch)
|
||
if supply.feasible:
|
||
action = self._resource_intent(snapshot, supply, effective_task, number, step, policy)
|
||
if action is not None:
|
||
return action
|
||
return block(supply.reason + ";" + supply.next_step)
|
||
farming = self.farming_intents(snapshot, step, effective_task, policy, ranch)
|
||
if farming:
|
||
return farming[0]
|
||
eligible = kind == "killMonster" and effective_task.get("stepValue") is not None or kind == "getItem" or kind == "getMonster" and _integer((step.get("statusValue") or {}).get("mode"), -1) == 0
|
||
if policy.auto_farm and eligible and ((step.get("statusValue") or {}).get("remove") is not True or policy.allow_items):
|
||
requirement += ";没有满足解锁、资源保护和任务位置规则的已验证普通地图来源"
|
||
return block(requirement)
|
||
# Check both scripts before committing any server mutation. Linear
|
||
# beforeStory is skipped for already-satisfied non-none conditions, as
|
||
# in TaskStartPanel.checkTask; NONE and both battle types still play it.
|
||
story = (step.get("story") or "") if kind in ("none", "battle", "passStage") else ""
|
||
for script in (story, step.get("afterStory") or ""):
|
||
reason = self._script_gate(script)
|
||
if reason:
|
||
return block(reason)
|
||
if script and not policy.auto_dialogue:
|
||
return block("自动对话未启用")
|
||
if has_battle:
|
||
local_action = self._battle_preflight_needed(step, record, number)
|
||
reason = self._battle_step_gate(snapshot, policy, ranch, scope, account, task, info, step, number, kind,
|
||
capability=local_action)
|
||
if reason:
|
||
return block(reason)
|
||
if step.get("position") and account["position"] != step["position"]:
|
||
return make("progression_navigate", "前往任务位置:" + self.location_text(step["position"]))
|
||
if story and number not in record["before"]:
|
||
return make("progression_dialogue", "完成任务对话:" + story, story=story, phase="before")
|
||
if has_battle:
|
||
return make("progression_battle", "执行任务战斗:" + info.get("name", ""),
|
||
path="battleService/battleStart", payload={"battleType": "task", "taskTypeId": str(task["typeId"])})
|
||
return make("progression_step", "提交任务步骤:" + requirement,
|
||
path="taskService/taskCompleteStep", payload={"taskId": _integer(task["id"]), "taskTypeId": str(task["typeId"]), "removeIds": ids})
|
||
|
||
@staticmethod
|
||
def _battle_preflight_needed(step, record, number):
|
||
"""Only local actions need the early runtime/team readiness check."""
|
||
return bool(step.get("position") or step.get("story") and number not in record["before"])
|
||
|
||
def _battle_step_gate(self, snapshot, policy, ranch, scope, account, task, info, step, number, kind, *, capability):
|
||
"""Reject an unusable battle before navigation or its before-story."""
|
||
if _integer(snapshot.raw["master"].get("ti")) < policy.reserve_ti:
|
||
return "当前体力低于保留体力"
|
||
if reason := loss_retry_reason(account, snapshot.now, policy):
|
||
return reason
|
||
if kind == "battle" and not step.get("battle"):
|
||
return "任务战斗配置缺失"
|
||
if kind == "passStage":
|
||
value = step.get("statusValue") or {}
|
||
stage_id, level = str(value.get("stage", "")), _integer(value.get("level"), -1)
|
||
reason = self._stage_gate(snapshot, account, stage_id, level)
|
||
if reason:
|
||
return reason
|
||
stage = self.data.stage(stage_id)
|
||
entry = (stage.get("level") or {}).get(str(level), {})
|
||
if not entry.get("battle_available", bool(entry.get("battle"))):
|
||
return "关卡战斗配置缺失"
|
||
reason = self._battle_resources(snapshot, policy, ranch, stage, level)
|
||
if reason:
|
||
return reason
|
||
check = getattr(self, "battle_capability", None) if capability else None
|
||
if callable(check):
|
||
intent = self._intent(scope, task, number, step, "progression_battle",
|
||
"执行任务战斗:" + info.get("name", ""), policy,
|
||
path="battleService/battleStart",
|
||
payload={"battleType": "task", "taskTypeId": str(task["typeId"])})
|
||
key = (getattr(self, "battle_capability_key", None), scope, intent.task_id, intent.task_type_id, number, intent.position, intent.stage_id,
|
||
intent.difficulty, intent.team, intent.battle_mode,
|
||
tuple(sorted((str(row.get("id")), row.get("curStep")) for row in snapshot.raw.get("currentTasks", []))),
|
||
account["losses"])
|
||
cached = getattr(self, "_battle_capability_cache", {}).get(key)
|
||
supported, reason = cached if cached is not None else check(intent)
|
||
if not hasattr(self, "_battle_capability_cache"):
|
||
self._battle_capability_cache = {}
|
||
self._battle_capability_cache[key] = (supported, reason)
|
||
while len(self._battle_capability_cache) > 64:
|
||
self._battle_capability_cache.pop(next(iter(self._battle_capability_cache)))
|
||
if not supported:
|
||
return reason or "战斗运行时或阵容尚不可用"
|
||
return ""
|
||
|
||
def _battle_resources(self, snapshot, policy, ranch, stage, level):
|
||
base = stage.get("cost") or {}
|
||
cost = _integer(base.get("ti")) + _integer((stage.get("level") or {}).get(str(level), {}).get("cost"))
|
||
if _integer(snapshot.raw["master"].get("ti")) - cost < policy.reserve_ti:
|
||
return "体力不足或将低于保留体力"
|
||
if _integer(base.get("ke")):
|
||
return "关卡需要氪金,推进器不自动消费"
|
||
money = _integer(base.get("money"))
|
||
if money and (money > policy.max_money or _integer(snapshot.raw["master"].get("money")) - money < ranch.keep_money):
|
||
return "关卡金币消耗超过限制或保留量"
|
||
for item in _values(base.get("items")):
|
||
key = str(item.get("typeId", item.get("type", "")))
|
||
count = _integer(item.get("num"), -1)
|
||
available = sum(_integer(row.get("num")) for row in snapshot.raw.get("items", [])
|
||
if str(row.get("typeId")) == key and not any(row.get(flag) for flag in ("lock", "feedLock", "sysLock")))
|
||
reserve = max(policy.item_reserves.get(key, 0), _integer(ranch.reserved_eggs.get(key)), _integer(ranch.gift_items.get(key, {}).get("reserve")))
|
||
if count < 0 or available - count < reserve or not policy.allow_items:
|
||
return "关卡门票不足、受保留保护或未启用消耗道具"
|
||
return ""
|
||
|
||
def _farm_intercepted(self, snapshot, account, stage, difficulty):
|
||
active, unlocked, finished = self._tasks(snapshot, account)
|
||
base = f"city{stage.get('city')}_wild_stage{stage.get('id')}"
|
||
for key in (set(active) | unlocked) - finished:
|
||
info = self.data.task(key)
|
||
if not info:
|
||
return True # Cannot prove that an unknown task will not intercept.
|
||
if key in active:
|
||
number = self._record(active[key], account)["cursor"]
|
||
steps = info.get("steps") or []
|
||
current = steps[number - 1] if 1 <= number <= len(steps) else {}
|
||
else:
|
||
current = info.get("startStep") or {}
|
||
position = current.get("position")
|
||
if position == base + f"_level{difficulty}":
|
||
return True # StageStartPanel.getTaskByPosition matches exactly.
|
||
if position == base and (current.get("story") or current.get("statusType") == "battle"):
|
||
return True
|
||
return False
|
||
|
||
def farming_intents(self, snapshot, step, task, policy, ranch_policy, *, limit=12):
|
||
"""Rank ordinary map/sweep sources for an unmet objective.
|
||
|
||
Counts and loot are potential configuration sources. These intents have
|
||
task_id=0 and task_type_id=''; their source_task_* fields are diagnostic
|
||
only. The battle/sweep runner settles them and refreshes authoritative
|
||
inventory/kill counters. Never acknowledge them as task steps.
|
||
"""
|
||
if not policy.auto_farm or not self.condition(step.get("condition"), snapshot)[0]:
|
||
return []
|
||
if step.get("passGuide") and indexed((snapshot.raw.get("history") or {}).get("guide_record"), step["passGuide"]) is not True:
|
||
return []
|
||
kind, value = step.get("statusType"), step.get("statusValue") or {}
|
||
key = str(value.get("type", ""))
|
||
if not key.isdigit():
|
||
return []
|
||
if kind == "killMonster":
|
||
target = task.get("stepValue")
|
||
kills = indexed((snapshot.raw.get("history") or {}).get("numKillMonsters"), key)
|
||
if _integer(task.get("id")) > 0 and (target is None or _integer(target, -1) < 0):
|
||
return []
|
||
if target is not None and kills is not None and _integer(kills) >= _integer(target):
|
||
return []
|
||
source_kind = "kills"
|
||
elif kind == "getItem" or kind == "getMonster" and _integer(value.get("mode"), -1) == 0:
|
||
count = _integer(value.get("num"), -1)
|
||
if count < 1 or value.get("remove") is True and not policy.allow_items:
|
||
return []
|
||
reserve = max(policy.item_reserves.get(key, 0), _integer(ranch_policy.reserved_eggs.get(key)),
|
||
_integer(ranch_policy.gift_items.get(key, {}).get("reserve"))) if value.get("remove") is True else 0
|
||
available = sum(_integer(item.get("num")) for item in snapshot.raw.get("items", [])
|
||
if str(item.get("typeId")) == key and not any(item.get(flag) for flag in ("lock", "feedLock", "sysLock")))
|
||
if available >= count + reserve:
|
||
return []
|
||
source_kind = "items"
|
||
else:
|
||
return []
|
||
scope, account = self._account(snapshot)
|
||
if loss_retry_reason(account, snapshot.now, policy):
|
||
return []
|
||
ranked = []
|
||
seen = set()
|
||
for source in self.data.farming.get(source_kind, {}).get(key, []):
|
||
stage_id, level = str(source.get("stage_id", "")), _integer(source.get("difficulty"), -1)
|
||
stage = self.data.stage(stage_id)
|
||
if not stage or stage.get("special") or stage.get("posmode") or (stage_id, level) in seen:
|
||
continue
|
||
seen.add((stage_id, level))
|
||
if self._stage_gate(snapshot, account, stage_id, level) or self._battle_resources(snapshot, policy, ranch_policy, stage, level):
|
||
continue
|
||
entry = (stage.get("level") or {}).get(str(level), {})
|
||
if not entry.get("battle_available", bool(entry.get("battle"))) or self._farm_intercepted(snapshot, account, stage, level):
|
||
continue
|
||
base_cost = stage.get("cost") or {}
|
||
if _integer(base_cost.get("ke")) or any(str(item.get("typeId", item.get("type"))) == key and _integer(item.get("num")) > 0
|
||
for item in _values(base_cost.get("items"))):
|
||
continue
|
||
sweep = (source_kind == "items" and policy.allow_sweep
|
||
and all(self._passed_stage(snapshot, account, "passStage", stage_id, difficulty) for difficulty in (1, 2, 3)))
|
||
position = f"city{stage.get('city')}_wild_stage{stage_id}_level{level}"
|
||
farm_step = {"position": position, "statusValue": {"stage": stage_id, "level": level}}
|
||
text = ("扫荡获取潜在掉落" if sweep else "普通战斗狩猎成年目标" if source_kind == "kills" else "普通战斗获取潜在掉落")
|
||
action = self._intent(scope, {}, 0, farm_step, "sweep" if sweep else "stage_battle",
|
||
f"{text}:{self.catalog.item_name(key)} · {stage.get('name') or stage_id}", policy,
|
||
battle_kind="sweep" if sweep else "ordinary_stage",
|
||
path="" if sweep else "stageService/stageStart",
|
||
payload={} if sweep else {"stageTypeId": stage_id, "stageLevel": str(level)},
|
||
source_task_id=_integer(task.get("id")), source_task_type_id=str(task.get("typeId", "")),
|
||
source_step_number=_integer(task.get("curStep")), farming_target=f"{source_kind}:{key}")
|
||
stamina = _integer(base_cost.get("ti")) + _integer(entry.get("cost"))
|
||
ranked.append(((not sweep, stamina, level, stage_id), action))
|
||
ranked.sort(key=lambda pair: pair[0])
|
||
return [action for _, action in ranked[:max(1, min(100, _integer(limit, 12)))]]
|
||
|
||
@staticmethod
|
||
def _selected(info, policy):
|
||
return (info.get("type") == 1 and policy.mainline or info.get("type") == 2 and policy.sidequests)
|
||
|
||
def _commission_policy(self, quest_policy, battle_policy=None):
|
||
base = battle_policy or ProgressionPolicy()
|
||
return replace(base, enabled=bool(quest_policy.enabled), mainline=False, sidequests=False,
|
||
commissions=True, accept=bool(quest_policy.accept), repair_chain=False, auto_farm=True,
|
||
allow_items=bool(quest_policy.allow_items), allow_monsters=bool(quest_policy.allow_monsters),
|
||
max_money=quest_policy.max_money, item_reserves=dict(quest_policy.item_reserves))
|
||
|
||
@staticmethod
|
||
def _loop_day(snapshot, timestamp):
|
||
context = snapshot.raw.get("client_context") or {}
|
||
return int((seconds(timestamp) + (9 if context.get("lang") == "JP" else 8) * 3600) // 86400)
|
||
|
||
def _loop_view(self, snapshot, account):
|
||
history, local = snapshot.raw.get("history") or {}, account["commissions"]
|
||
today = self._loop_day(snapshot, snapshot.now - 10)
|
||
recorded = self._loop_day(snapshot, history["loopTaskTime"]) if history.get("loopTaskTime") is not None else None
|
||
if local["day"] is not None and local["day"] != today:
|
||
local.update(day=None, remaining=None, offers=None, accepted=[], finished=[])
|
||
same_local_day = local["day"] == today
|
||
offers = (local["offers"] if same_local_day and recorded != today and local["offers"] is not None
|
||
else history.get("loopTask") or {})
|
||
remaining = _integer(history.get("loopTaskNum"))
|
||
if same_local_day and local["remaining"] is not None:
|
||
remaining = min(remaining, local["remaining"]) if recorded == today else local["remaining"]
|
||
offers = deepcopy(offers) if isinstance(offers, dict) else {}
|
||
if same_local_day:
|
||
for accepted in local["accepted"]:
|
||
city, key = accepted.split(":", 1)
|
||
offers[city] = [offer for offer in _values(offers.get(city)) if str(offer) != key]
|
||
return today, recorded, max(0, remaining), offers
|
||
|
||
def _commission_next(self, snapshot, quest_policy, policy, ranch, scope, account, task, info):
|
||
record = self._record(task, account)
|
||
number, steps = record["cursor"], info.get("steps") or []
|
||
if (1 <= number <= len(steps) and steps[number - 1].get("statusType") in ("battle", "passStage")
|
||
and not quest_policy.battle_tasks and number not in record["acknowledged"]):
|
||
reason = "委托战斗开关未启用"
|
||
return self._intent(scope, task, number, steps[number - 1], "progression_blocked", reason, policy, block_reason=reason)
|
||
return self._next(snapshot, policy, ranch, scope, account, task, info)
|
||
|
||
def remaining_resource_plan(self, snapshot, info, task, policy, ranch):
|
||
"""One remaining-step/coin-reserve calculation for planning and dispatch."""
|
||
effective_task = dict(task)
|
||
number = 1
|
||
if _integer(task.get("id")) > 0:
|
||
_, account = self._account(snapshot)
|
||
record = self._record(task, account)
|
||
number = record["cursor"]
|
||
if number != _integer(task.get("curStep")):
|
||
effective_task["stepValue"] = record["next_value"]
|
||
effective_task["curStep"] = number
|
||
steps = (info.get("steps") or [])[max(0, number - 1):]
|
||
money = sum(_integer((step.get("statusValue") or {}).get("money")) for step in steps
|
||
if step.get("statusType") == "getMoney" and (step.get("statusValue") or {}).get("remove") is True)
|
||
return self.resource_plan(snapshot, steps, effective_task, policy,
|
||
replace(ranch, keep_money=ranch.keep_money + money))
|
||
|
||
def resource_plan(self, snapshot, steps, task, policy, ranch):
|
||
def sources(trial):
|
||
actions = self.farming_intents(snapshot, trial, task, policy, ranch)
|
||
check = getattr(self, "battle_capability", None)
|
||
supported, reasons = [], []
|
||
for action in actions:
|
||
ok, reason = (True, "") if action.kind == "sweep" or not callable(check) else check(action)
|
||
if ok:
|
||
supported.append(action)
|
||
elif reason:
|
||
reasons.append(reason)
|
||
return supported, ";".join(dict.fromkeys(reasons))
|
||
return self.procurement.plan(snapshot, steps, policy, ranch,
|
||
daily_left=self.procurement_daily_left, farm_sources=sources)
|
||
|
||
def _resource_intent(self, snapshot, supply, task, number, step, policy):
|
||
if supply.sources:
|
||
return supply.sources[0]
|
||
scope, _ = self._account(snapshot)
|
||
if supply.action:
|
||
action = supply.action
|
||
note = ";先补资源,未提交任务步骤" if _integer(task.get("id")) else ";先补资源,尚未接取委托,未消耗接取次数"
|
||
return self._intent(scope, {}, 0, {}, "progression_procure", action.description + note, policy,
|
||
path=action.path, payload=deepcopy(action.payload), phase=action.kind,
|
||
source_task_id=_integer(task.get("id")), source_task_type_id=str(task.get("typeId", "")),
|
||
source_step_number=number)
|
||
if not supply.ready:
|
||
reason = supply.reason + ";" + supply.next_step
|
||
return self._intent(scope, task, number, step, "progression_blocked", reason, policy, block_reason=reason)
|
||
return None
|
||
|
||
def _commission_offer_ready(self, snapshot, quest_policy, policy, ranch, info):
|
||
if info.get("closed"):
|
||
return False, "委托已关闭"
|
||
ok, reason = self.condition((info.get("startStep") or {}).get("condition"), snapshot)
|
||
if not ok:
|
||
return False, reason
|
||
# Acceptance spends a daily slot. Keep the old scheduler's conservative
|
||
# resource preflight, now allowing verified linear story completion.
|
||
money = 0
|
||
scope, account = self._account(snapshot)
|
||
for number, step in enumerate(info.get("steps") or [], 1):
|
||
ok, reason = self.condition(step.get("condition"), snapshot)
|
||
reason = reason if not ok else self._location_gate(str(step.get("position") or ""), snapshot, account)
|
||
if not reason and step.get("passGuide") and indexed((snapshot.raw.get("history") or {}).get("guide_record"), step["passGuide"]) is not True:
|
||
reason = "等待引导记录:" + str(step["passGuide"])
|
||
if reason:
|
||
return False, f"第{number}步:{reason}"
|
||
for script in (step.get("story"), step.get("afterStory")):
|
||
reason = self._script_gate(script)
|
||
if reason or script and not policy.auto_dialogue:
|
||
return False, reason or "自动对话未启用"
|
||
kind, value = step.get("statusType"), step.get("statusValue") or {}
|
||
if kind in ("battle", "passStage"):
|
||
if not quest_policy.battle_tasks:
|
||
return False, "委托战斗开关未启用"
|
||
if kind == "battle" and not step.get("battle"):
|
||
return False, "委托战斗配置缺失"
|
||
if kind == "passStage" and not self.data.stage(value.get("stage")):
|
||
return False, "委托关卡配置缺失"
|
||
elif not resource_kind(step):
|
||
ready, _, reason = self.requirement(snapshot, step, {}, policy, ranch)
|
||
if not ready:
|
||
preview = {"id": 0, "typeId": str(info.get("id", "")), "curStep": number}
|
||
if not self.farming_intents(snapshot, step, preview, policy, ranch):
|
||
return False, reason
|
||
if value.get("remove") is True:
|
||
if kind == "getMoney":
|
||
money += _integer(value.get("money"))
|
||
if money and (money > policy.max_money or _integer(snapshot.raw["master"].get("money")) - money < ranch.keep_money):
|
||
return False, "整份委托提交金币超过设置或保留量"
|
||
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": str(info.get("id", ""))},
|
||
policy, replace(ranch, keep_money=ranch.keep_money + money))
|
||
if not supply.feasible:
|
||
return False, supply.reason
|
||
return (True, "可接取") if info.get("steps") else (False, "委托没有有效步骤")
|
||
|
||
def commission_plan(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None):
|
||
"""Plan full type-4 progression using the existing commission policy.
|
||
|
||
The engine must call this INSTEAD OF TaskPlanner.plan for commissions.
|
||
Exact loop payloads remain taskLoopFlush:{} and
|
||
taskLoopReceive:{taskTypeId,city}; quotas decrement only on acceptance
|
||
acknowledgement. Current battle/passStage never become sweep intents.
|
||
"""
|
||
self.commission_selection = {}
|
||
self.commission_offer_rows = []
|
||
if not quest_policy.enabled:
|
||
return []
|
||
policy = self._commission_policy(quest_policy, battle_policy)
|
||
scope, account = self._account(snapshot)
|
||
self.reconcile(snapshot)
|
||
candidates = self.commission_offers(snapshot, quest_policy, ranch_policy,
|
||
battle_policy=battle_policy, accept_supported=accept_supported)
|
||
self.commission_offer_rows = candidates
|
||
if account["pending"]:
|
||
reason = "存在未确认请求,委托等待核对,禁止重发"
|
||
return [self._intent(scope, {}, 0, {}, "progression_blocked", reason, policy, block_reason=reason)]
|
||
today, recorded, remaining, offers = self._loop_view(snapshot, account)
|
||
if recorded is not None and recorded != today and account["commissions"]["day"] != today:
|
||
action = self._intent(scope, {}, 0, {}, "progression_loop_reset", "刷新跨日委托并废弃旧实例", policy,
|
||
path="taskService/taskLoopFlush", payload={}, phase=str(today))
|
||
self._issued[action.token] = action.to_dict()
|
||
return [action]
|
||
active, _, finished = self._tasks(snapshot, account)
|
||
blocked = []
|
||
for key, task in sorted(active.items(), key=lambda pair: commission_priority(self.data.task(pair[0]) or {})):
|
||
info = self.data.task(key)
|
||
if not info or info.get("type") != 4 or key in finished:
|
||
continue
|
||
action = self._commission_next(snapshot, quest_policy, policy, ranch_policy, scope, account, task, info)
|
||
if not action.blocked:
|
||
actions = self._expand_farming(snapshot, action, task, info, policy, ranch_policy, account)
|
||
for candidate in actions:
|
||
self._issued[candidate.token] = candidate.to_dict()
|
||
return actions
|
||
blocked.append(action)
|
||
if blocked or not quest_policy.accept or remaining <= 0:
|
||
return blocked
|
||
rejected = []
|
||
for candidate in candidates:
|
||
city, key = candidate["city"], candidate["task_type_id"]
|
||
info = self.data.task(key)
|
||
if candidate.get("preparable"):
|
||
money = sum(_integer((s.get("statusValue") or {}).get("money")) for s in info.get("steps") or []
|
||
if s.get("statusType") == "getMoney" and (s.get("statusValue") or {}).get("remove") is True)
|
||
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key}, policy,
|
||
replace(ranch_policy, keep_money=ranch_policy.keep_money + money))
|
||
action = self._resource_intent(snapshot, supply, {"id": 0, "typeId": key}, 0, {}, policy)
|
||
if action is not None:
|
||
if not action.blocked:
|
||
self._issued[action.token] = action.to_dict()
|
||
return [action]
|
||
if not candidate["eligible"]:
|
||
rejected.append(candidate)
|
||
if candidate["blocked_by_support"]:
|
||
blocked.append(self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {},
|
||
"progression_loop_accept", "暂不接取:" + info.get("name", key), policy,
|
||
path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today),
|
||
block_reason=candidate["reason"]))
|
||
continue
|
||
self.commission_selection = {"task_type_id": key, "city": city,
|
||
**commission_selection(info, candidates, rejected)}
|
||
action = self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {},
|
||
"progression_loop_accept", f"接取城市委托:{info.get('name', key)}(预计{candidate['expected_ke']}氪金);" + self.commission_selection["selection_reason"], policy,
|
||
path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today))
|
||
self._issued[action.token] = action.to_dict()
|
||
return [action]
|
||
return blocked
|
||
|
||
def commission_offers(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None):
|
||
"""Offline eligibility for every offer; raw presence never means receivable."""
|
||
policy = self._commission_policy(quest_policy, battle_policy)
|
||
_, account = self._account(snapshot)
|
||
today, recorded, remaining, offers = self._loop_view(snapshot, account)
|
||
active, _, finished = self._tasks(snapshot, account)
|
||
has_active = any((self.data.task(key) or {}).get("type") == 4 and key not in finished for key in active)
|
||
rows = []
|
||
ranked = sorted(((city, key) for city, values in offers.items() for key in _values(values)),
|
||
key=lambda pair: commission_priority(self.data.task(str(pair[1])) or {}))
|
||
for offered_city, offered_key in ranked:
|
||
city, key = _integer(offered_city), str(offered_key)
|
||
info = self.data.task(key) or {}
|
||
if info.get("type") != 4:
|
||
continue
|
||
support_blocked = False
|
||
city_info = self.city_diagnostic(city, snapshot)
|
||
supply = None
|
||
reason = ("城市编号无效" if city <= 0 else
|
||
commission_quota_reason(snapshot) if remaining <= 0 else
|
||
f"策略限定城市 {quest_policy.city}" if quest_policy.city and city != quest_policy.city else
|
||
city_info["city_reason"] if not city_info["city_unlocked"] else
|
||
"委托列表已跨日,等待刷新确认" if recorded is not None and recorded != today and account["commissions"]["day"] != today else
|
||
"自动委托未启用" if not quest_policy.enabled else "自动接取未启用" if not quest_policy.accept else
|
||
"存在未确认请求,等待核对" if account["pending"] else
|
||
"该委托已接取或已完成" if key in active or key in finished else
|
||
"已有委托优先完成" if has_active else "")
|
||
if not reason:
|
||
ready, reason = self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info)
|
||
if ready:
|
||
reason = ""
|
||
if accept_supported is not None:
|
||
result = accept_supported(key)
|
||
supported, detail = result if isinstance(result, tuple) else (result, "")
|
||
if not supported:
|
||
reason = detail or "委托后续战斗或条件当前无法自动完成"
|
||
support_blocked = True
|
||
if not reason:
|
||
money = sum(_integer((s.get("statusValue") or {}).get("money")) for s in info.get("steps") or []
|
||
if s.get("statusType") == "getMoney" and (s.get("statusValue") or {}).get("remove") is True)
|
||
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key},
|
||
policy, replace(ranch_policy, keep_money=ranch_policy.keep_money + money))
|
||
if not supply.ready:
|
||
reason = supply.reason + ";" + supply.next_step + ";补齐并核对后再接取,不消耗接取次数"
|
||
elif any(resource_kind(s) for s in info.get("steps") or []):
|
||
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key}, policy, ranch_policy)
|
||
if supply.feasible:
|
||
supply = None # A hard prerequisite failed; procurement cannot bypass it.
|
||
rows.append({"task_type_id": key, "name": info.get("name", key), "city": city,
|
||
"expected_ke": -commission_priority(info), "eligible": not reason, "reason": reason or "可接取",
|
||
"blocked_by_support": support_blocked, "preparable": bool(supply and supply.feasible and not supply.ready and not support_blocked),
|
||
**city_info, "remaining_quota": remaining,
|
||
"reason_kind": supply.reason_kind if supply and not supply.ready and not support_blocked else commission_reason_kind(reason),
|
||
"resources": supply.resources if supply else [], "progress_plan": supply.progress_plan if supply else [],
|
||
"next_step": supply.next_step if supply and not supply.ready else reason or "按奖励优先接取城市委托"})
|
||
return rows
|
||
|
||
def commission_rows(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None):
|
||
policy = self._commission_policy(quest_policy, battle_policy)
|
||
return [row for row in self.rows(snapshot, policy, ranch_policy, quest_policy=quest_policy)
|
||
if row.get("category") == "commission"]
|
||
|
||
def _chain_update(self, snapshot, policy, scope, account):
|
||
if not policy.repair_chain:
|
||
return None
|
||
active, unlocked, finished = self._tasks(snapshot, account)
|
||
receive, unlock, remove = [], [], []
|
||
seen_receive, seen_unlock = set(), set()
|
||
legacy = self.data.setting.get("useOldNewTaskFunction") is True
|
||
if legacy:
|
||
parents, stack = [], ["1001001"]
|
||
visited = set()
|
||
while stack:
|
||
parent = stack.pop()
|
||
if parent in visited or parent not in finished:
|
||
continue
|
||
visited.add(parent)
|
||
parents.append(parent)
|
||
stack.extend(str(key) for key in _values((self.data.task(parent) or {}).get("nextTasks")))
|
||
else:
|
||
parents = sorted(finished)
|
||
for parent in parents:
|
||
info = self.data.task(parent)
|
||
if not info or not legacy and info.get("closed") is True:
|
||
continue
|
||
for key in _values(info.get("nextTasks")):
|
||
key, target = str(key), self.data.task(key)
|
||
if (target and not target.get("closed") and self._selected(target, policy) and policy.accept
|
||
and key not in finished and key not in active and key not in unlocked and key not in seen_receive):
|
||
receive.append({"prev": parent, "taskTypeId": key})
|
||
seen_receive.add(key)
|
||
for key in _values(info.get("unlockTasks")):
|
||
key, target = str(key), self.data.task(key)
|
||
if (target and not target.get("closed") and self._selected(target, policy)
|
||
and key not in finished and key not in active and key not in unlocked and key not in seen_unlock):
|
||
unlock.append({"prev": parent, "taskTypeId": key})
|
||
seen_unlock.add(key)
|
||
if not legacy:
|
||
remove = [_integer(task.get("id")) for key, task in active.items()
|
||
if (self.data.task(key) or {}).get("closed") is True
|
||
and self._selected(self.data.task(key), policy) and _integer(task.get("id")) > 0]
|
||
if not (receive or unlock or remove):
|
||
return None
|
||
return self._intent(scope, {}, 0, {}, "progression_update", "按已完成任务图修复后继与解锁", policy,
|
||
path="taskService/taskUpdate", payload={"unlockTasks": unlock, "receiveTasks": receive, "removeTasks": remove})
|
||
|
||
def _merge_local_progress(self, snapshot, local_progress):
|
||
"""Import only acknowledged, role/instance-matched runner checkpoints.
|
||
|
||
The optional BattleJournal shape is {"id:type": {task_id,
|
||
task_type_id, steps: {"1": {kind, phase, acknowledged, response}}}}.
|
||
A bare local dialogue checkpoint is NEVER a server step completion.
|
||
Local-step checkpoints require an explicit server_acknowledged marker
|
||
or a previously imported server response for that same step.
|
||
"""
|
||
if local_progress is None:
|
||
return
|
||
if not isinstance(local_progress, dict):
|
||
raise ValueError("local_progress must be a role-scoped checkpoint mapping")
|
||
_, account = self._account(snapshot)
|
||
current, _, _ = self._tasks(snapshot, account)
|
||
for key, checkpoint in local_progress.items():
|
||
if not isinstance(checkpoint, dict):
|
||
continue
|
||
type_id = str(checkpoint.get("task_type_id", ""))
|
||
task = current.get(type_id)
|
||
if not task or _integer(task.get("id")) != _integer(checkpoint.get("task_id")) or key != f"{_integer(task.get('id'))}:{type_id}":
|
||
continue
|
||
record = self._record(task, account)
|
||
entries = checkpoint.get("steps") or {}
|
||
if not isinstance(entries, dict):
|
||
continue
|
||
for number, entry in sorted(entries.items(), key=lambda pair: _integer(pair[0])):
|
||
number = _integer(number, -1)
|
||
if not isinstance(entry, dict) or entry.get("acknowledged") is not True or number < record["cursor"]:
|
||
continue
|
||
kind, response = entry.get("kind"), entry.get("response")
|
||
if kind in ("progression_step", "quest_step", "task_step", "progression_battle", "task_battle", "battle") and isinstance(response, dict):
|
||
if number not in record["acknowledged"]:
|
||
record["acknowledged"].append(number)
|
||
record["next_value"] = response.get("taskStepValue")
|
||
elif kind in ("progression_dialogue", "dialogue", "local_dialogue"):
|
||
phase = entry.get("phase")
|
||
collection = "after" if phase == "after" else "before" if phase in ("before", "start") else None
|
||
if collection and (phase != "after" or number in record["acknowledged"]) and number not in record[collection]:
|
||
record[collection].append(number)
|
||
elif kind in ("progression_local_step", "local_step"):
|
||
if entry.get("server_acknowledged") is True or number in record["acknowledged"]:
|
||
record["cursor"] = max(record["cursor"], number + 1)
|
||
|
||
def rows(self, snapshot, policy, ranch_policy, *, local_progress=None, quest_policy=None):
|
||
self._merge_local_progress(snapshot, local_progress)
|
||
scope, account = self._account(snapshot)
|
||
active, unlocked, finished = self._tasks(snapshot, account)
|
||
_, _, commission_remaining, offers = self._loop_view(snapshot, account)
|
||
offer_cities = {str(key): _integer(city) for city, values in offers.items() for key in _values(values)}
|
||
keys = set(self.data.tasks) | set(active) | unlocked | finished
|
||
rows = []
|
||
for key in keys:
|
||
info = self.data.task(key)
|
||
task = active.get(key) or {"id": 0, "typeId": key}
|
||
if not info:
|
||
rows.append({"task_type_id": key, "task_id": _integer(task.get("id")), "name": "配置缺失:" + key,
|
||
"category": "unknown", "category_name": "未知", "state": "blocked", "step_number": _integer(task.get("curStep")),
|
||
"total_steps": 0, "position": "", "requirement": "完整静态配置中不存在此任务", "next_action": "重新核对资源版本",
|
||
"battle_kind": "", "npc": "", "npc_name": "", "location": "", "block_reason": "任务配置缺失"})
|
||
continue
|
||
task_type = _integer(info.get("type"), -1)
|
||
category, category_name = CATEGORIES.get(task_type, ("unknown", f"未知类型 {task_type}"))
|
||
state = "finished" if key in finished else "received" if key in active else "unlocked" if key in unlocked else "locked"
|
||
if task_type == 4 and key in offer_cities and key not in active and key not in finished:
|
||
state = "offered"
|
||
number = self._record(task, account)["cursor"] if state == "received" else 0
|
||
steps = info.get("steps") or []
|
||
step = steps[number - 1] if 1 <= number <= len(steps) else info.get("startStep") or {}
|
||
position, npc = str(step.get("position") or ""), str(step.get("npc") or "")
|
||
requirement = "任务已完成" if state == "finished" else "任务尚未解锁" if state == "locked" else "等待接取"
|
||
next_action, block_reason = "", ""
|
||
battle_kind = "task" if step.get("statusType") == "battle" else "passStage" if step.get("statusType") == "passStage" else ""
|
||
if state in ("received", "unlocked"):
|
||
if task_type in (1, 2) or task_type == 4 and quest_policy is not None and state == "received":
|
||
intent = (self._commission_next(snapshot, quest_policy, self._commission_policy(quest_policy, policy), ranch_policy, scope, account, task, info)
|
||
if task_type == 4 else self._next(snapshot, policy, ranch_policy, scope, account, task, info, state == "unlocked"))
|
||
next_action, block_reason = intent.description, intent.block_reason
|
||
if intent.farming_target:
|
||
battle_kind = intent.battle_kind
|
||
if state == "received":
|
||
effective = dict(task)
|
||
if number != _integer(task.get("curStep")):
|
||
effective["stepValue"] = self._record(task, account)["next_value"]
|
||
requirement = "可领取整任务奖励" if number == len(steps) + 1 else self.requirement(snapshot, step, effective, policy, ranch_policy)[2]
|
||
if intent.kind == "progression_complete":
|
||
state = "ready_to_reward"
|
||
else:
|
||
block_reason = "委托由独立 QuestPolicy 调度" if task_type == 4 else "此任务类型尚未支持自动推进"
|
||
next_action = block_reason
|
||
if state == "offered":
|
||
requirement = f"城市 {offer_cities[key]} 委托,当日剩余接取 {commission_remaining} 次"
|
||
next_action = "由 QuestPolicy 检查城市、资源和战斗开关后接取"
|
||
if quest_policy is not None:
|
||
if not quest_policy.enabled or not quest_policy.accept:
|
||
block_reason = "委托自动接取未启用"
|
||
elif commission_remaining <= 0:
|
||
block_reason = "当日委托接取次数已用完"
|
||
elif quest_policy.city and quest_policy.city != offer_cities[key]:
|
||
block_reason = "委托不在设置城市"
|
||
elif not snapshot.city_unlocked(offer_cities[key]):
|
||
block_reason = "委托城市尚未解锁"
|
||
else:
|
||
ready, reason = self._commission_offer_ready(snapshot, quest_policy, self._commission_policy(quest_policy, policy), ranch_policy, info)
|
||
block_reason = "" if ready else reason
|
||
next_action = block_reason or "接取城市委托"
|
||
if task_type not in CATEGORIES:
|
||
block_reason = "未知任务类型,未自动推进:" + str(task_type)
|
||
next_action = block_reason
|
||
if account["pending"] and state in ("received", "unlocked", "ready_to_reward"):
|
||
block_reason = "存在等待核对的请求:" + account["pending"].get("reason", "进行中")
|
||
next_action = block_reason
|
||
rows.append({"task_type_id": key, "task_id": _integer(task.get("id")), "task_type": task_type,
|
||
"name": info.get("name") or key, "category": category, "category_name": category_name,
|
||
"state": state, "step_number": number, "total_steps": len(steps), "position": position,
|
||
"location": self.location_text(position), "location_text": self.location_text(position),
|
||
"npc": npc, "npc_name": self.data.npc_name(npc), "requirement": requirement,
|
||
"next_action": next_action, "battle_kind": battle_kind, "block_reason": block_reason,
|
||
"supported": not bool(block_reason) and state not in ("locked", "finished") and (task_type in (1, 2) or task_type == 4 and quest_policy is not None),
|
||
"dialogue": ("前置:" + str(step.get("story")) if step.get("story") else "")
|
||
+ (" 后续:" + str(step.get("afterStory")) if step.get("afterStory") else ""),
|
||
"stage_id": str((step.get("statusValue") or {}).get("stage") or ""),
|
||
"difficulty": _integer((step.get("statusValue") or {}).get("level"), 1)})
|
||
priorities = {"received": 0, "ready_to_reward": 0, "unlocked": 1, "offered": 1, "blocked": 2, "locked": 3, "finished": 4}
|
||
rows.sort(key=lambda row: (priorities.get(row["state"], 5), row.get("task_type", 999), row["task_type_id"]))
|
||
return rows
|
||
|
||
def plan(self, snapshot, policy, ranch_policy, *, local_progress=None):
|
||
if not policy.enabled:
|
||
return []
|
||
self._merge_local_progress(snapshot, local_progress)
|
||
scope, account = self._account(snapshot)
|
||
self.reconcile(snapshot)
|
||
if account["pending"]:
|
||
reason = "存在未确认请求,禁止自动重发:" + account["pending"].get("reason", "进行中")
|
||
return [self._intent(scope, {}, 0, {}, "progression_blocked", reason, policy, block_reason=reason)]
|
||
active, unlocked, finished = self._tasks(snapshot, account)
|
||
blocked = []
|
||
candidates = [(key, task, False) for key, task in active.items() if key not in finished]
|
||
candidates += [(key, {"id": 0, "typeId": key}, True) for key in unlocked - set(active) - finished]
|
||
candidates.sort(key=lambda item: (item[2], (self.data.task(item[0]) or {}).get("type", 999), item[0]))
|
||
for key, task, is_unlocked in candidates:
|
||
info = self.data.task(key)
|
||
if not info:
|
||
reason = "任务配置缺失,需重新核对资源版本:" + key
|
||
blocked.append(self._intent(scope, task, 0, {}, "progression_blocked", reason, policy, block_reason=reason))
|
||
continue
|
||
if info.get("type") == 4 and policy.commissions:
|
||
reason = "委托由独立 QuestPolicy 调度"
|
||
blocked.append(self._intent(scope, task, 0, {}, "progression_blocked", reason, policy, block_reason=reason))
|
||
if not self._selected(info, policy):
|
||
continue
|
||
intent = self._next(snapshot, policy, ranch_policy, scope, account, task, info, is_unlocked)
|
||
if not intent.blocked:
|
||
intents = self._expand_farming(snapshot, intent, task, info, policy, ranch_policy, account)
|
||
for candidate in intents:
|
||
self._issued[candidate.token] = candidate.to_dict()
|
||
return intents
|
||
blocked.append(intent)
|
||
update = self._chain_update(snapshot, policy, scope, account)
|
||
if update:
|
||
if update.token in account["applied"]:
|
||
reason = "任务补链已确认,等待权威任务列表更新,禁止重复提交"
|
||
return [self._intent(scope, {}, 0, {}, "progression_blocked", reason, policy, block_reason=reason)]
|
||
self._issued[update.token] = update.to_dict()
|
||
return [update]
|
||
return blocked
|
||
|
||
def _expand_farming(self, snapshot, intent, task, info, policy, ranch, account):
|
||
if not intent.farming_target:
|
||
return [intent]
|
||
number = intent.source_step_number
|
||
steps = info.get("steps") or []
|
||
if not 1 <= number <= len(steps):
|
||
return [intent]
|
||
effective = dict(task)
|
||
if number != _integer(task.get("curStep")):
|
||
effective["stepValue"] = self._record(task, account)["next_value"]
|
||
effective["curStep"] = number
|
||
return self.farming_intents(snapshot, steps[number - 1], effective, policy, ranch) or [intent]
|
||
|
||
def mark_started(self, snapshot, intent):
|
||
scope, account = self._account(snapshot)
|
||
if intent.account_key != scope or self._issued.get(intent.token) != intent.to_dict() or intent.blocked:
|
||
raise ValueError("Intent was not issued for this account")
|
||
if intent.kind not in WIRE_KINDS:
|
||
return
|
||
if account["pending"] and account["pending"].get("token") != intent.token:
|
||
raise ValueError("Another progression request is unresolved")
|
||
account["pending"] = {"token": intent.token, "intent": intent.to_dict(), "reason": "请求进行中", "uncertain": False,
|
||
"started_at": int(snapshot.now)}
|
||
|
||
def mark_uncertain(self, snapshot, intent, reason="请求结果不明,需重新同步"):
|
||
self.mark_started(snapshot, intent)
|
||
_, account = self._account(snapshot)
|
||
account["pending"].update(reason=str(reason), uncertain=True)
|
||
|
||
def acknowledge(self, snapshot, intent, response=None, *, _from_snapshot=False):
|
||
"""Apply a confirmed wire response or an executed logical local action.
|
||
|
||
Does not mutate snapshot. Returns False for a duplicate acknowledgement.
|
||
Battle intent responses MUST be successful taskCompleteStep settlements.
|
||
"""
|
||
scope, account = self._account(snapshot)
|
||
if intent.account_key != scope:
|
||
raise ValueError("Intent belongs to a different account")
|
||
if intent.token in account["applied"]:
|
||
return False
|
||
if self._issued.get(intent.token) != intent.to_dict() or intent.blocked:
|
||
raise ValueError("Unknown, changed, or blocked progression intent")
|
||
if intent.kind in WIRE_KINDS and not isinstance(response, dict):
|
||
raise ValueError("A confirmed server response is required")
|
||
if _from_snapshot and intent.kind in ("progression_step", "progression_battle"):
|
||
if not any(_integer(task.get("id")) == intent.task_id and str(task.get("typeId")) == intent.task_type_id
|
||
and _integer(task.get("curStep")) > intent.step_number for task in snapshot.raw.get("currentTasks") or []):
|
||
raise ValueError("Fresh authoritative step advancement is required")
|
||
if isinstance(response, dict) and response.get("resCode", 0) not in (0, "0"):
|
||
raise ValueError("Cannot acknowledge a rejected server request")
|
||
if intent.kind == "progression_battle" and not _from_snapshot and not any(key in response for key in ("taskStepValue", "reward", "stageReward", "costTi", "monsterExpInfos")):
|
||
raise ValueError("Battle requires the confirmed taskCompleteStep settlement, not a start reply or local result")
|
||
if account["pending"] and account["pending"].get("token") != intent.token:
|
||
raise ValueError("Another progression request is unresolved")
|
||
key, number = f"{intent.task_id}:{intent.task_type_id}", intent.step_number
|
||
record = account["tasks"].get(key)
|
||
if intent.kind == "progression_navigate":
|
||
account["position"] = intent.position
|
||
elif intent.kind == "progression_dialogue":
|
||
if not record:
|
||
raise ValueError("Dialogue task instance disappeared")
|
||
collection = "after" if intent.phase == "after" else "before"
|
||
if collection == "after" and number not in record["acknowledged"]:
|
||
raise ValueError("After-story requires server step acknowledgement")
|
||
record[collection].append(number)
|
||
elif intent.kind in ("progression_step", "progression_battle"):
|
||
if not record or record["cursor"] != number:
|
||
raise ValueError("Step acknowledgement no longer matches the client cursor")
|
||
record["acknowledged"].append(number)
|
||
record["next_value"] = response.get("taskStepValue")
|
||
if intent.kind == "progression_battle" and not _from_snapshot:
|
||
account["losses"] = 0
|
||
account["last_loss_at"] = None
|
||
if intent.battle_kind == "passStage":
|
||
# Exact TaskStartPanel.step2WinHandler -> passLocalStage
|
||
# effects, only after the real step settlement succeeded.
|
||
stage_key = f"{intent.stage_id}:{intent.difficulty}"
|
||
if stage_key not in account["stage_passes"]:
|
||
account["stage_passes"].append(stage_key)
|
||
stage = self.data.stage(intent.stage_id) or {}
|
||
if not stage.get("special") and intent.difficulty < 3:
|
||
next_level = f"{intent.stage_id}:{intent.difficulty + 1}"
|
||
if next_level not in account["stage_levels"]:
|
||
account["stage_levels"].append(next_level)
|
||
for stage_id in _values(response.get("unlockStage")):
|
||
self._unlock_local_stage(account, stage_id)
|
||
for stage_id in _values(response.get("lockStage")):
|
||
stage_id = str(stage_id)
|
||
if stage_id not in account["stage_locks"]:
|
||
account["stage_locks"].append(stage_id)
|
||
account["stage_unlocks"] = [key for key in account["stage_unlocks"] if key != stage_id]
|
||
account["stage_levels"] = [key for key in account["stage_levels"] if not key.startswith(stage_id + ":")]
|
||
elif intent.kind == "progression_local_step":
|
||
step = self.data.task(intent.task_type_id)["steps"][number - 1]
|
||
if not record or number not in record["acknowledged"]:
|
||
raise ValueError("Local completion requires confirmed server step completion")
|
||
if step.get("afterStory") and number not in record["after"]:
|
||
raise ValueError("After-story has not completed")
|
||
record["cursor"] = number + 1
|
||
for stage in _values(step.get("unlockStages")):
|
||
self._unlock_local_stage(account, stage)
|
||
elif intent.kind in ("progression_accept", "progression_loop_accept"):
|
||
task = response.get("task")
|
||
if (not isinstance(task, dict) or _integer(task.get("id")) <= 0 or str(task.get("typeId")) != intent.task_type_id
|
||
or intent.kind == "progression_loop_accept" and _integer(task.get("curStep")) < 1):
|
||
self.mark_uncertain(snapshot, intent, "接取成功回包缺少有效任务实例,需重新同步")
|
||
return False
|
||
task = {key: deepcopy(task[key]) for key in ("id", "typeId", "curStep", "stepValue") if key in task}
|
||
task.setdefault("curStep", 1) # receiveTaskHandler sets step=0.
|
||
account["received"][intent.task_type_id] = task
|
||
account["tasks"].pop(f"{task['id']}:{intent.task_type_id}", None)
|
||
if intent.kind == "progression_loop_accept":
|
||
today, _, remaining, offers = self._loop_view(snapshot, account)
|
||
loop = account["commissions"]
|
||
loop.update(day=today, remaining=remaining if _from_snapshot else max(0, remaining - 1), offers=offers)
|
||
accepted = f"{intent.payload['city']}:{intent.task_type_id}"
|
||
if accepted not in loop["accepted"]:
|
||
loop["accepted"].append(accepted)
|
||
loop["finished"] = [key for key in loop["finished"] if key != intent.task_type_id]
|
||
loop["expired_ids"] = [key for key in loop["expired_ids"] if key != str(task["id"])]
|
||
elif intent.kind == "progression_loop_reset":
|
||
offers = response.get("loopTask")
|
||
if not isinstance(offers, dict) and offers != []:
|
||
self.mark_uncertain(snapshot, intent, "委托刷新回包缺少候选列表,需重新同步")
|
||
return False
|
||
loop = account["commissions"]
|
||
for task in list(account["received"].values()) + list(snapshot.raw.get("currentTasks") or []):
|
||
if (self.data.task(task.get("typeId")) or {}).get("type") == 4:
|
||
task_id = str(task.get("id"))
|
||
if task_id not in loop["expired_ids"]:
|
||
loop["expired_ids"].append(task_id)
|
||
account["received"] = {key: task for key, task in account["received"].items() if (self.data.task(key) or {}).get("type") != 4}
|
||
quota = _integer(self.data.game_setting.get("loopTaskMaxNum", self.catalog.data.get("game_setting", {}).get("loopTaskMaxNum", 0)))
|
||
if _from_snapshot:
|
||
quota = _integer((snapshot.raw.get("history") or {}).get("loopTaskNum"))
|
||
loop.update(day=_integer(intent.phase, self._loop_day(snapshot, snapshot.now - 10)), remaining=quota,
|
||
offers=deepcopy(offers) if isinstance(offers, dict) else {}, accepted=[], finished=[])
|
||
elif intent.kind in ("progression_complete", "progression_update"):
|
||
task_field = "nextTasks" if intent.kind == "progression_complete" else "receiveTasks"
|
||
for task in _values(response.get(task_field)):
|
||
if isinstance(task, dict) and task.get("typeId") is not None and _integer(task.get("id")) > 0 and _integer(task.get("curStep")) > 0:
|
||
account["received"][str(task["typeId"])] = {key: deepcopy(task[key]) for key in ("id", "typeId", "curStep", "stepValue") if key in task}
|
||
record_key = f"{_integer(task['id'])}:{task['typeId']}"
|
||
if account["tasks"].get(record_key, {}).get("removed"):
|
||
del account["tasks"][record_key]
|
||
if intent.kind == "progression_update":
|
||
removed = set(intent.payload.get("removeTasks") or [])
|
||
for task in list(account["received"].values()) + list(snapshot.raw.get("currentTasks") or []):
|
||
if _integer(task.get("id")) in removed:
|
||
type_id = str(task.get("typeId"))
|
||
account["tasks"].setdefault(f"{_integer(task['id'])}:{type_id}", {})["removed"] = True
|
||
if _integer((account["received"].get(type_id) or {}).get("id")) == _integer(task["id"]):
|
||
account["received"].pop(type_id, None)
|
||
for type_id in _values(response.get("unlockTasks")):
|
||
if isinstance(type_id, (str, int)) and str(type_id) not in account["unlocked"]:
|
||
account["unlocked"].append(str(type_id))
|
||
if intent.kind == "progression_complete":
|
||
if (self.data.task(intent.task_type_id) or {}).get("type") == 4:
|
||
loop = account["commissions"]
|
||
loop["day"] = self._loop_day(snapshot, snapshot.now - 10)
|
||
loop["finished"].append(intent.task_type_id)
|
||
loop["expired_ids"].append(str(intent.task_id))
|
||
else:
|
||
account["finished"].append(intent.task_type_id)
|
||
account["received"].pop(intent.task_type_id, None)
|
||
for stage in _values(response.get("unlockStages")):
|
||
self._unlock_local_stage(account, stage)
|
||
for city_id, city in (self.data.game_setting.get("cityInfo") or {}).items():
|
||
if city.get("openTask") == intent.task_type_id and str(city_id) not in account["city_unlocks"]:
|
||
account["city_unlocks"].append(str(city_id))
|
||
else:
|
||
raise ValueError("This intent is not a task progression action")
|
||
account["applied"].append(intent.token)
|
||
if account["pending"] and account["pending"]["token"] == intent.token:
|
||
account["pending"] = None
|
||
self._issued.pop(intent.token, None)
|
||
return True
|
||
|
||
def reconcile(self, snapshot):
|
||
"""Only fresh authoritative task state can resolve an ambiguous send."""
|
||
scope, account = self._account(snapshot)
|
||
history = snapshot.raw.get("history") or {}
|
||
# Retire local source effects once the authoritative history includes
|
||
# them, so a later server lock cannot be overridden by an old overlay.
|
||
for field, name in (("passStage", "stage_passes"), ("unlockStage", "stage_levels")):
|
||
account[name] = [key for key in account[name] if not stage_has_level(history, field, *key.rsplit(":", 1))]
|
||
account["stage_unlocks"] = [key for key in account["stage_unlocks"] if not stage_has_level(history, "unlockStage", key, 1)]
|
||
account["stage_locks"] = [key for key in account["stage_locks"]
|
||
if any(stage_has_level(history, "unlockStage", key, level) for level in (1, 2, 3))]
|
||
pending = account["pending"]
|
||
if not pending or not pending.get("uncertain"):
|
||
return
|
||
intent = ProgressionIntent(**pending["intent"])
|
||
active = {str(task["typeId"]): task for task in snapshot.raw.get("currentTasks") or [] if isinstance(task, dict) and "typeId" in task}
|
||
task = active.get(intent.task_type_id)
|
||
if (intent.kind in ("progression_step", "progression_battle") and task
|
||
and _integer(task.get("id")) == intent.task_id and _integer(task.get("curStep")) > intent.step_number):
|
||
record = account["tasks"].get(f"{intent.task_id}:{intent.task_type_id}")
|
||
if record:
|
||
record["cursor"] = intent.step_number
|
||
self._issued[intent.token] = intent.to_dict()
|
||
self.acknowledge(snapshot, intent, {}, _from_snapshot=True)
|
||
elif intent.kind == "progression_complete" and not task and intent.task_type_id in _flags((snapshot.raw.get("history") or {}).get("passTask")):
|
||
self._issued[intent.token] = intent.to_dict()
|
||
self.acknowledge(snapshot, intent, {})
|
||
elif intent.kind in ("progression_accept", "progression_loop_accept") and task and _integer(task.get("id")) > 0:
|
||
self._issued[intent.token] = intent.to_dict()
|
||
self.acknowledge(snapshot, intent, {"task": task}, _from_snapshot=True)
|
||
elif intent.kind == "progression_loop_reset":
|
||
timestamp = seconds(history.get("loopTaskTime"))
|
||
if timestamp >= pending.get("started_at", float("inf")) and self._loop_day(snapshot, timestamp) == _integer(intent.phase, -1):
|
||
self._issued[intent.token] = intent.to_dict()
|
||
self.acknowledge(snapshot, intent, {"loopTask": history.get("loopTask")}, _from_snapshot=True)
|
||
elif intent.kind == "progression_update":
|
||
unlocked = _flags(history.get("unlockTask"))
|
||
finished = _flags(history.get("passTask"))
|
||
current_ids = {_integer(task.get("id")) for task in active.values()}
|
||
payload = intent.payload
|
||
if (all(str(entry["taskTypeId"]) in active or str(entry["taskTypeId"]) in finished for entry in payload["receiveTasks"])
|
||
and all(str(entry["taskTypeId"]) in unlocked | set(active) | finished for entry in payload["unlockTasks"])
|
||
and all(task_id not in current_ids for task_id in payload["removeTasks"])):
|
||
self._issued[intent.token] = intent.to_dict()
|
||
self.acknowledge(snapshot, intent, {})
|
||
|
||
def battle_lost(self, snapshot, intent):
|
||
"""A definite failed battle does not acknowledge any task step."""
|
||
scope, account = self._account(snapshot)
|
||
if intent.account_key != scope or intent.kind != "progression_battle":
|
||
raise ValueError("Battle intent/account mismatch")
|
||
account["losses"] += 1
|
||
account["last_loss_at"] = snapshot.now
|
||
if account["pending"] and account["pending"]["token"] == intent.token:
|
||
account["pending"] = None
|
||
|
||
def export_state(self):
|
||
# State has hashed account keys and minimal response task descriptors;
|
||
# no session material or raw response bodies ever enter this mapping.
|
||
return {"version": 1, "accounts": deepcopy(self._accounts)}
|
||
|
||
def pending(self, snapshot):
|
||
"""Minimal unresolved-send descriptor for an account's runtime guard."""
|
||
_, account = self._account(snapshot)
|
||
return deepcopy(account["pending"])
|
||
|
||
def state_signature(self, snapshot):
|
||
"""Include this in UI/engine cache keys when authoritative steps lag."""
|
||
_, account = self._account(snapshot)
|
||
return hashlib.sha256(json.dumps(account, sort_keys=True, ensure_ascii=True).encode()).hexdigest()
|
||
|
||
def restore_state(self, state):
|
||
if not isinstance(state, dict) or state.get("version") != 1 or not isinstance(state.get("accounts"), dict):
|
||
raise ValueError("Unsupported local progression state")
|
||
# Round trip also rejects objects that cannot safely be serialized.
|
||
restored = json.loads(json.dumps(state["accounts"], allow_nan=False))
|
||
for scope, account in restored.items():
|
||
if not re.fullmatch(r"[0-9a-f]{64}", scope) or not isinstance(account, dict):
|
||
raise ValueError("Invalid local progression account")
|
||
account.setdefault("last_loss_at", None)
|
||
for key in ("stage_passes", "stage_levels", "stage_locks"):
|
||
account.setdefault(key, [])
|
||
account.setdefault("commissions", {"day": None, "remaining": None, "offers": None, "accepted": [], "expired_ids": [], "finished": []})
|
||
required = {"position", "tasks", "received", "unlocked", "finished", "stage_unlocks", "city_unlocks", "pending", "losses", "applied", "stage_passes", "stage_levels", "stage_locks", "commissions"}
|
||
required.add("last_loss_at")
|
||
if set(account) != required or not isinstance(account["tasks"], dict) or not isinstance(account["received"], dict):
|
||
raise ValueError("Invalid local progression state fields")
|
||
if account["pending"]:
|
||
account["pending"]["uncertain"] = True
|
||
account["pending"]["reason"] = "上次进程请求尚未核对,禁止重发"
|
||
self._accounts = restored
|