- browser-harness/SKILL.md:§1 起法整段重写为「只允许这一种 —— 本会话的后台任务」(字面命令/
为什么只许这一种/守卫语义/已知代价/起不来对照表);§3 补一条排障 —— 认进程命令行与它自己的日志,
⛔ 别信 pid 父链;**「删掉脚本」≠「停掉进程」**(依据 2026-10-10 实测:孤儿守卫在脚本已删后仍把浏览器拉回)
- browser-harness/agent-workspace/bh_chrome_keepalive.py:守卫语义分两档 —— Chrome 正常关窗(rc=0) ⇒ 停手退出;
异常退出(rc≠0) ⇒ 重拉(依据:用户手关被无条件拉回,连关三次弹三次)
- session-mechanism/scripts/selftest.py:删掉重复定义的 `t_check_cooldown_no_pileup`(两段逐字相同);自测 PASS 109 / FAIL 0
- session-mechanism/references/humanizer-en/SKILL.md:与顶层 `humanizer` 技能同名冲突 ⇒ 去掉本包这份的注册
(`user-invocable: false` + `disable-model-invocation: true`),6 个文件正文一字未动
- session-mechanism/references/01-文档索引.md:补登 `04-决策方法论.md`/`dsh-decision-method/`/`作业规矩/`/`humanizer-en/`
140 lines
6.7 KiB
Python
140 lines
6.7 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""常驻守端口:让本机有一个可用的独立 Chrome 实例(默认 9223,固定 profile ⇒ 登录态保留)。
|
||
|
||
## 它解决什么
|
||
|
||
本机沙箱**在父进程退出时连带杀子进程** ⇒ 会话/工具调用里起的浏览器,调用一返回就死
|
||
(症状:`netstat` 查不到端口、`curl` 报 `WinError 10061`)。
|
||
要的是:浏览器活在一个**永不退出的循环**里 —— 起完 Chrome 就守在端口上。
|
||
|
||
## 怎么用(Windows 实测 2026-10-10)
|
||
|
||
🔴 **只允许一种起法**(用户 2026-10-10 令:「只允许这一种方式,使用 browser harness 打开浏览器的时候
|
||
也必须用这种方式打开浏览器」):**在本会话的后台任务里跑本文件**,stdout 全重定向到文件。
|
||
|
||
1、命令**整段抄**(见 `SKILL.md`「调 AI 工具」§1),解释器用 **`pythonw.exe`**
|
||
2、**交给你这个会话的后台任务去跑**(后台任务只活到本会话结束 ⇒ 会话在、浏览器在;会话收工、浏览器下线)
|
||
3、⛔ 不往工作区复制副本、⛔ 不建 Windows 计划任务(计划任务跨会话常驻,会把用户手关的浏览器拉回来)
|
||
⛔ 也不在同步调用里跑(父进程一退 Chrome 就死)
|
||
|
||
**为什么必须有这一步**:后台任务的 stdout 会灌进会话日志 ⇒ 超 ~10 MiB 后宿主丢日志、界面看着卡死
|
||
⇒ 所以命令里那截 `>> …_bh_bg.out 2>&1` 不能省。
|
||
|
||
## 做法约定
|
||
|
||
- **幂等**:端口已在听 ⇒ 立刻退出。(避免叠加第二个实例、避免两个实例抢同一个 profile)
|
||
- **守**:`while True` 里看着子进程;它**异常**退出(rc≠0)就重新起。
|
||
- 🔴 **手关窗 ⇒ 停手**:Chrome 正常退出(rc=0,=用户点的关闭窗口)时脚本**自己退出**,不再拉起。
|
||
依据(实测 2026-10-10):用户关掉浏览器,守卫在 1 秒内把它拉回,连关三次弹三次。
|
||
要重新开,跑一条命令起本脚本即可(见 `SKILL.md`「调 AI 工具」§1)。
|
||
- **僵死态只记日志**:端口不应答而进程仍在时,脚本**不自动重启** —— 那会把正在被排查的现场清掉,
|
||
留给人/会话按 SKILL.md 的判据处置。
|
||
- **清代理 env**:`HTTP_PROXY` / `HTTPS_PROXY` 会劫持本地 CDP 连接(报 `502 Bad Gateway`)。
|
||
- **只用独立实例**:⛔ 不附着用户日常 Chrome(那是 9222,会弹「允许远程调试?」动到用户浏览器)。
|
||
|
||
用法:
|
||
pythonw bh_chrome_keepalive.py --log "E:/ProgramData/.workbuddy/tmp/_bh_chrome.log"
|
||
(整条命令见 SKILL.md「调 AI 工具」§1;本脚本要放在**会话的后台任务**里跑)
|
||
可选:`--port` `--chrome` `--profile` `--proxy` `--log`(都有默认值,见下)
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import io
|
||
import os
|
||
import socket
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
|
||
# 清掉会劫持本地 CDP 的代理变量(要在起 Chrome 之前做)
|
||
for _k in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"):
|
||
os.environ.pop(_k, None)
|
||
os.environ.setdefault("NO_PROXY", "127.0.0.1,localhost")
|
||
|
||
DEFAULT_CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
|
||
DEFAULT_PROFILE = r"E:/ProgramData/.workbuddy/tmp/bu-chatgpt-profile"
|
||
DEFAULT_PORT = 9223
|
||
|
||
|
||
def _log(path, msg):
|
||
if not path:
|
||
return
|
||
try:
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
with io.open(path, "a", encoding="utf-8") as f:
|
||
f.write("[%s] %s\n" % (time.strftime("%m-%d %H:%M:%S"), msg))
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _listening(port: int) -> bool:
|
||
try:
|
||
s = socket.create_connection(("127.0.0.1", port), 1)
|
||
s.close()
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _launch(chrome: str, profile: str, port: int, proxy: str = ""):
|
||
cmd = [chrome, "--remote-debugging-port=%d" % port,
|
||
"--user-data-dir=%s" % profile,
|
||
"--no-first-run", "--no-default-browser-check"]
|
||
if proxy:
|
||
# 目标站点要走代理时才加(例:--proxy socks5://127.0.0.1:10800)
|
||
cmd.append("--proxy-server=%s" % proxy)
|
||
cmd.append("about:blank")
|
||
return subprocess.Popen(
|
||
cmd,
|
||
# DETACHED | CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP
|
||
creationflags=0x00000008 | 0x08000000 | 0x00000200,
|
||
)
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(add_help=True)
|
||
ap.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||
ap.add_argument("--chrome", default=os.environ.get("BH_CHROME") or DEFAULT_CHROME)
|
||
ap.add_argument("--profile", default=os.environ.get("BH_PROFILE") or DEFAULT_PROFILE)
|
||
ap.add_argument("--log", default=os.environ.get("BH_LOG") or "")
|
||
ap.add_argument("--proxy", default=os.environ.get("BH_PROXY") or "",
|
||
help='目标站点要走代理时才给,例 --proxy socks5://127.0.0.1:10800')
|
||
a = ap.parse_args()
|
||
|
||
if not os.path.isfile(a.chrome):
|
||
_log(a.log, "chrome 可执行体不存在:%s ⇒ 停(⛔ 不静默)" % a.chrome)
|
||
print("✗ 找不到 chrome:%s" % a.chrome, file=sys.stderr)
|
||
return 2
|
||
|
||
# ── 幂等前置:端口已在听 ⇒ 什么都不做 ──────────────────────────
|
||
if _listening(a.port):
|
||
_log(a.log, "port %d already listening ⇒ exit (idempotent)" % a.port)
|
||
return 0
|
||
|
||
p = _launch(a.chrome, a.profile, a.port, a.proxy)
|
||
_log(a.log, "launched pid=%s" % p.pid)
|
||
|
||
# ── 守:循环不结束 ⇒ Chrome 不被连坐 ───────────────────────────
|
||
# 🔴 退出码分两档(2026-10-10 用户报障「关掉就自动打开」后改):
|
||
# rc=0 = 正常关窗(用户自己点的关闭)⇒ **停手退出**,把浏览器还给用户;
|
||
# rc≠0 = 异常退出(崩溃/被杀)⇒ 重拉。
|
||
# 依据(实测):`[22:45:06] chrome exited rc=0 ⇒ relaunch` —— 用户手关三次、被拉回三次。
|
||
while True:
|
||
time.sleep(5)
|
||
if p.poll() is not None:
|
||
if p.returncode == 0:
|
||
_log(a.log, "chrome closed cleanly (rc=0) ⇒ stop guarding, exit")
|
||
return 0
|
||
_log(a.log, "chrome exited rc=%s ⇒ relaunch" % p.returncode)
|
||
p = _launch(a.chrome, a.profile, a.port, a.proxy)
|
||
_log(a.log, "relaunched pid=%s" % p.pid)
|
||
elif not _listening(a.port):
|
||
# ⚠️ 僵死态(端口不应答、进程还在):只记日志,⛔ 不自动重启 ——
|
||
# 自动重启会把"正在被排查的现场"清掉。判据与处置见 SKILL.md §1。
|
||
_log(a.log, "port %d not answering (pid alive=True)" % a.port)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|