diff --git a/backend/core/accounts.py b/backend/core/accounts.py
index f82c414..d7d3715 100644
--- a/backend/core/accounts.py
+++ b/backend/core/accounts.py
@@ -76,6 +76,9 @@ def list_accounts():
# 存下来就不用每次挂机都问一遍——这是唯一必须问用户的字段,
# 猜错的表现是切号死循环(MAA 找不到账号名,重试到超时)。
'maaAccountName': _dict(snap.get('maa')).get('accountName') or '',
+ # 切号名的来源:manual=用户手填过(以他为准)/ profile=跟着配置文件走
+ # (读那份档案 StartUp 的 AccountName)。规则在 acctbind.py。
+ 'maaAccountNameFrom': _dict(snap.get('maa')).get('accountNameFrom') or '',
'maaDir': _dict(snap.get('maa')).get('dir') or '',
'syncedAt': _dict(snap.get('sync')).get('syncedAt'),
# 关卡进度摘要(主线还差几关、活动几个区、剿灭几张没满);
diff --git a/backend/core/acctbind.py b/backend/core/acctbind.py
new file mode 100644
index 0000000..8c7c50d
--- /dev/null
+++ b/backend/core/acctbind.py
@@ -0,0 +1,89 @@
+# -*- coding: utf-8 -*-
+r"""账号 ↔ MAA 切号名(AccountName)的解析与绑定
+
+为什么单独一个模块
+------------------
+「这个账号跑 StartUp 时写哪个切号名」有三个调用方:助手建方案(agent._roster)、
+单个 skill 唤醒(skills.skills_wakeup)、多账号编排(multiacct.candidates)。
+2026-11-22 之前规则是「唯一来源 = 账号自己存的 maa.accountName,绝不读用户的
+MAA 配置」——理由是 agent 跑的是临时配置,不碰用户的 gui.new.json。
+
+用户随后提了更实际的要求:**设置里选了配置文件,就按那份档案的账号名来**
+(他已经在 MAA 里配过一次,不该再手抄一遍)。所以现在的规则是:
+
+1. ``maa.profile`` 选了档案、且没被手动改过 → 读该档案 StartUp 的 AccountName
+2. 否则用账号里存的 ``maa.accountName``(手填的 / 上次对话里报的)
+3. 都没有 → 空串,调用方去问用户(官服问后 4 位)
+
+**只读,绝不写回用户的 MAA 配置**:档案是用户的,程序只在 ``maa.profile``
+这一格引用它的名字;切换 / 改字段都走别的入口(写作业那套)。
+
+``accountNameFrom`` 是这里唯一的新状态:``manual`` = 用户手填过(听他的),
+``profile`` = 从配置档案带出来的(跟着档案走)。老账号没这个字段,按
+profile 处理——反正没选档案时也不会去读配置。
+"""
+from __future__ import annotations
+
+from . import accounts, acctname, maa
+
+
+def _maa_of(snap) -> dict:
+ m = (snap or {}).get('maa')
+ return m if isinstance(m, dict) else {}
+
+
+def channel_of(snap) -> str:
+ a = (snap or {}).get('account')
+ return str((a.get('channelName') if isinstance(a, dict) else '') or '')
+
+
+def profile_name(profile, maa_dir=None) -> str:
+ """档案里的 AccountName(读不到就给空串,绝不抛)"""
+ try:
+ return maa.profile_account_name(profile, maa_dir or None)
+ except Exception:
+ return ''
+
+
+def resolve(file, snap=None):
+ """账号跑 StartUp 时用的切号名 → ``(名字, 来源)``
+
+ 来源取值:``profile``(读自配置档案)/ ``saved``(账号里存的)/
+ ``''``(还没有,要问用户)。名字已经过 ``acctname.check`` 归一化,
+ 直接可以写进 StartUp 任务参数。
+ """
+ if snap is None:
+ try:
+ snap = accounts.get_account(file)
+ except Exception:
+ snap = {}
+ m = _maa_of(snap)
+ ch = channel_of(snap)
+ stored, _ = acctname.check(m.get('accountName') or '', ch)
+ stored = stored or ''
+ prof = str(m.get('profile') or '').strip()
+ src = str(m.get('accountNameFrom') or '').strip()
+ if prof and src != 'manual':
+ live, _ = acctname.check(profile_name(prof, m.get('dir') or None), ch)
+ if live:
+ return live, 'profile'
+ return stored, ('saved' if stored else '')
+
+
+def bind(file, raw, channel=None):
+ """把用户报的切号名存进账号(``maa.accountName``,标记为手填)
+
+ 返回 ``(归一化后的名字, 原因)``;名字不可用时不落盘,原因交给调用方
+ 原样告诉用户(官服填昵称这类)。
+ """
+ snap = {}
+ try:
+ snap = accounts.get_account(file)
+ except Exception:
+ pass
+ ch = channel if channel is not None else channel_of(snap)
+ nm, why = acctname.check(raw, ch)
+ if not nm:
+ return '', why
+ accounts.save_maa_meta(file, {'accountName': nm, 'accountNameFrom': 'manual'})
+ return nm, ''
diff --git a/backend/core/acctname.py b/backend/core/acctname.py
index 76d52ed..368b8a8 100644
--- a/backend/core/acctname.py
+++ b/backend/core/acctname.py
@@ -14,14 +14,16 @@
StartUp 任务的切号是拿 ``AccountName`` 去和登录界面 OCR 出来的那行做
**包含**比较,所以下面三种都认(官方说明原话):
-- 纯尾号 ``5505`` —— **首选**。问用户只要后四位,基本不会撞号
+- 纯尾号 ``5505`` —— 最省事,问用户就要后四位
+- 前 3 后 4 ``1573635`` / ``157 3635`` —— 2026-11-22 用户要求也收(他常记前三位)
- 部分掩码 ``23****45``
-- 完整掩码 ``181****5505``
+- 完整掩码 ``157****3635``
用户手里往往只有一个片段。**能补全的补成完整掩码,补不全的原样保留**,
别拿"格式不对"去卡他——格式错是我们的活,不是他的。
-对话里一律问「手机号后 4 位」,别让用户去拼 ``****``:拼错的是他,报错的是我们。
+对话里问「手机号后 4 位」就行;用户主动给「前 3 位 + 后 4 位」
+(``157****3635``)同样收下,别让他去数星号有几个:拼错的是他,报错的是我们。
"""
from __future__ import annotations
@@ -147,6 +149,7 @@ def check(nm, channel=None):
if not s:
return None, '没填'
if is_official_channel(channel) and not looks_official(s):
- return None, ('官服切号名要用手机号(给后 4 位就行,如 5505);'
- '「%s」不是手机号,像昵称,对不上官服账号列表' % raw)
+ return None, ('官服切号名要用手机号(后 4 位如 5505,或前 3 位 + 后 4 位如'
+ ' 157****3635);「%s」不是手机号,像昵称,对不上官服账号列表'
+ % raw)
return s, ''
diff --git a/backend/core/agent.py b/backend/core/agent.py
index 3d1c483..3fb49f1 100644
--- a/backend/core/agent.py
+++ b/backend/core/agent.py
@@ -32,7 +32,7 @@
import urllib.request
import uuid
-from . import (accounts, asstlog, copilot, maa, multiacct, progress,
+from . import (accounts, acctbind, asstlog, copilot, maa, multiacct, progress,
resources, settings, skills, tasks, vault, watch)
MAX_TURNS = 12
@@ -353,13 +353,24 @@ def _tool(name, desc, props=None, required=None):
'description': '抄作业时是否自动编队,默认 true'},
'names': {'type': 'object',
'description': '{账号文件名: 切号名}。官服填手机号后 4 位'
- '(如 5505),B 服填游戏内用户名。'
+ '(如 5505),前 3 位 + 后 4 位也行'
+ '(如 157****3635);B 服填游戏内用户名。'
'缺的时候要问用户,**原样传**,别自己拼格式'},
'limitStages': {'type': 'integer', 'description': '最多挂几关,默认 8'},
'profile': {'type': 'string',
'description': '档案名后缀,比如「活动-时间啊向前」。不给就自动起名'},
'start': {'type': 'boolean', 'description': '写完是否立刻启动,默认 true'}},
[]),
+ _tool('set_account_name',
+ '**配置账号登录尾号**:用户说出某个账号的手机号尾号(后 4 位,或'
+ '「前 3 位 + 后 4 位」如 157****3635)时,把它存进那个账号的设置'
+ '(设置 → MAA 路径 → 切号名),下次挂机、切号都不用再问。'
+ '只改本程序自己的账号配置,**不会动 MAA 的任何字段**。'
+ '用户只是顺口报了个尾号、还没说要挂什么时也可以先存下来。',
+ {'account': _ACC,
+ 'accountName': {'type': 'string',
+ 'description': '用户给的尾号/切号名,**原样传**,别自己拼格式'}},
+ ['accountName']),
_tool('list_profiles',
'看 MAA 里现在有哪些配置档案、当前用的是哪个、各自挂了几个作业。'
'用户问「现在跑的是哪个号」时用它。'),
@@ -374,7 +385,8 @@ def _tool(name, desc, props=None, required=None):
# ---- 挂关 skill 化(2026-11-17):唤醒 / 导航 / 剧情 / 战斗 / 签到 / 周目 ----
_tool('skill_wakeup',
'唤醒游戏到主界面(游戏没开/停在登录页/START 页时用)。'
- '可选 accountName 按切号名换账号(官服=手机号后 4 位,如 5505)。'
+ '可选 accountName 按切号名换账号(官服=手机号后 4 位,如 5505;'
+ '也可以给前 3 位 + 后 4 位,如 157****3635)。'
'返回 taskId,后台跑。',
{'account': _ACC,
'accountName': {'type': 'string',
@@ -490,7 +502,7 @@ def _tool(name, desc, props=None, required=None):
'description': '简写模式的专精目标,如 [0,3,0]'},
'account': _ACC,
'accountName': {'type': 'string',
- 'description': '切号名(官服=手机号后 4 位)。'
+ 'description': '切号名(官服=手机号后 4 位,或前 3 位 + 后 4 位)。'
'账号已绑定尾号(list_accounts 的 '
'accountName 非空)时不用传,程序会自己用'},
'switchAccount': {'type': 'boolean',
@@ -519,7 +531,7 @@ def _tool(name, desc, props=None, required=None):
'description': '默认 true(先唤醒到主界面);游戏已经开着'
'并停在关卡列表时传 false'},
'accountName': {'type': 'string',
- 'description': '切号名(官服=手机号后 4 位)'}},
+ 'description': '切号名(官服=手机号后 4 位,或前 3 位 + 后 4 位)'}},
['stage']),
_tool('skill_tool',
'**MAA 小工具(牛杂)**:跑 MAA「小工具 → 牛杂」里的功能。会自动导航到'
@@ -593,6 +605,14 @@ def _tool_list_accounts(args):
for c in accounts.list_accounts():
if (c.get('game') or 'arknights') != 'arknights':
continue
+ # 绑了配置文件的账号:列表里的切号名要用生效值(档案里的那个),
+ # 否则用户在设置里选过档案、模型还是看到空值,照样重复问一遍
+ acc_name = c.get('maaAccountName') or ''
+ if c.get('maaProfile'):
+ try:
+ acc_name, _src = acctbind.resolve(c['file'])
+ except Exception:
+ pass
p = c.get('progress') or {}
out.append({
# 账号列表给的是 nickName / alias / channelName,没有 name / channel
@@ -606,7 +626,7 @@ def _tool_list_accounts(args):
# 已绑定的切号名(手机尾号)必须给出来:用户 2026-11-18 报
# 「设置里配过尾号,助手每次还问」——列表里带出来,模型就不用
# 再开口问;只有这里是空的才轮到问用户。
- 'accountName': c.get('maaAccountName') or '',
+ 'accountName': acc_name,
# 字段名对齐 progress.summary():mainRemaining / activityLeft /
# activityStages 才是真名(曾经写成 mainLeft / activityZones,
# 结果每个账号都返回 null,模型只能挨个再问一遍 account_progress)
@@ -618,9 +638,56 @@ def _tool_list_accounts(args):
'activityStages': p.get('activityStages'),
})
return {'accounts': out, 'count': len(out),
- 'hint': 'accountName 就是已绑定的切号名(手机尾号):**非空的直接按它跑,'
- '不要再问用户**;只有为空的账号才问「手机号后 4 位」'
- '(B 服问游戏内用户名)'}
+ 'hint': 'accountName 就是已绑定的切号名(手机号后 4 位 / 前 3 位 + 后 4 位)'
+ ':**非空的直接按它跑,不要再问用户**;只有为空的账号才问'
+ '「手机号后 4 位」(B 服问游戏内用户名)。用户报了尾号就顺手用'
+ ' set_account_name 存下来,下次不用再问'}
+
+
+def _tool_set_account_name(args):
+ """配置账号登录尾号:把用户报的尾号存进对应账号的切号名
+
+ 只写本程序自己的账号 json(``maa.accountName`` + ``accountNameFrom=manual``),
+ MAA 的配置文件一个字段都不动。存下来之后 list_accounts 就能看到,
+ 下次挂机 / 切号不用再问。
+ """
+ raw = str(args.get('accountName') or args.get('tail') or '').strip()
+ if not raw:
+ return {'error': '没给尾号(后 4 位,或前 3 位 + 后 4 位)'}
+ rows = [c for c in accounts.list_accounts()
+ if (c.get('game') or 'arknights') == 'arknights']
+ if not rows:
+ return {'error': '左侧还没有明日方舟账号'}
+ want = str(args.get('account') or '').strip()
+ file = ''
+ if want:
+ for c in rows:
+ names = (c['file'], c.get('nickName') or '', c.get('alias') or '')
+ if want in names or want in (c.get('nickName') or ''):
+ file = c['file']
+ break
+ if not file:
+ return {'error': '找不到账号:%s' % want,
+ 'accounts': [{'file': c['file'], 'name': c.get('nickName')}
+ for c in rows],
+ 'hint': '按 list_accounts 的 file 或昵称再传一次'}
+ elif len(rows) == 1:
+ file = rows[0]['file']
+ else:
+ return {'need_info': 'account',
+ 'accounts': [{'file': c['file'], 'name': c.get('nickName')}
+ for c in rows],
+ 'note': '有多个账号,问用户这个尾号是哪个号的(按昵称确认)'}
+
+ nm, why = acctbind.bind(file, raw)
+ if not nm:
+ return {'error': why, 'hint': '官服要手机号(后 4 位,或前 3 位 + 后 4 位);'
+ 'B 服填游戏内用户名'}
+ row = next((c for c in rows if c['file'] == file), {})
+ return {'ok': True, 'account': file, 'name': row.get('nickName') or file,
+ 'accountName': nm,
+ 'note': '已存进「设置 → MAA 路径 → %s 的切号名」,下次挂机直接用;'
+ '没改 MAA 里任何配置' % (row.get('nickName') or file)}
def _tool_list_activities(args):
@@ -719,7 +786,8 @@ def _tool_op_detail(args):
opers = copilot.detail_opers(content, owned)
lack, borrow = [], []
for o in opers:
- if o.get('owned') is False:
+ # 命中替换规则(sub,#92)的不算缺:写入 MAA 时会被练度等价的替补顶掉
+ if o.get('owned') is False and not o.get('sub'):
borrow.append(o.get('name'))
return {
'id': int(cid),
@@ -727,9 +795,10 @@ def _tool_op_detail(args):
'stage': content.get('stage_name') or '',
'opers': [{'name': o.get('name'), 'owned': o.get('owned'),
'ok': o.get('ok'), 'elite': o.get('elite'),
- 'level': o.get('level')} for o in opers],
+ 'level': o.get('level'), 'sub': o.get('sub')} for o in opers],
'notOwned': borrow,
- 'note': 'owned=false 是要借的人;ok=false 是练度不够',
+ 'note': 'owned=false 是要借的人;ok=false 是练度不够;'
+ 'sub 有值 = 该干员写入 MAA 时会被替换(如黍1顶塞1,#92)',
}
@@ -871,7 +940,8 @@ def _tool_add_stages(args, session=None):
return blocked
tid = maa.start_apply(items, profile=None, mode='replace',
auto_start=start,
- maa_dir=(accounts.get_account(acc).get('maa') or {}).get('dir') or None)
+ maa_dir=(accounts.get_account(acc).get('maa') or {}).get('dir') or None,
+ account=acc) # 带上账号:写盘时做干员替换(#92)
return {'started': True, 'taskId': tid, 'count': len(items),
'skipped': skipped, 'note': '已提交写入 MAA,不要在这里等它跑完'}
@@ -950,15 +1020,14 @@ def _check_account_name(nm, channel):
def _roster(want_files, names, maa_dir):
"""把「哪些账号 + 各自的切号名」理出来
- 切号名的来源,只有两个可信的:
+ 切号名的来源(规则只有一份,在 ``acctbind.resolve``):
1. 用户这次显式给的 ``names``(还会回写账号文件,下次不用再问)
- 2. 账号文件里存过的 ``maa.accountName``(上次给的 / 设置页填的)
+ 2. 账号绑的配置文件里「开始唤醒」的 AccountName(2026-11-22 用户要求:
+ 他在 MAA 里配过一次,就别再让他抄一遍)
+ 3. 账号文件里存过的 ``maa.accountName``(手填的 / 上次对话里报的)
- **不从用户的 MAA 配置档案里猜**(2026-11-18 用户口径:agent 模式不碰
- 用户的 MAA 配置):以前会拿 ``maa.profile`` 档案里的 AccountName、甚至
- 拿昵称去比对档案名来凑切号名——程序里两个游戏账号对 MAA 里五个尾号
- 档案,档案名和 AccountName 根本说不清谁是谁,错配的代价是官服传错号
- MAA 在账号列表里死找 4 分钟超时,整轮挂机死在「登录」。宁可多问一句。
+ **只读用户的 MAA 配置,绝不写回**;也绝不拿昵称去凑切号名——官服认的是
+ 手机号,传昵称 MAA 在账号列表里死找 4 分钟超时,整轮挂机死在「登录」。
"""
cands = multiacct.candidates()
if want_files:
@@ -971,9 +1040,9 @@ def _roster(want_files, names, maa_dir):
for c in cands:
raw = (names.get(c['file']) or names.get(c['name']) or '')
raw = str(raw).strip() if raw else ''
- # check() 自己会归一化(181 5505 / 181*5505 / 5505 都能吃下),
- # 这里别再提前 norm 一遍——曾经两层各自处理,第二层收到的已经是
- # 半成品,星号数量被改坏后又被严格正则判成非法。
+ # check() 自己会归一化(181 5505 / 181*5505 / 5505 / 157****3635
+ # 都能吃下),这里别再提前 norm 一遍——曾经两层各自处理,第二层收到
+ # 的已经是半成品,星号数量被改坏后又被严格正则判成非法。
nm, why = _check_account_name(raw, c.get('channel'))
source = 'user'
if not nm:
@@ -987,8 +1056,9 @@ def _roster(want_files, names, maa_dir):
pass
if not nm:
official = _is_official(c.get('channel'))
- ask = ('手机号后 4 位是多少?给这四位就行(如 5505)——'
- 'MAA 切号用的就是它,基本不会撞号'
+ ask = ('手机号后 4 位是多少?给这四位就行(如 5505),'
+ '前 3 位 + 后 4 位也行(如 157****3635)——'
+ 'MAA 切号用的就是它'
if official else '在 MAA 里切号用的名字是什么?(B 服填游戏内用户名)')
missing.append({
'file': c['file'], 'name': c['name'],
@@ -1002,7 +1072,9 @@ def _roster(want_files, names, maa_dir):
continue
if source == 'user':
try:
- accounts.save_maa_meta(c['file'], {'accountName': nm})
+ # 手填的值必须打上 manual:不然绑了配置文件的账号下次又被
+ # 档案里的旧号码盖回去,用户改了等于没改
+ acctbind.bind(c['file'], nm, c.get('channel'))
except Exception:
pass
rows.append({'file': c['file'], 'name': c['name'],
@@ -1386,6 +1458,7 @@ def _tool_skill_tool(args, session=None):
_HANDLERS = {
'list_accounts': _tool_list_accounts,
+ 'set_account_name': _tool_set_account_name,
'list_activities': _tool_list_activities,
'search_stages': _tool_search_stages,
'find_ops': _tool_find_ops,
@@ -1526,17 +1599,22 @@ def run_tool(name, args, session=None):
## 常见对话怎么做
**「帮我把所有账号挂上 TL-5」**
-1. list_accounts —— **先看 accountName(已绑定的手机尾号)**:非空的账号
+1. list_accounts —— **先看 accountName(已绑定的切号名)**:非空的账号
直接沿用,**绝对不要再问一遍**(用户 2026-11-18 报过这个:设置里配过
尾号,助手还在问)
2. build_run(accounts=[]、mode=copy、keyword=TL-5)
-3. 返回 need_info 时:**一次性把所有缺的账号列出来问**。官服只问
- 「手机号后 4 位」(如 5505),B 服问游戏内用户名。
- **不要让用户去拼 `181****5505`**——格式是程序的事。用户给全号、
- 带横线、星号多少、只给尾号,一律原样放进 names,程序会归一化。
+3. 返回 need_info 时:**一次性把所有缺的账号列出来问**。官服问
+ 「手机号后 4 位」(如 5505)——用户给「前 3 位 + 后 4 位」
+ (157****3635)、全号、带横线都行;B 服问游戏内用户名。
+ **不要让用户必须拼 `181****5505`**——格式是程序的事,给什么都能吃。
拿到后带 names 再调一次
4. 返回 need_confirm 时,把确认卡片上的内容用自己的话复述要点
+**「这个号尾号是 5505」/「官服号尾号 157****3635」**
+set_account_name(account 尽量给上,按昵称或 file 认)。存进设置之后
+list_accounts 的 accountName 就有值了,后面挂机不用再问。
+只改我们自己的账号配置,MAA 里一个字都不动。
+
**「清一下日常」/「帮我收菜」**
build_run(mode=daily,不用 keyword)。这就是一键长草。
@@ -1642,9 +1720,11 @@ def run_tool(name, args, session=None):
- skill_fight / skill_skip_story / skill_weekly / skill_train 同样要先确认再跑
(工具会自动摆确认卡)
- 多账号缺切号名时,明确说「这个信息森空岛拿不到,得你告诉我」;
- 官服只要**手机号后 4 位**(如 5505),不要要求用户拼星号。
+ 官服问**手机号后 4 位**(如 5505)就行,用户主动给「前 3 位 + 后 4 位」
+ (157****3635)也照收,不要要求他数星号。
**问之前先看 list_accounts 的 accountName**:非空就是已经绑好的,
- 直接用,别重复问(用户设置里配过的东西,助手再问一遍很烦)
+ 直接用,别重复问(用户设置里配过的东西,助手再问一遍很烦)。
+ 用户报出尾号后调 set_account_name 存进设置,下次不用再问。
- 多账号是**串行**的(一个模拟器同时只能登一个号),一个跑完自动切下一个
- **模拟器不用你操心**:每个 skill 开跑前会自动确认模拟器在不在、没开就替用户
启动(路径从 MAA 配置里读)。任务报「环境没准备好」时,把日志那句话原样转给
diff --git a/backend/core/api.py b/backend/core/api.py
index a30df4e..9a5cc6e 100644
--- a/backend/core/api.py
+++ b/backend/core/api.py
@@ -9,7 +9,8 @@
from . import (accounts, agent, appupdate, asstlog, copilot, gacha, garrison,
maa, maaplan, multiacct, operbox, packsync, paradox, resources,
- settings, signin, skills, sklogin, tasks, updater, version, watch)
+ scheduler, settings, signin, skills, sklogin, tasks, updater,
+ version, watch)
WEB = settings.static_dir()
@@ -156,10 +157,17 @@ def api_account_maa(_q, body):
patch['dir'] = settings._norm_dir(patch.get('dir') or '')
if patch['dir']:
settings.remember_maa_dir(patch['dir'])
+ if 'profile' in patch:
+ # 配置文件(MAA 的 Configuration):只记名字,**不读写用户的档案内容**。
+ # 切号名优先按这份档案里「开始唤醒」的 AccountName 来(acctbind.resolve)。
+ patch['profile'] = str(patch.get('profile') or '').strip()[:60]
+ if 'accountNameFrom' in patch:
+ v = str(patch.get('accountNameFrom') or '').strip().lower()
+ patch['accountNameFrom'] = v if v in ('manual', 'profile') else ''
if 'accountName' in patch:
# 切号名统一走 acctname:用户给「5505」「181 5505」「181****5505」
- # 都能吃下,官服填了昵称则当场拦下——这一格填错的代价是 MAA 在
- # 账号列表里死找、4 分钟超时后整轮挂机废掉。
+ # 「157****3635」都能吃下,官服填了昵称则当场拦下——这一格填错的
+ # 代价是 MAA 在账号列表里死找、4 分钟超时后整轮挂机废掉。
# 留空是合法状态(还没填 / 想清掉),不能当成「填错」拦下。
from . import acctname
raw = (patch.get('accountName') or '').strip()
@@ -170,6 +178,9 @@ def api_account_maa(_q, body):
if why:
raise ValueError('切号名不对:%s' % why)
patch['accountName'] = name
+ # 没明说来源的一律按手填:老调用方(CLI/脚本)给的值不能被
+ # 绑定的配置文件悄悄盖回去
+ patch.setdefault('accountNameFrom', 'manual')
else:
patch['accountName'] = ''
return {'maa': accounts.save_maa_meta(body['file'], patch)}
@@ -440,11 +451,20 @@ def api_skland_login_cancel(_q, _body):
def api_maa_probe(q, _body):
- """检测一个目录是不是 MAA 根目录(首次引导 / 设置里用)"""
+ """检测一个目录是不是 MAA / MAAEND 根目录(首次引导 / 设置里用)
+
+ kind=endfield 时按 MAAEND 的主程序名去找:终末地那套是另一个程序,
+ 主程序可能叫 MaaEnd.exe 或 mxu.exe(三月七脚本里两种都出现过)。这一步
+ 只是把路径先管起来,MAAEND 的任务链还没接。
+ """
d = (q.get('dir') or '').strip()
if not d:
raise ValueError('缺少目录参数')
- exe = os.path.join(d, 'MAA.exe')
+ kind = (q.get('kind') or 'arknights').strip().lower()
+ names = (['MaaEnd.exe', 'MAAEND.exe', 'mxu.exe', 'MAA.exe']
+ if kind == 'endfield' else ['MAA.exe'])
+ exe_name = next((n for n in names if os.path.isfile(os.path.join(d, n))), '')
+ exe = os.path.join(d, exe_name or names[0])
cfg_path = os.path.join(d, 'config', 'gui.new.json')
profiles = []
if os.path.isfile(cfg_path):
@@ -457,7 +477,8 @@ def api_maa_probe(q, _body):
ob = operbox.probe(d)
return {
'dir': d,
- 'exeExists': os.path.isfile(exe),
+ 'exeExists': bool(exe_name),
+ 'exeName': exe_name,
'configExists': os.path.isfile(cfg_path),
'profiles': profiles,
'operbox': ob['exists'],
@@ -491,7 +512,9 @@ def api_maa_apply(_q, body):
tid = maa.start_apply(items, profile=body.get('profile'),
mode=body.get('mode') or 'replace',
auto_start=body.get('autoStart', True),
- maa_dir=_maa_dir_for(body.get('file')))
+ maa_dir=_maa_dir_for(body.get('file')),
+ # 带上账号:写盘时按该账号练度做干员替换(#92)
+ account=str(body.get('file') or '').strip() or None)
return {'taskId': tid}
@@ -596,6 +619,12 @@ def api_garrison_download(_q, _body):
return garrison.start_download()
+def api_garrison_opts(_q, body):
+ """保存用户改过的速刷选项(按账号持久化,只存与 MAA 默认不同的键)"""
+ body = body or {}
+ return garrison.save_opts(_account_for(body.get('file')), body.get('options') or {})
+
+
def _garrison_options(q, body):
"""test/start/resume 共用:账号 + 前端提交的连接选项"""
body = body or {}
@@ -839,6 +868,22 @@ def api_export(_q, body):
return {'path': path, 'count': len(data)}
+def api_schedule_status(q, _body):
+ return scheduler.status(q.get('since') or 0)
+
+
+def api_schedule_save(_q, body):
+ return scheduler.save(body or {})
+
+
+def api_schedule_run(_q, body):
+ return scheduler.run_now((body or {}).get('id') or '')
+
+
+def api_schedule_stop(_q, _body):
+ return scheduler.stop_current()
+
+
ROUTES = {
'/api/bootstrap': bootstrap,
'/api/settings': api_settings,
@@ -890,6 +935,7 @@ def api_export(_q, body):
# 卫戍协议·策略刻章速刷
'/api/garrison/status': api_garrison_status,
'/api/garrison/download/start': api_garrison_download,
+ '/api/garrison/opts': api_garrison_opts,
'/api/garrison/test': api_garrison_test,
'/api/garrison/start': api_garrison_start,
'/api/garrison/resume': api_garrison_resume,
@@ -908,6 +954,11 @@ def api_export(_q, body):
'/api/maa/capabilities': api_maa_capabilities,
'/api/maa/profile': api_maa_profile,
'/api/maa/build': api_maa_build,
+ # 定时任务(时间触发 / 链式启动)
+ '/api/schedule/status': api_schedule_status,
+ '/api/schedule/save': api_schedule_save,
+ '/api/schedule/run': api_schedule_run,
+ '/api/schedule/stop': api_schedule_stop,
# 内置助手(M4)
'/api/agent/status': api_agent_status,
'/api/agent/config': api_agent_config,
diff --git a/backend/core/copilot.py b/backend/core/copilot.py
index 270d15b..04387df 100644
--- a/backend/core/copilot.py
+++ b/backend/core/copilot.py
@@ -172,6 +172,63 @@ def norm(name):
return re.sub(r'\s+', '', str(name or ''))
+# ---------------------------------------------------------------- 干员替换(#92)
+# 作业站的老作业经常点名塞雷娅这类开服六星,后来的号未必有、或练度跟不上。
+# 这里按「干员名 + 技能号」硬编码一批替换规则,分两档:
+# force 强制替换:账号里有替补且练度等价(按被替条目的要求判,见
+# sub_rule_for)就换——原干员有没有、达不达标都不看
+# fallback 可替:原干员缺卡或练度不足时才用替补顶上(目前没有条目)
+# 只做单向:反向(作业要黍1 用塞1 顶)不做,需要时加一条新规则即可。
+# 匹配侧(match_operation / detail_opers)与写 MAA 侧(apply_substitutions)
+# 都走 sub_rule_for 这同一个判定,两边口径不会漂。
+SUB_RULES = [
+ # 塞雷娅 1 技能(奶盾)由 黍 1 技能顶替:黍是上位替代,练度等价就强制换
+ {'from': '塞雷娅', 'from_skill': 1, 'to': '黍', 'to_skill': 1, 'kind': 'force'},
+]
+
+
+def sub_rule_for(op, owned_map, siblings=()):
+ """作业条目命中的替换规则(None = 不换)。
+
+ 命中条件:条目名 + 技能号与规则一致(MaaCore 里 skill 缺省是 0=不指定
+ 技能,所以只有显式写了技能号的条目才参与替换),且账号拥有替补、替补按
+ **这条目的要求**判定达标(等价练度)。force 档到此即命中;fallback 档还
+ 要原干员本身不可用(缺卡或练度不足)才顶上。
+
+ siblings 是同一容器(顶层 opers / 同一个 group)里已点名的干员:替补已经
+ 在里面就不换,否则会把一份作业写出两个同名条目(同位置重复部署)。
+ """
+ if not owned_map or not isinstance(op, dict):
+ return None
+ name = norm(op.get('name'))
+ try:
+ skill = int(op.get('skill') or 0)
+ except (TypeError, ValueError):
+ return None
+ named = {norm(s) for s in siblings if s}
+ owned = owned_map.get(name)
+ for r in SUB_RULES:
+ if name != norm(r['from']) or skill != r['from_skill']:
+ continue
+ if norm(r['to']) in named:
+ continue
+ sub = owned_map.get(norm(r['to']))
+ if not sub or not req_met(op, sub):
+ continue # 替补没有 / 练度不等价 → 不换
+ if r['kind'] == 'force':
+ return r
+ if not owned or not req_met(op, owned):
+ return r # 可替:原干员不可用才顶上
+ return None
+
+
+def sub_brief(rule):
+ """规则 → 前端标注用的短结构(名字 + 技能号),没命中返回 None"""
+ if not rule:
+ return None
+ return {'name': rule['to'], 'skill': rule['to_skill']}
+
+
# ---------------------------------------------------------------- 匹配
def progress_score(rarity, elite, level):
lv = MAX_LEVELS.get(int(rarity or 6), MAX_LEVELS[6])
@@ -251,10 +308,15 @@ def req_met(req, owned):
def _group_ok(group, owned_map):
- cands = [c for c in (group.get('opers') or []) if isinstance(c, dict)
- and norm(c.get('name')) in owned_map]
+ members = [c for c in (group.get('opers') or []) if isinstance(c, dict)]
+ named = [c.get('name') for c in members]
+ cands = [c for c in members if norm(c.get('name')) in owned_map]
if any(req_met(c, owned_map[norm(c.get('name'))]) for c in cands):
return 'ready'
+ # 组内没一个直接可用时再看替换:干员组「满足任一即可」,某个成员能被
+ # 替补顶上(见 SUB_RULES)整个组就算齐(#92)
+ if any(sub_rule_for(c, owned_map, named) for c in members):
+ return 'ready'
return 'train' if cands else 'missing'
@@ -276,12 +338,17 @@ def match_operation(content, owned_map):
six = 0
wsum = 0.0
+ # 替换规则按「同容器已点名」判重(替补已在阵容里就不换),顶层 opers 的
+ # siblings 是全部具名干员(#92)
+ top_names = [o.get('name') for o in opers]
+
for op in opers:
name = norm(op.get('name'))
owned = owned_map.get(name)
- wsum += op_weight(name)
- ok = bool(owned and req_met(op, owned))
- if not owned:
+ sub = sub_rule_for(op, owned_map, top_names)
+ wsum += op_weight(norm(sub['to'])) if sub else op_weight(name)
+ ok = bool(owned and req_met(op, owned)) or sub is not None
+ if not owned and not sub:
missing.append(op.get('name'))
elif not ok:
training.append(op.get('name'))
@@ -301,6 +368,9 @@ def match_operation(content, owned_map):
'req': req,
'skill': op.get('skill'),
'skillKnown': bool(owned.get('skillKnown', True)) if owned else None,
+ # 命中替换时 ok=True 但账号里未必有原干员;sub 给前端在详情里
+ # 标注「由黍1替换塞1」,列表卡片保持无感(#92)
+ 'sub': sub_brief(sub),
})
for g in groups:
@@ -878,23 +948,105 @@ def detail_opers(content, owned_map=None):
"""
idx = _char_index()
out = []
+ # 顶层 opers 整体当 siblings(与 match_operation 同口径):替补已被作者
+ # 自己写进阵容时不再替换(#92)
+ top_names = [o.get('name') for o in (content.get('opers') or [])
+ if isinstance(o, dict)]
for op in content.get('opers') or []:
o = dict(op)
stars = (idx.get(o.get('name') or '') or (6,))[0]
owned = (owned_map or {}).get(norm(o.get('name')))
known = bool(owned.get('skillKnown', True)) if owned else True
+ sub = sub_rule_for(op, owned_map, top_names) if owned_map else None
# 键名与搜索侧 _item 的 'req' 统一:两处各叫各的(req/requirements),
# 任一侧改名另一侧就静默显示「无特殊要求」(#63)
o['req'] = effective_req(op, stars, strict_skill=known)
o['skillKnown'] = known if owned else None
o['owned'] = bool(owned) if owned_map is not None else None
- o['ok'] = (bool(owned) and req_met(op, owned)) if owned_map is not None else None
+ o['ok'] = ((bool(owned) and req_met(op, owned)) or sub is not None) \
+ if owned_map is not None else None
o['elite'] = owned.get('elite') if owned else None
o['level'] = owned.get('level') if owned else None
+ o['sub'] = sub_brief(sub)
out.append(o)
return out
+def apply_substitutions(content, owned_map):
+ """写往 MAA 的作业按 SUB_RULES 换干员(#92),返回 (新 json, 说明列表)。
+
+ 没命中时不拷贝原样返回(预取缓存里那份绝不能被就地改掉——它是跨账号
+ 共用的);命中才深拷贝重写。条目的 requirements 原样保留:能换的前提就是
+ 替补按这套要求判过「等价练度」,MAA 编队时还会再核一遍。
+ """
+ hits = _sub_hits(content, owned_map)
+ if not hits:
+ return content, []
+ c = json.loads(json.dumps(content, ensure_ascii=False)) # 深拷贝,不动缓存
+ idx = _char_index()
+ notes = []
+ applied = {} # from 名 → 规则:actions 改名要与实际生效的替换一致
+
+ def rewrite(ops, siblings):
+ for op in ops:
+ r = sub_rule_for(op, owned_map, siblings) # 与 _sub_hits 同参同判
+ if not r:
+ continue
+ op['name'] = r['to']
+ op['skill'] = r['to_skill']
+ # 换完再过一遍 MAA 合法性修正(技能号与星级、精英下限),规则是
+ # 手工维护的,这条只是兜底
+ _fix_oper(op, idx, notes)
+ applied[norm(r['from'])] = r
+ notes.append('%s(技能%d)由 %s(技能%d)替换:账号练度等价'
+ % (r['from'], r['from_skill'], r['to'], r['to_skill']))
+
+ tops = [o for o in (c.get('opers') or []) if isinstance(o, dict)]
+ rewrite(tops, [o.get('name') for o in tops])
+ for g in (c.get('groups') or []):
+ if isinstance(g, dict):
+ members = [o for o in (g.get('opers') or []) if isinstance(o, dict)]
+ rewrite(members, [o.get('name') for o in members])
+ # actions 里按名字点被替干员的(没给坐标时 MaaCore 拿名字去场上找,
+ # BattleProcessTask 的 m_oper_in_group),roster 换了名字它也得跟着换,
+ # 否则「开技能」类的动作会指空。带着 role 的把 role 一并去掉——规则的
+ # 替补未必同职业,名字才是可靠键
+ for a in (c.get('actions') or []):
+ if not isinstance(a, dict):
+ continue
+ r = applied.get(norm(a.get('name')))
+ if r:
+ a['name'] = r['to']
+ a.pop('role', None)
+ return c, notes
+
+
+def _sub_hits(content, owned_map):
+ """content 里有没有条目命中替换规则(顶层 opers 与干员组分开算 siblings)"""
+ hits = []
+ tops = [o for o in (content.get('opers') or []) if isinstance(o, dict)]
+ top_names = [o.get('name') for o in tops]
+ hits += [op for op in tops if sub_rule_for(op, owned_map, top_names)]
+ for g in (content.get('groups') or []):
+ if not isinstance(g, dict):
+ continue
+ members = [o for o in (g.get('opers') or []) if isinstance(o, dict)]
+ named = [o.get('name') for o in members]
+ hits += [op for op in members if sub_rule_for(op, owned_map, named)]
+ return hits
+
+
+def owned_of(file):
+ """账号文件名 → owned_map(没给 / 读不到返回 None):写 MAA 时判替换用"""
+ if not file:
+ return None
+ try:
+ from . import accounts # 懒加载:copilot 被到处 import,别成环
+ return build_owned(accounts.get_account(file))
+ except Exception:
+ return None
+
+
# ---------------------------------------------------------------- 交给 MAA 前修正
# 作业站的原始 json 里经常有「技能选择与稀有度不匹配」「精英要求填 0 但技能等级
# 要求精一」这类历史遗留问题。MAA 桌面端在「添加作业」时会自己修一遍再存盘,
diff --git a/backend/core/garrison.py b/backend/core/garrison.py
index e149427..996c5f0 100644
--- a/backend/core/garrison.py
+++ b/backend/core/garrison.py
@@ -42,6 +42,10 @@
PATCH_FILE = os.path.join(settings.RES, 'resources', 'garrison', 'patches.json')
DEVICES = ('mumu', 'ldplayer', 'pc')
+# 速刷目标(核心 goal 注册表,v1.1.7 起):medal=策略徽章(默认);
+# task-N=实验性叠层目标(先锋服实测口径:task-1..5 为 100 层、task-6/7 为 50 层)。
+# 与 resources/garrison/host.mjs 的 GOALS 保持一致。
+GOALS = ('medal', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7')
SHOT_METHODS = ('auto', 'fast', 'adb')
BUSY = ('running', 'starting', 'stopping')
@@ -192,14 +196,10 @@ def _maa_dir_for(file: str) -> str:
return settings.load()['maaDir']
-def defaults(file: str):
- """速刷默认参数:从账号绑定 MAA 的连接配置里抄。
-
- 返回 ``(options, 来源)``;MAA 配置读不到时给核心自己的兜底值
- (mumu + 16384),前端会展示来源让用户知道这份默认值从哪来。
- """
+def _maa_defaults(file: str):
+ """从账号绑定 MAA 的连接配置里抄出来的裸默认值(不含用户偏好 overlay)"""
opts = {
- 'device': 'mumu', 'mode': 'quick', 'speed': 1.5, 'medalWins': 3,
+ 'device': 'mumu', 'mode': 'quick', 'goal': 'medal', 'speed': 1.5, 'medalWins': 3,
'adbAddress': '127.0.0.1:16384', 'adbPath': '',
'screenshotMethod': 'auto', 'pcUiScale': 90,
}
@@ -227,6 +227,58 @@ def defaults(file: str):
return opts, src
+# 可持久化的速刷选项键(账号 json 里的 garrisonOpts 只认这些)
+OPT_KEYS = ('device', 'mode', 'goal', 'adbAddress', 'adbPath', 'medalWins', 'speed',
+ 'screenshotMethod', 'pcUiScale')
+
+
+def _stored_opts(file: str) -> dict:
+ """账号 json 里存过的用户改动(garrisonOpts),按白名单取"""
+ if not file:
+ return {}
+ try:
+ from . import accounts
+ snap = accounts.get_account(file)
+ st = snap.get('garrisonOpts') or {}
+ return {k: st[k] for k in OPT_KEYS
+ if isinstance(st, dict) and k in st}
+ except Exception:
+ return {}
+
+
+def defaults(file: str):
+ """速刷默认参数:MAA 配置抄来的基底 + 账号里存过的用户改动。
+
+ 返回 ``(options, 来源)``。用户在面板改过的选项按账号持久化
+ (save_opts 只存与 MAA 基底不同的键),重启不丢;没改过的键
+ 继续跟随 MAA 配置。
+ """
+ opts, src = _maa_defaults(file)
+ stored = _stored_opts(file)
+ for k in OPT_KEYS:
+ if k in stored and k in opts:
+ opts[k] = stored[k]
+ return opts, src
+
+
+def save_opts(file: str, options: dict) -> dict:
+ """用户改的速刷选项写回账号 json。
+
+ 以账号**当前生效值**为基底叠加传入项再清洗(只传一个键不会把别的
+ 键锁到全局兜底值),然后与「MAA 抄来的裸默认」逐键比对,只存不同
+ 的键——改回默认值的键自动剔除,没动过的键永远跟着 MAA 配置走。
+ 返回合并后的生效默认值(含实际存了哪些键,便于排查)。
+ """
+ cur, _src0 = defaults(file)
+ clean = sanitize({**cur, **(options or {})})
+ base, _src = _maa_defaults(file)
+ diff = {k: clean[k] for k in OPT_KEYS if clean.get(k) != base.get(k)}
+ from . import accounts as _acc
+ _acc.save_pref(file, {'garrisonOpts': diff})
+ merged, src = defaults(file)
+ return {'defaults': merged, 'fromMaa': src, 'saved': diff}
+
+
def sanitize(body: dict) -> dict:
"""前端提交的选项清洗:只放行核心认识的枚举与范围,其余回默认"""
body = body or {}
@@ -239,6 +291,7 @@ def sanitize(body: dict) -> dict:
return {
'device': device,
'mode': body.get('mode') if body.get('mode') in ('quick', 'standard') else 'quick',
+ 'goal': body.get('goal') if body.get('goal') in GOALS else 'medal',
'medalWins': 6 if str(body.get('medalWins')) == '6' else 3,
'speed': speed,
'adbAddress': str(body.get('adbAddress') or dft['adbAddress']).strip() or dft['adbAddress'],
@@ -418,6 +471,8 @@ def status(file: str) -> dict:
核心缺失时带 ``needsDownload`` + 下载进度(garrisondl 的状态机),
前端据此自动开始下载并显示进度条;下载是全局一份(不分账号)。
+ 核心升级(保持最新)不在轮询里做:由「程序启动」和「速刷任务全部
+ 停止后」(stop())两个事件触发 garrisondl.check_update()。
"""
node = node_exe()
core = core_dir()
@@ -477,7 +532,49 @@ def stop(file: str) -> dict:
h = host_of(file)
if not _alive(h):
raise ValueError('当前没有速刷任务在跑')
- return _call(h, 'POST', '/api/stop', {}, timeout=15) # type: ignore[arg-type]
+ r = _call(h, 'POST', '/api/stop', {}, timeout=15) # type: ignore[arg-type]
+ _schedule_update_check()
+ return r
+
+
+def _schedule_update_check():
+ """速刷任务被停止后安排一次更新检查(后台、全闲才动手)。
+
+ 只在有宿主存在时才起线程:stop 失败(没有宿主)不应触发检查,
+ 否则会在不该动手的时刻(比如宿主都关了)意外开始升级。
+ """
+ with _lock:
+ has_hosts = bool(_HOSTS)
+ if not has_hosts:
+ return
+ threading.Thread(target=_check_update_when_idle, daemon=True,
+ name='garrison-upd-check').start()
+
+
+def _check_update_when_idle(timeout=45.0):
+ """等全部速刷任务停稳(stopping→stopped),都闲下来了就查一次更新。"""
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ with _lock:
+ hosts = list(_HOSTS.items())
+ busy_any = False
+ for _f, h in hosts:
+ if not _alive(h):
+ continue
+ try:
+ if (_state_of(h).get('state') or {}).get('status') in BUSY:
+ busy_any = True
+ break
+ except Exception:
+ busy_any = True # 拿不到状态先当它在跑,别在忙时动手
+ break
+ if not busy_any:
+ try:
+ garrisondl.check_update()
+ except Exception:
+ pass
+ return
+ time.sleep(2.0)
def stop_all(timeout=6.0):
diff --git a/backend/core/garrisondl.py b/backend/core/garrisondl.py
index c762e08..0dfe7ef 100644
--- a/backend/core/garrisondl.py
+++ b/backend/core/garrisondl.py
@@ -36,17 +36,46 @@
PKG_ID = 'ai-desktop.arknights-medal-farm'
PKG_DIR_RE = re.compile(r'^medal-farm-v(\d+(?:\.\d+)*)$')
-FALLBACK = {
- 'version': '1.1.4',
- 'url': ('https://static.max-c.com/heybox/desktop/extension/'
- 'ai-desktop.arknights-medal-farm/version/1.1.4/'
- '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff-'
- '20261118T140851382Z/ai-desktop.arknights-medal-farm-1.1.4.hbext'),
- 'sha256': '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff',
- 'bytes': 61071704,
- 'files': None,
- 'source': '官方直链(回退)',
-}
+# 已验证直链(匿名可下载,整包 sha256 锚定):按版本降序作回退链——
+# 记录里的新版不在适配表时,装「表内最新」的直链版本而不是一味落到最老。
+FALLBACKS = [
+ {
+ 'version': '1.1.7',
+ 'url': ('https://static.max-c.com/heybox/desktop/extension/'
+ 'ai-desktop.arknights-medal-farm/version/1.1.7/'
+ '6bc385116129d13b2e66679d100551950c6b03c793a92cfe1bc9f53f6db3166b-'
+ '20261120T150609837Z/ai-desktop.arknights-medal-farm-1.1.7.hbext'),
+ 'sha256': '6bc385116129d13b2e66679d100551950c6b03c793a92cfe1bc9f53f6db3166b',
+ 'bytes': 61089122,
+ 'files': None,
+ 'source': '官方直链(回退)',
+ },
+
+ {
+ 'version': '1.1.5',
+ 'url': ('https://static.max-c.com/heybox/desktop/extension/'
+ 'ai-desktop.arknights-medal-farm/version/1.1.5/'
+ '596196307afbdc4c102d66b85b7210ebb292612fd6f1e0d2d2c51ab83445c8b0-'
+ '20261119T163854129Z/ai-desktop.arknights-medal-farm-1.1.5.hbext'),
+ 'sha256': '596196307afbdc4c102d66b85b7210ebb292612fd6f1e0d2d2c51ab83445c8b0',
+ 'bytes': 61083080,
+ 'files': None,
+ 'source': '官方直链(回退)',
+ },
+ {
+ 'version': '1.1.4',
+ 'url': ('https://static.max-c.com/heybox/desktop/extension/'
+ 'ai-desktop.arknights-medal-farm/version/1.1.4/'
+ '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff-'
+ '20261118T140851382Z/ai-desktop.arknights-medal-farm-1.1.4.hbext'),
+ 'sha256': '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff',
+ 'bytes': 61071704,
+ 'files': None,
+ 'source': '官方直链(回退)',
+ },
+]
+FALLBACK = FALLBACKS[-1] # 最老一档,兼容旧引用
+
MIN_TOTAL_BYTES = 50 * 1024 * 1024
MIN_FILE_COUNT = 100
@@ -141,7 +170,25 @@ def record_candidates():
def candidates():
- return record_candidates() + [dict(FALLBACK)]
+ # 全部下载源:本机记录 ∪ 已验证直链,按版本降序(同版本记录优先——
+ # 带官方逐文件 sha256 清单,校验更严)
+ recs = record_candidates()
+ seen = {r['version'] for r in recs}
+ out = recs + [dict(f) for f in FALLBACKS if f['version'] not in seen]
+ out.sort(key=lambda r: ver_key(r['version']), reverse=True)
+ return out
+
+def _pick_candidate(installed: str):
+ # 该装哪个:候选里第一个「适配表内且比已装新」的;没有返回 None。
+ # 记录里只有表外新版(如 1.1.6)时,顺着回退链选表内最新的直链版本
+ # (如 1.1.5),而不是一味落到最老的 1.1.4。
+ for rec in candidates():
+ if not _is_adapted(rec['version']):
+ continue
+ if installed and ver_key(rec['version']) <= ver_key(installed):
+ continue
+ return rec
+ return None
# ---------------------------------------------------------------- 引擎
@@ -274,8 +321,34 @@ def _extract_verify(hbext, out_dir, manifest=None):
return len(got)
+def _adapted_versions():
+ """patches.json 里硬编码的「已适配核心版号」表;读不到按无限制处理
+
+ 更新器只升到表内版本(表外新版等补丁适配后再放行),比在暂存区上
+ 数补丁命中更直白,也省一次 61MB 的无效下载。
+ """
+ p = os.path.join(settings.RES, 'resources', 'garrison', 'patches.json')
+ try:
+ with open(p, encoding='utf-8') as f:
+ v = (json.load(f) or {}).get('adaptedVersions')
+ return [str(x) for x in v] if isinstance(v, list) else None
+ except (OSError, ValueError):
+ return None
+
+
+def _is_adapted(version: str) -> bool:
+ allowed = _adapted_versions()
+ return allowed is None or str(version) in allowed
+
+
def _install(hbext, version, manifest=None):
- """解压校验 → 前置校验 → 原子落位 garrison/medal-farm-v<版本>;失败不伤旧版。"""
+ """解压校验 → 前置校验 → 补丁兼容门禁 → 原子落位;失败不伤旧版。
+
+ 门禁:上游换版本常把混淆产物整个重排(v1.1.4 → v1.1.5 连文案都换了),
+ 我们的补丁一条都命不中=这个版本没适配过,升上去等于把已修的 OCR
+ 容错/弹窗识别全丢掉。宁可停在旧版等适配——全新安装同理会顺着回退
+ 链落到已适配的版本上。
+ """
pkg = os.path.join(garrison_dir(), 'medal-farm-v%s' % version)
stage = os.path.join(download_dir(), 'stage')
shutil.rmtree(stage, ignore_errors=True)
@@ -330,18 +403,51 @@ def state() -> dict:
def start() -> dict:
- """启动(或继续)下载;已在跑/已完成时原样返回。返回 state 快照。"""
+ """启动(或继续)下载/升级;已在跑/已是最新时原样返回。返回 state 快照。
+
+ 没装过 → 走下载链装「表内最新」(记录 ∪ 已验证直链);装着旧版且
+ 候选里有「适配表内且更新」的版本(_pick_candidate)→ 升级;升级
+ 失败不影响已装版本继续使用。
+ """
with _LOCK:
running = _RUNNING[0]
if running:
return state()
- if _installed_pkg_dir():
+ cur = _installed_pkg_dir()
+ if cur and _pick_candidate(cur) is None:
_set(stage='done', error='', endedAt=time.time())
return state()
threading.Thread(target=_run, daemon=True, name='garrison-dl').start()
return state()
+def check_update() -> None:
+ """看一眼有没有可升的目标(适配表内且比已装新),有就后台升级。
+
+ 触发时机由调用方决定:程序启动时(main)、速刷任务全部停止后
+ (garrison.stop)。没有可升目标就是一次本地扫描,零成本;记录里的
+ 新版不在适配表时记一行日志、不动已装版本。
+ """
+ with _LOCK:
+ running = _RUNNING[0]
+ if running:
+ return
+ cur = _installed_pkg_dir()
+ if not cur:
+ return
+ target = _pick_candidate(cur)
+ if not target:
+ recs = record_candidates()
+ if recs and ver_key(recs[0]['version']) > ver_key(cur) \
+ and not _is_adapted(recs[0]['version']):
+ applog.log('[卫戍协议] 核心新版本 v%s 尚无对应补丁(已适配:%s),暂不更新'
+ % (recs[0]['version'], '/'.join(_adapted_versions() or ['?'])))
+ return
+ applog.log('[卫戍协议] 检测到核心新版本(本机 v%s → v%s),后台升级'
+ % (cur, target['version']))
+ threading.Thread(target=_run, daemon=True, name='garrison-upgrade').start()
+
+
def _run():
with _LOCK:
if _RUNNING[0]:
@@ -364,7 +470,12 @@ def _run():
shutil.rmtree(lock_dir, ignore_errors=True)
os.mkdir(lock_dir)
+ installed = _installed_pkg_dir()
for rec in candidates():
+ if not _is_adapted(rec['version']):
+ continue # 版号不在适配表:等补丁,不下载
+ if installed and ver_key(rec['version']) <= ver_key(installed):
+ continue # 防降级:已装新版时旧记录/回退直链一律不装
label = 'v%s(%s)' % (rec['version'], rec['source'])
try:
_set(stage='connecting', source=rec['source'], version=rec['version'],
diff --git a/backend/core/maa.py b/backend/core/maa.py
index 192aa4d..8b3ac01 100644
--- a/backend/core/maa.py
+++ b/backend/core/maa.py
@@ -286,10 +286,16 @@ def _safe(name):
return SAFE.sub('_', name).strip() or 'stage'
-def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, maa_dir=None):
- """items: [{copilotId, stageCode, title}] → 写入 MAA 多作业列表"""
+def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, maa_dir=None,
+ account=None):
+ """items: [{copilotId, stageCode, title}] → 写入 MAA 多作业列表
+
+ account 是账号文件名:给了就按该账号练度做干员替换(#92,见
+ copilot.SUB_RULES),落盘的作业里塞雷娅这类条目会被练度等价的替补顶掉。
+ """
log = tasks.log_factory(tid) if tid else (lambda *_: None)
d = _dir(maa_dir)
+ owned = copilot.owned_of(account)
log('MAA 目录:%s' % d)
# 先校验配置可读、档案存在,再关进程:目录配错 / gui.new.json 损坏时
@@ -371,6 +377,10 @@ def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, m
log('[%d/%d] 复用已就绪的作业 #%s %s' % (idx, len(items), cid, it.get('title') or ''))
else:
content, flags, sname = fetched[cid]
+ if owned:
+ content, sub_notes = copilot.apply_substitutions(content, owned)
+ for n in sub_notes:
+ log(' 替换:%s' % n)
fname = '%s_%s.json' % (_safe(stage_code), cid)
os.makedirs(_copilot_dir(d), exist_ok=True)
fpath = os.path.join(_copilot_dir(d), fname)
@@ -424,13 +434,14 @@ def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, m
'added': len(new_entries), 'files': files, 'started': started}
-def start_apply(items, profile=None, mode='replace', auto_start=True, maa_dir=None):
+def start_apply(items, profile=None, mode='replace', auto_start=True, maa_dir=None, account=None):
title = '写入 MAA(%d 份作业)' % len(items or [])
holder = {}
def go():
try:
- res = apply_plan(items, profile, mode, auto_start, holder['tid'], maa_dir=maa_dir)
+ res = apply_plan(items, profile, mode, auto_start, holder['tid'],
+ maa_dir=maa_dir, account=account)
tasks.finish(holder['tid'], result=res)
except Exception as e:
import traceback
@@ -509,6 +520,28 @@ def profiles(maa_dir=None):
return {'current': cfg.get('Current') or '', 'profiles': out}
+def profile_account_name(profile, maa_dir=None):
+ """读某个配置档案「开始唤醒」里的 AccountName(只读,不改用户配置)
+
+ 设置 → MAA 路径里选了「配置文件」之后,切号名就优先按这里的值来:
+ 用户自己的档案(moren / 136 / 157…)本来就在 MAA 里配好了账号切换,
+ 再让他手抄一遍纯属重复劳动。**只读**——写回用户的档案是另一条路
+ (``set_tasklist`` / ``apply_plan``),这里一个字段都不许动。
+
+ 读不到(MAA 没装、档案被删、配置坏)就返回空串,调用方回落手填值。
+ """
+ name = str(profile or '').strip()
+ if not name:
+ return ''
+ cfg = _load_cfg(maa_dir)
+ conf = (cfg.get('Configurations') or {}).get(name)
+ if not isinstance(conf, dict):
+ return ''
+ su = next((t for t in (conf.get('TaskQueue') or [])
+ if isinstance(t, dict) and t.get('TaskType') == 'StartUp'), None)
+ return str(((su or {}).get('AccountName') or '')).strip()
+
+
def tasklist(profile=None, maa_dir=None):
cfg = _load_cfg(maa_dir)
profile = profile or cfg.get('Current') or ''
diff --git a/backend/core/maaplan.py b/backend/core/maaplan.py
index 6543c3b..65e6c37 100644
--- a/backend/core/maaplan.py
+++ b/backend/core/maaplan.py
@@ -515,11 +515,13 @@ def _copilot_dir(maa_dir):
return os.path.join(maa_dir, 'config', 'copilot')
-def prepare_copilot(ops, maa_dir, log=None):
+def prepare_copilot(ops, maa_dir, log=None, account=None):
"""下载并落盘作业,返回 MaaCore 的 copilot_list 条目
``filename`` **必须是绝对路径**(实测:相对路径不报错,但任务静默不入队)。
+ ``account`` 是账号文件名:给了就按该账号练度做干员替换(#92)再落盘。
+
``stage_name`` 是 **导航名**,必须是**关卡代号**(``TL-S-1`` / ``1-7``),
不是作业里的关卡内部 id。看 MaaCore 的 MultiCopilotTaskPlugin::_run:
@@ -535,6 +537,7 @@ def prepare_copilot(ops, maa_dir, log=None):
from . import copilot
log = log or (lambda *_: None)
+ owned = copilot.owned_of(account)
os.makedirs(_copilot_dir(maa_dir), exist_ok=True)
rows, done = [], {}
for it in ops or []:
@@ -542,6 +545,9 @@ def prepare_copilot(ops, maa_dir, log=None):
code = it.get('stageCode') or str(cid)
if cid not in done:
content, flags, sname, notes, pre = copilot.fetch_prepared(cid)
+ sub_notes = []
+ if owned:
+ content, sub_notes = copilot.apply_substitutions(content, owned)
fname = '%s_%s.json' % (_SAFE.sub('_', code).strip() or 'stage', cid)
path = os.path.normpath(os.path.join(_copilot_dir(maa_dir), fname))
with open(path, 'w', encoding='utf-8') as f:
@@ -551,6 +557,8 @@ def prepare_copilot(ops, maa_dir, log=None):
it.get('title') or ''))
for n in notes or []:
log(' 修正:%s' % n)
+ for n in sub_notes or []:
+ log(' 替换:%s' % n)
path, sname, flags = done[cid]
nav = _clean_stage(code)
variants = copilot.entry_variants(flags, it.get('variant'), sname)
@@ -1784,7 +1792,8 @@ def _retry_failed(eng, spec, state, log, d, deadline, conn=None):
if not new_ops:
log('没有更多能换的作业了(每关的候选都试过)')
break
- rows = prepare_copilot(new_ops, d, log=lambda m: log(' ' + m))
+ rows = prepare_copilot(new_ops, d, account=spec.get('accountFile'),
+ log=lambda m: log(' ' + m))
for key, code, var, prev, nxt in picked:
used = attempted.setdefault(key, set())
used.add(nxt)
@@ -1861,7 +1870,7 @@ def run_plan(rows, spec_base, tid=None):
cp = []
if r.get('ops'):
log('准备 %d 份作业…' % len(r['ops']))
- cp = prepare_copilot(r['ops'], d,
+ cp = prepare_copilot(r['ops'], d, account=r.get('file'),
log=lambda m: log(' ' + m))
spec = dict(spec_base)
spec.update({
@@ -1869,6 +1878,8 @@ def run_plan(rows, spec_base, tid=None):
'switchAccount': True,
'clientType': client_type_of(r.get('channel')),
'copilotList': cp,
+ # 重挂(_retry_failed)换作业时按同一账号练度做替换(#92)
+ 'accountFile': r.get('file') or '',
})
try:
res = run_core(spec, tid)
diff --git a/backend/core/multiacct.py b/backend/core/multiacct.py
index 1df0c1d..06d2067 100644
--- a/backend/core/multiacct.py
+++ b/backend/core/multiacct.py
@@ -60,10 +60,21 @@ def candidates():
终末地账号(``game != 'arknights'``)MAA 根本不管,混进来会让后面
对着它的练度去找明日方舟作业,结果一片「全部打不了」。
"""
+ from . import acctbind
+
out = []
for row in accounts.list_accounts():
if (row.get('game') or 'arknights') != 'arknights':
continue
+ # 绑了配置文件的账号:切号名以那份档案里的为准(用户 2026-11-22 要求,
+ # 规则在 acctbind)。没绑就用手填的,别为此去读 MAA 配置——列表接口
+ # 每次启动都会走一遍,能省一次文件读取就省一次。
+ nm = row.get('maaAccountName') or ''
+ if row.get('maaProfile'):
+ try:
+ nm, _src = acctbind.resolve(row['file'])
+ except Exception:
+ pass
out.append({
'file': row['file'],
'name': row.get('alias') or row.get('nickName') or row['file'],
@@ -71,7 +82,7 @@ def candidates():
'channel': row.get('channelName') or '',
'level': row.get('level'),
'maaProfile': row.get('maaProfile') or '',
- 'accountName': row.get('maaAccountName') or '',
+ 'accountName': nm,
'maaDir': row.get('maaDir') or '',
'progress': row.get('progress') or {},
})
@@ -196,7 +207,11 @@ def _match(c):
nm, why = acctname.check(names.get(c['file']) or '', c.get('channel'))
reuse = ''
if not nm:
- # 没给名字就看 MAA 里有没有现成的档案对得上。
+ # 设置里绑过的直接用(手填的尾号 / 选了配置文件带出来的账号名):
+ # candidates 给的已经是生效值,用户配过一次就不该再问(2026-11-22)
+ nm, _ = acctname.check(c.get('accountName') or '', c.get('channel'))
+ if not nm:
+ # 还没绑:看 MAA 里有没有现成的档案对得上。
# 注意取的是档案里的 **AccountName**,不是档案名:`maaProfile`
# 是 moren / 136 这种档案名,拿它当账号名写进 StartUp,MAA 切号
# 必然失败(切号要的是登录界面那行 181****5505)。
@@ -210,8 +225,8 @@ def _match(c):
missing.append({
'what': 'accountName', 'file': c['file'], 'name': c['name'],
'question': '账号「%s」(%s)的手机号后 4 位是多少?给这四位就行'
- '(如 5505,MAA 切号用的就是它);'
- 'B 服填游戏里显示的用户名。%s'
+ '(如 5505);前 3 位 + 后 4 位也行(如 157****3635)。'
+ 'MAA 切号用的就是它;B 服填游戏里显示的用户名。%s'
% (c['name'], c['channel'] or '未知渠道',
('你给的「%s」%s。' % (names.get(c['file']), why))
if names.get(c['file']) and why else ''),
@@ -385,9 +400,11 @@ def apply(plan_data, tid=None):
for o in r['ops']]
log('[%d/%d] 给「%s」写 %d 份作业(切号名 %s)'
% (i, len(written), name, len(items), r['accountName']))
- # auto_start=False:全部写完再统一启动,不然每写一个就拉起一次 MAA
+ # auto_start=False:全部写完再统一启动,不然每写一个就拉起一次 MAA;
+ # account 带上:写盘时按各账号练度做干员替换(#92)
res = maa.apply_plan(items, profile=name, mode='replace',
- auto_start=False, tid=tid, maa_dir=d)
+ auto_start=False, tid=tid, maa_dir=d,
+ account=r.get('file'))
total += res.get('added') or 0
log('全部写完,共 %d 份作业;MAA 启动后会自动开始' % total)
return {'profiles': [n for n, _ in written], 'ops': total}
diff --git a/backend/core/scheduler.py b/backend/core/scheduler.py
new file mode 100644
index 0000000..d0a7f89
--- /dev/null
+++ b/backend/core/scheduler.py
@@ -0,0 +1,591 @@
+# -*- coding: utf-8 -*-
+"""定时任务:按时间启动程序 + 链式启动
+
+语义照搬三月七助手的「定时任务配置」,只保留在我们这儿能落地、也确实是
+用户在用的那部分(朋友要搬的 autostart-138.exe / OneDragon-Launcher.exe /
+cmd 批处理都属于这一类):
+
+ - 触发两种:time(每周指定几天、某个 HH:MM)与 chain(上一条退出后接着跑)
+ - 动作一种:启动一个外部程序。三月七的「本体任务」我们不做——MAA 自己的
+ 任务链由 skills 那一层负责,这里只当启动器
+ - 同一时刻只跑一个任务。冲突策略 stop(停掉在跑的)/ skip(跳过本次)
+ - 链式任务失败后 continue(继续后面的)/ stop(停掉整条链)
+
+为什么不用 Windows 计划任务:链式启动(等上一个进程退出)系统计划任务
+表达不了;而且时间触发只在程序运行时生效——跟三月七一致,要开机自启
+得用户把本程序放进启动项。
+
+数据存 config/schedule.json(原子写);日志写 debug/schedule.log,同时留
+一段内存环形缓冲给界面读(含 seq,供前端轮询拿「刚跑完」的通知)。
+"""
+from __future__ import annotations
+
+import collections
+import datetime
+import os
+import queue
+import re
+import shlex
+import shutil
+import subprocess
+import threading
+import time
+import uuid
+
+from . import settings
+from .atomicio import dump_json
+
+VERSION = 1
+MAX_TASKS = 60
+CONFLICTS = ('stop', 'skip')
+ON_FAIL = ('continue', 'stop')
+_TICK = 5.0
+_LOG_MAX = 1024 * 1024
+
+_lock = threading.RLock()
+_cache = None
+_running = None # {id,name,proc,startedAt,killed}
+_queue = queue.Queue()
+_fired = {} # task id -> 'YYYY-MM-DD HH:MM'(同一分钟不重复触发)
+_last = {} # task id -> {at,ok,code,text}
+_events = collections.deque(maxlen=400)
+_seq = 0
+_started = False
+
+
+# ---------------------------------------------------------------- 存储
+def _path() -> str:
+ # 每次取 settings 的当前值:冒烟测试会把 CONFIG_DIR 指到临时目录
+ return os.path.join(settings.CONFIG_DIR, 'schedule.json')
+
+
+def _defaults() -> dict:
+ return {'version': VERSION, 'conflict': 'stop', 'onChainFail': 'continue', 'tasks': []}
+
+
+def _new_id() -> str:
+ return 's' + uuid.uuid4().hex[:8]
+
+
+def _norm_time(v) -> str:
+ m = re.match(r'^(\d{1,2}):(\d{1,2})$', str(v or '').strip())
+ if not m:
+ return ''
+ h, mi = int(m.group(1)), int(m.group(2))
+ if h > 23 or mi > 59:
+ return ''
+ return '%02d:%02d' % (h, mi)
+
+
+def _parse_time(v):
+ s = _norm_time(v)
+ if not s:
+ return None
+ return int(s[:2]), int(s[3:])
+
+
+def _norm_weekdays(v):
+ """1=周一 … 7=周日。缺省/脏数据一律当每天全选(宁可按天跑,不要静默不跑)"""
+ if v is None:
+ return list(range(1, 8))
+ out = set()
+ for d in (v if isinstance(v, (list, tuple, set)) else []):
+ if isinstance(d, bool):
+ continue
+ try:
+ n = int(d)
+ except (TypeError, ValueError):
+ continue
+ if 1 <= n <= 7:
+ out.add(n)
+ return sorted(out)
+
+
+def _norm_timeout(v) -> int:
+ try:
+ n = int(v)
+ except (TypeError, ValueError):
+ return 0
+ return max(0, min(n, 7 * 86400))
+
+
+def normalize_task(raw) -> dict:
+ raw = raw if isinstance(raw, dict) else {}
+ mode = 'chain' if str(raw.get('mode') or '').strip().lower() == 'chain' else 'time'
+ name = str(raw.get('name') or '').strip()[:40] or '未命名任务'
+ return {
+ 'id': str(raw.get('id') or '').strip()[:24] or _new_id(),
+ 'enabled': raw.get('enabled') is not False,
+ 'name': name,
+ 'mode': mode,
+ 'time': _norm_time(raw.get('time')) or '08:00',
+ 'weekdays': _norm_weekdays(raw.get('weekdays')),
+ 'program': settings.norm_dir(str(raw.get('program') or '')),
+ 'args': str(raw.get('args') or '').strip()[:1000],
+ 'cwd': settings.norm_dir(str(raw.get('cwd') or '')),
+ 'timeout': _norm_timeout(raw.get('timeout')),
+ 'notify': bool(raw.get('notify')),
+ }
+
+
+def load() -> dict:
+ global _cache
+ with _lock:
+ if _cache is not None:
+ return _copy(_cache)
+ data = _defaults()
+ try:
+ import io
+ import json
+ with io.open(_path(), encoding='utf-8') as f:
+ saved = json.load(f)
+ if isinstance(saved, dict):
+ if saved.get('conflict') in CONFLICTS:
+ data['conflict'] = saved['conflict']
+ if saved.get('onChainFail') in ON_FAIL:
+ data['onChainFail'] = saved['onChainFail']
+ tasks = saved.get('tasks')
+ if isinstance(tasks, list):
+ data['tasks'] = [normalize_task(t) for t in tasks[:MAX_TASKS]]
+ except Exception:
+ pass # 没文件 / 坏了都按默认跑,坏文件留给用户自己看
+ _cache = data
+ return _copy(data)
+
+
+def _copy(cfg) -> dict:
+ return {
+ 'version': VERSION,
+ 'conflict': cfg.get('conflict') or 'stop',
+ 'onChainFail': cfg.get('onChainFail') or 'continue',
+ 'tasks': [dict(t) for t in (cfg.get('tasks') or [])],
+ }
+
+
+def save(patch: dict) -> dict:
+ """整表保存(tasks / conflict / onChainFail),返回落盘后的视图"""
+ global _cache
+ patch = patch or {}
+ with _lock:
+ cur = load()
+ if 'conflict' in patch and patch['conflict'] in CONFLICTS:
+ cur['conflict'] = patch['conflict']
+ if 'onChainFail' in patch and patch['onChainFail'] in ON_FAIL:
+ cur['onChainFail'] = patch['onChainFail']
+ if isinstance(patch.get('tasks'), list):
+ seen = set()
+ tasks = []
+ for raw in patch['tasks'][:MAX_TASKS]:
+ t = normalize_task(raw)
+ while t['id'] in seen:
+ t['id'] = _new_id()
+ seen.add(t['id'])
+ tasks.append(t)
+ cur['tasks'] = tasks
+ os.makedirs(settings.CONFIG_DIR, exist_ok=True)
+ dump_json(_path(), cur)
+ _cache = cur
+ return _copy(cur)
+
+
+# ---------------------------------------------------------------- 时间计算
+def _due_slot(task, now_ts=None) -> str:
+ """当前这一分钟正好是这个任务的计划点就返回槽位串,否则空。
+
+ 只认「当前分钟」,不回看上一分钟:程序关着的时候错过的点不补跑——
+ 补跑会在开机瞬间一口气把昨天所有的任务全拉起来,比漏一次更糟。
+ """
+ if task.get('mode') != 'time':
+ return ''
+ t = _parse_time(task.get('time'))
+ wd = task.get('weekdays') or []
+ if not t or not wd:
+ return ''
+ dt = datetime.datetime.fromtimestamp(now_ts if now_ts is not None else time.time())
+ if dt.isoweekday() not in wd:
+ return ''
+ if (dt.hour, dt.minute) != t:
+ return ''
+ return dt.strftime('%Y-%m-%d %H:%M')
+
+
+def next_run_ts(task, now_ts=None) -> int:
+ if task.get('mode') != 'time':
+ return 0
+ t = _parse_time(task.get('time'))
+ wd = task.get('weekdays') or []
+ if not t or not wd:
+ return 0
+ now = datetime.datetime.fromtimestamp(now_ts if now_ts is not None else time.time())
+ # 同一分钟内还没触发过的,就算「下一次就是现在」,界面上不会显示成下周
+ if _due_slot(task, now.timestamp()) and _fired.get(task.get('id')) != \
+ now.strftime('%Y-%m-%d %H:%M'):
+ return int(now.replace(second=0, microsecond=0).timestamp())
+ for off in range(0, 9):
+ day = (now + datetime.timedelta(days=off)).date()
+ if day.isoweekday() not in wd:
+ continue
+ cand = datetime.datetime.combine(day, datetime.time(*t))
+ if cand > now:
+ return int(cand.timestamp())
+ return 0
+
+
+def _chain_after(task, tasks) -> list:
+ """紧跟在 task 后面的一串 chain 任务(中间夹一条 time 任务就断链)"""
+ idx = next((i for i, t in enumerate(tasks) if t.get('id') == task.get('id')), -1)
+ if idx < 0:
+ return []
+ out = []
+ for t in tasks[idx + 1:]:
+ if t.get('mode') != 'chain':
+ break
+ if t.get('enabled'):
+ out.append(t)
+ return out
+
+
+# ---------------------------------------------------------------- 日志/事件
+def _log_path() -> str:
+ return os.path.join(settings.DEBUG_DIR, 'schedule.log')
+
+
+def _rotate_log():
+ try:
+ if os.path.getsize(_log_path()) > _LOG_MAX:
+ os.replace(_log_path(), _log_path() + '.1')
+ except Exception:
+ pass
+
+
+def _emit(kind, text, level='info', task=None) -> dict:
+ global _seq
+ task = task or {}
+ with _lock:
+ _seq += 1
+ ev = {
+ 'seq': _seq,
+ 'ts': int(time.time()),
+ 'time': time.strftime('%m-%d %H:%M:%S'),
+ 'kind': kind,
+ 'level': level,
+ 'text': text,
+ 'taskId': task.get('id') or '',
+ 'name': task.get('name') or '',
+ 'notify': bool(task.get('notify')),
+ }
+ _events.append(ev)
+ try:
+ os.makedirs(settings.DEBUG_DIR, exist_ok=True)
+ _rotate_log()
+ with open(_log_path(), 'a', encoding='utf-8') as f:
+ f.write('%s [%s] %s\n' % (ev['time'], level, text))
+ except Exception:
+ pass
+ return ev
+
+
+def log_lines(limit=80) -> list:
+ with _lock:
+ return list(_events)[-limit:]
+
+
+# ---------------------------------------------------------------- 执行
+def _split_args(s: str) -> list:
+ s = str(s or '').strip()
+ if not s:
+ return []
+ if os.name != 'nt':
+ return shlex.split(s)
+ # Windows 下跟 CreateProcess 用同一套解析(引号、反斜杠转义都能对上),
+ # shlex(posix=False) 会把引号留在参数里
+ try:
+ import ctypes
+ from ctypes import wintypes
+ fn = ctypes.WinDLL('shell32', use_last_error=True).CommandLineToArgvW
+ fn.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)]
+ fn.restype = ctypes.POINTER(wintypes.LPWSTR)
+ free = ctypes.WinDLL('kernel32', use_last_error=True).LocalFree
+ free.argtypes = [wintypes.HLOCAL]
+ free.restype = wintypes.HLOCAL
+ n = ctypes.c_int()
+ arr = fn('m ' + s, ctypes.byref(n))
+ if not arr:
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ return [arr[i] for i in range(1, n.value)]
+ finally:
+ free(ctypes.cast(arr, wintypes.HLOCAL))
+ except Exception:
+ return [p.strip('"') for p in re.findall(r'"[^"]*"|\S+', s)]
+
+
+def _argv(task) -> list:
+ program = settings.norm_dir(task.get('program') or '')
+ if not program:
+ raise ValueError('没有填要运行的程序')
+ if not os.path.isabs(program):
+ found = shutil.which(program)
+ if found:
+ program = found
+ if not os.path.isfile(program):
+ raise ValueError('程序不存在:%s' % program)
+ args = _split_args(task.get('args'))
+ ext = os.path.splitext(program)[1].lower()
+ if ext in ('.bat', '.cmd'):
+ comspec = os.environ.get('COMSPEC') or 'cmd.exe'
+ # cmd /c 后面整条命令行要作为一个参数传,路径带空格时才不会被拆错
+ return [comspec, '/d', '/c', subprocess.list2cmdline([program] + args)]
+ return [program] + args
+
+
+def _popen(argv, cwd):
+ os.makedirs(settings.DEBUG_DIR, exist_ok=True)
+ _rotate_log()
+ log = open(_log_path(), 'a', encoding='utf-8')
+ flags = getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0) if os.name == 'nt' else 0
+ try:
+ proc = subprocess.Popen(
+ argv, cwd=cwd, stdin=subprocess.DEVNULL, stdout=log,
+ stderr=subprocess.STDOUT, creationflags=flags)
+ finally:
+ log.close() # 子进程持有自己的句柄,父进程不需要一直开着
+ return proc
+
+
+def _kill(entry, why='') -> None:
+ entry['killed'] = True
+ proc = entry.get('proc')
+ if not proc:
+ return
+ if why:
+ _emit('kill', '停止「%s」:%s' % (entry.get('name') or '', why), 'warn',
+ {'id': entry.get('id'), 'name': entry.get('name')})
+ try:
+ if os.name == 'nt':
+ # .bat 是 cmd 的子进程,只 terminate cmd 会留下孤儿;整棵树一起收
+ subprocess.run(['taskkill', '/F', '/T', '/PID', str(proc.pid)],
+ capture_output=True, timeout=10)
+ else:
+ proc.terminate()
+ except Exception:
+ pass
+ try:
+ proc.wait(timeout=3)
+ except Exception:
+ try:
+ proc.kill()
+ except Exception:
+ pass
+
+
+def _now_running_view():
+ with _lock:
+ if not _running:
+ return None
+ return {
+ 'id': _running.get('id'),
+ 'name': _running.get('name'),
+ 'pid': _running.get('pid'),
+ 'startedAt': _running.get('startedAt'),
+ 'seconds': int(time.time() - (_running.get('startedAt') or time.time())),
+ }
+
+
+def _enqueue(task, reason, respect_conflict=True) -> bool:
+ cfg = load()
+ victim = None
+ with _lock:
+ if _running and respect_conflict:
+ if cfg['conflict'] == 'skip':
+ _emit('skip', '跳过「%s」:任务「%s」还在跑(冲突策略=跳过本次)'
+ % (task.get('name'), (_running or {}).get('name')), 'warn', task)
+ return False
+ victim = _running
+ if victim:
+ _kill(victim, '被「%s」顶掉(冲突策略=停止正在运行的)' % task.get('name'))
+ _queue.put({'task': dict(task), 'reason': reason})
+ _emit('queue', '排队「%s」(%s)' % (task.get('name'), reason), 'info', task)
+ return True
+
+
+def _exec(job) -> None:
+ global _running
+ task = job['task']
+ name = task.get('name') or '未命名任务'
+ try:
+ argv = _argv(task)
+ except Exception as e:
+ _emit('finish', '「%s」没跑起来:%s' % (name, e), 'err', task)
+ _last[task.get('id')] = {'at': int(time.time()), 'ok': False, 'code': None, 'text': str(e)}
+ return
+
+ program = argv[0] if argv else ''
+ cwd = task.get('cwd') or ''
+ if not cwd:
+ cwd = os.path.dirname(settings.norm_dir(task.get('program') or '')) or settings.project_root()
+ if not os.path.isdir(cwd):
+ cwd = settings.project_root()
+
+ _emit('start', '启动「%s」:%s' % (name, subprocess.list2cmdline(argv)), 'info', task)
+ try:
+ proc = _popen(argv, cwd)
+ except Exception as e:
+ _emit('finish', '「%s」启动失败:%s' % (name, e), 'err', task)
+ _last[task.get('id')] = {'at': int(time.time()), 'ok': False, 'code': None, 'text': str(e)}
+ return
+
+ entry = {'id': task.get('id'), 'name': name, 'proc': proc,
+ 'pid': proc.pid, 'startedAt': time.time(), 'killed': False}
+ with _lock:
+ _running = entry
+
+ started = time.time()
+ timeout = task.get('timeout') or 0
+ timed_out = False
+ while True:
+ try:
+ code = proc.wait(timeout=0.5)
+ break
+ except subprocess.TimeoutExpired:
+ if timeout and time.time() - started > timeout:
+ timed_out = True
+ _kill(entry, '超过 %d 秒,强制结束' % timeout)
+ try:
+ code = proc.wait(timeout=5)
+ except Exception:
+ code = None
+ break
+
+ elapsed = int(time.time() - started)
+ killed = bool(entry.get('killed')) and not timed_out
+ ok = (code == 0) and not killed and not timed_out
+ with _lock:
+ _running = None
+ _last[task.get('id')] = {
+ 'at': int(time.time()), 'ok': ok, 'code': code,
+ 'text': ('已停止' if killed else ('超时' if timed_out else '退出码 %s' % code)),
+ }
+
+ took = '%d 分 %d 秒' % (elapsed // 60, elapsed % 60) if elapsed >= 60 else '%d 秒' % elapsed
+ if killed:
+ text = '「%s」已停止(用时 %s)' % (name, took)
+ level = 'warn'
+ elif timed_out:
+ text = '「%s」超时被结束(%s)' % (name, took)
+ level = 'err'
+ elif ok:
+ text = '「%s」完成,用时 %s' % (name, took)
+ level = 'ok'
+ else:
+ text = '「%s」失败,退出码 %s(用时 %s)' % (name, code, took)
+ level = 'err'
+ _emit('finish', text, level, task)
+
+ # 被顶掉/手动停止的任务不再往下链,否则会跟新任务打架
+ if killed:
+ return
+ cfg = load()
+ if ok or cfg['onChainFail'] == 'continue':
+ # 只排下一个:链上的每个任务跑完都会接着排它后面那个。一次性把整条链
+ # 全排进去的话,后一个会被「上一条的链」和「自己前面那条的链」各排一次,
+ # 同一个任务跑两遍(实测踩过)
+ nxt = _chain_after(task, cfg['tasks'])[:1]
+ for item in nxt:
+ _enqueue(item, '链式', respect_conflict=False)
+ remaining = len(_chain_after(task, cfg['tasks']))
+ if not ok and cfg['onChainFail'] == 'stop' and remaining:
+ _emit('chain', '「%s」失败,链式后续 %d 个任务不再执行' % (name, remaining),
+ 'warn', task)
+
+
+def _worker() -> None:
+ while True:
+ job = _queue.get()
+ try:
+ _exec(job)
+ except Exception as e: # 单条任务炸了不能把整条调度线程带走
+ _emit('error', '调度出错:%s' % e, 'err', job.get('task'))
+ finally:
+ _queue.task_done()
+
+
+def _loop() -> None:
+ last_tick = time.time()
+ while True:
+ try:
+ now = time.time()
+ # 系统休眠/改时间后往回跳:把已触发记录清掉,否则同一分钟会再触发一次
+ if now < last_tick - 90:
+ _fired.clear()
+ last_tick = now
+ for t in load()['tasks']:
+ if not t.get('enabled') or t.get('mode') != 'time':
+ continue
+ slot = _due_slot(t, now)
+ if not slot or _fired.get(t['id']) == slot:
+ continue
+ _fired[t['id']] = slot
+ _enqueue(t, '定时')
+ except Exception as e:
+ _emit('error', '调度循环出错:%s' % e, 'err')
+ time.sleep(_TICK)
+
+
+def start() -> bool:
+ """起调度线程(幂等)。必须在数据根确定之后调用。"""
+ global _started
+ with _lock:
+ if _started:
+ return False
+ _started = True
+ for fn, nm in ((_worker, 'sched-worker'), (_loop, 'sched-loop')):
+ threading.Thread(target=fn, daemon=True, name=nm).start()
+ _emit('boot', '定时任务已就绪(%d 条)' % len(load()['tasks']))
+ return True
+
+
+# ---------------------------------------------------------------- 对外
+def status(since=0) -> dict:
+ cfg = load()
+ now = time.time()
+ tasks = []
+ for i, t in enumerate(cfg['tasks']):
+ row = dict(t)
+ row['index'] = i
+ ts = next_run_ts(t, now)
+ row['nextRun'] = time.strftime('%m-%d %H:%M', time.localtime(ts)) if ts else ''
+ row['nextRunTs'] = ts
+ row['last'] = _last.get(t['id'])
+ tasks.append(row)
+ with _lock:
+ seq = _seq
+ events = [e for e in _events if since and e['seq'] > int(since)]
+ return {
+ 'ok': True,
+ 'tasks': tasks,
+ 'conflict': cfg['conflict'],
+ 'onChainFail': cfg['onChainFail'],
+ 'running': _now_running_view(),
+ 'seq': seq,
+ 'events': events,
+ 'log': log_lines(80),
+ 'logPath': _log_path(),
+ }
+
+
+def run_now(task_id) -> dict:
+ cfg = load()
+ task = next((t for t in cfg['tasks'] if t.get('id') == task_id), None)
+ if not task:
+ raise ValueError('任务不存在:%s' % (task_id or '(没选)'))
+ _enqueue(task, '手动')
+ return status()
+
+
+def stop_current() -> dict:
+ with _lock:
+ entry = _running
+ if entry:
+ _kill(entry, '手动停止')
+ return status()
diff --git a/backend/core/settings.py b/backend/core/settings.py
index c628a1d..cb30434 100644
--- a/backend/core/settings.py
+++ b/backend/core/settings.py
@@ -181,6 +181,10 @@ def ensure_dirs():
DEFAULTS = {
'maaDir': '',
+ # 明日方舟终末地那一栏用的 MAAEND 根目录(设置里按游戏分 tab,互不覆盖)。
+ # 目前只做到「能配路径」,MAAEND 的任务链还没接——先留位,免得以后
+ # 加进来时还要动一次配置格式。
+ 'maaEndDir': '',
'maaDirs': [], # 用过的 MAA 根目录历史(添加账号时「已存过」列表的数据源)
'autoStartMaa': True,
'autoUpdatePack': True, # 启动后自动拉取新的游戏资源包(关卡/干员/活动)
@@ -401,6 +405,8 @@ def save(patch: dict) -> dict:
continue
if k == 'maaDir':
v = _norm_dir(v)
+ elif k == 'maaEndDir':
+ v = _norm_dir(v)
elif k == 'proxy':
v = _norm_proxy(v)
elif k == 'charBlacklist':
diff --git a/backend/core/skills.py b/backend/core/skills.py
index 182b78d..14ff211 100644
--- a/backend/core/skills.py
+++ b/backend/core/skills.py
@@ -77,28 +77,22 @@ def _account_file(name):
def _account_name_tail(file):
"""账号的切号名(MAA StartUp 切号用的那个)
- **唯一来源:账号自己绑定的 ``maa.accountName``**(设置 → MAA 路径里填的
- 手机尾号,或对话里用户报给助手后回存的)。给空串就退回 adb 重启那条路,
+ 规则只有一份,在 ``acctbind.resolve``:**选了配置文件就读那份档案里的
+ AccountName**(用户在 MAA 里已经配过切号,不该再手抄),没选 / 手填过
+ 就用账号自己存的 ``maa.accountName``。给空串就退回 adb 重启那条路,
调用方负责提示去设置页填。
- 用户口径(2026-11-18):agent 模式跑的是**临时配置**——StartUp 任务参数
- 只有「开始唤醒 + 手机号」,MaaCore 按参数自己换号,**不读也不改用户的
- MAA 配置档案**。以前这里会退回读 MAA 当前档案的 ``AccountName`` / 档案名
- (moren / 136 / 157…)来猜,两个问题:一是违背上面的口径(agent 不该碰
- 用户的 MAA 配置);二是猜错代价大——程序里两个游戏账号对 MAA 里五个尾号
- 档案,档案名和 AccountName 根本说不清谁是谁,错配了 MAA 在账号列表里
- 死找 4 分钟超时。谁要用哪个尾号,只有账号绑定这一个可信来源。
+ 用户口径(2026-11-18 起,2026-11-22 放宽):agent 模式跑的是**临时配置**
+ ——StartUp 任务参数只有「开始唤醒 + 切号名」,MaaCore 按参数自己换号,
+ **不读也不改用户的 MAA 配置档案**;读档案只发生在「用户指定了这个账号
+ 用哪份档案」的时候,而且只读一个字段。
**昵称绝不能拿来顶**:官服切号认的是手机号,拿昵称 MAA 在账号列表里
翻不到,acctname.check 会当场拒。
"""
- try:
- snap = accounts.get_account(file)
- except Exception:
- snap = {}
- maa = snap.get('maa') if isinstance(snap, dict) else None
- maa = maa if isinstance(maa, dict) else {}
- return (maa.get('accountName') or '').strip()
+ from . import acctbind
+ nm, _src = acctbind.resolve(file)
+ return nm
def _client_of(file):
@@ -186,16 +180,37 @@ def norm_stage(raw, log=None):
# ---------------------------------------------------------------- wakeup
+def _remember_tail(file, raw):
+ """用户在对话里报了尾号 → 存进账号设置(下次不用再问)
+
+ 只写本程序自己的账号 json(``maa.accountName`` + ``accountNameFrom=manual``),
+ MAA 那边一个字段都不动。存不进去(文件被占/没权限)不挡主流程。
+ """
+ if not str(raw or '').strip():
+ return ''
+ try:
+ from . import acctbind
+ nm, _why = acctbind.bind(file, raw, _client_of(file))
+ return nm
+ except Exception:
+ return ''
+
+
def skill_wakeup(params, log, tid=None):
"""skill 1:唤醒游戏到主界面
accountName / tail 有值时走 MAA StartUp(能按切号名换账号,官服填手机号
- 后 4 位如 5505);没给就用 adb 直连重启(快,且登录页/START 页/弹窗都能
- 自己处理——stagenav.restart_app)。
+ 后 4 位如 5505,也可以给前 3 位 + 后 4 位如 157****3635);没给就用 adb
+ 直连重启(快,且登录页/START 页/弹窗都能自己处理——stagenav.restart_app)。
"""
file = _account_file(params.get('account') or '')
- tail = (params.get('accountName') or params.get('tail')
- or _account_name_tail(file)).strip()
+ given = (params.get('accountName') or params.get('tail') or '').strip()
+ if given:
+ # 用户亲口报的尾号顺手存进设置:下次挂机 / 换 skill 都不用再问
+ saved = _remember_tail(file, given)
+ if saved:
+ log('切号名 %s 已记到这个账号(设置 → MAA 路径)' % saved)
+ tail = (given or _account_name_tail(file)).strip()
if tail:
# 临时配置:StartUp 任务参数只有「开始唤醒 + 切号名」,MaaCore 按参数
# 自己换号——不读也不改用户的 MAA 配置档案
@@ -214,7 +229,7 @@ def skill_wakeup(params, log, tid=None):
log('adb:%s' % detail)
if not alive:
raise RuntimeError(detail)
- log('这个账号没绑定切号名(设置 → MAA 路径里填手机尾号,'
+ log('这个账号没绑定切号名(设置 → MAA 路径里填手机号后 4 位,'
'或对话里直接告诉我),只能重启当前账号的游戏')
if stagenav.at_home(t) and not stagenav.on_login_page(t) \
and not stagenav.in_story_page(t) and not stagenav.in_story_dialog(t):
@@ -1133,8 +1148,10 @@ def skill_train(params, log, tid=None):
if not params.get('account') and saved.get('account'):
params = dict(params, account=saved['account'])
file = _account_file(params.get('account') or '')
- tail = (params.get('accountName') or params.get('tail')
- or _account_name_tail(file) or '').strip()
+ given = (params.get('accountName') or params.get('tail') or '').strip()
+ if given:
+ _remember_tail(file, given) # 用户报了尾号就存进设置,别下次再问
+ tail = (given or _account_name_tail(file) or '').strip()
switch = params.get('switchAccount')
if switch is None:
switch = bool(tail) # 只有显式给了切号名才切号
@@ -1165,7 +1182,7 @@ def skill_train(params, log, tid=None):
log('先开始唤醒,切到 %s' % tail)
else:
log('先开始唤醒(不切号%s)' % (';要切号去设置 → MAA 路径里给账号'
- '填手机尾号' if not tail else ''))
+ '填手机号后 4 位' if not tail else ''))
spec = {
'tasks': (['startup', 'operprogress'] if wakeup else ['operprogress']),
diff --git a/backend/main.py b/backend/main.py
index cc267e0..9629a38 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -295,6 +295,24 @@ def choose_folder(self, title='选择文件夹', initial=''):
except Exception as e:
return {'path': None, 'error': str(e)}
+ def choose_file(self, title='选择程序', initial=''):
+ """选一个文件(定时任务里挑要启动的 exe / bat)。没有 pywebview 时返回空。"""
+ import webview
+ try:
+ res = webview.windows[0].create_file_dialog(
+ webview.OPEN_DIALOG,
+ directory=initial or '',
+ allow_multiple=False,
+ file_types=('可执行文件 (*.exe;*.bat;*.cmd)', '所有文件 (*.*)'),
+ )
+ if not res:
+ return {'path': None}
+ if isinstance(res, (list, tuple)):
+ return {'path': res[0] if res else None}
+ return {'path': res}
+ except Exception as e:
+ return {'path': None, 'error': str(e)}
+
def open_path(self, path):
"""用系统默认方式打开文件/文件夹"""
try:
@@ -400,6 +418,20 @@ def main():
# 先完成初始化再起 HTTP:窗口期打进来的 /api/app/install 会因 quit hook
# 未装而「前端收到已拉起安装、进程永远不退」(#61)
settings.ensure_dirs() # config/ 与 debug/ 在启动时才建(import 不建)
+ # 卫戍协议核心「保持最新」:启动时看一眼本机小黑盒记录,有新版就后台
+ # 升级(幂等;下载校验失败不动已装版本)
+ try:
+ from core import garrisondl as _gdl
+ threading.Thread(target=_gdl.check_update, daemon=True,
+ name='garrison-upd-check').start()
+ except Exception:
+ pass
+ # 定时任务:时间触发 + 链式启动。线程自己 sleep 轮询,起不来不影响主流程
+ try:
+ from core import scheduler as _sched
+ _sched.start()
+ except Exception:
+ log('[警告] 定时任务没起来\n' + traceback.format_exc())
# 程序自更新:装完后由 api 层调 install(),需要让整个进程退出,
# 而 api 不能 import main,所以反过来把退出函数注册进去
appupdate.set_quit_hook(lambda reason: _quit(0, reason))
diff --git a/docs/agent.md b/docs/agent.md
index 0bf0fab..73b603c 100644
--- a/docs/agent.md
+++ b/docs/agent.md
@@ -162,20 +162,30 @@ MAA 的多账号机制只有一条:**一个配置档案 = 一个账号**。
"AccountSwitchEnabled": true, ...}
```
-`AccountName` 是 MAA 拿去和登录界面那行 OCR 结果做**子串匹配**的,所以三种写法都认(官方说明原话:「可输入 123****4567、4567 或 23****45」):
+`AccountName` 是 MAA 拿去和登录界面那行 OCR 结果做**子串匹配**的,所以四种写法都认(官方说明原话:「可输入 123****4567、4567 或 23****45」):
-- 手机号后 4 位 `5505` —— **对话里只问这个**
+- 手机号后 4 位 `5505` —— **对话里默认问这个**
+- 前 3 位 + 后 4 位 `1573635` / `157 3635` —— 2026-11-22 用户要求也收
- 部分掩码 `23****45`
-- 完整掩码 `181****5505`
+- 完整掩码 `181****5505` / `157****3635`
本机 MAA 里用户自己的档案写的就是 `136` / `3635` / `1686` / `181****5505`,混着用的。
-**这个信息森空岛给不了、MAA 也给不了**——只能问用户。但有个省事的办法:MAA 里已经配过的档案,`AccountName` 和森空岛昵称对得上就直接复用(`multiacct._match()`,容忍 `小卡拉帕鲁灰#6408` ↔ `小卡拉帕鲁灰`)。对不上的才进 `missing` 让助手问。
+**这个信息森空岛给不了**——要么问用户,要么照他绑的配置文件读。三条来源按顺序(`acctbind.resolve()`):
+
+1. 账号绑了 MAA 配置文件(设置 → MAA 路径 → 配置文件)→ 读那份档案 StartUp 的 `AccountName`。**只读**,MAA 里一个字段都不改。
+2. 账号存的 `maa.accountName`(设置里手填的、或对话里报过后 `set_account_name` 存下来的)。
+3. 都没有 → 问用户(官服问后 4 位;用户主动给 `157****3635` 也照收)。
+ 用户一报尾号就调 `set_account_name` 存进设置,下次不用再问。
+
+`multiacct._match()` 还留了一条按昵称对档案的兜底(容忍 `小卡拉帕鲁灰#6408` ↔ `小卡拉帕鲁灰`),对不上的才进 `missing`。
问的时候**别让用户拼星号**,直接问「手机号后 4 位是多少」。用户给全号、带横线、星号数量不对、全角数字都行,`acctname.normalize()` 会统一成 `前3****后4`;给 3~4 位片段就原样保留交给 MAA 子串匹配。
> 2026-11-17:这之前校验写死成 `^\d{3}\*{4}\d{4}$`,用户照 MAA 文档只给尾号就被判非法,助手只能反复追问,任务最后出不来。规则现在只有一份:`backend/core/acctname.py`,别再在别处写第二份正则。
+> 2026-11-22:`_roster` 原来完全禁读用户的 MAA 档案(怕档案和账号对不上号)。现在不是猜——哪份档案由用户在设置里点,程序照他点的读;他手改过的切号名(`accountNameFrom=manual`)优先,不让档案里的旧号码盖回去。
+
另外 `maaProfile` 是**档案名**(`moren` / `136`),不是切号名。曾经 `multiacct.plan()` 里写成 `names.get(...) or c['maaProfile']`,等于把档案名当账号名写进 StartUp,MAA 切号必然失败——整轮挂机死在「登录」这一步。
流程:
diff --git a/docs/backend.md b/docs/backend.md
index 22471be..dc87210 100644
--- a/docs/backend.md
+++ b/docs/backend.md
@@ -35,7 +35,8 @@
| `core/asstlog.py` | MAA 日志观测:`debug/asst.log` 的回调 JSON + `debug/gui.log` 的 `Start/Completed Task Chain` → 结构化事件流;增量读、轮转识别、状态推导(idle/running/stalled/failed/done)、`failures()` 还原「跑过哪几关、哪几关没跑完」 |
| `core/maalog.py` | 直连跑机时的 MAA 日志桥:`maalog.Tap` 从 `asst.log` **末尾**开始增量读(`Tail.seek_end()`,不重放历史),只把 `[ERR]/[WRN]` 里能解释问题的行翻成人话(认不出关卡名 / 干员不存在 / 参数不合法),噪行丢弃、同句 20 秒去重。回调 JSON 行不读——那部分由 `maacore` 回调负责,避免同一件事写两遍 |
| `core/watch.py` | 自愈层:后台线程盯 `asstlog` 的状态,判停滞就关 MAA → 从当前关续写作业列表 → 重启。同一关连续 3 次救不回来就停手报给用户 |
-| `core/acctname.py` | 切号名(MAA `AccountName`)的归一化与校验,**唯一一份规则**。MAA 是拿它和登录界面那行 OCR 做子串匹配,所以 `5505` / `136` / `23****45` / `181****5505` 都合法;用户给全号、带横线、全角数字、星号数量不对都归一成 `前3****后4`。官服只拦「填了昵称」(拿昵称切号会死循环几十次然后失败),B 服不拦 |
+| `core/acctname.py` | 切号名(MAA `AccountName`)的归一化与校验,**唯一一份规则**。MAA 是拿它和登录界面那行 OCR 做子串匹配,所以 `5505` / `136` / `23****45` / `157****3635` / `181****5505` 都合法;用户给全号、带横线、全角数字、星号数量不对都归一成 `前3****后4`,只给「前 3 + 后 4」(`1573635` / `157 3635`)也收。官服只拦「填了昵称」(拿昵称切号会死循环几十次然后失败),B 服不拦 |
+| `core/acctbind.py` | 「这个账号跑 StartUp 写哪个切号名」的唯一解析入口:账号绑了配置文件(`maa.profile`)且没手改过 → 读那份档案 StartUp 的 `AccountName`(`maa.profile_account_name()`,**只读**);否则用账号存的 `maa.accountName`;都没有才返回空让调用方去问用户。手改过的值标 `accountNameFrom=manual`,不会被档案里的旧号码盖回去 |
| `core/multiacct.py` | 多账号编排:MAA「一个配置档案 = 一个账号」,按各账号练度各挑作业,串行切换执行。档案一律新建 `PRTS-` 前缀的那份,用户自己的档案一个字段都不动。切号名统一走 `acctname.check()`;`maaProfile` 是档案名不是切号名,别混用 |
| `core/maaplan.py` | 把「用户想怎么挂」翻成可执行的东西,两条路线:① `build_queue`/`ensure_profile` 写 GUI 的 `TaskQueue` + `RunDirectly`(能看界面,但**不能抄作业**:MAA 的 `InitializeItems` 不认 CopilotTask,会抛 NotImplementedException 让整个任务列表空白);② `core_tasks`/`run_core` 生成 MaaCore 的任务序列直接驱动(能抄作业、能跑 Custom 小活动、自己按开始)。`run_core` 跑抄作业固定四段:**登录(StartUp)→ `AsstStop` 把 MAA 停住 → 用 `stagenav` 点到关卡地图 → 再 append Copilot + `AsstStart`**。停这一步不能省:不停的话 MaaCore 还在按自己的逻辑截屏/滑动,和我们的 adb 点击抢界面。导航失败且这一关有卡片模板(老故事集)时**直接报错**,不把作业交给 MAA——它只会横向滑主线,白跑 30 秒再失败(2026-11-17 SV 实测:停住后 24 秒内 MAA 就在地图上 OCR 到 SV-1、点开始行动、自动编队开打) |
| `core/maacore.py` | MaaCore 直连:`AsstCreateEx` → `AsstLoadResource` → `AsstConnect` → `AsstAppendTask` → `AsstStart`,回调翻成事件流。三个坑写在文件头:`AsstCreateEx` 的 restype 必须是 `c_void_p`(否则 64 位句柄截断成 32 位,每次 append 都 access violation)、Copilot 的 `filename` 必须绝对路径、`copilot_list` 的键是 `filename` 不是 `file_name`(写错会让进程 C++ 异常崩溃) |
@@ -84,7 +85,7 @@ main()
| POST | `/api/settings` | 保存设置(白名单 `maaDir` / `profile` / `autoStartMaa` / `lastAccount`) |
| GET | `/api/accounts` | 账号列表(含每个账号的统计摘要) |
| GET | `/api/account?file=` | 单个账号完整配置:account / stats / missing / chars |
-| POST | `/api/account/maa` | 把 `maa.profile` 等用户字段写回账号 JSON(同步不覆盖的那几个)。`dir` 会归一化并并入「用过的 MAA」历史;`accountName`(切号名)统一走 `acctname.check()`——`5505` / `181 5505` / `181****5505` 都收成 `181****5505`,官服填昵称当场 400,**留空合法**(还没填 / 想清掉) |
+| POST | `/api/account/maa` | 把 `maa.profile` 等用户字段写回账号 JSON(同步不覆盖的那几个)。`dir` 会归一化并并入「用过的 MAA」历史;`profile` 是 MAA 的配置档案名(只记名字,**不读写档案内容**);`accountName`(切号名)统一走 `acctname.check()`——`5505` / `181 5505` / `157****3635` 都收成规范写法,官服填昵称当场 400,**留空合法**(还没填 / 想清掉)。`accountNameFrom`:`manual`=手填(以用户为准)/ `profile`=跟着配置文件走;不传时按 `manual` |
| POST | `/api/account/token` | 设置 → 账号管理用:返回 `{has, broken, token, mask}`。`token` 是明文(只在本地窗口里展示,不落日志、不进 bootstrap),`mask` 只留尾 4 位;`broken=true` 表示密文本机解不开(换电脑 / 换 Windows 用户),与「没存过」分开 |
| POST | `/api/account/token/check` | 拿 grant 接口验一次 token 还能不能用(最长约 12 秒)。只有明确失效才回 `ok:false`,网络问题走异常——界面据此决定要不要解锁「修改」 |
| POST | `/api/account/token/set` | 换 token:先 `Skland(token)` 登录 + 取绑定,确认 token 绑的 uid 就是这个账号,才把密文写回 `skd` 段(练度 / 进度 / MAA 绑定一个字段都不动)。uid 对不上直接报错,防止粘错号把凭证静默换掉 |
@@ -454,18 +455,19 @@ MAA 事件日志通过 tid 透传进同一条任务日志,右栏日志栏与
永远拿不到,StartUp 不带 `account_name`:游戏已在主界面时这条链 2 秒就
「完成」,什么都没做,用户看到的就是「没唤醒就开始导航/培养」。
**昵称绝不能顶**:官服切号认手机号,拿昵称 MAA 在账号列表里翻不到。
-2. **agent 模式切号 = 临时配置,不碰用户的 MAA 档案**(用户口径,2026-11-18
- 晚再定版)。agent 跑 MAA 从不读写用户的 `gui.new.json` 档案:所谓的
- 「配置」就是 StartUp **任务参数**——只配「开始唤醒 + 该账号绑定的手机
- 尾号」,MaaCore 的 `StartUpTask` 拿到非空 `account_name` 就自己换号
+2. **agent 模式切号 = 临时配置,只读用户的 MAA 档案**(2026-11-18 定口径,
+ 2026-11-22 放宽一处)。agent 跑 MAA 从不**写**用户的 `gui.new.json` 档案:
+ 所谓的「配置」就是 StartUp **任务参数**——只配「开始唤醒 + 该账号的切号
+ 名」,MaaCore 的 `StartUpTask` 拿到非空 `account_name` 就自己换号
(核对过 6.20.1 源码:`set_params` 只认 `account_name` / `client_type` /
`start_game_enabled` 三个键,**没有** `account_switch_enabled`,给了也
- 被忽略)。切号名的**唯一来源**是账号绑定 `maa.accountName`(设置 → MAA
- 路径填的,或对话里用户报给助手后回存的);中间版曾加过「读 MAA 当前
- 档案 AccountName / 纯数字档案名」的 fallback,已按上面口径拆掉——
- 程序里两个游戏账号对 MAA 里五个尾号档案,档案名和 AccountName 说不清
- 谁是谁,猜错 MAA 在账号列表里死找 4 分钟。预检(`agent._roster`)同理:
- 只信用户这次给的 + 账号文件里存过的,没有就**问用户**,不从档案猜。
+ 被忽略)。切号名的来源按顺序(`acctbind.resolve`):① 账号绑的配置文件
+ 里 StartUp 的 `AccountName`(用户 2026-11-22 要求:他在 MAA 里已经配过
+ 一次,不该再抄一遍,**这一处破例读档案,但只读一个字段**);② 账号存的
+ `maa.accountName`(手填的 / 对话里报的);③ 都没有就**问用户**。
+ 中间版(2026-11-18)曾完全禁读档案,因为「两个游戏账号对 MAA 里五个
+ 尾号档案,档案名和 AccountName 说不清谁是谁」——现在不是猜:绑哪份档案
+ 由用户在设置里点名,程序照他点的读,手改过的值(`manual`)优先。
2. **「培养干员没进去就报错」——`Engine.wait` 启动竞态**。asst.log 现场:
StartUp 完成 → append OperProgress → `start` → **同一毫秒 `~Assistant`
析构**,任务「完成」但培养一步没跑。原因:AsstStart 异步生效,刚 start
@@ -1213,10 +1215,16 @@ MaaCore 只会报 `adb 连不上`,用户第一反应是程序坏了。放一
`accountName` 现在可以直接在设置 → MAA 路径里按账号填。规则不在这儿重写,
一律 `acctname.check(nm, channel)`:能吃 `5505` / `136` / `23****45` /
-`181****5505` / 全角与带横线的写法;官服只拦「填了昵称」(MAA 拿昵称去
+`157****3635` / 全角与带横线的写法;官服只拦「填了昵称」(MAA 拿昵称去
账号列表里子串匹配,死找几十次后超时,整轮挂机废掉)。**空串放行**——
「还没填」和「填错了」是两件事,用 `check()` 原文会把清空输入框也拦下。
+同一个接口还收 `profile`(MAA 的配置档案名)和 `accountNameFrom`
+(`manual` / `profile`)。设置页里选了配置文件,前端会把该档案 StartUp 的
+`AccountName` 带进输入框、来源标 `profile`;用户一改就标 `manual`,之后
+`acctbind.resolve` 以他填的为准。**档案本身只读**,`gui.new.json` 一个字段
+都不写。
+
## 卫戍协议速刷(`garrison.py` / `garrisondl.py` / `resources/garrison/`,2026-11-20)
**核心不在仓库里**。真正干活的 `service.mjs` 是第三方插件
@@ -1278,3 +1286,38 @@ MAA 的 `gui.new.json` 里 `ConnectSettings` 抄(MuMu→`mumu`+Extras 快速
**推论**:以后核心升到 v1.2.0、v2.0.0 都不用改代码;只有把包挪到非
`medal-farm-v*` 的目录结构时才需要动 `core_dir()`。
+
+## 定时任务(`scheduler.py`,2026-11-22)
+
+设置里的「定时任务」页:到点启动外部程序,支持链式启动。只做「把用户的脚本
+按时拉起来」这一件事——`autostart-*.exe`、`OneDragon-Launcher.exe`、cmd
+批处理这类现成脚本都能原样填进来(程序 + 参数照抄)。
+
+| 概念 | 实现 |
+|---|---|
+| 触发 | `mode=time`:`weekdays`(1=周一…7=周日)+ `time`(HH:MM);`mode=chain`:接在上一条后面 |
+| 动作 | 启动一个程序(exe / bat / cmd)。bat/cmd 走 `cmd /d /c "<整条命令行>"`,路径带空格也不会拆错 |
+| 冲突 | 同一时刻只跑一个:`conflict=stop` 停掉在跑的,`skip` 跳过本次 |
+| 链式失败 | `onChainFail=continue` 继续下一个,`stop` 停掉整条链 |
+
+几个踩过的点:
+
+- **只认当前分钟,不补跑**。程序关着时错过的计划点直接跳过——开机瞬间把前几天
+ 的任务一起补跑,比漏一次更糟。
+- **链式只排下一个**。每条任务跑完只找它后面最近的一条 chain 任务;一次性把
+ 整条链全排进队列的话,同一个任务会被前后两条各排一次(实测跑了两遍)。
+- **停用的 chain 跳过但不截断**:A → B(停用)→ C 会跑 A、C。
+- **杀进程要杀树**。bat 是 cmd 的子进程,只 terminate cmd 会留下孤儿;Windows
+ 上统一 `taskkill /F /T /PID`。
+- **参数按 `CommandLineToArgvW` 拆**(跟 CreateProcess 同一套规则)。`shlex`
+ 在 Windows 上会把引号留在参数里,`--x "a b"` 会变成 `'"a b"'`。
+- **数据/日志**:`config/schedule.json`(原子写);`debug/schedule.log` +
+ 内存环形缓冲。设置页 5 秒轮一次 `/api/schedule/status`,跑完的提示靠
+ `events`(带 seq,同一个事件不会弹两遍)。
+
+接口:`/api/schedule/status`(`?since=
每个账号可以绑自己的 MAA(包含 MAA.exe 的目录),没绑就用下面的默认目录。
- 切号名是 MAA「开始唤醒 → 账号切换」里要比对的那行:官服填手机号后 4 位(如 5505),
- B 服填游戏内用户名。填错的代价是 MAA 在账号列表里死找、4 分钟超时后整轮挂机作废。
Default / moren),
+ 程序会从它的「开始唤醒」里读出切号名——官服是手机号(后 4 位
+ 5505,或前 3 位 + 后 4 位 157****3635,
+ bilibili服是游戏内用户名),读出来还能手改。
+ 只读不写:MAA 里那份档案我们一个字段都不动。填错的代价是 MAA
+ 在账号列表里死找、4 分钟超时后整轮挂机作废。
到点自动启动一个程序:exe、bat、cmd 批处理都行,参数照程序自己 + 的说明填。常见用法是定时跑挂机脚本、到点打开模拟器或别的工具;多条任务 + 还能链式启动——上一个程序退出后接着跑下一个。定时只在程序运行时 + 生效,要开机自启请把本程序放进系统启动项;「通知」是在程序里弹提示, + 程序关着就收不到。
+