Repository navigation
Expand file tree
/
Copy pathruntime_lock.py
More file actions
843 lines (759 loc) · 40.3 KB
/
Copy pathruntime_lock.py
File metadata and controls
843 lines (759 loc) · 40.3 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# -*- coding: utf-8 -*-
"""Permanent-file OS locks shared by the runtime synchronizer and Node helpers."""
import argparse
import errno
import hashlib
import json
import os
import re
import shutil
import stat
import sys
import tempfile
import time
from contextlib import ExitStack, contextmanager
from pathlib import Path
_MKSTEMP_ATTEMPTS = 16
def bounded_mkstemp(prefix, dir=None, suffix=""):
"""受限次数的临时文件创建:与 tempfile.mkstemp 同形态(返回可用 fd 与路径),
但 PermissionError 单次即原样抛出;形参顺序与 tempfile.mkstemp 不同,
只应关键字传参。stdlib 的 _mkstemp_inner 在 Windows 上吞掉 PermissionError
换随机名重试:旧形态(3.13.12 及更早、3.12 全线、3.14.0-3.14.3)还要求
os.access 报可写(os.access 看不见 ACL,受保护目录恒真),TMP_MAX 取
Windows 的 2^31-1,等于无限挂起(issue #360);新形态(3.13.13+ 与 3.14.4+)
自限 TMP_MAX=20 不再挂起、受保护目录上最终仍原样抛 PermissionError,但仍有
20 次无谓重试且行为跨版本不一致。os.open 的单次失败是快错:只有
FileExistsError(随机名碰撞)才换名重试,至多 _MKSTEMP_ATTEMPTS 次。"""
directory = os.fspath(dir) if dir is not None else tempfile.gettempdir()
for _ in range(_MKSTEMP_ATTEMPTS):
name = os.path.join(directory, prefix + os.urandom(8).hex() + suffix)
try:
return os.open(name, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600), name
except FileExistsError:
continue
raise FileExistsError(errno.EEXIST, "No usable temporary file name found")
@contextmanager
def bounded_tempdir(prefix, dir=None, suffix=""):
"""受限次数的临时目录创建与容错清理:stdlib 的 tempfile.mkdtemp 在 Windows 上
与 _mkstemp_inner 同构(os.access 看不见 ACL 时吞掉 PermissionError 重试 TMP_MAX 次),
且 TemporaryDirectory.__exit__ 在 Windows 子进程/杀软短暂持有句柄时会因 rmtree
PermissionError(WinError 32/5)把已成功的上层调用打崩(Python 3.8/3.9 亦无
ignore_cleanup_errors)。这里单次快错 PermissionError、仅 FileExistsError 换名重试
至多 _MKSTEMP_ATTEMPTS 次,退出时 ignore_errors=True 清理。"""
base = os.fspath(dir) if dir is not None else tempfile.gettempdir()
created = None
for _ in range(_MKSTEMP_ATTEMPTS):
candidate = os.path.join(base, prefix + os.urandom(8).hex() + suffix)
try:
os.mkdir(candidate, 0o700)
created = candidate
break
except FileExistsError:
continue
if created is None:
raise FileExistsError(errno.EEXIST, "No usable temporary directory name found")
try:
yield created
finally:
try:
shutil.rmtree(created, ignore_errors=True)
except OSError:
pass
def sudo_user(sys_platform=None):
"""sudo 运行时的真实用户名(POSIX;非 sudo / Windows 返回 None)。"""
plat = sys.platform if sys_platform is None else sys_platform
if plat == "win32" or not os.environ.get("SUDO_USER"):
return None
try:
return os.environ["SUDO_USER"] if os.geteuid() == 0 else None
except AttributeError:
return None
def real_home(sudo_user_fn=None, home_fn=None):
"""真实用户家目录:sudo 会重置 HOME,Path.home() 指向 /root,而数据/运行目录与配置
必须落在 SUDO_USER 的家目录。"""
user = (sudo_user if sudo_user_fn is None else sudo_user_fn)()
if user:
try:
import pwd
return Path(pwd.getpwnam(user).pw_dir)
except (KeyError, OSError, ImportError, AttributeError):
pass
return (Path.home if home_fn is None else home_fn)()
def fixed_drives(letters):
"""本地固定盘盘符:离线的映射网络盘一被访问就触发重连(可卡数秒),光驱/读卡器可能无介质。"""
try:
import ctypes
drive_type = ctypes.windll.kernel32.GetDriveTypeW
except (ImportError, AttributeError, OSError):
return []
return [letter for letter in letters if drive_type(f"{letter}:\\") == 3] # DRIVE_FIXED
class FileLockBusy(TimeoutError):
"""An advisory lock stayed held until its acquisition deadline."""
# os.replace / os.unlink 遇并发读者的短暂重试(同 token_rate._replace_state_file)。
_REPLACE_ATTEMPTS = 20
_REPLACE_WAIT_S = 0.01
def _replace_retrying(source, target):
"""os.replace 短暂重试。Windows 上目标被任何句柄打开时替换都被拒绝——读者、杀软,也包括
主进程自己的 fs 句柄(实测不论共享模式);这些读者都是微秒级短开,重试窗口远大于它。
静默放弃会丢掉重启待办,手机安装意图的回滚失败还会留下一条永不销账的
pending-install。POSIX 的 rename 不受并发读者影响,重试零成本;永久性拒绝只是多等
(_REPLACE_ATTEMPTS − 1) × _REPLACE_WAIT_S(约 190ms)才上抛同一异常。"""
for attempt in range(_REPLACE_ATTEMPTS):
try:
os.replace(source, target)
return
except PermissionError:
if attempt == _REPLACE_ATTEMPTS - 1:
raise
time.sleep(_REPLACE_WAIT_S)
def _unlink_retrying(path):
"""同 _replace_retrying,用于删除标记;文件本就不在按成功处理。"""
for attempt in range(_REPLACE_ATTEMPTS):
try:
os.unlink(path)
return
except FileNotFoundError:
return
except PermissionError:
if attempt == _REPLACE_ATTEMPTS - 1:
raise
time.sleep(_REPLACE_WAIT_S)
def _discard_tmp(name):
"""丢弃没发布的临时文件(尽力清理,不打断已经在传播的异常)。带 preserve 的写入会把
临时文件 chmod 成目标的权限位:Windows 上目标只读时它也只读,unlink 被拒——先补回写
权限再删,否则每次失败都留下一个 .tmp。"""
try:
os.unlink(name)
except FileNotFoundError:
return
except PermissionError:
try:
os.chmod(name, stat.S_IWRITE | stat.S_IREAD)
os.unlink(name)
except OSError:
pass
except OSError:
pass
@contextmanager
def file_lock(path, timeout=10.0):
"""Acquire an advisory lock or raise TimeoutError; never unlink the lock file."""
fd = os.open(os.fspath(path), os.O_RDWR | os.O_CREAT, 0o600)
locked = False
deadline = time.monotonic() + max(0.0, timeout)
try:
if os.name == "nt":
import msvcrt
if os.fstat(fd).st_size == 0:
# 两个进程同时首次创建同一锁文件时,后到者在先到者补写之前看到大小 0,这次
# 补写会撞上对方刚锁定的首字节(EACCES)。这只是锁被占,落到下面的取锁
# 循环按 busy 处理;其它错误原样上抛。
try:
os.write(fd, b"\0")
except OSError as exc:
if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
else:
import fcntl
while True:
try:
if os.name == "nt":
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
locked = True
break
except OSError as exc:
if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
remaining = deadline - time.monotonic()
if remaining <= 0:
raise FileLockBusy("runtime lock is busy: " + os.fspath(path)) from exc
time.sleep(min(0.05, remaining))
yield
finally:
try:
if locked:
if os.name == "nt":
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)
def _read_marker(marker, unreadable=None):
"""JSON 损坏/非对象按空标记(合并与发布链据此重建);读不到(OSError)返回 unreadable。
缺省仍是空标记;record_restart/ack_restart 传 False 以区分「读不到」与「没有待办」。
文件不存在恒为空标记:「没有标记」不是读失败。"""
try:
raw = marker.read_text(encoding="utf-8")
except (FileNotFoundError, UnicodeDecodeError):
return {}
except OSError:
return {} if unreadable is None else unreadable
return _parse_marker(raw)
def _parse_marker(raw):
try:
if isinstance(raw, bytes):
raw = raw.decode("utf-8")
data = json.loads(raw)
except ValueError:
return {}
return data if isinstance(data, dict) else {}
def _hashes(value):
if not isinstance(value, dict):
return {}
return {key: digest for key, digest in value.items()
if isinstance(key, str) and not key.startswith("_")
and isinstance(digest, str) and digest}
# 运行中的 loader 启动时对固定清单做指纹,并把清单(`_tracked`)随 --ack-restart
# 上报。旧 loader 只上报成功算出摘要的文件名,所以「缺 key」有两种可能:该文件不在
# 这个 loader 的契约里,或者文件在契约里但本次读失败。新 loader 显式声明清单;旧
# loader 则从 inject-main.cjs 里启动指纹数组的字面量还原。尽力而为:源码缺失或结构
# 未知时,调用方回退到既有的「盘上有目标字节就保留」保守语义。
_TRACKED_LIST_RE = re.compile(r"for\s*\(\s*const\s+name\s+of\s*\[(.*?)\]", re.S)
_TRACKED_NAME_RE = re.compile(r'"([^"]{1,128})"')
def _plain_runtime_name(name):
return (isinstance(name, str) and 0 < len(name) <= 128
and name.endswith((".cjs", ".js", ".py"))
and not name.startswith(".")
and "/" not in name and "\\" not in name and "\x00" not in name)
def _loader_tracked_files(runtime):
"""尽力还原运行中 loader 的启动指纹清单;读不到返回 None。"""
try:
source = (runtime / "inject-main.cjs").read_text(encoding="utf-8", errors="replace")
except OSError:
return None
# 只扫描启动指纹块:新 loader 里还有大量同名 for-loop(quota/宠物/工具清单),
# 全文件扫描会把无关文件名混进契约,误剔盘上仍待重启的文件。
start = source.find("loadedHashes")
if start < 0:
return None
end = source.find("function acknowledgeRestart", start)
if end < 0:
# 夹具/极简 loader 可能没有 acknowledgeRestart:只取声明后的短窗口,
# 不把文件后半段的其它 for-loop 混进启动契约。
end = min(len(source), start + 4096)
names = set()
for block in _TRACKED_LIST_RE.findall(source[start:end]):
names.update(_TRACKED_NAME_RE.findall(block))
names = {name for name in names if _plain_runtime_name(name)}
return names or None
def _ack_tracked_files(runtime, loaded):
"""优先用 loader 的 _tracked 显式清单,旧 loader 回退源码解析。"""
declared = loaded.get("_tracked")
if isinstance(declared, list):
names = {name for name in declared if _plain_runtime_name(name)}
if names:
return names
return _loader_tracked_files(runtime)
def _write_marker(marker, data, preserve=None):
fd, name = bounded_mkstemp(prefix=marker.name + ".", suffix=".tmp", dir=marker.parent)
try:
if preserve is not None:
if os.name != "nt":
current = os.fstat(fd)
if (current.st_uid, current.st_gid) != (preserve.st_uid, preserve.st_gid):
os.fchown(fd, preserve.st_uid, preserve.st_gid)
os.chmod(name, stat.S_IMODE(preserve.st_mode))
with os.fdopen(fd, "w", encoding="utf-8") as stream:
fd = None
json.dump(data, stream, ensure_ascii=False)
stream.write("\n")
_replace_retrying(name, marker)
finally:
if fd is not None:
os.close(fd)
_discard_tmp(name)
def _restore_marker_bytes(marker, previous):
if previous is None:
_unlink_retrying(marker)
return
fd, name = bounded_mkstemp(prefix=marker.name + ".", suffix=".tmp", dir=marker.parent)
try:
with os.fdopen(fd, "wb") as stream:
fd = None
stream.write(previous)
stream.flush()
os.fsync(stream.fileno())
_replace_retrying(name, marker)
finally:
if fd is not None:
os.close(fd)
_discard_tmp(name)
def update_config(runtime, changes, defaults=None, merge=None):
"""Reread under lock, then apply defaults, top-level changes and one-level merges.
merge maps literal top-level object keys to direct child replacements; it never
interprets dot paths or recursively merges values.
"""
if not isinstance(changes, dict) or (defaults is not None and not isinstance(defaults, dict)):
raise ValueError("config changes/defaults must be JSON objects")
if merge is not None:
if not isinstance(merge, dict):
raise ValueError("config merge must be a JSON object")
unsafe_keys = {"__proto__", "constructor", "prototype"}
for key, value in merge.items():
if not isinstance(key, str) or key in unsafe_keys or not isinstance(value, dict):
raise ValueError("config merge must map safe string keys to JSON objects")
if any(not isinstance(child, str) or child in unsafe_keys for child in value):
raise ValueError("config merge child keys must be safe strings")
runtime = Path(runtime)
runtime.mkdir(parents=True, exist_ok=True)
config = runtime / "config.json"
lock_path = runtime / "plugin-config.lock"
with file_lock(lock_path):
owner = config.stat() if config.exists() else runtime.stat()
if os.name != "nt" and hasattr(os, "geteuid") and os.geteuid() == 0:
lock_stat = lock_path.stat()
if (lock_stat.st_uid, lock_stat.st_gid) != (owner.st_uid, owner.st_gid):
os.chown(lock_path, owner.st_uid, owner.st_gid)
try:
current = json.loads(config.read_text(encoding="utf-8"))
except FileNotFoundError:
current = {}
if not isinstance(current, dict):
raise ValueError("config.json must be a JSON object")
updated = dict(current)
for key, value in (defaults or {}).items():
updated.setdefault(key, value)
updated.update(changes)
merge_changed = False
for key, value in (merge or {}).items():
previous = updated.get(key)
nested = dict(previous) if isinstance(previous, dict) else {}
nested.update(value)
updated[key] = nested
# Python considers True == 1 and False == 0; a merge must persist JSON types.
merge_changed = merge_changed or (json.dumps(nested, sort_keys=True)
!= json.dumps(current.get(key), sort_keys=True))
if not merge_changed and updated == current and config.exists():
return False
_write_marker(config, updated, config.stat() if config.exists() else None)
return True
class ReconcileResult(object):
"""reconcile_python_path 的结论;action 供 doctor/诊断消费,不写日志文件。"""
__slots__ = ("changed", "action", "python_path")
def __init__(self, changed, action, python_path):
self.changed = changed
self.action = action
self.python_path = python_path
def __repr__(self):
return "ReconcileResult(changed=%r, action=%r, python_path=%r)" % (self.changed, self.action, self.python_path)
def managed_entry_path(environ=None, sys_platform=None):
"""PATH 首项目录下的宿主托管稳定入口(bin/zcode-python.exe,POSIX 为同名入口脚本)
绝对路径,找不到返回 None。只读探测:只看 stable_managed_python 的判据 1、2,不绑定
执行端——「入口在不在」与「本进程是不是它拉起的」是两件事:体检由系统解释器执行时
入口可以好好地在 PATH 首项,不能报成「找不到入口」。"""
environ = os.environ if environ is None else environ
if sys_platform is None:
sys_platform = sys.platform
if str(environ.get("ZCODE_PREINSTALLED_TOOLS_AVAILABLE", "")) != "1":
return None
raw_path = environ.get("PATH") or ""
head = raw_path.split(os.pathsep)[0] if raw_path else ""
if not head.strip():
return None
bin_dir = os.path.abspath(os.path.normpath(head))
entry = os.path.join(bin_dir, "zcode-python.exe" if sys_platform == "win32" else "zcode-python")
if not os.path.isfile(entry):
return None
release_root = os.path.dirname(bin_dir)
if os.path.basename(os.path.dirname(release_root)) != "preinstalled-tools":
return None
return entry
def stable_managed_python(environ=None, executable=None, sys_platform=None):
"""本解释器确由宿主托管入口拉起时,返回稳定入口的绝对路径(bin/zcode-python.exe,
POSIX 为同名入口脚本),否则 None。只读探测:不执行入口、不读安装记录、不写任何文件。
三条判据缺一不可(managed-python-runtime.md(git 历史) §5、HOST-CONTRACT HC3):
1. ``ZCODE_PREINSTALLED_TOOLS_AVAILABLE=1``——引擎后代合同在(只证明环境,不证明来源);
2. PATH 首项目录下确有 ``zcode-python(.exe)``(引擎把 binDir 放在 PATH[0],不猜 HOME/版本目录);
3. ``sys.executable`` 位于该入口同一 ``preinstalled-tools/<release>`` 发布根内——绑定
「本进程确由该入口拉起」的观察事实,防伪造 env/PATH。
判据 1、2 由 managed_entry_path 回答(只问入口在不在);这里再加判据 3。
"""
environ = os.environ if environ is None else environ
executable = sys.executable if executable is None else executable
if not executable:
return None
entry = managed_entry_path(environ, sys_platform)
if entry is None:
return None
release_root = os.path.dirname(os.path.dirname(entry)) # <…>/preinstalled-tools/<release>
exe_abs = os.path.abspath(executable)
try:
# Windows 的 ntpath.commonpath 保留首参大小写(C:\Foo vs c:\foo 视为不同前缀),
# env 给的 PATH[0] casing 与 GetModuleFileName 的盘上 casing 可能不同 → 两侧先 normcase
if os.path.normcase(os.path.commonpath([exe_abs, release_root])) != os.path.normcase(release_root):
return None
except (ValueError, OSError): # 不同盘符/空路径等 commonpath 异常:绑定不成立
return None
return entry
def _reconcile_same_path(left, right):
return os.path.normcase(os.path.normpath(left)) == os.path.normcase(os.path.normpath(right))
def reconcile_python_path(runtime, executing, managed_stable=None, extra_changes=None):
"""锁内按来源判定 ``python_path`` 是否跟随,顺带在同一事务里应用 ``extra_changes``。
- 缺失/空/非字符串 → 写入 desired(managed_stable 优先,否则 executing)并标 ``auto``;
- ``python_path_source == "manual"`` → 显式 custom,永不自动覆盖(含已消失的情况);
- ``python_path_source == "auto"`` → 跟随新值;
- 无标记(存量 legacy/unknown,可能是手写)→ 原值在时不动;已消失且与当前已验证托管入口
同属一个 ``preinstalled-tools/<release>`` 发布根 → 判定为历史自动写入的过期托管记录,
改写为稳定入口;其余已消失 → 保留原值(由解析器只读回退与 doctor 诊断兜底,不写回)。
update_config 的 defaults/changes/merge 语义不动;损坏 JSON 同样抛 ValueError 不重建。
"""
runtime = Path(runtime)
runtime.mkdir(parents=True, exist_ok=True)
config = runtime / "config.json"
lock_path = runtime / "plugin-config.lock"
if extra_changes is not None and not isinstance(extra_changes, dict):
raise ValueError("config extra_changes must be a JSON object")
desired = managed_stable if managed_stable else executing
if not desired or not isinstance(desired, str):
raise ValueError("reconcile needs an executing or managed interpreter path")
with file_lock(lock_path):
try:
current = json.loads(config.read_text(encoding="utf-8"))
except FileNotFoundError:
current = {}
if not isinstance(current, dict):
raise ValueError("config.json must be a JSON object")
old = current.get("python_path")
source = current.get("python_path_source")
if not isinstance(old, str) or not old.strip():
action = "fill"
elif source == "manual":
action = "keep_custom"
elif source == "auto":
if managed_stable:
# 有已验证托管入口:一律跟随(含从系统解释器切回托管入口)
action = "same" if _reconcile_same_path(old, managed_stable) else "refresh"
elif os.path.isfile(old):
# 无托管上下文且旧值仍可用:保持不churn(本会话经系统解释器跑 hook 不降级记录)
action = "keep"
else:
action = "refresh" # 旧值已失效:跟随当前执行解释器
elif os.path.isfile(old):
action = "keep"
elif managed_stable and _under_managed_release_root(old, managed_stable):
action = "migrate_stale_managed"
else:
action = "keep_stale_unknown"
updated = dict(current)
changed_keys = False
if action in ("fill", "refresh", "migrate_stale_managed"):
updated["python_path"] = desired
updated["python_path_source"] = "auto"
changed_keys = True
for key, value in (extra_changes or {}).items():
if updated.get(key) != value:
updated[key] = value
changed_keys = True
result = ReconcileResult(changed_keys, action, updated.get("python_path"))
if not changed_keys and config.exists():
return result
_write_marker(config, updated, config.stat() if config.exists() else None)
return result
def _under_managed_release_root(old, managed_stable):
"""old 是否落在 managed_stable 所在的 ``<…>/preinstalled-tools/<release>`` 发布根内。"""
try:
root = os.path.dirname(os.path.dirname(os.path.abspath(managed_stable))) # 发布根
old_abs = os.path.abspath(old)
if os.path.basename(os.path.dirname(root)) != "preinstalled-tools":
return False
# normcase 见 stable_managed_python 同款注释(Windows commonpath 大小写敏感假阴性)
return os.path.normcase(os.path.commonpath([old_abs, root])) == os.path.normcase(root)
except (ValueError, OSError):
return False
def update_enhance_provider(runtime, revision, changes):
"""Update the restricted enhancement settings under the shared runtime lock.
POSIX enforces owner-only access (uid + 0600 mode); Windows has no equivalent
owner semantics, so those checks are skipped there and the file relies on the
profile-directory ACL like quota-secrets.json (issue #442 lifted the old
unconditional fail-closed gate).
"""
if not isinstance(revision, int) or isinstance(revision, bool) or revision < 0 or not isinstance(changes, dict):
raise ValueError("invalid enhancement settings")
fields = {"mode", "source", "providerId", "target", "baseUrl", "protocol", "model", "keyAction", "apiKey", "allowDowngrade", "saveHistory"}
if set(changes) - fields or changes.get("keyAction", "keep") not in ("keep", "replace", "clear"):
raise ValueError("invalid enhancement settings")
runtime = Path(runtime)
info = runtime.stat()
if not stat.S_ISDIR(info.st_mode):
raise ValueError("unsafe runtime directory")
if os.name != "nt" and info.st_uid != os.geteuid():
raise ValueError("unsafe runtime directory")
config = runtime / "enhance-provider.json"
lock = runtime / "enhance-provider.lock"
if lock.is_symlink():
raise ValueError("unsafe lock")
with file_lock(lock):
try:
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(os.fspath(config), flags)
except FileNotFoundError:
current = {"version": 1, "revision": 0, "mode": "default"}
else:
with os.fdopen(fd, "r", encoding="utf-8") as stream:
st = os.fstat(stream.fileno())
if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1 or (
os.name != "nt" and (st.st_uid != os.geteuid() or st.st_mode & 0o077)):
raise ValueError("unsafe enhancement settings")
current = json.load(stream)
if not isinstance(current, dict) or current.get("version") != 1 or not isinstance(current.get("revision"), int):
raise ValueError("invalid enhancement settings")
if current["revision"] != revision:
raise ValueError("enhancement settings conflict")
updated = dict(current)
for key in fields - {"keyAction", "apiKey"}:
if key in changes:
value = changes[key]
if key in ("allowDowngrade", "saveHistory"):
if not isinstance(value, bool):
raise ValueError("invalid enhancement settings")
elif not isinstance(value, str) or len(value) > 2048 or any(ord(c) < 32 for c in value):
raise ValueError("invalid enhancement settings")
updated[key] = value
action = changes.get("keyAction", "keep")
if action == "replace":
key = changes.get("apiKey")
if not isinstance(key, str) or not key or len(key) > 4096 or any(ord(c) < 32 for c in key):
raise ValueError("invalid enhancement settings")
updated["apiKey"] = key
elif action == "clear":
updated.pop("apiKey", None)
if updated.get("mode") not in ("default", "custom") or updated.get("source", "manual") not in ("manual", "host"):
raise ValueError("invalid enhancement settings")
if (current.get("baseUrl"), current.get("protocol"), current.get("source", "manual")) != (updated.get("baseUrl"), updated.get("protocol"), updated.get("source", "manual")) and action == "keep":
updated.pop("apiKey", None)
updated["revision"] = revision + 1
fd, name = bounded_mkstemp(prefix=".enhance-provider-", suffix=".tmp", dir=runtime)
try:
if hasattr(os, "fchmod"):
os.fchmod(fd, 0o600) # POSIX:收紧到属主;Windows 无此调用,随目录 ACL(quota-secrets.json 同款取舍)
with os.fdopen(fd, "w", encoding="utf-8") as stream:
fd = None
json.dump(updated, stream, ensure_ascii=False)
stream.write("\n")
_replace_retrying(name, config) # 同标记写入:Windows 上并发读者会让替换被拒
finally:
if fd is not None:
os.close(fd)
_discard_tmp(name)
return updated
def _merge_restart(previous, data):
hashes = _hashes(previous.get("hashes"))
hashes.update(_hashes(data.get("hashes")))
if data.get("state") == "pending-install":
previous.pop("publishedAt", None) # A retry/new intent cannot inherit an earlier publication.
previous.update(data)
previous.update(createdAt=time.time(), hashes=hashes)
return previous
def record_restart(runtime, data):
"""Merge a restart notification while holding the independent marker lock."""
if not isinstance(data, dict):
raise ValueError("restart data must be a JSON object")
runtime = Path(runtime)
marker = runtime / ".plugin-restart-required"
with file_lock(runtime / "plugin-restart.lock"):
previous = _read_marker(marker, unreadable=False)
if previous is False:
# 读不到 ≠ 没有旧通知,不能用新记录覆盖无法读取的旧待办。
raise OSError("restart marker unreadable")
_write_marker(marker, _merge_restart(previous, data))
return {"ok": True}
def _confirm_publication(marker, data):
if marker.is_file() and _read_marker(marker) == data:
data["publishedAt"] = time.time() * 1000
try:
_write_marker(marker, data)
except OSError as exc:
# ASAR is already published. Leave the intent unconfirmed, not a false success.
print("[zusage-plugin] installation publication record failed: " + str(exc), file=sys.stderr)
@contextmanager
def publish_install(runtime, installation):
"""ASAR publication and its existing intent share the ack lock; never recreate a marker."""
runtime = Path(runtime)
marker = runtime / ".plugin-restart-required"
if not marker.is_file():
yield
return
with file_lock(runtime / "plugin-restart.lock"):
data = _read_marker(marker)
owned = data.get("installation") == installation
yield
if owned:
_confirm_publication(marker, data)
class RestartMarkerBusy(TimeoutError):
"""The independent restart-marker advisory lock could not be acquired."""
@contextmanager
def publish_supplement(runtime, installation, *, committed):
"""Own the patch intent through direct replacement or validated pending publication."""
runtime = Path(runtime)
marker = runtime / ".plugin-restart-required"
pending = False
def keep_pending():
nonlocal pending
pending = True
with ExitStack() as stack:
try:
stack.enter_context(file_lock(runtime / "plugin-restart.lock", timeout=0.0))
except FileLockBusy as error:
raise RestartMarkerBusy("restart marker lock is busy") from error
try:
previous = marker.read_bytes()
except FileNotFoundError:
previous = None
data = _merge_restart(_parse_marker(previous) if previous is not None else {},
{"state": "pending-install", "installation": installation})
try:
_write_marker(marker, data)
yield keep_pending
except BaseException:
if not pending and _read_marker(marker) == data and not committed():
try:
_restore_marker_bytes(marker, previous)
except OSError as exc:
print("[zusage-plugin] patch installation intent rollback failed: " + str(exc),
file=sys.stderr)
raise
if not pending and data.get("installation") == installation:
_confirm_publication(marker, data)
def ack_restart(runtime, loaded):
"""Remove only hashes actually loaded; preserve newer legacy notifications."""
if not isinstance(loaded, dict):
raise ValueError("loaded hashes must be a JSON object")
runtime = Path(runtime)
marker = runtime / ".plugin-restart-required"
with file_lock(runtime / "plugin-restart.lock"):
if not marker.exists():
return {"ok": True, "cleared": False}
data = _read_marker(marker, unreadable=False)
if data is False or (not data and not marker.exists()):
# 瞬态读失败 ≠ 没有待办:保留标记,下次 ack 再核(此前按空标记直接删除,
# 一次读失败就把「需要重启」的红点误销)。判存在后读完即被外部删除同理:
# 什么都没销、也不重建标记
return {"ok": True, "cleared": False}
loaded_at = loaded.get("_loadedAt")
hot_loaded = loaded.get("_hotLoadedAt")
created_at = data.get("createdAt")
if not isinstance(created_at, (int, float)) or isinstance(created_at, bool):
created_at = marker.stat().st_mtime
if isinstance(loaded_at, (int, float)) and not isinstance(loaded_at, bool) and created_at * 1000 > loaded_at:
# 本进程启动后才写入的 marker 默认不动(启动快照没见过这份通知)。唯一例外:
# 主进程在运行期热重载了全部相关模块——_hotLoadedAt[文件]=热替换完成时刻,
# 且 loaded 已持有 marker 记录的同一 digest(热替换加载的正是 marker 想让
# 重启后生效的字节)。inject-main.cjs 是 loader 自身,永远只能随进程重启
# 生效,不参与热销账。缺任何一项证据整单保留;下方 pending-install /
# installation 门控不受热时间戳影响(asar 替换必须真重启)。
hot_cleared = False
if isinstance(hot_loaded, dict):
hot_hashes = _hashes(data.get("hashes"))
if hot_hashes:
hot_cleared = True
for hot_key, hot_digest in hot_hashes.items():
hot_stamp = hot_loaded.get(hot_key)
if (hot_key == "inject-main.cjs" or loaded.get(hot_key) != hot_digest
or not isinstance(hot_stamp, (int, float)) or isinstance(hot_stamp, bool)
or hot_stamp != hot_stamp or hot_stamp < created_at * 1000): # != 自身过滤 NaN(json.loads 会放行)
hot_cleared = False
break
if hot_cleared and data.get("asarPatch") is True:
# asar 中段补丁只能随进程完全重启加载;热重载的运行时模块不能替它
# 销账——即使合并进来的 pending-sync hashes 已全部热加载。下一次真正
# 启动(createdAt 早于 loadedAt)仍走下方正常 hash/installation 流程清除。
return {"ok": True, "cleared": False}
if not hot_cleared:
return {"ok": True, "cleared": False}
installation = data.get("installation")
if data.get("state") == "pending-install" or installation is not None:
published_at = data.get("publishedAt")
if (not isinstance(installation, dict)
or not isinstance(published_at, (int, float)) or isinstance(published_at, bool)
or not isinstance(loaded_at, (int, float)) or isinstance(loaded_at, bool)
or published_at != published_at # NaN:json.loads 放行,比较恒假会把销账放行
or loaded_at <= published_at):
return {"ok": True, "cleared": False}
hashes = _hashes(data.get("hashes"))
if hashes:
tracked = _ack_tracked_files(runtime, loaded)
remaining = {}
for key, digest in hashes.items():
if loaded.get(key) == digest:
continue # 本进程已持有目标字节
# 防孤儿 marker(2026-11-21 实机红点常亮):digest 已不在盘上 = 记录后运行文件被第三方改写
#(如 preserved 保护的开发部署覆盖了同步写入的字节)。该目标重启也
# 加载不到(loaded 恒不等于 digest),保留只会让 ⚙ 红点永亮——以盘上
# 现状为准视为已被超越,从待办剔除;目标仍有效(盘上==digest)则照常保留。
if (os.path.splitdrive(key)[0] or os.path.isabs(key) or "\x00" in key
or key in (os.curdir, os.pardir)
or os.sep in key or (os.altsep and os.altsep in key)):
continue # 损坏 marker 的路径形键:正常写入方全白名单,拒读防拼路径逃逸
if tracked is not None and key not in tracked:
# 运行中的 loader 启动时不认领这个文件:它的内存里没有旧副本可替换,
# 再重启同一版本也永远不会 ack。磁盘字节已由同步写为目标版本,按已生效
# 剔除,避免 marker 永驻(旧 loader 被 preserved 时 1.5.29+ 新增冷模块
# 正是这种形态)。新 loader 用 _tracked 显式声明,旧 loader 靠源码解析。
continue
try:
on_disk = hashlib.sha256((runtime / key).read_bytes()).hexdigest()
except (FileNotFoundError, IsADirectoryError, NotADirectoryError):
on_disk = None # 文件已不在盘上:目标永加载不到,按已被超越剔除
except OSError:
# Windows 读目录占位抛 PermissionError 而非 IsADirectoryError:目录永不
# 匹配 digest,同样按已被超越剔除;其余瞬态读失败保守保留待办,下次 ack 再核
on_disk = None if (runtime / key).is_dir() else digest
if on_disk != digest:
continue
remaining[key] = digest
if remaining:
data["hashes"] = remaining
_write_marker(marker, data)
return {"ok": True, "cleared": False}
_unlink_retrying(marker) # 同标记替换:Windows 上并发读者会让 unlink 被拒
return {"ok": True, "cleared": True}
def main():
parser = argparse.ArgumentParser()
operation = parser.add_mutually_exclusive_group(required=True)
operation.add_argument("--hold", metavar="LOCKPATH")
operation.add_argument("--record-restart", metavar="RUNTIME")
operation.add_argument("--ack-restart", nargs=2, metavar=("RUNTIME", "HASHES_JSON"))
operation.add_argument("--update-config", metavar="RUNTIME")
operation.add_argument("--update-enhance-provider", metavar="RUNTIME")
args = parser.parse_args()
if args.hold:
try:
with file_lock(args.hold, timeout=0):
print(json.dumps({"locked": True}, separators=(",", ":")), flush=True)
while sys.stdin.buffer.read(65536):
pass
except TimeoutError:
print(json.dumps({"locked": False}, separators=(",", ":")), flush=True)
elif args.record_restart:
print(json.dumps(record_restart(args.record_restart, json.load(sys.stdin))))
elif args.update_enhance_provider:
try:
data = json.load(sys.stdin)
updated = update_enhance_provider(args.update_enhance_provider, data.get("revision"), data.get("changes"))
print(json.dumps({"ok": True, "revision": updated["revision"]}))
except (OSError, ValueError, TypeError, AttributeError):
print(json.dumps({"ok": False, "error": "enhance_provider_save_failed"}))
return 1
elif args.update_config:
data = json.load(sys.stdin)
if not isinstance(data, dict) or "changes" not in data:
raise ValueError("config update must contain changes")
changed = update_config(args.update_config, data["changes"], data.get("defaults"), data.get("merge"))
print(json.dumps({"ok": True, "changed": changed}))
else:
print(json.dumps(ack_restart(args.ack_restart[0], json.loads(args.ack_restart[1]))))
if __name__ == "__main__":
# 入站 JSON(--record-restart / --update-config / --update-enhance-provider 的载荷)按 UTF-8
# 严格解码:主进程与更新器按 JSON.stringify 写 stdin、spawn 时不注入 PYTHONUTF8,中文 Windows
# 的管道默认按区域代码页解码——含非 ASCII 的载荷(经 stdin 的调用方里只有
# --update-enhance-provider 可能如此:模型名、密钥、地址这些自由落盘的字符串)会被读成乱码
# 或留下孤立代理项(后者让这次保存失败)。一次性命令行没有读循环要保护:畸形字节直接以
# 非零退出失败,不把替换字符写进配置(字符串内的坏字节若换成 U+FFFD 会照常解析并落盘)。
try:
sys.stdin.reconfigure(encoding="utf-8")
except Exception:
pass
raise SystemExit(main()) # main() 的 return 1(事务失败)必须传播为非零退出码,否则调用方把失败当成功