Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions docs/superpowers/specs/2026-11-08-jsonc-support-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,21 @@ def loads(text: str) -> Any
不写递归下降解析器,走「预处理 + 标准库」:

1. **剥注释**:扫描文本,跟踪字符串字面量与转义状态;注释内容替换成**等长空白**
(块注释内的换行保留),因此字节偏移与行号完全不变。
(块注释内的换行保留),因此字节偏移与行号完全不变。实现按「片段」拼接而不是
逐字符列表(`list(text)`),峰值内存从文件大小的 ~9 倍降到 ~2 倍。
行注释只以 `\n` 结束——与 meojson 一致(meojson 的行注释扫描同样只认 `\n`,
仅用 CR 换行的文件在 MaaFramework 里也会被整段吞掉)。
2. **拦非法字面量**:再扫一遍,识别 `NaN` / `Infinity` / `-Infinity` 并报错。
3. **剥尾逗号**:再扫一遍,把「其后(跳过空白)是 `}` 或 `]`」且「前面已经有过至少
一个成员」的 `,` 替换成空格——meojson 的解析循环必须先完成一个键值对才会收尾,
所以 `{,}`、`[,]` 是语法错误,必须同样拒绝。
4. **交给标准库**:`json.loads(cleaned, object_pairs_hook=_make_pairs_hook(doc),
parse_float=_make_parse_float(doc))`——前者拒绝重复键,后者拒绝溢出数字。
另外把解释器整数位数限制抛出的 `ValueError`(3.10.7+ 默认 4300 位,
3.10.12+/3.11.4+/3.12+ 的 C scanner 强制执行)转成 `JsoncDecodeError`,
否则它会逃出调用方的 `except json.JSONDecodeError` 分支。
5. **修代理字符**:解析后递归处理字符串,把 `\uXXXX` 代理对还原成真实码点,
落单的代理字符直接报错。
落单的代理字符直接报错;键在规范化后撞车时同样按重复键报错(不能静默覆盖)。

因为偏移量没变,stdlib `JSONDecodeError` 自带的行列号(`line X column Y`)可以直接
用,不需要自己算位置(BOM 在解析前被剥掉,带 BOM 的文件位置会偏移一个字符)。
Expand All @@ -109,9 +115,9 @@ def loads(text: str) -> Any
前两条源于 MaaMCP 与 MaaFramework 的调用方式不同——MaaMCP 要把解析结果重新序列化
成严格 JSON 再交给 `Resource.override_pipeline`。

已确认与 meojson **一致**(无需偏离):注释、尾逗号(含 `{,}` / `[,]` 这类空容器
逗号都拒绝)、重复键、NaN / Infinity、落单代理字符、顶层值之后非 `/` 开头的尾部
垃圾(两者都报错)、顶层值之后的尾部注释(两者都接受)。
已确认与 meojson **一致**(无需偏离):注释(含「行注释只以 `\n` 结束」)、尾逗号
(含 `{,}` / `[,]` 这类空容器逗号都拒绝)、重复键、NaN / Infinity、落单代理字符、
顶层值之后非 `/` 开头的尾部垃圾(两者都报错)、顶层值之后的尾部注释(两者都接受)。

### 错误信息

Expand All @@ -123,6 +129,7 @@ def loads(text: str) -> Any
| 溢出数字 | `1e999 is not a finite number`(无位置) |
| 落单代理字符 | `lone surrogate in string`(无位置) |
| 重复键 | `Duplicate key 'X'`(无位置,stdlib hook 无法定位) |
| 超大整数(超出解释器位数限制) | `invalid number: Exceeds the limit (N digits) ...`(无位置) |

## 接入点

Expand Down
69 changes: 53 additions & 16 deletions maa_mcp/jsonc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

与 MaaFramework(= meojson `json::parsec`)一致的接受集合:

- 允许 `//` 行注释、`/* */` 块注释
- 允许 `//` 行注释、`/* */` 块注释(行注释只以 `\n` 结束,与 meojson 一致)
- 允许对象 / 数组尾逗号(但 `{,}`、`[,]` 这类空容器里的逗号是语法错误,
MaaFramework 同样拒绝)
- 其余严格遵循 JSON 规范:键必须是双引号字符串,拒绝单引号、拒绝
Expand All @@ -31,12 +31,18 @@
方向是「更严」:MaaMCP 不会接受 MaaFramework 拒绝的文件,只会在这类病态的
尾部残余上报错(`Extra data` / `Unterminated comment`)。
注:未闭合注释出现在文档**内部**时,两边都拒绝,行为一致。

