1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
| """检查、修补或还原 Codex VS Code 扩展的发送锁返回值错误(仅标准库)。"""
from __future__ import annotations
import argparse import json import os from pathlib import Path import re import shutil import subprocess import sys import tempfile
BACKUP_NAME = "extension.js.before-send-lock-fix" HANDLER_KEY = re.compile(rb'["\']queued-follow-up-send-lock-release["\']\s*:') HANDLER = re.compile( HANDLER_KEY.pattern + rb"\s*async\s*\(\s*\{[^{}]{1,300}\}\s*\)\s*=>\s*\{" + rb"(?P<release>\s*this\.queuedFollowUpSendLocks\.release\(" + rb"\s*\{[^{}]{1,300}\}\s*\)\s*;?\s*)" + rb"(?P<returned>return\s+(?:\{[^{}]{0,200}\}|null|true|!0)\s*;?\s*)?\}" )
def inspect_handler(content: bytes) -> tuple[re.Match[bytes], bool]: keys = list(HANDLER_KEY.finditer(content)) if len(keys) != 1: raise ValueError("发送锁处理函数未唯一匹配,拒绝修改此版本。") match = HANDLER.match(content, keys[0].start()) if match is None: raise ValueError("发送锁处理函数结构已经变化,需要重新检查此版本。") return match, match.group("returned") is not None
def patched_content(content: bytes) -> bytes: match, has_return = inspect_handler(content) if has_return: return content position = match.end() - 1 return content[:position] + b";return {success:true}" + content[position:]
def replace_file(path: Path, content: bytes) -> None: """Write beside the source and replace it only after the complete write.""" temporary = None try: with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream: temporary = Path(stream.name) stream.write(content) stream.flush() os.fsync(stream.fileno()) shutil.copymode(path, temporary) os.replace(temporary, path) finally: if temporary is not None: temporary.unlink(missing_ok=True)
def process_file(path: Path, action: str, dry_run: bool = False) -> str: content = path.read_bytes() backup = path.with_name(BACKUP_NAME) if action == "restore": original = backup.read_bytes() _, backup_has_return = inspect_handler(original) if backup_has_return: raise ValueError("备份不是修补前的原文件,拒绝还原。") if content == original: return "已经还原" if content != patched_content(original): raise ValueError("当前文件与此备份不属于同一次修补,拒绝覆盖。") if dry_run: return "将还原(未写入)" replace_file(path, original) return "已还原,备份保留"
_, has_return = inspect_handler(content) if has_return: return "已有返回值,无需修补" if action == "check": return "需要修补" if backup.exists() and backup.read_bytes() != content: raise ValueError("已有备份与当前原文件不同,拒绝覆盖备份或扩展。") if dry_run: return "将修补并备份(未写入)" if not backup.exists(): with backup.open("xb") as stream: stream.write(content) stream.flush() os.fsync(stream.fileno()) shutil.copystat(path, backup) if path.read_bytes() != content: raise ValueError("读取后扩展文件发生变化,拒绝修改;备份已保留。") replace_file(path, patched_content(content)) return "已修补,备份:" + str(backup)
def native_roots(user_home: Path) -> list[Path]: roots = [ user_home / name / "extensions" for name in ( ".vscode", ".vscode-insiders", ".vscode-server", ".vscode-server-insiders", ) ] if os.environ.get("VSCODE_PORTABLE"): roots.append(Path(os.environ["VSCODE_PORTABLE"]) / "extensions") return roots
def is_wsl() -> bool: if sys.platform != "linux": return False return ( bool(os.environ.get("WSL_DISTRO_NAME")) or "microsoft" in os.uname().release.lower() )
def windows_profile_from_wsl(user_home: Path) -> Path: """Resolve only the current Windows profile, without scanning other users.""" profile = os.environ.get("USERPROFILE") powershell = shutil.which("powershell.exe") if not profile and powershell: try: result = subprocess.run( [ powershell, "-NoProfile", "-NonInteractive", "-Command", "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " "[Environment]::GetFolderPath('UserProfile')", ], capture_output=True, timeout=8, check=True, ) profile = result.stdout.decode("utf-8-sig").strip() except (OSError, subprocess.SubprocessError, UnicodeError): pass if profile: if profile.startswith("/"): return Path(profile) try: result = subprocess.run( ["wslpath", "-u", profile], capture_output=True, text=True, timeout=5, check=True, ) return Path(result.stdout.strip()) except (OSError, subprocess.SubprocessError): pass matches = [ path for path in Path("/mnt/c/Users").glob("*") if path.is_dir() and path.name.casefold() == user_home.name.casefold() ] if len(matches) == 1: return matches[0] raise ValueError("无法确定 Windows 用户目录,请用 --extensions-dir 指定扩展目录。")
def discover_roots(target: str, user_home: Path) -> list[Path]: roots = native_roots(user_home) if target in ("native", "all") else [] if target in ("windows", "all"): if sys.platform == "win32": roots.extend(native_roots(user_home)) elif is_wsl(): profile = windows_profile_from_wsl(user_home) roots.extend( profile / name / "extensions" for name in (".vscode", ".vscode-insiders") ) elif target == "windows": raise ValueError( "当前不是 Windows 或 WSL,请用 --extensions-dir 指定目录。" ) return list(dict.fromkeys(path.resolve() for path in roots))
def select_extensions(root: Path) -> list[Path]: """Prefer registered versions; cached older installations are not selected.""" registry = root / "extensions.json" if registry.exists(): entries = json.loads(registry.read_text(encoding="utf-8-sig")) if not isinstance(entries, list): raise ValueError("extensions.json 不是扩展列表。") selected = [] for entry in entries: if not isinstance(entry, dict) or not isinstance( entry.get("identifier"), dict ): raise ValueError("extensions.json 包含无效登记项。") if entry.get("identifier", {}).get("id", "").lower() != "openai.chatgpt": continue relative = entry.get("relativeLocation") if not relative: raise ValueError( "登记项缺少 relativeLocation,请显式指定扩展安装目录。" ) path = (root / relative).resolve() if path.parent != root.resolve(): raise ValueError("登记项路径超出扩展目录,拒绝使用。") selected.append(path) return list(dict.fromkeys(selected))
candidates = [] for path in root.glob("openai.chatgpt-*"): manifest = path / "package.json" if manifest.exists(): metadata = json.loads(manifest.read_text(encoding="utf-8-sig")) if not isinstance(metadata, dict): raise ValueError("package.json 不是扩展信息对象。") version = str(metadata.get("version", "")) if re.fullmatch(r"\d+\.\d+\.\d+", version): candidates.append((tuple(map(int, version.split("."))), path)) return [max(candidates, key=lambda item: item[0])[1]] if candidates else []
def extension_file(path: Path) -> Path: manifest = json.loads((path / "package.json").read_text(encoding="utf-8-sig")) if not isinstance(manifest, dict): raise ValueError("package.json 不是扩展信息对象。") if manifest.get("publisher") != "openai" or manifest.get("name") != "chatgpt": raise ValueError("此目录不是 openai.chatgpt 扩展。") return path / "out" / "extension.js"
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "action", nargs="?", choices=("check", "patch", "restore"), default="check" ) parser.add_argument( "--target", choices=("native", "windows", "all"), default="native", help="默认当前系统;WSL 中可选 windows 或 all。", ) parser.add_argument( "--extensions-dir", type=Path, action="append", help="自定义扩展集合目录,或具体 openai.chatgpt 安装目录;可重复指定。", ) parser.add_argument( "--dry-run", action="store_true", help="仅显示修补或还原计划,不写入。" ) args = parser.parse_args() try: roots = args.extensions_dir or discover_roots(args.target, Path.home()) installations = [] for root in roots: root = root.expanduser().resolve() if (root / "package.json").exists(): installations.append(root) elif root.is_dir(): installations.extend(select_extensions(root)) installations = list(dict.fromkeys(installations)) if not installations: raise ValueError("未找到 Codex 扩展,请用 --extensions-dir 指定目录。") failed = False for installation in installations: try: status = process_file( extension_file(installation), args.action, args.dry_run ) print(str(installation) + "\n " + status) except (OSError, ValueError) as error: print(str(installation) + "\n 失败:" + str(error), file=sys.stderr) failed = True if args.action != "check" and not args.dry_run and not failed: print("等当前任务结束后,在 VS Code 中运行 Developer: Reload Window。") return 1 if failed else 0 except (OSError, ValueError) as error: print("失败:" + str(error), file=sys.stderr) return 1
if __name__ == "__main__": raise SystemExit(main())
|