另一处与 Python 解释器相关、而非与 meojson 相关的差异:Python 3.10.7+ 限制整数字
符串的转换位数(默认 4300 位),3.10.12+ / 3.11.4+ / 3.12+ 的 json C scanner 会强制
执行并抛 `ValueError`。本模块把它转成 `JsoncDecodeError`,避免它逃出调用方的
`except json.JSONDecodeError` 分支直接冲到 MCP 工具调用之外。
"""

from __future__ import annotations

import json
import math
import re
from typing import Any, Callable

__all__ = ["JsoncDecodeError", "loads"]
Expand All @@ -45,6 +51,8 @@
_WHITESPACE = " \t\r\n"
# 标准库 json 默认接受、但 JSON 规范与 MaaFramework 都不接受的字面量
_NON_JSON_CONSTANTS = frozenset({"NaN", "Infinity", "-Infinity"})
# 注释内容置空时保留换行(换行影响行号,不能被抹掉)
_BLANK_NON_NEWLINE = re.compile(r"[^\n]")


class JsoncDecodeError(json.JSONDecodeError):
Expand Down Expand Up @@ -72,8 +80,17 @@ def _strip_comments(text: str) -> str:

注释内容替换为空格(块注释内的换行保留),返回文本与入参等长,
行列号完全一致,后续步骤的报错位置可以直接沿用。

实现上按「片段」拼接而不是逐字符列表:注释通常只占文件很小一部分,
这样峰值内存是文件大小的常数倍,而不是每字符一个指针(8 字节/字符)。

行注释只以 `\\n` 结束——**裸 `\\r` 不结束行注释**,与 meojson 一致
(meojson 的行注释扫描同样只认 `\\n`,因此仅用 CR 换行的文件在
MaaFramework 里也会被整段吞掉)。保持一致才能保证「同一个文件在
MaaFramework 与 MaaMCP 里的解析结果相同」。
"""
out = list(text)
parts: list[str] = []
last = 0 # 尚未输出的原文本片段起点
i = 0
n = len(text)
in_string = False
Expand Down Expand Up @@ -101,24 +118,26 @@ def _strip_comments(text: str) -> str:
# 行注释:到行尾为止(换行符本身保留)
end = text.find("\n", i)
end = n if end == -1 else end
for k in range(i, end):
out[k] = " "
parts.append(text[last:i])
parts.append(" " * (end - i))
last = end
i = end
continue
if marker == "*":
# 块注释:到 */ 为止
end = text.find("*/", i + 2)
if end == -1:
raise JsoncDecodeError("Unterminated comment", text, i)
for k in range(i, end + 2):
if text[k] != "\n":
out[k] = " "
parts.append(text[last:i])
parts.append(_BLANK_NON_NEWLINE.sub(" ", text[i : end + 2]))
last = end + 2
i = end + 2
continue

i += 1

return "".join(out)
parts.append(text[last:])
return "".join(parts)


def _strip_trailing_commas(text: str) -> str:
Expand All @@ -129,7 +148,8 @@ def _strip_trailing_commas(text: str) -> str:
的逗号是语法错误,MaaFramework 会拒绝。这里必须同样拒绝,否则 MaaMCP
会接受 MaaFramework 拒绝的文件。
"""
out = list(text)
parts: list[str] = []
last = 0
i = 0
n = len(text)
in_string = False
Expand Down Expand Up @@ -163,15 +183,18 @@ def _strip_trailing_commas(text: str) -> str:
while j < n and text[j] in _WHITESPACE:
j += 1
if j < n and text[j] in "}]" and prev not in "{[,":
out[i] = " "
parts.append(text[last:i])
parts.append(" ")
last = i + 1
prev = ","
i += 1
continue

prev = ch
i += 1

return "".join(out)
parts.append(text[last:])
return "".join(parts)


def _reject_non_json_constants(text: str) -> None:
Expand Down Expand Up @@ -289,16 +312,24 @@ def _decode_surrogates(text: str, doc: str) -> str:


def _sanitize_surrogates(value: Any, doc: str) -> Any:
"""递归处理解析结果里的字符串(键与值),还原代理对、拒绝落单代理。"""
"""递归处理解析结果里的字符串(键与值),还原代理对、拒绝落单代理。

键在规范化后可能撞车(同一字符既以字面形式又以代理对转义形式出现),
此时必须报错而不是让后来的值静默覆盖前面的值——meojson 在解析阶段
就把 `\\uXXXX` 合成真实码点,因此同样会判定为重复键。
"""
if isinstance(value, str):
return _decode_surrogates(value, doc)
if isinstance(value, list):
return [_sanitize_surrogates(item, doc) for item in value]
if isinstance(value, dict):
return {
_decode_surrogates(key, doc): _sanitize_surrogates(item, doc)
for key, item in value.items()
}
result: dict[str, Any] = {}
for key, item in value.items():
new_key = _decode_surrogates(key, doc)
if new_key in result:
raise JsoncDecodeError(f"Duplicate key {new_key!r}", doc)
result[new_key] = _sanitize_surrogates(item, doc)
return result
return value


Expand Down Expand Up @@ -338,5 +369,11 @@ def loads(text: str) -> Any:
raise
# 用原文重新抛出:偏移量一致,位置信息对用户仍然准确
raise JsoncDecodeError(e.msg, doc, e.pos) from e
except ValueError as e:
# json.JSONDecodeError 是 ValueError 的子类,上面已先捕获。
# 这里剩下的是解释器的整数位数限制(Python 3.10.7+ 默认 4300 位,
# 3.10.12+ / 3.11.4+ / 3.12+ 的 json C scanner 会强制执行)抛出的
# ValueError——它不是 JSONDecodeError,会逃出调用方的 except 分支。
raise JsoncDecodeError(f"invalid number: {e}", doc) from e

return _sanitize_surrogates(parsed, doc)
83 changes: 82 additions & 1 deletion tests/test_jsonc.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

from maa_mcp.agent_supervisor import load_agent_config
from maa_mcp.jsonc import loads
from maa_mcp.jsonc import _sanitize_surrogates, _strip_comments, loads
from maa_mcp.pipeline_tools import (
_read_and_validate_pipelines,
load_pipeline,
Expand Down Expand Up @@ -210,6 +211,86 @@ def test_trailing_slash_residue_rejected(self) -> None:
with pytest.raises(json.JSONDecodeError):
loads('{"A": 1}/x')

def test_cr_only_line_comment_matches_meojson(self) -> None:
"""仅用 CR 换行时,行注释会吞掉后续内容——与 meojson 一致。

meojson 的行注释扫描只认 `\\n`,因此仅用 CR 换行的文件在 MaaFramework
里同样会被整段吞掉。这里必须保持一致,否则同一份文件在两边解析结果
不同(MaaFramework 能读、MaaMCP 读不了,或反之)。
"""
with pytest.raises(json.JSONDecodeError):
loads('// 注释\r{"A": 1}')
# 注释在末尾时不影响已解析出的内容
assert loads('{"A": 1}// 注释\r') == {"A": 1}

def test_normalized_key_collision_rejected(self) -> None:
"""规范化后撞车的键必须报错,而不是让后来的值静默覆盖。"""
payload = {chr(0x1F600): 1, chr(0xD83D) + chr(0xDE00): 2}

with pytest.raises(json.JSONDecodeError, match="Duplicate key"):
_sanitize_surrogates(payload, "{}")

def test_comment_stripping_blanks_comments_and_preserves_length(self) -> None:
"""注释必须真的被置空,且长度不变(错误位置才对得上原文)。"""
text = '{\n// 注释\n"A": 1 /* 块注释 */\n}'

result = _strip_comments(text)

# 长度不变:位置信息才对得上原文
assert len(result) == len(text)
# 注释内容确实被抹掉(不是原样返回)
assert "//" not in result
assert "/*" not in result
assert "注释" not in result
# 抹掉注释后仍是合法 JSON,且内容不变
assert json.loads(result) == {"A": 1}

def test_value_error_converted_to_decode_error(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""json.loads 抛出的 ValueError 必须转成 JsoncDecodeError。

解释器的整数位数限制(Python 3.10.7+)就是这么抛的——它不是
JSONDecodeError,会逃出调用方的 `except json.JSONDecodeError` 分支。
这里用 monkeypatch 模拟,不依赖解释器版本与限制是否生效。
"""

def boom(*args: object, **kwargs: object) -> None:
raise ValueError(
"Exceeds the limit (4300 digits) for integer string conversion"
)

monkeypatch.setattr(json, "loads", boom)

with pytest.raises(json.JSONDecodeError, match="invalid number"):
loads('{"A": 1}')

def test_huge_integer_reported_as_decode_error(self) -> None:
"""超大整数应转成 JSONDecodeError,而不是逃出裸 ValueError。

Python 3.10.7+ 有整数位数限制(默认 4300 位);3.10.12+ / 3.11.4+ /
3.12+ 的 json C scanner 会强制执行并抛 ValueError——它不是
JSONDecodeError,会逃出调用方的 `except` 分支直接冲到工具调用之外。
"""
setter = getattr(sys, "set_int_max_str_digits", None)
if setter is None:
pytest.skip("当前解释器没有整数位数限制")

# 解释器要求上限至少是 640(0 表示不限制),取最小值再超一点
old = sys.get_int_max_str_digits()
setter(640)
try:
try:
loads('{"A": ' + "9" * 700 + "}")
except json.JSONDecodeError:
pass # 期望路径:已转成 JSONDecodeError 子类
except ValueError as e:
pytest.fail(f"ValueError 逃出了 JSONDecodeError: {e}")
else:
pytest.skip("当前解释器的 json scanner 未强制整数位数限制")
finally:
setter(old)

@pytest.mark.parametrize(
"payload",
[
Expand Down
22 changes: 21 additions & 1 deletion tests/test_performance_stress.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from maa_mcp.vision import ocr, screencap
from maa_mcp.control import click, swipe, input_text, click_key, scroll, double_click
from maa_mcp.core import controller_info_registry, ControllerType
from maa_mcp.core import controller_info_registry, object_registry, ControllerType
from maa_mcp.adb import find_adb_device_list, connect_adb_device
from maa_mcp.win32 import find_window_list, connect_window

Expand Down Expand Up @@ -269,8 +269,28 @@ def setup_class(self):
pytest.skip(
f"指定的窗口 {window_name!r} 不存在,可用窗口: {window_list}"
)
# connect_window 按标题查名字注册的表,同名窗口会互相覆盖,
# 可能连到另一个同名窗口上去——标题不唯一时宁可跳过。
if window_list.count(window_name) > 1:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 中 · 压力测试针对了错误的窗口

如果另一次 find_window_list 调用在唯一性检查与 connect_window 之间更新了注册表,connect_window 会通过更新后的注册表解析标题,并连接到新注册的同名窗口,因此压力测试会向错误的应用程序发送输入。

应将发现窗口和连接窗口设为原子操作,或者使用稳定的窗口标识进行连接,而不是在检查后再查找标题。

面向 AI 代理的提示
在 `tests/test_performance_stress.py` 第 274 行:

**压力测试针对了错误的窗口**

如果另一次 `find_window_list` 调用在唯一性检查与 `connect_window` 之间更新了注册表,`connect_window` 会通过更新后的注册表解析标题,并连接到新注册的同名窗口,因此压力测试会向错误的应用程序发送输入。

应将发现窗口和连接窗口设为原子操作,或者使用稳定的窗口标识进行连接,而不是在检查后再查找标题。
Original comment in English

🟡 Medium · Stress test targets the wrong window

When another find_window_list call updates the registry between the uniqueness check and connect_window, connect_window resolves the title through the updated registry and connects to the newly registered same-title window, so the stress test sends input to the wrong application.

Make discovery and connection atomic, or connect using a stable window identity instead of looking up the title after the check.

Prompt for AI agents
In `tests/test_performance_stress.py` at line 274:

**Stress test targets the wrong window**

When another `find_window_list` call updates the registry between the uniqueness check and `connect_window`, `connect_window` resolves the title through the updated registry and connects to the newly registered same-title window, so the stress test sends input to the wrong application.

Make discovery and connection atomic, or connect using a stable window identity instead of looking up the title after the check.

pytest.skip(
f"窗口标题 {window_name!r} 不唯一(同名窗口 "
f"{window_list.count(window_name)} 个),"
f"为避免误操作其他窗口而跳过"
)
# 记下校验过的那个窗口的 hwnd:connect_window 是按标题回查注册表
# 的,检查与连接之间若被别的 find_window_list() 刷新过,可能连到
# 另一个同名窗口。连接后核对 hwnd 对不上就放弃。
expected_hwnd = getattr(object_registry.get(window_name), "hwnd", None)
self.window_name = window_name
self.controller_id = _call_tool(connect_window, self.window_name)
if self.controller_id and expected_hwnd is not None:
info = controller_info_registry.get(self.controller_id)
actual_hwnd = info.connection_params.get("hwnd") if info else None
if actual_hwnd != expected_hwnd:
pytest.skip(
f"连接到的窗口 hwnd {actual_hwnd!r} 与校验过的 "
f"{expected_hwnd!r} 不一致,为避免误操作其他窗口而跳过"
)
print(
f" 使用Windows窗口: {self.window_name}, 控制器ID: {self.controller_id}"
)
Expand Down
Loading