⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

version unknown

autosure

293163-lgtm@293163-lgtm⭐ 0 stars· last commit 6mo ago· 0 open issues

Enterprise-grade OpenClaw unattended ops with vendored autosure-resume, optional auto-resume-lite, bounded /autosure success-loop, circuit breaker, idle grace, phrase pool, and one-command install for long-running hands-off sessions.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐ 0 on GitHubGitHub ↗

New / niche

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Autosure for OpenClaw

可分发的无人值守增强包(Skill + Plugins + Docs + UI Capsule Repair Pack)

文档权威顺序(先看这个)

如果你想快速判断“现在这套 autosure 到底以什么为准”,按下面顺序读:

  1. SKILL.md —— skill 入口、边界、主命令
  2. docs/PRD.md —— 产品范围与验收口径
  3. docs/ARCHITECTURE.md —— 当前架构真相
  4. docs/UI_CAPSULE_SPEC.md —— 当前 UI 冻结基线
  5. README.md —— 使用 / 安装 / 运维总览
  6. DEPLOY.md / HANDOFF_FOR_AGENT.md / 小白使用说明.md —— 面向不同操作者的执行文档

已归档的历史/过程文件

以下文件已从前台产品文档面移入 archive/,默认只作为历史参考:

  • archive/root-workfiles/architecture.md
  • archive/root-workfiles/findings.md
  • archive/root-workfiles/progress.md
  • archive/root-workfiles/task_plan.md
  • archive/docs-history/HANDOFF_CONTINUATION_2026-04-18.md
  • archive/docs-history/TRACK_A_VALIDATION_NOTE_2026-04-18.md
  • archive/docs-history/USERSCRIPT_CARRIER_HEALTH_NOTE_2026-04-18.md
  • archive/docs-history/UI_CONVERGENCE_GAP.md
  • archive/docs-history/UI_CONVERGENCE_PLAN.md
  • archive/docs-history/UI_CAPSULE_VNEXT_PLAN.md
  • archive/docs-history/AUTOSURE_TEST_HARNESS_PLAN_2026-04-18.md
  • archive/docs-history/REPAIR_CENTER_STABILIZATION_PLAN_2026-04-18.md
  • 其他阶段性 plan / note / handoff 文档

如果你要追历史脉络,读 archive/README.md。

项目背景(中文)

autosure 用于解决 OpenClaw 在长任务中的两个核心痛点:

  1. 任务中断后需要人工反复“接着干”;
  2. 任务成功后想自动推进,但又要保证“人类优先、可停止、可回退”。

当前版本把能力分为 核心层 与 可选增强层:

  • 核心层:autosure-resume(主)/auto-resume-lite(极简互斥);
  • 增强层:A1 userscript 胶囊(可视化快捷操作,失效不影响核心)。

Background (English)

autosure is a distributable add-on for OpenClaw unattended workflows.

It provides:

  • failure-safe resume with circuit governance,
  • success-loop continuation via /autosure commands,
  • optional UI capsule (userscript) for direct controls,
  • deployment and operational docs for handoff scenarios.

安装方式 / Installation

快速安装(推荐)

python3 skills/autosure/scripts/install_bundle.py --dry-run
python3 skills/autosure/scripts/install_bundle.py --mode full

然后将脚本输出的 plugins 片段合并到 ~/.openclaw/openclaw.json(allow/load.paths 追加,不覆盖现有条目)。

若你在维护历史 lite 安装,旧目录 plugins/openclaw-auto-resume-lite 仍可暂时保留;新版安装器在 --mode lite 下会同步刷新这个 legacy 别名目录,但长期应迁回 canonical 路径 plugins/auto-resume-lite。

UI 胶囊安装顺序(新增建议)

优先级:

  1. 先走 Tampermonkey userscript(默认分发形态)
  2. 若确认脚本已安装但在本机 127.0.0.1:18789/chat* 不执行,再启用 native fallback:
python3 skills/autosure/scripts/patch_control_ui.py reinstall

或走 Repair Center 的幂等入口:

python3 skills/autosure/scripts/repair_center.py native-install

这里推荐 reinstall / native-install,而不是只依赖旧式 install 检测,因为 marker 已存在并不代表当前 Control UI dist 已吃到最新 capsule 代码。

这会把 autosure 控件直接注入本机 OpenClaw Control UI 的 index.html,适合作为浏览器 userscript 层失效时的维修方案。

当前机器(mini49)已验证结论

在当前这台机器上,Tampermonkey 执行层已确认不可靠,native fallback 是当前本机优先可用路径。

本机验收建议:

  • 正常使用:http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain
  • 可视化验收:http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain&autosureDebug=1

其中 autosureDebug=1 会临时强制展开胶囊并显示 Autosure / AUTOSURE DEBUG 文案,方便截图、OCR 与肉眼确认;默认 /chat 交付行为不受影响。

自检

python3 skills/autosure/scripts/verify_health.py --mode full
python3 skills/autosure/scripts/verify_health.py --mode lite
openclaw plugins inspect autosure-resume

Repair Center / Carrier Doctor(新增)

当你需要一次性看清:

  • native fallback 是否已安装
  • 007 主浏览器身份里是否存在 userscript manager
  • userscript 文件是否已 staged
  • 当前机器应优先走哪条 carrier
  • 是否存在 native rollback backup
  • 当前恢复状态属于 healthy / blocked / mixed 的哪一类

直接运行:

python3 skills/autosure/scripts/repair_center.py verify

关键输出字段:

  • statusSummary
  • recommendedAction
  • carrierDiagnosis
  • recommendedCarrier
  • nextSteps

常用动作:

python3 skills/autosure/scripts/repair_center.py stage-userscript
python3 skills/autosure/scripts/repair_center.py native-install
python3 skills/autosure/scripts/repair_center.py native-uninstall
python3 skills/autosure/scripts/repair_center.py native-rollback
python3 skills/autosure/scripts/repair_center.py open-acceptance-url

返回是结构化 JSON,适合 handoff、运维排查、以及后续 doctor/test harness 接入。

运行步骤 / Runtime Use

核心命令

  • /autosure:不限轮次自动继续(直到 /autosure stop 或人工消息覆盖)
  • /autosure N:继续 N 轮(不含本命令这条;启动命令本身只代表已接收启动,不计入 completedRounds)
  • /autosure status:查看状态
  • /autosure stop:停止
  • /autosure-demo:演示模式(短答演示,不等同生产推进)

状态判断口径(重要)

不要只看 phase。

在 autosure 的 bounded loop 语义里,真正 authoritative 的判断应优先看:

  • loopControl.active
  • loopControl.targetRounds
  • loopControl.remainingRounds
  • loopControl.completedRounds
  • loopControl.lastCommandRaw
  • inflightResume

如果验证脚本输出:

  • effectiveLoopState
  • phaseAuthoritativeForLoop = false
  • terminalTailObserved
  • authoritativeLoopFinished

则应以这些字段为最终结论,而不是因为 phase 仍显示 running 就误判“还在继续跑”。

UI 胶囊(可选)

ui-capsule/repair-pack/autosure-capsule.user.js
通过 Tampermonkey 启用,提供 3/6/9/不限/暂停/状态快捷按钮。
暂停语义固定:/autosure stop。

核心功能 / Core Features

  • 失败续跑:timeout/tool_error/agent_error 等触发安全续跑;
  • 成功连轮:空窗等待 + 发动词注入;
  • 去重、冷却、熔断;
  • 取消双保险:before_dispatch + message_received 映射取消;
  • 可分发:vendor 插件 + 安装脚本 + 交接文档;
  • 可回退:禁用胶囊后,核心命令链路不受影响。

目录结构 / Directory Structure

前台产品文档面

  • SKILL.md:Skill 入口
  • README.md:总览说明
  • DEPLOY.md:部署指南
  • HANDOFF_FOR_AGENT.md:部署 Agent 入口
  • 小白使用说明.md:人类操作入口
  • docs/PRD.md:产品需求(v2.1)
  • docs/ARCHITECTURE.md:架构说明(v2.1)
  • docs/UI_CAPSULE_SPEC.md:胶囊专项设计

执行/交付相关

  • MANIFEST.json:包清单与版本
  • vendor/autosure-resume/:主插件副本
  • vendor/auto-resume-lite/:极简插件副本(互斥)
  • scripts/install_bundle.py:安装脚本
  • scripts/verify_health.py:健康检查
  • ui-capsule/repair-pack/:胶囊与修复包
  • RELEASE_NOTES.md:版本说明

历史归档

  • archive/:阶段性计划、排障、handoff、工作记录(非当前权威入口)

// HOW IT'S BUILT

// FILES

35 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skill/autosure/SKILL.md4.2 KB40d198597bceupstream ↗
    ---
    name: autosure
    description: "Enterprise-grade OpenClaw unattended ops with vendored autosure-resume, optional auto-resume-lite, bounded /autosure success-loop, circuit breaker, idle grace, phrase pool, and one-command install for long-running hands-off sessions."
    metadata:
      openclaw:
        emoji: 🛡️
        audience: ops
    ---
    
    # autosure
    
    ## Purpose
    
    `autosure` is a **distributable skill pack** for OpenClaw that standardizes:
    
    - **Safe auto-resume** on verified failure signals (via **`autosure-resume`** plugin, vendored under `vendor/`).
    - **Optional minimal resume** via bundled **`auto-resume-lite`** (mutually exclusive with the main plugin).
    - **Dialable success-loop** (`/autosure`, `/autosure N`) with **idle grace** and **rotating phrases** from `发动词.txt`.
    - **Professional closure** templates for checkpoint / progress / session handoff.
    
    ## Read this first
    
    - 中文入口:`references/cn.md`
    - Product truth: `docs/PRD.md`
    - Runtime truth: `docs/ARCHITECTURE.md`
    - UI capsule spec: `docs/UI_CAPSULE_SPEC.md`
    
    ## When to use
    
    - You ship OpenClaw to **another machine** or **customer agent** and need a **repeatable install story**.
    - Long jobs should **continue after benign failures** without spamming the session.
    - You want **bounded** auto-continue after successful turns **without** telling the model a fixed “round budget” in prose.
    
    ## One-line deploy (human or agent)
    
    1. Copy this directory to `OPENCLAW_WORKSPACE/skills/autosure`.
    2. Run `python3 skills/autosure/scripts/install_bundle.py --mode full`.
    3. Merge printed `plugins` JSON into `~/.openclaw/openclaw.json`, then `openclaw config validate` + `openclaw daemon restart`.
    4. Verify with `python3 skills/autosure/scripts/verify_health.py --mode full`.
    
    Full handoff text for another agent: **`HANDOFF_FOR_AGENT.md`**. Customer-facing steps: **`小白使用说明.md`** + **`DEPLOY.md`**.
    
    ## Guardrails
    
    1. Never auto-resume blindly on a fixed wall-clock alone.
    2. Only resume on **verified interruption signals** (timeout/tool/provider/agent error paths — see plugin).
    3. Enforce **circuit breaker** when failures repeat.
    4. Pause resume pressure after **human override** (non-system user message while loop active clears loop).
    5. Prefer **mutually exclusive** plugins: **`autosure-resume` XOR `auto-resume-lite`**.
    
    ## Required file sync (project lanes)
    
    For planning-with-files lanes, each meaningful round should synchronize checkpoint / progress / session state; use `templates/CLOSURE.md` as the canonical block.
    
    ## Phrase pool
    
    Web UI loop injects user-visible lines from **`发动词.txt`** (one phrase per line, `#` comments ignored). **~30** generic, high-standard “推进” lines ship by default; edit freely.
    
    ## Product docs (this pack)
    
    | Doc | Role |
    |-----|------|
    | `docs/PRD.md` | 需求、范围、验收 |
    | `docs/ARCHITECTURE.md` | 分层、双通道、状态、依赖 |
    | `docs/UI_CAPSULE_SPEC.md` | A1 胶囊(userscript)交互与修复包设计 |
    | `RELEASE_NOTES.md` | 发版叙事与边界 |
    | `MANIFEST.json` | 机器可读组件清单 |
    | `vendor/README.md` | 插件 vendor 说明 |
    | `references/cn.md` | 中文入口与瘦身说明 |
    
    ## UI capsule repair pack
    
    - Userscript: `ui-capsule/repair-pack/autosure-capsule.user.js`
    - Native fallback source: `ui-capsule/repair-pack/native-control-ui-capsule.js`
    - Enable helper: `ui-capsule/repair-pack/enable.sh`
    - Disable helper: `ui-capsule/repair-pack/disable.sh`
    - Native patch helper: `scripts/patch_control_ui.py`
    - Repair notes: `ui-capsule/repair-pack/ENABLE_DISABLE.md`
    
    Default path is still **Tampermonkey userscript**.
    If a machine proves that Tampermonkey installs the script but does **not execute** it on `127.0.0.1:18789/chat*`, use the **native fallback patch** to inject the same controls into local OpenClaw Control UI.
    
    - `/autosure` — unlimited delegated continues until `/autosure stop` or a normal user message clears the loop.
    - `/autosure N` — **N** counts **delegated** injects only (not the command line itself).
    - `/autosure stop` / `/autosure status`
    - `/autosure-demo` — **short-reply demo** only; not production loop semantics.
    
    ## Stop conditions
    
    - Circuit opened (repeated failure threshold).
    - Human override / `/autosure stop`.
    - Risk boundary violation (operator policy).
    
  • skill/autosure/README.md7.7 KB57eef52a72b8upstream ↗
    # Autosure for OpenClaw
    
    > 可分发的无人值守增强包(Skill + Plugins + Docs + UI Capsule Repair Pack)
    
    ## 文档权威顺序(先看这个)
    
    如果你想快速判断“现在这套 autosure 到底以什么为准”,按下面顺序读:
    
    1. `SKILL.md` —— skill 入口、边界、主命令
    2. `docs/PRD.md` —— 产品范围与验收口径
    3. `docs/ARCHITECTURE.md` —— 当前架构真相
    4. `docs/UI_CAPSULE_SPEC.md` —— 当前 UI 冻结基线
    5. `README.md` —— 使用 / 安装 / 运维总览
    6. `DEPLOY.md` / `HANDOFF_FOR_AGENT.md` / `小白使用说明.md` —— 面向不同操作者的执行文档
    
    ### 已归档的历史/过程文件
    
    以下文件已从前台产品文档面移入 `archive/`,默认只作为历史参考:
    
    - `archive/root-workfiles/architecture.md`
    - `archive/root-workfiles/findings.md`
    - `archive/root-workfiles/progress.md`
    - `archive/root-workfiles/task_plan.md`
    - `archive/docs-history/HANDOFF_CONTINUATION_2026-04-18.md`
    - `archive/docs-history/TRACK_A_VALIDATION_NOTE_2026-04-18.md`
    - `archive/docs-history/USERSCRIPT_CARRIER_HEALTH_NOTE_2026-04-18.md`
    - `archive/docs-history/UI_CONVERGENCE_GAP.md`
    - `archive/docs-history/UI_CONVERGENCE_PLAN.md`
    - `archive/docs-history/UI_CAPSULE_VNEXT_PLAN.md`
    - `archive/docs-history/AUTOSURE_TEST_HARNESS_PLAN_2026-04-18.md`
    - `archive/docs-history/REPAIR_CENTER_STABILIZATION_PLAN_2026-04-18.md`
    - 其他阶段性 plan / note / handoff 文档
    
    如果你要追历史脉络,读 `archive/README.md`。
    
    ## 项目背景(中文)
    
    `autosure` 用于解决 OpenClaw 在长任务中的两个核心痛点:
    
    1. 任务中断后需要人工反复“接着干”;
    2. 任务成功后想自动推进,但又要保证“人类优先、可停止、可回退”。
    
    当前版本把能力分为 **核心层** 与 **可选增强层**:
    
    - **核心层**:`autosure-resume`(主)/`auto-resume-lite`(极简互斥);
    - **增强层**:A1 userscript 胶囊(可视化快捷操作,失效不影响核心)。
    
    ## Background (English)
    
    `autosure` is a distributable add-on for OpenClaw unattended workflows.
    
    It provides:
    
    - failure-safe resume with circuit governance,
    - success-loop continuation via `/autosure` commands,
    - optional UI capsule (userscript) for direct controls,
    - deployment and operational docs for handoff scenarios.
    
    ## 安装方式 / Installation
    
    ### 快速安装(推荐)
    
    ```bash
    python3 skills/autosure/scripts/install_bundle.py --dry-run
    python3 skills/autosure/scripts/install_bundle.py --mode full
    ```
    
    然后将脚本输出的 `plugins` 片段**合并**到 `~/.openclaw/openclaw.json`(`allow`/`load.paths` 追加,不覆盖现有条目)。
    
    > 若你在维护历史 lite 安装,旧目录 `plugins/openclaw-auto-resume-lite` 仍可暂时保留;新版安装器在 `--mode lite` 下会同步刷新这个 legacy 别名目录,但长期应迁回 canonical 路径 `plugins/auto-resume-lite`。
    
    ### UI 胶囊安装顺序(新增建议)
    
    优先级:
    
    1. **先走 Tampermonkey userscript**(默认分发形态)
    2. 若确认脚本已安装但在本机 `127.0.0.1:18789/chat*` **不执行**,再启用 **native fallback**:
    
    ```bash
    python3 skills/autosure/scripts/patch_control_ui.py reinstall
    ```
    
    或走 Repair Center 的幂等入口:
    
    ```bash
    python3 skills/autosure/scripts/repair_center.py native-install
    ```
    
    这里推荐 `reinstall` / `native-install`,而不是只依赖旧式 `install` 检测,因为 marker 已存在并不代表当前 Control UI dist 已吃到最新 capsule 代码。
    
    这会把 autosure 控件直接注入本机 OpenClaw Control UI 的 `index.html`,适合作为浏览器 userscript 层失效时的维修方案。
    
    ### 当前机器(mini49)已验证结论
    
    在当前这台机器上,Tampermonkey 执行层已确认不可靠,**native fallback 是当前本机优先可用路径**。
    
    本机验收建议:
    
    - 正常使用:`http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain`
    - 可视化验收:`http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain&autosureDebug=1`
    
    其中 `autosureDebug=1` 会临时强制展开胶囊并显示 `Autosure` / `AUTOSURE DEBUG` 文案,方便截图、OCR 与肉眼确认;默认 `/chat` 交付行为不受影响。
    
    ### 自检
    
    ```bash
    python3 skills/autosure/scripts/verify_health.py --mode full
    python3 skills/autosure/scripts/verify_health.py --mode lite
    openclaw plugins inspect autosure-resume
    ```
    
    ## Repair Center / Carrier Doctor(新增)
    
    当你需要一次性看清:
    - native fallback 是否已安装
    - 007 主浏览器身份里是否存在 userscript manager
    - userscript 文件是否已 staged
    - 当前机器应优先走哪条 carrier
    - 是否存在 native rollback backup
    - 当前恢复状态属于 healthy / blocked / mixed 的哪一类
    
    直接运行:
    
    ```bash
    python3 skills/autosure/scripts/repair_center.py verify
    ```
    
    关键输出字段:
    - `statusSummary`
    - `recommendedAction`
    - `carrierDiagnosis`
    - `recommendedCarrier`
    - `nextSteps`
    
    常用动作:
    
    ```bash
    python3 skills/autosure/scripts/repair_center.py stage-userscript
    python3 skills/autosure/scripts/repair_center.py native-install
    python3 skills/autosure/scripts/repair_center.py native-uninstall
    python3 skills/autosure/scripts/repair_center.py native-rollback
    python3 skills/autosure/scripts/repair_center.py open-acceptance-url
    ```
    
    返回是结构化 JSON,适合 handoff、运维排查、以及后续 doctor/test harness 接入。
    
    ## 运行步骤 / Runtime Use
    
    ### 核心命令
    
    - `/autosure`:不限轮次自动继续(直到 `/autosure stop` 或人工消息覆盖)
    - `/autosure N`:继续 N 轮(不含本命令这条;启动命令本身只代表**已接收启动**,不计入 `completedRounds`)
    - `/autosure status`:查看状态
    - `/autosure stop`:停止
    - `/autosure-demo`:演示模式(短答演示,不等同生产推进)
    
    ### 状态判断口径(重要)
    
    不要只看 `phase`。
    
    在 autosure 的 bounded loop 语义里,真正 authoritative 的判断应优先看:
    - `loopControl.active`
    - `loopControl.targetRounds`
    - `loopControl.remainingRounds`
    - `loopControl.completedRounds`
    - `loopControl.lastCommandRaw`
    - `inflightResume`
    
    如果验证脚本输出:
    - `effectiveLoopState`
    - `phaseAuthoritativeForLoop = false`
    - `terminalTailObserved`
    - `authoritativeLoopFinished`
    
    则应以这些字段为最终结论,而不是因为 `phase` 仍显示 `running` 就误判“还在继续跑”。
    
    ### UI 胶囊(可选)
    
    `ui-capsule/repair-pack/autosure-capsule.user.js`  
    通过 Tampermonkey 启用,提供 3/6/9/不限/暂停/状态快捷按钮。  
    暂停语义固定:`/autosure stop`。
    
    ## 核心功能 / Core Features
    
    - 失败续跑:timeout/tool_error/agent_error 等触发安全续跑;
    - 成功连轮:空窗等待 + 发动词注入;
    - 去重、冷却、熔断;
    - 取消双保险:`before_dispatch` + `message_received` 映射取消;
    - 可分发:vendor 插件 + 安装脚本 + 交接文档;
    - 可回退:禁用胶囊后,核心命令链路不受影响。
    
    ## 目录结构 / Directory Structure
    
    ### 前台产品文档面
    - `SKILL.md`:Skill 入口
    - `README.md`:总览说明
    - `DEPLOY.md`:部署指南
    - `HANDOFF_FOR_AGENT.md`:部署 Agent 入口
    - `小白使用说明.md`:人类操作入口
    - `docs/PRD.md`:产品需求(v2.1)
    - `docs/ARCHITECTURE.md`:架构说明(v2.1)
    - `docs/UI_CAPSULE_SPEC.md`:胶囊专项设计
    
    ### 执行/交付相关
    - `MANIFEST.json`:包清单与版本
    - `vendor/autosure-resume/`:主插件副本
    - `vendor/auto-resume-lite/`:极简插件副本(互斥)
    - `scripts/install_bundle.py`:安装脚本
    - `scripts/verify_health.py`:健康检查
    - `ui-capsule/repair-pack/`:胶囊与修复包
    - `RELEASE_NOTES.md`:版本说明
    
    ### 历史归档
    - `archive/`:阶段性计划、排障、handoff、工作记录(非当前权威入口)
    
    
  • skill/autosure/scripts/README.md1.7 KBe301ee075a6eupstream ↗
    # autosure / scripts
    
    | 脚本 | 用途 |
    |------|------|
    | `init_run.py` | 初始化运行卡片(项目收口用) |
    | `verify_health.py` | 检查 `openclaw` CLI、`autosure-resume` 已加载、配置片段、`发动词.txt`、**vendor 包内主插件文件**是否存在 |
    | `repair_center.py` | 统一 doctor / repair 入口:检测 native patch、userscript carrier、staged userscript,并支持 native install/uninstall/rollback、open acceptance URL;其中 `native-install` 现默认走 **幂等刷新语义**(内部调用 `patch_control_ui.py reinstall`),避免 marker 已存在但 dist 仍吃旧 capsule |
    | `autosure_doctor.py` | Track C 统一 harness:聚合 core health、ui carrier、runtime state、ui contract,输出 `summary`、`recommendedNextAction`、`statusClass`、`severity`,并支持 `--json-only / --pretty` |
    | `autosure_validate_runtime.py` | 独立测试会话的 runtime validator:读取 autosure state,输出 session snapshot / diff,用于记录 loop/phase/stop 前后变化 |
    | `autosure_validate_session.py` | 独立测试会话验证助手:prepare/finalize 两阶段串联 doctor + runtime snapshot/diff,并生成 artifacts 目录与行为检查清单 |
    | `install_bundle.py` | 将 `vendor/autosure-resume` 或 `vendor/auto-resume-lite` 安装到 `OPENCLAW_WORKSPACE/plugins/`,并打印需合并的 `plugins` JSON |
    | `sync_vendor_from_workspace.sh` | 在 **skill 根目录**执行:`bash scripts/sync_vendor_from_workspace.sh`,从 `workspace/plugins/autosure-resume` 回刷 `vendor/autosure-resume` |
    
    ## 示例
    
    ```bash
    python3 install_bundle.py --mode full --dry-run
    python3 install_bundle.py --mode lite
    ```
    
    `--mode lite` 仅安装极简 `auto-resume-lite`(请确保配置中关闭 `autosure-resume`)。
    
  • skill/autosure/ui-capsule/README.md695 B0c69d7840fb1upstream ↗
    # Autosure UI Capsule(A1 userscript)
    
    这是一个**可选增强层**,不属于 autosure 核心执行链。
    
    - 启用它:获得可视化胶囊与快捷按钮(3/6/9/不限/暂停/状态)。
    - 关闭它:`/autosure` 系命令仍可手工输入,核心功能不受影响。
    
    ## 目录
    
    - `repair-pack/autosure-capsule.user.js`:主 userscript。
    - `repair-pack/selectors.json`:挂载与发送按钮选择器策略。
    - `repair-pack/CHANGELOG.md`:修复记录。
    - `repair-pack/ENABLE_DISABLE.md`:启停与修复说明。
    
    ## 关键语义
    
    - “暂停”按钮固定发送:`/autosure stop`(B1)。
    - 胶囊挂载失败时自动降级为右上角浮层,不阻塞 chat。
    
    
  • skill/autosure/scripts/autosure_doctor.py7.4 KB323e32817ffeupstream ↗
    #!/usr/bin/env python3
    from __future__ import annotations
    
    import argparse
    import json
    import subprocess
    import sys
    from pathlib import Path
    
    
    ACTIVE_PLUGIN = "autosure-resume"
    
    
    def skill_root() -> Path:
        return Path(__file__).resolve().parents[1]
    
    
    def plugin_state_file() -> Path:
        return Path.home() / ".openclaw" / "plugins" / ACTIVE_PLUGIN / "state.json"
    
    
    def run_json(cmd: list[str]) -> tuple[int, dict, str, str]:
        result = subprocess.run(cmd, capture_output=True, text=True, check=False)
        out = (result.stdout or "").strip()
        err = (result.stderr or "").strip()
        payload = {}
        if out:
            try:
                payload = json.loads(out)
            except Exception:
                payload = {}
        return result.returncode, payload, out, err
    
    
    def static_contracts(userscript_path: Path, native_path: Path) -> dict:
        userscript_text = userscript_path.read_text(encoding="utf-8") if userscript_path.exists() else ""
        native_text = native_path.read_text(encoding="utf-8") if native_path.exists() else ""
    
        def has_mount_anchor_contract(text: str) -> bool:
            return all(token in text for token in ["findChatControls", "findChatControlsAnchor", "mountIntoToolbar"])
    
        def has_menu_portal_contract(text: str) -> bool:
            return all(token in text for token in ["document.body.appendChild(menu)", "placeMenu", 'position = "fixed"'])
    
        def has_theme_contract(text: str) -> bool:
            return all(token in text for token in ["detectDarkTheme", "applyTheme", "data-theme"])
    
        userscript = {
            "path": str(userscript_path),
            "exists": userscript_path.exists(),
            "mountAnchor": has_mount_anchor_contract(userscript_text),
            "menuPortal": has_menu_portal_contract(userscript_text),
            "themeReadability": has_theme_contract(userscript_text),
        }
        native = {
            "path": str(native_path),
            "exists": native_path.exists(),
            "mountAnchor": has_mount_anchor_contract(native_text),
            "menuPortal": has_menu_portal_contract(native_text),
            "themeReadability": has_theme_contract(native_text),
        }
        ok = all([
            userscript["exists"], native["exists"],
            userscript["mountAnchor"], native["mountAnchor"],
            userscript["menuPortal"], native["menuPortal"],
            userscript["themeReadability"], native["themeReadability"],
        ])
        return {
            "ok": ok,
            "userscript": userscript,
            "native": native,
        }
    
    
    def runtime_state_contract() -> dict:
        state_path = plugin_state_file()
        if not state_path.exists():
            return {
                "ok": False,
                "path": str(state_path),
                "exists": False,
                "sessionsObject": False,
                "runsObject": False,
                "hasAnySession": False,
                "detail": "plugin state file missing",
            }
        try:
            payload = json.loads(state_path.read_text(encoding="utf-8"))
        except Exception as e:
            return {
                "ok": False,
                "path": str(state_path),
                "exists": True,
                "sessionsObject": False,
                "runsObject": False,
                "hasAnySession": False,
                "detail": f"state file unreadable: {e}",
            }
    
        sessions = payload.get("sessions") if isinstance(payload, dict) else None
        runs = payload.get("runs") if isinstance(payload, dict) else None
        sessions_object = isinstance(sessions, dict)
        runs_object = isinstance(runs, dict)
        has_any_session = sessions_object and len(sessions) > 0
        return {
            "ok": sessions_object and runs_object,
            "path": str(state_path),
            "exists": True,
            "sessionsObject": sessions_object,
            "runsObject": runs_object,
            "hasAnySession": bool(has_any_session),
            "sessionCount": len(sessions) if sessions_object else 0,
            "runCount": len(runs) if runs_object else 0,
            "detail": "state file shape ok" if (sessions_object and runs_object) else "state file shape mismatch",
        }
    
    
    def classify_status(core_ok: bool, ui_carrier_ok: bool, runtime_ok: bool, ui_contract_ok: bool) -> tuple[str, str]:
        if core_ok and ui_carrier_ok and runtime_ok and ui_contract_ok:
            return "healthy", "info"
        if not core_ok or not runtime_ok:
            return "critical", "error"
        if not ui_carrier_ok:
            return "degraded", "warn"
        if not ui_contract_ok:
            return "contract-drift", "warn"
        return "mixed", "warn"
    
    
    def build_payload() -> tuple[dict, int]:
        root = skill_root()
        verify_cmd = [sys.executable, str(root / "scripts" / "verify_health.py"), "--mode", "full"]
        repair_cmd = [sys.executable, str(root / "scripts" / "repair_center.py"), "verify"]
    
        core_rc, core_payload, core_out, core_err = run_json(verify_cmd)
        carrier_rc, carrier_payload, carrier_out, carrier_err = run_json(repair_cmd)
        contracts = static_contracts(
            root / "ui-capsule" / "repair-pack" / "autosure-capsule.user.js",
            root / "ui-capsule" / "repair-pack" / "native-control-ui-capsule.js",
        )
        runtime_state = runtime_state_contract()
    
        ui_carrier_ok = carrier_payload.get("statusSummary") in {"healthy-native", "healthy-userscript-ready"}
        core_ok = bool(core_payload.get("ok", False)) and core_rc == 0
        ui_contract_ok = bool(contracts.get("ok", False))
        runtime_ok = bool(runtime_state.get("ok", False))
        status_class, severity = classify_status(core_ok, ui_carrier_ok, runtime_ok, ui_contract_ok)
    
        recommended_next_action = (
            carrier_payload.get("recommendedAction")
            or ("fix-runtime-state" if not runtime_ok else ("fix-core-plugin-health" if not core_ok else "inspect-ui-contract"))
        )
    
        summary_parts = []
        summary_parts.append("core-ok" if core_ok else "core-failed")
        summary_parts.append(carrier_payload.get("statusSummary", "carrier-unknown"))
        summary_parts.append("runtime-state-ok" if runtime_ok else "runtime-state-failed")
        summary_parts.append("ui-contract-ok" if ui_contract_ok else "ui-contract-failed")
    
        payload = {
            "ok": core_ok and ui_carrier_ok and runtime_ok and ui_contract_ok,
            "statusClass": status_class,
            "severity": severity,
            "summary": " | ".join(summary_parts),
            "recommendedNextAction": recommended_next_action,
            "core": {
                "ok": core_ok,
                "command": " ".join(verify_cmd),
                "payload": core_payload,
                "stdout": core_out if not core_payload else "",
                "stderr": core_err,
            },
            "uiCarrier": {
                "ok": ui_carrier_ok,
                "command": " ".join(repair_cmd),
                "payload": carrier_payload,
                "stdout": carrier_out if not carrier_payload else "",
                "stderr": carrier_err,
            },
            "runtimeState": runtime_state,
            "uiContract": contracts,
        }
        exit_code = 0 if payload["ok"] else 1
        return payload, exit_code
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description="Autosure unified doctor/test harness")
        ap.add_argument("--json-only", action="store_true", help="Emit compact JSON on a single line")
        ap.add_argument("--pretty", action="store_true", help="Emit pretty JSON (default)")
        args = ap.parse_args()
    
        payload, exit_code = build_payload()
        if args.json_only:
            print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
        else:
            print(json.dumps(payload, ensure_ascii=False, indent=2))
        return exit_code
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • skill/autosure/scripts/autosure_validate_runtime.py5.3 KBab503ae0b2e8upstream ↗
    #!/usr/bin/env python3
    from __future__ import annotations
    
    import argparse
    import json
    from pathlib import Path
    
    
    ACTIVE_PLUGIN = "autosure-resume"
    DEFAULT_SESSION_KEY = "agent:main:main"
    
    
    def state_file() -> Path:
        return Path.home() / ".openclaw" / "plugins" / ACTIVE_PLUGIN / "state.json"
    
    
    def load_state() -> dict:
        path = state_file()
        if not path.exists():
            raise FileNotFoundError(f"state file not found: {path}")
        return json.loads(path.read_text(encoding="utf-8"))
    
    
    def snapshot_for_session(payload: dict, session_key: str) -> dict:
        sessions = payload.get("sessions") if isinstance(payload, dict) else {}
        runs = payload.get("runs") if isinstance(payload, dict) else {}
        session = sessions.get(session_key, {}) if isinstance(sessions, dict) else {}
        loop = session.get("loopControl", {}) if isinstance(session, dict) else {}
    
        inflight_resume = session.get("inflightResume") if isinstance(session, dict) else None
        loop_active = loop.get("active") if isinstance(loop, dict) else None
        loop_target_rounds = loop.get("targetRounds") if isinstance(loop, dict) else None
        loop_remaining_rounds = loop.get("remainingRounds") if isinstance(loop, dict) else None
        loop_completed_rounds = loop.get("completedRounds") if isinstance(loop, dict) else None
        phase = session.get("phase", "missing") if isinstance(session, dict) else "missing"
    
        effective_loop_state = "unknown"
        terminal_tail = False
        if isinstance(session, dict) and session:
            if loop_active is True:
                effective_loop_state = "loop-active"
            elif inflight_resume is True:
                effective_loop_state = "resume-inflight"
            else:
                effective_loop_state = "loop-idle"
                terminal_tail = phase == "running"
    
        return {
            "sessionKey": session_key,
            "statePath": str(state_file()),
            "sessionExists": isinstance(session, dict) and bool(session),
            "phase": phase,
            "failureStreak": session.get("failureStreak") if isinstance(session, dict) else None,
            "consecutiveAutoResumes": session.get("consecutiveAutoResumes") if isinstance(session, dict) else None,
            "inflightResume": inflight_resume,
            "loopActive": loop_active,
            "loopUnlimited": loop.get("unlimited") if isinstance(loop, dict) else None,
            "loopTargetRounds": loop_target_rounds,
            "loopRemainingRounds": loop_remaining_rounds,
            "loopCompletedRounds": loop_completed_rounds,
            "loopLastCommandRaw": loop.get("lastCommandRaw") if isinstance(loop, dict) else None,
            "lastDecision": session.get("lastDecision") if isinstance(session, dict) else None,
            "lastResumeReason": session.get("lastResumeReason") if isinstance(session, dict) else None,
            "effectiveLoopState": effective_loop_state,
            "phaseAuthoritativeForLoop": False,
            "terminalTailObserved": terminal_tail,
            "updatedAt": session.get("updatedAt") if isinstance(session, dict) else None,
            "lastSuccessAt": session.get("lastSuccessAt") if isinstance(session, dict) else None,
            "lastAgentEndAt": session.get("lastAgentEndAt") if isinstance(session, dict) else None,
            "sessionCount": len(sessions) if isinstance(sessions, dict) else 0,
            "runCount": len(runs) if isinstance(runs, dict) else 0,
        }
    
    
    def diff_snapshots(before: dict, after: dict) -> dict:
        keys = sorted(set(before.keys()) | set(after.keys()))
        changed = {}
        for key in keys:
            if before.get(key) != after.get(key):
                changed[key] = {
                    "before": before.get(key),
                    "after": after.get(key),
                }
        return changed
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description="Autosure runtime validation helper for independent test sessions")
        ap.add_argument("action", choices=("snapshot", "diff"))
        ap.add_argument("--session-key", default=DEFAULT_SESSION_KEY, help="Session key to inspect in autosure state.json")
        ap.add_argument("--before", type=Path, default=None, help="Path to a previously saved snapshot JSON")
        ap.add_argument("--save", type=Path, default=None, help="Optional path to save the current snapshot JSON")
        args = ap.parse_args()
    
        current = snapshot_for_session(load_state(), args.session_key)
    
        if args.action == "snapshot":
            if args.save is not None:
                args.save.parent.mkdir(parents=True, exist_ok=True)
                args.save.write_text(json.dumps(current, ensure_ascii=False, indent=2), encoding="utf-8")
            print(json.dumps({"ok": True, "snapshot": current}, ensure_ascii=False, indent=2))
            return 0
    
        if args.before is None:
            raise SystemExit("--before is required for diff")
        before_payload = json.loads(args.before.read_text(encoding="utf-8"))
        before = before_payload.get("snapshot", before_payload)
        changed = diff_snapshots(before, current)
        result = {
            "ok": True,
            "before": before,
            "after": current,
            "changed": changed,
            "changedCount": len(changed),
        }
        if args.save is not None:
            args.save.parent.mkdir(parents=True, exist_ok=True)
            args.save.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • skill/autosure/scripts/autosure_validate_session.py6.1 KBc8ef13f0c652upstream ↗
    #!/usr/bin/env python3
    from __future__ import annotations
    
    import argparse
    import json
    import re
    import subprocess
    import sys
    from datetime import datetime, timezone
    from pathlib import Path
    
    
    DEFAULT_SESSION_KEY = "agent:main:main"
    
    
    def skill_root() -> Path:
        return Path(__file__).resolve().parents[1]
    
    
    def artifacts_root() -> Path:
        return skill_root() / "artifacts" / "runtime-validation"
    
    
    def safe_slug(text: str) -> str:
        cleaned = re.sub(r"[^a-zA-Z0-9._-]+", "-", text.strip())
        return cleaned.strip("-") or "session"
    
    
    def utc_stamp() -> str:
        return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    
    
    def run_json(cmd: list[str]) -> tuple[int, dict, str, str]:
        result = subprocess.run(cmd, capture_output=True, text=True, check=False)
        out = (result.stdout or "").strip()
        err = (result.stderr or "").strip()
        payload = {}
        if out:
            try:
                payload = json.loads(out)
            except Exception:
                payload = {}
        return result.returncode, payload, out, err
    
    
    def plan_dir(base_dir: Path | None, session_key: str) -> Path:
        if base_dir is not None:
            return base_dir.expanduser().resolve()
        return artifacts_root() / f"{utc_stamp()}-{safe_slug(session_key)}"
    
    
    def write_json(path: Path, payload: dict) -> None:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    
    
    def prepare(session_key: str, out_dir: Path) -> int:
        root = skill_root()
        doctor_cmd = [sys.executable, str(root / "scripts" / "autosure_doctor.py"), "--pretty"]
        snapshot_cmd = [
            sys.executable,
            str(root / "scripts" / "autosure_validate_runtime.py"),
            "snapshot",
            "--session-key",
            session_key,
            "--save",
            str(out_dir / "before.json"),
        ]
    
        doctor_rc, doctor_payload, doctor_out, doctor_err = run_json(doctor_cmd)
        snap_rc, snap_payload, snap_out, snap_err = run_json(snapshot_cmd)
    
        result = {
            "ok": doctor_rc == 0 and snap_rc == 0,
            "sessionKey": session_key,
            "outDir": str(out_dir),
            "doctor": doctor_payload if doctor_payload else {"stdout": doctor_out, "stderr": doctor_err, "ok": doctor_rc == 0},
            "before": snap_payload if snap_payload else {"stdout": snap_out, "stderr": snap_err, "ok": snap_rc == 0},
            "artifacts": {
                "doctor": str(out_dir / "doctor.json"),
                "before": str(out_dir / "before.json"),
                "after": str(out_dir / "after.json"),
                "diff": str(out_dir / "diff.json"),
            },
            "checklist": [
                "/autosure status",
                "/autosure 3",
                "observe at least one loop injection",
                "/autosure stop",
                f"python3 skills/autosure/scripts/autosure_validate_session.py finalize --session-key {session_key} --out-dir {out_dir}",
            ],
        }
    
        write_json(out_dir / "doctor.json", result["doctor"] if isinstance(result["doctor"], dict) else {"raw": result["doctor"]})
        write_json(out_dir / "prepare.json", result)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0 if result["ok"] else 1
    
    
    def finalize(session_key: str, out_dir: Path) -> int:
        root = skill_root()
        after_cmd = [
            sys.executable,
            str(root / "scripts" / "autosure_validate_runtime.py"),
            "snapshot",
            "--session-key",
            session_key,
            "--save",
            str(out_dir / "after.json"),
        ]
        diff_cmd = [
            sys.executable,
            str(root / "scripts" / "autosure_validate_runtime.py"),
            "diff",
            "--session-key",
            session_key,
            "--before",
            str(out_dir / "before.json"),
            "--save",
            str(out_dir / "diff.json"),
        ]
    
        after_rc, after_payload, after_out, after_err = run_json(after_cmd)
        diff_rc, diff_payload, diff_out, diff_err = run_json(diff_cmd)
    
        changed = diff_payload.get("changed", {}) if isinstance(diff_payload, dict) else {}
        after_snapshot = (after_payload or {}).get("snapshot", after_payload) if isinstance(after_payload, dict) else {}
        behavior_summary = {
            "phaseChanged": "phase" in changed,
            "loopFieldsChanged": any(k.startswith("loop") for k in changed.keys()),
            "updatedAtChanged": "updatedAt" in changed,
            "lastSuccessChanged": "lastSuccessAt" in changed,
            "lastAgentEndChanged": "lastAgentEndAt" in changed,
            "effectiveLoopState": after_snapshot.get("effectiveLoopState"),
            "terminalTailObserved": after_snapshot.get("terminalTailObserved"),
            "phaseAuthoritativeForLoop": after_snapshot.get("phaseAuthoritativeForLoop"),
            "authoritativeLoopFinished": bool(
                after_snapshot.get("sessionExists")
                and after_snapshot.get("inflightResume") is False
                and after_snapshot.get("loopActive") is False
                and after_snapshot.get("loopRemainingRounds") in (0, None)
            ),
        }
    
        result = {
            "ok": after_rc == 0 and diff_rc == 0,
            "sessionKey": session_key,
            "outDir": str(out_dir),
            "after": after_payload if after_payload else {"stdout": after_out, "stderr": after_err, "ok": after_rc == 0},
            "diff": diff_payload if diff_payload else {"stdout": diff_out, "stderr": diff_err, "ok": diff_rc == 0},
            "behaviorSummary": behavior_summary,
        }
        write_json(out_dir / "finalize.json", result)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0 if result["ok"] else 1
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description="Autosure independent test-session validator helper")
        ap.add_argument("action", choices=("prepare", "finalize"))
        ap.add_argument("--session-key", default=DEFAULT_SESSION_KEY, help="Autosure session key to validate")
        ap.add_argument("--out-dir", type=Path, default=None, help="Artifact output directory")
        args = ap.parse_args()
    
        out_dir = plan_dir(args.out_dir, args.session_key)
        out_dir.mkdir(parents=True, exist_ok=True)
    
        if args.action == "prepare":
            return prepare(args.session_key, out_dir)
        return finalize(args.session_key, out_dir)
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • skill/autosure/scripts/init_run.py1.6 KB5360f1fc4dfcupstream ↗
    #!/usr/bin/env python3
    import argparse
    import json
    from datetime import datetime, timezone
    from pathlib import Path
    
    
    def utc_now() -> str:
        return datetime.now(timezone.utc).isoformat()
    
    
    def main() -> int:
        parser = argparse.ArgumentParser(description="Initialize autosure run card.")
        parser.add_argument("--run-id", required=True, help="Run identifier")
        parser.add_argument("--project", required=True, help="Project lane name")
        parser.add_argument("--root", required=True, help="Project root path")
        parser.add_argument(
            "--output-dir",
            default=str(Path.home() / ".openclaw" / "workspace" / "runs"),
            help="Base runs directory (default: ~/.openclaw/workspace/runs)",
        )
        args = parser.parse_args()
    
        run_dir = Path(args.output_dir) / args.run_id
        run_dir.mkdir(parents=True, exist_ok=True)
    
        run_card = {
            "run_id": args.run_id,
            "project": args.project,
            "project_root": args.root,
            "created_at": utc_now(),
            "updated_at": utc_now(),
            "autosure": {
                "mode": "bounded-auto-resume",
                "max_auto_resumes": 1,
                "cooldown_ms": 15000,
                "circuit_threshold": 3,
                "circuit_open_ms": 120000,
                "compression_wait_ms": 60000,
            },
            "status": "initialized",
            "notes": [],
        }
    
        out = run_dir / "AUTOSURE-RUN.json"
        out.write_text(json.dumps(run_card, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        print(f"initialized: {out}")
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • skill/autosure/scripts/install_bundle.py7.6 KBecbd1f0205aeupstream ↗
    #!/usr/bin/env python3
    """
    Autosure OpenClaw bundle installer.
    Copies vendored plugins from this skill into OPENCLAW_WORKSPACE/plugins and prints merge hints for openclaw.json.
    """
    from __future__ import annotations
    
    import argparse
    import json
    import os
    import shutil
    import sys
    from pathlib import Path
    
    
    PLUGIN_NAMES = ("autosure-resume", "auto-resume-lite")
    LEGACY_PLUGIN_DIR_ALIASES = {
        "autosure-resume": (),
        "auto-resume-lite": ("openclaw-auto-resume-lite",),
    }
    
    
    def skill_root() -> Path:
        return Path(__file__).resolve().parents[1]
    
    
    def default_workspace() -> Path:
        env = (os.environ.get("OPENCLAW_WORKSPACE") or "").strip()
        if env:
            return Path(env).expanduser()
        return Path.home() / ".openclaw" / "workspace"
    
    
    def ensure_workspace_root(ws: Path) -> None:
        if not ws.exists():
            ws.mkdir(parents=True, exist_ok=True)
        if not ws.is_dir():
            raise NotADirectoryError(f"workspace is not a directory: {ws}")
    
    
    def backup_dir(dst: Path, dry: bool) -> Path | None:
        if not dst.exists():
            return None
        backup = dst.with_name(f"{dst.name}.bak")
        if dry:
            print(f"[dry-run] would backup existing plugin: {dst} -> {backup}")
            return backup
        if backup.exists():
            shutil.rmtree(backup)
        shutil.copytree(dst, backup)
        print(f"OK backup: {backup}")
        return backup
    
    
    def copytree(src: Path, dst: Path, dry: bool) -> Path | None:
        backup = backup_dir(dst, dry)
        if dry:
            print(f"[dry-run] would sync: {src} -> {dst}")
            return backup
        if dst.exists():
            shutil.rmtree(dst)
        shutil.copytree(src, dst)
        print(f"OK copied: {dst}")
        return backup
    
    
    def sync_legacy_aliases(src: Path, plugins_dir: Path, plugin_name: str, dry: bool) -> list[tuple[Path, Path | None]]:
        synced: list[tuple[Path, Path | None]] = []
        for alias in LEGACY_PLUGIN_DIR_ALIASES.get(plugin_name, ()):
            alias_dst = plugins_dir / alias
            if not alias_dst.exists():
                continue
            backup = copytree(src, alias_dst, dry)
            synced.append((alias_dst, backup))
        return synced
    
    
    def inactive_plugin_name(mode: str) -> str:
        return "auto-resume-lite" if mode == "full" else "autosure-resume"
    
    
    def build_snippet(mode: str, plugin_path: Path) -> dict:
        resolved = str(plugin_path.resolve())
        if mode == "full":
            return {
                "plugins": {
                    "allow": ["autosure-resume"],
                    "entries": {
                        "autosure-resume": {
                            "enabled": True,
                            "config": {
                                "maxAutoResumes": 1,
                                "cooldownMs": 15000,
                                "compressionWaitMs": 60000,
                                "circuitThreshold": 3,
                                "circuitOpenMs": 120000,
                                "dedupeTtlMs": 120000,
                                "enableNonActionResume": False,
                                "commandMaxRounds": 1000000,
                                "demoInjectRounds": 2,
                                "loopIdleGraceMs": 15000,
                            },
                        },
                        "auto-resume-lite": {
                            "enabled": False,
                            "config": {
                                "cooldownMs": 20000,
                            },
                        },
                    },
                    "load": {"paths": [resolved]},
                }
            }
        return {
            "plugins": {
                "allow": ["auto-resume-lite"],
                "entries": {
                    "auto-resume-lite": {
                        "enabled": True,
                        "config": {"enabled": True, "cooldownMs": 20000},
                    },
                    "autosure-resume": {
                        "enabled": False,
                        "config": {
                            "maxAutoResumes": 1,
                            "cooldownMs": 15000,
                            "compressionWaitMs": 60000,
                            "circuitThreshold": 3,
                            "circuitOpenMs": 120000,
                            "dedupeTtlMs": 120000,
                            "enableNonActionResume": False,
                            "commandMaxRounds": 1000000,
                            "demoInjectRounds": 2,
                            "loopIdleGraceMs": 15000,
                        },
                    },
                },
                "load": {"paths": [resolved]},
            }
        }
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description="Install Autosure vendored plugins into OpenClaw workspace.")
        ap.add_argument(
            "--workspace",
            type=Path,
            default=None,
            help="OpenClaw workspace root (default: OPENCLAW_WORKSPACE or ~/.openclaw/workspace)",
        )
        ap.add_argument(
            "--mode",
            choices=("full", "lite"),
            default="full",
            help="full=autosure-resume only (recommended). lite=auto-resume-lite only (minimal).",
        )
        ap.add_argument("--dry-run", action="store_true", help="Print actions without writing files.")
        args = ap.parse_args()
    
        root = skill_root()
        vendor = root / "vendor"
        ws = (args.workspace or default_workspace()).expanduser().resolve()
        plugins_dir = ws / "plugins"
        dry = args.dry_run
    
        if not vendor.is_dir():
            print("vendor/ missing — skill pack incomplete", file=sys.stderr)
            return 2
    
        ensure_workspace_root(ws)
        plugins_dir.mkdir(parents=True, exist_ok=True)
    
        print(f"Skill root:   {root}")
        print(f"Workspace:    {ws}")
        print(f"Plugins dir:  {plugins_dir}")
        print(f"Mode:         {args.mode}")
        print(f"Dry run:      {dry}")
        print()
    
        selected = "autosure-resume" if args.mode == "full" else "auto-resume-lite"
        src = vendor / selected
        if not src.is_dir():
            print(f"vendor/{selected} missing", file=sys.stderr)
            return 2
    
        dst = plugins_dir / selected
        backup = copytree(src, dst, dry)
        legacy_synced = sync_legacy_aliases(src, plugins_dir, selected, dry)
        inactive = inactive_plugin_name(args.mode)
        inactive_dst = plugins_dir / inactive
        inactive_note = f"Inactive plugin directory still present: {inactive_dst}" if inactive_dst.exists() else f"Inactive plugin directory not installed: {inactive_dst}"
    
        snippet = build_snippet(args.mode, dst)
    
        print()
        print("--- Merge the following into ~/.openclaw/openclaw.json ---")
        print(json.dumps(snippet, ensure_ascii=False, indent=2))
        print("--- end snippet ---")
        print()
        print("Merge rules:")
        print(f"- Append plugins.allow with '{selected}' instead of replacing existing items.")
        print(f"- Append plugins.load.paths with '{dst.resolve()}' if not already present.")
        if legacy_synced:
            legacy_paths = ", ".join(str(path) for path, _ in legacy_synced)
            print(f"- Legacy compatible path(s) refreshed in place: {legacy_paths}")
            print("- If your openclaw.json still points to a legacy lite path, it can keep working; prefer migrating load.paths to the canonical autosure path above.")
        print(f"- Keep '{inactive}' disabled in plugins.entries (do not enable both autosure plugins).")
        print(f"- {inactive_note}")
        if backup is not None:
            print(f"- Backup created for rollback: {backup}")
        if legacy_synced:
            for legacy_path, legacy_backup in legacy_synced:
                if legacy_backup is not None:
                    print(f"- Legacy rollback backup: {legacy_backup}")
        print()
        print("Next commands:")
        print("- openclaw config validate")
        print(f"- openclaw plugins inspect {selected}")
        print("- openclaw daemon restart   # or your service manager")
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
    
  • skill/autosure/scripts/patch_control_ui.py4.9 KBcff8b323388cupstream ↗
    #!/usr/bin/env python3
    from __future__ import annotations
    
    import argparse
    import re
    import shutil
    from pathlib import Path
    
    MODULE_SCRIPT_RE = re.compile(r'^\s*<script type="module" crossorigin src="\./assets/index-[^"]+\.js"></script>$', re.MULTILINE)
    MARKER_START = '    <script>\n      (function () {\n        var ROOT_ID = "autosure-native-capsule";'
    
    
    def default_control_ui_index() -> Path:
        candidates = [
            Path.home() / '.volta' / 'tools' / 'image' / 'packages' / 'openclaw' / 'lib' / 'node_modules' / 'openclaw' / 'dist' / 'control-ui' / 'index.html',
            Path('/opt/homebrew/lib/node_modules/openclaw/dist/control-ui/index.html'),
            Path('/usr/local/lib/node_modules/openclaw/dist/control-ui/index.html'),
        ]
        for path in candidates:
            if path.exists():
                return path
        return candidates[0]
    
    
    def find_module_script_tag(html: str) -> str:
        match = MODULE_SCRIPT_RE.search(html)
        if not match:
            raise RuntimeError('Cannot find control-ui module script tag')
        return match.group(0)
    
    
    def snippet_text(js_text: str, module_script_tag: str) -> str:
        indented = '\n'.join('      ' + line if line else '' for line in js_text.rstrip().splitlines())
        return (
            '    <script>\n'
            f'{indented}\n'
            '    </script>\n'
            f'{module_script_tag}'
        )
    
    
    def install(index_path: Path, js_path: Path, dry_run: bool, force: bool = False) -> int:
        html = index_path.read_text(encoding='utf-8')
        module_script_tag = find_module_script_tag(html)
        if MARKER_START in html:
            if not force:
                print(f'Autosure native capsule already installed: {index_path}')
                return 0
            start = html.index(MARKER_START)
            end = html.index(module_script_tag, start)
            html = html[:start] + module_script_tag + html[end + len(module_script_tag):]
        js_text = js_path.read_text(encoding='utf-8')
        patched = html.replace(module_script_tag, snippet_text(js_text, module_script_tag), 1)
        backup = index_path.with_suffix(index_path.suffix + '.autosure.bak')
        if dry_run:
            print(f'[dry-run] would backup {index_path} -> {backup}')
            print(f'[dry-run] would inject native capsule from {js_path}')
            print('[dry-run] force reinstall enabled' if force else '[dry-run] normal install mode')
            return 0
        shutil.copy2(index_path, backup)
        index_path.write_text(patched, encoding='utf-8')
        if force:
            print(f'Backup refreshed: {backup}')
            print(f'Reinstalled autosure native capsule into: {index_path}')
        else:
            print(f'Backup created: {backup}')
            print(f'Installed autosure native capsule into: {index_path}')
        return 0
    
    
    def uninstall(index_path: Path, dry_run: bool) -> int:
        html = index_path.read_text(encoding='utf-8')
        if MARKER_START not in html:
            print(f'Autosure native capsule not present: {index_path}')
            return 0
        module_script_tag = find_module_script_tag(html)
        start = html.index('    <script>\n      (function () {\n        var ROOT_ID = "autosure-native-capsule";')
        end = html.index(module_script_tag, start)
        patched = html[:start] + module_script_tag + html[end + len(module_script_tag):]
        backup = index_path.with_suffix(index_path.suffix + '.autosure.remove.bak')
        if dry_run:
            print(f'[dry-run] would backup {index_path} -> {backup}')
            print(f'[dry-run] would remove native capsule block from {index_path}')
            return 0
        shutil.copy2(index_path, backup)
        index_path.write_text(patched, encoding='utf-8')
        print(f'Backup created: {backup}')
        print(f'Removed autosure native capsule from: {index_path}')
        return 0
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description='Install/remove autosure native fallback capsule into OpenClaw Control UI index.html')
        ap.add_argument('action', choices=['install', 'uninstall', 'reinstall'])
        ap.add_argument('--index', type=Path, default=default_control_ui_index(), help='Path to OpenClaw control-ui index.html')
        ap.add_argument('--js', type=Path, default=Path(__file__).resolve().parents[1] / 'ui-capsule' / 'repair-pack' / 'native-control-ui-capsule.js', help='Path to native capsule JS source')
        ap.add_argument('--dry-run', action='store_true')
        ap.add_argument('--force', action='store_true', help='Replace existing autosure native capsule block if already installed')
        args = ap.parse_args()
    
        index_path = args.index.expanduser().resolve()
        if not index_path.exists():
            raise FileNotFoundError(f'control-ui index not found: {index_path}')
    
        if args.action in ('install', 'reinstall'):
            js_path = args.js.expanduser().resolve()
            if not js_path.exists():
                raise FileNotFoundError(f'native capsule source not found: {js_path}')
            return install(index_path, js_path, args.dry_run, force=(args.force or args.action == 'reinstall'))
        return uninstall(index_path, args.dry_run)
    
    
    if __name__ == '__main__':
        raise SystemExit(main())
    
  • skill/autosure/scripts/repair_center.py15 KB5b819f95f157upstream ↗
    #!/usr/bin/env python3
    from __future__ import annotations
    
    import argparse
    import json
    import os
    import shutil
    import subprocess
    import sys
    from pathlib import Path
    
    KNOWN_USERSCRIPT_MANAGERS = {
        "dhdgffkkebhmkfjojejmpbldmpobfkfo": "Tampermonkey",
        "iikmkjmpaadaobahmlepeloendndfphd": "Tampermonkey Beta",
        "jinjaccalgkegednnccohejagnlnfdag": "Violentmonkey",
        "mhmadkmgjjelhpedgfedcmjnfdelnlfo": "Userscripts",
    }
    USERSCRIPT_MANAGER_TOKENS = (
        "tampermonkey",
        "violentmonkey",
        "userscript",
    )
    
    
    def skill_root() -> Path:
        return Path(__file__).resolve().parents[1]
    
    
    def workspace_root() -> Path:
        env_ws = (os.environ.get("OPENCLAW_WORKSPACE") or "").strip()
        if env_ws:
            return Path(env_ws).expanduser().resolve()
        return (Path.home() / ".openclaw" / "workspace").resolve()
    
    
    def primary_profile_root() -> Path:
        return (Path.home() / ".openclaw" / "browser" / "openclaw" / "user-data").resolve()
    
    
    def default_control_ui_index() -> Path:
        candidates = [
            (
                Path.home()
                / ".volta"
                / "tools"
                / "image"
                / "packages"
                / "openclaw"
                / "lib"
                / "node_modules"
                / "openclaw"
                / "dist"
                / "control-ui"
                / "index.html"
            ).resolve(),
            Path("/opt/homebrew/lib/node_modules/openclaw/dist/control-ui/index.html").resolve(),
            Path("/usr/local/lib/node_modules/openclaw/dist/control-ui/index.html").resolve(),
        ]
        for path in candidates:
            if path.exists():
                return path
        return candidates[0]
    
    
    def userscript_source() -> Path:
        return skill_root() / "ui-capsule" / "repair-pack" / "autosure-capsule.user.js"
    
    
    def native_source() -> Path:
        return skill_root() / "ui-capsule" / "repair-pack" / "native-control-ui-capsule.js"
    
    
    def native_install_backup_path(index_path: Path) -> Path:
        return index_path.with_suffix(index_path.suffix + ".autosure.bak")
    
    
    def native_remove_backup_path(index_path: Path) -> Path:
        return index_path.with_suffix(index_path.suffix + ".autosure.remove.bak")
    
    
    def acceptance_url(debug: bool = True) -> str:
        url = "http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain"
        return url + ("&autosureDebug=1" if debug else "")
    
    
    def run_cmd(cmd: list[str]) -> tuple[int, str, str]:
        result = subprocess.run(cmd, capture_output=True, text=True, check=False)
        return result.returncode, result.stdout.strip(), result.stderr.strip()
    
    
    def detect_native_patch(index_path: Path) -> dict:
        if not index_path.exists():
            return {
                "ok": False,
                "present": False,
                "detail": f"control-ui index missing: {index_path}",
            }
        html = index_path.read_text(encoding="utf-8", errors="replace")
        markers = {
            "root_id": 'autosure-native-capsule' in html,
            "debug_query": 'autosureDebug=1' in html,
            "state_key": 'autosure.capsule.state.v2' in html,
            "debug_label": 'AUTOSURE DEBUG' in html,
        }
        present = all(markers.values())
        return {
            "ok": present,
            "present": present,
            "detail": str(index_path),
            "markers": markers,
        }
    
    
    def detect_native_backups(index_path: Path) -> dict:
        install_backup = native_install_backup_path(index_path)
        remove_backup = native_remove_backup_path(index_path)
        payload = {
            "installBackup": {
                "path": str(install_backup),
                "exists": install_backup.exists(),
            },
            "removeBackup": {
                "path": str(remove_backup),
                "exists": remove_backup.exists(),
            },
        }
        return payload
    
    
    def read_manifest_name(manifest_path: Path) -> str:
        try:
            data = json.loads(manifest_path.read_text(encoding="utf-8"))
        except Exception:
            return "UNKNOWN"
        name = data.get("name", "UNKNOWN")
        if isinstance(name, str) and name.startswith("__MSG_") and name.endswith("__"):
            token = name[len("__MSG_") : -2]
            for locale in ("en", "en_US", "zh_CN", "zh", "default"):
                messages = manifest_path.parent / "_locales" / locale / "messages.json"
                if not messages.exists():
                    continue
                try:
                    payload = json.loads(messages.read_text(encoding="utf-8"))
                except Exception:
                    continue
                if token in payload:
                    return payload[token].get("message", name)
        return name
    
    
    def detect_userscript_managers(profile_root: Path) -> dict:
        ext_root = profile_root / "Default" / "Extensions"
        if not ext_root.exists():
            return {
                "ok": False,
                "present": False,
                "detail": f"extensions dir missing: {ext_root}",
                "managers": [],
            }
    
        managers: list[dict] = []
        for ext_dir in sorted(p for p in ext_root.iterdir() if p.is_dir()):
            versions = sorted(p for p in ext_dir.iterdir() if p.is_dir())
            if not versions:
                continue
            manifest = versions[-1] / "manifest.json"
            if not manifest.exists():
                continue
            resolved_name = read_manifest_name(manifest)
            lowered = resolved_name.lower()
            known = KNOWN_USERSCRIPT_MANAGERS.get(ext_dir.name)
            if known or any(token in lowered for token in USERSCRIPT_MANAGER_TOKENS):
                managers.append(
                    {
                        "id": ext_dir.name,
                        "version": versions[-1].name,
                        "name": known or resolved_name,
                        "path": str(versions[-1]),
                    }
                )
    
        return {
            "ok": bool(managers),
            "present": bool(managers),
            "detail": str(ext_root),
            "managers": managers,
        }
    
    
    def detect_staged_userscript(target_dir: Path) -> dict:
        staged = target_dir / "autosure-capsule.user.js"
        disabled = target_dir / "autosure-capsule.user.js.disabled"
        source = userscript_source()
        return {
            "ok": source.exists(),
            "source": str(source),
            "sourceExists": source.exists(),
            "stagedPath": str(staged),
            "stagedExists": staged.exists(),
            "disabledPath": str(disabled),
            "disabledExists": disabled.exists(),
        }
    
    
    def build_next_steps(native: dict, managers: dict, staged: dict) -> list[str]:
        steps: list[str] = []
        if not managers["present"]:
            steps.append("Install or connect a userscript manager in the 007 primary browser profile if you want the userscript carrier.")
        if managers["present"] and not staged["stagedExists"]:
            steps.append("Run `python3 skills/autosure/scripts/repair_center.py stage-userscript` to stage the latest autosure userscript for import.")
        if not native["present"]:
            steps.append("Run `python3 skills/autosure/scripts/repair_center.py native-install` to restore the local native fallback.")
        if native["present"]:
            steps.append("Open the acceptance page with `python3 skills/autosure/scripts/repair_center.py open-acceptance-url` for local visual confirmation.")
        return steps
    
    
    def summarize_status(native: dict, managers: dict, staged: dict, recommended_carrier: str) -> tuple[str, str, str]:
        if recommended_carrier == "native-fallback" and native["present"]:
            return (
                "healthy-native",
                "use-native-fallback",
                "No userscript manager is currently available in the 007 primary browser profile, so native fallback is the only healthy carrier on this machine.",
            )
        if recommended_carrier == "userscript" and managers["present"] and staged["sourceExists"]:
            if staged["stagedExists"]:
                return (
                    "healthy-userscript-ready",
                    "open-acceptance-url",
                    "A userscript manager is present and the autosure userscript is already staged, so the userscript carrier is ready for import/acceptance.",
                )
            return (
                "mixed-needs-attention",
                "stage-userscript-import",
                "A userscript manager is present, but the latest autosure userscript is not staged for import yet.",
            )
        if not native["present"] and not managers["present"]:
            return (
                "blocked-no-carrier",
                "restore-native-patch",
                "Neither native fallback nor a userscript manager is currently available, so the machine has no healthy UI carrier.",
            )
        if not native["present"] and managers["present"]:
            if staged["stagedExists"]:
                return (
                    "mixed-needs-attention",
                    "open-acceptance-url",
                    "Userscript carrier may be available, but native fallback is absent and visual acceptance should be confirmed before treating the machine as healthy.",
                )
            return (
                "mixed-needs-attention",
                "stage-userscript-import",
                "Userscript manager exists, but native fallback is absent and no staged userscript import file is present.",
            )
        return (
            "mixed-needs-attention",
            "open-acceptance-url",
            "The machine has partial autosure UI capability, but the carrier state still needs explicit acceptance confirmation.",
        )
    
    
    
    def verify_payload(target_dir: Path) -> dict:
        index_path = default_control_ui_index()
        native = detect_native_patch(index_path)
        backups = detect_native_backups(index_path)
        managers = detect_userscript_managers(primary_profile_root())
        staged = detect_staged_userscript(target_dir)
        recommended_carrier = "userscript" if managers["present"] else "native-fallback"
        status_summary, recommended_action, carrier_diagnosis = summarize_status(native, managers, staged, recommended_carrier)
        payload = {
            "ok": native["ok"] and staged["sourceExists"],
            "workspace": str(workspace_root()),
            "primaryProfile": str(primary_profile_root()),
            "acceptanceUrl": acceptance_url(debug=True),
            "statusSummary": status_summary,
            "recommendedAction": recommended_action,
            "carrierDiagnosis": carrier_diagnosis,
            "nativePatch": native,
            "nativeBackups": backups,
            "userscriptManagers": managers,
            "userscript": staged,
            "recommendedCarrier": recommended_carrier,
            "notes": [],
            "nextSteps": [],
        }
        if not managers["present"]:
            payload["notes"].append("No userscript manager detected in the 007 primary browser profile; userscript visual acceptance is currently carrier-blocked.")
        if native["present"]:
            payload["notes"].append("Native fallback is currently installed in local OpenClaw Control UI.")
        else:
            payload["notes"].append("Native fallback is not currently installed in local OpenClaw Control UI.")
        if staged["stagedExists"]:
            payload["notes"].append("A userscript file is already staged for import.")
        elif staged["sourceExists"]:
            payload["notes"].append("Userscript source exists, but no staged import file is present yet.")
        if backups["installBackup"]["exists"]:
            payload["notes"].append("An install-time native backup is available for rollback.")
        if backups["removeBackup"]["exists"]:
            payload["notes"].append("A remove-time native backup is available for restore/reference.")
        payload["nextSteps"] = build_next_steps(native, managers, staged)
        return payload
    
    
    def stage_userscript(target_dir: Path) -> int:
        src = userscript_source()
        if not src.exists():
            raise FileNotFoundError(f"userscript source missing: {src}")
        target_dir.mkdir(parents=True, exist_ok=True)
        dst = target_dir / "autosure-capsule.user.js"
        shutil.copy2(src, dst)
        print(json.dumps({
            "ok": True,
            "action": "stage-userscript",
            "source": str(src),
            "target": str(dst),
        }, ensure_ascii=False, indent=2))
        return 0
    
    
    def disable_staged_userscript(target_dir: Path) -> int:
        staged = target_dir / "autosure-capsule.user.js"
        disabled = target_dir / "autosure-capsule.user.js.disabled"
        if staged.exists():
            staged.rename(disabled)
            print(json.dumps({
                "ok": True,
                "action": "disable-userscript",
                "target": str(disabled),
            }, ensure_ascii=False, indent=2))
            return 0
        print(json.dumps({
            "ok": True,
            "action": "disable-userscript",
            "detail": f"No staged userscript at {staged}",
        }, ensure_ascii=False, indent=2))
        return 0
    
    
    def run_patch(action: str) -> int:
        script = skill_root() / "scripts" / "patch_control_ui.py"
        actual_action = "reinstall" if action == "install" else action
        rc, out, err = run_cmd([sys.executable, str(script), actual_action])
        payload = {
            "ok": rc == 0,
            "action": f"native-{action}",
            "executedAction": actual_action,
            "stdout": out,
            "stderr": err,
        }
        print(json.dumps(payload, ensure_ascii=False, indent=2))
        return rc
    
    
    def native_rollback(index_path: Path) -> int:
        backup = native_install_backup_path(index_path)
        if not backup.exists():
            print(json.dumps({
                "ok": False,
                "action": "native-rollback",
                "detail": f"install-time backup missing: {backup}",
            }, ensure_ascii=False, indent=2))
            return 1
        shutil.copy2(index_path, index_path.with_suffix(index_path.suffix + ".rollback.bak"))
        shutil.copy2(backup, index_path)
        print(json.dumps({
            "ok": True,
            "action": "native-rollback",
            "restoredFrom": str(backup),
            "target": str(index_path),
            "preRollbackBackup": str(index_path.with_suffix(index_path.suffix + ".rollback.bak")),
        }, ensure_ascii=False, indent=2))
        return 0
    
    
    def open_acceptance(debug: bool) -> int:
        url = acceptance_url(debug=debug)
        rc, out, err = run_cmd(["open", url])
        payload = {
            "ok": rc == 0,
            "action": "open-acceptance-url",
            "url": url,
            "stdout": out,
            "stderr": err,
        }
        print(json.dumps(payload, ensure_ascii=False, indent=2))
        return rc
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description="Autosure Repair Center / carrier doctor")
        ap.add_argument(
            "action",
            choices=(
                "verify",
                "native-install",
                "native-uninstall",
                "native-rollback",
                "stage-userscript",
                "disable-userscript",
                "open-acceptance-url",
            ),
        )
        ap.add_argument(
            "--target-dir",
            type=Path,
            default=Path(os.environ.get("AUTOSURE_TAMPERMONKEY_DIR", str(Path.home() / "Downloads"))).expanduser(),
            help="Directory used for staging autosure-capsule.user.js",
        )
        ap.add_argument("--normal", action="store_true", help="Use normal acceptance URL without autosureDebug=1")
        args = ap.parse_args()
    
        target_dir = args.target_dir.expanduser().resolve()
    
        if args.action == "verify":
            payload = verify_payload(target_dir)
            print(json.dumps(payload, ensure_ascii=False, indent=2))
            return 0 if payload["ok"] else 1
        if args.action == "stage-userscript":
            return stage_userscript(target_dir)
        if args.action == "disable-userscript":
            return disable_staged_userscript(target_dir)
        if args.action == "native-install":
            return run_patch("install")
        if args.action == "native-uninstall":
            return run_patch("uninstall")
        if args.action == "native-rollback":
            return native_rollback(default_control_ui_index())
        return open_acceptance(debug=not args.normal)
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • skill/autosure/scripts/sync_vendor_from_workspace.sh412 B0ef55b291e31upstream ↗
    #!/usr/bin/env bash
    # Maintainer: refresh vendor/autosure-resume from the live workspace plugin tree.
    set -euo pipefail
    ROOT="$(cd "$(dirname "$0")/.." && pwd)"
    SRC="${OPENCLAW_WORKSPACE:-$HOME/.openclaw/workspace}/plugins/autosure-resume"
    DST="$ROOT/vendor/autosure-resume"
    if [[ ! -d "$SRC" ]]; then
      echo "Source missing: $SRC" >&2
      exit 1
    fi
    rm -rf "$DST"
    cp -R "$SRC" "$DST"
    echo "OK synced $SRC -> $DST"
    
  • skill/autosure/scripts/verify_health.py6.8 KBe239d71df582upstream ↗
    #!/usr/bin/env python3
    from __future__ import annotations
    import argparse
    import json
    import os
    import re
    import subprocess
    from pathlib import Path
    
    
    PLUGIN_BY_MODE = {
        "full": "autosure-resume",
        "lite": "auto-resume-lite",
    }
    LEGACY_PLUGIN_DIR_ALIASES = {
        "autosure-resume": (),
        "auto-resume-lite": ("openclaw-auto-resume-lite",),
    }
    
    
    def run_cmd(cmd):
        result = subprocess.run(cmd, capture_output=True, text=True, check=False)
        return result.returncode, result.stdout.strip(), result.stderr.strip()
    
    
    def skill_root() -> Path:
        return Path(__file__).resolve().parents[1]
    
    
    def workspace_root() -> Path:
        env_ws = (os.environ.get("OPENCLAW_WORKSPACE") or "").strip()
        if env_ws:
            return Path(env_ws).expanduser()
        return Path.home() / ".openclaw" / "workspace"
    
    
    def detail_text(out: str, err: str) -> str:
        return (out or err or "").strip()[:4000]
    
    
    def plugin_installed_in_workspace(ws: Path, plugin_name: str) -> Path:
        return ws / "plugins" / plugin_name
    
    
    def legacy_plugin_paths(ws: Path, plugin_name: str) -> list[Path]:
        return [ws / "plugins" / alias for alias in LEGACY_PLUGIN_DIR_ALIASES.get(plugin_name, ())]
    
    
    def parse_install_path(inspect_output: str) -> Path | None:
        match = re.search(r"^Install path:\s*(.+)$", inspect_output, re.MULTILINE)
        if not match:
            return None
        return Path(match.group(1).strip()).expanduser()
    
    
    def main() -> int:
        ap = argparse.ArgumentParser(description="Verify Autosure bundle health inside an OpenClaw workspace.")
        ap.add_argument(
            "--mode",
            choices=("full", "lite"),
            default="full",
            help="full=check autosure-resume. lite=check auto-resume-lite.",
        )
        args = ap.parse_args()
    
        checks = []
        root = skill_root()
        ws = workspace_root()
        active_plugin = PLUGIN_BY_MODE[args.mode]
        inactive_plugin = PLUGIN_BY_MODE["lite" if args.mode == "full" else "full"]
        bundle_expected_path = plugin_installed_in_workspace(ws, active_plugin)
        legacy_paths = legacy_plugin_paths(ws, active_plugin)
    
        rc, out, err = run_cmd(["openclaw", "-V"])
        checks.append(("openclaw_version", rc == 0, detail_text(out, err)))
    
        rc, out, err = run_cmd(["openclaw", "plugins", "inspect", active_plugin])
        inspect_ok = rc == 0 and "Status: loaded" in out
        checks.append(("plugin_loaded", inspect_ok, detail_text(out, err)))
    
        actual_install_path = parse_install_path(out) if inspect_ok else None
        if actual_install_path is not None:
            checks.append(("plugin_install_path_discovered", True, str(actual_install_path)))
    
        rc, out, err = run_cmd(["openclaw", "config", "get", f"plugins.entries.{active_plugin}"])
        expected_tokens = {
            "autosure-resume": ("autosure-resume", "enabled", "maxAutoResumes", "loopIdleGraceMs", "commandMaxRounds"),
            "auto-resume-lite": ("auto-resume-lite", "enabled", "cooldownMs"),
        }[active_plugin]
        ok = rc == 0 and any(token in out for token in expected_tokens)
        checks.append(("plugin_config_present", ok, detail_text(out, err)))
    
        state_file = Path.home() / ".openclaw" / "plugins" / active_plugin / "state.json"
        checks.append(("state_file_path_known", True, str(state_file)))
    
        phrases = ws / "skills" / "autosure" / "发动词.txt"
        checks.append(
            (
                "phrases_file",
                phrases.is_file(),
                str(phrases) if phrases.is_file() else f"missing: {phrases} (plugin can fall back to built-in defaults)",
            )
        )
    
        vendored = root / "vendor" / active_plugin / "index.js"
        checks.append(
            (
                "skill_bundle_vendor_plugin",
                vendored.is_file(),
                str(vendored) if vendored.is_file() else f"missing pack file: {vendored}",
            )
        )
    
        canonical_present = bundle_expected_path.is_dir()
        legacy_present_paths = [path for path in legacy_paths if path.is_dir()]
        expected_ok = canonical_present or bool(legacy_present_paths)
        expected_detail = str(bundle_expected_path) if canonical_present else f"canonical missing: {bundle_expected_path}"
        if not canonical_present and legacy_present_paths:
            expected_detail += f"; legacy present: {', '.join(str(path) for path in legacy_present_paths)}"
        checks.append(("bundle_or_legacy_install_path_present", expected_ok, expected_detail))
    
        installed_dir = actual_install_path or bundle_expected_path
        if actual_install_path is not None and actual_install_path != bundle_expected_path:
            checks.append(
                (
                    "plugin_loaded_from_alternate_path",
                    True,
                    f"loaded from alternate path: {actual_install_path} (canonical bundle target: {bundle_expected_path})",
                )
            )
    
        checks.append(
            (
                "active_plugin_path_present",
                installed_dir.is_dir(),
                str(installed_dir) if installed_dir.is_dir() else f"missing installed plugin path: {installed_dir}",
            )
        )
    
        installed_index = installed_dir / "index.js"
        checks.append(
            (
                "active_plugin_entry_present",
                installed_index.is_file(),
                str(installed_index) if installed_index.is_file() else f"missing installed entry file: {installed_index}",
            )
        )
    
        if installed_index.is_file() and vendored.is_file():
            same = installed_index.read_text(encoding="utf-8") == vendored.read_text(encoding="utf-8")
            checks.append(
                (
                    "active_plugin_matches_vendor",
                    same,
                    f"{installed_index} matches skill vendor copy" if same else "installed plugin differs from vendored copy; re-run install_bundle.py or sync vendor first",
                )
            )
        else:
            checks.append(
                (
                    "active_plugin_matches_vendor",
                    False,
                    "comparison skipped because installed entry or vendored entry is missing",
                )
            )
    
        inactive_path = plugin_installed_in_workspace(ws, inactive_plugin)
        checks.append(
            (
                "inactive_plugin_presence_note",
                True,
                f"inactive plugin path {'present' if inactive_path.exists() else 'absent'}: {inactive_path}",
            )
        )
    
        capsule = root / "ui-capsule" / "repair-pack" / "autosure-capsule.user.js"
        checks.append(
            (
                "ui_capsule_pack_optional",
                capsule.is_file(),
                str(capsule) if capsule.is_file() else f"optional missing: {capsule}",
            )
        )
    
        payload = {
            "ok": all(item[1] for item in checks),
            "mode": args.mode,
            "activePlugin": active_plugin,
            "workspace": str(ws),
            "checks": [
                {"name": name, "ok": ok_item, "detail": detail}
                for (name, ok_item, detail) in checks
            ],
        }
        print(json.dumps(payload, ensure_ascii=False, indent=2))
        return 0 if payload["ok"] else 1
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • skill/autosure/references/cn.md4.6 KB0561b1d7c2f9upstream ↗
    # autosure 中文入口
    
    先读 `SKILL.md`。
    
    ## 文档权威顺序(重要)
    
    如果你只想知道**现在什么是真的**,按这个顺序读,不要反过来:
    
    1. `SKILL.md` —— skill 入口、范围、主边界
    2. `docs/PRD.md` —— 产品范围与验收口径
    3. `docs/ARCHITECTURE.md` —— 当前架构与分层真相
    4. `docs/UI_CAPSULE_SPEC.md` —— 当前 UI 冻结基线与交互合同
    5. `README.md` —— 面向使用/部署的总览说明
    6. `DEPLOY.md` / `HANDOFF_FOR_AGENT.md` / `小白使用说明.md` —— 面向不同操作者的执行入口
    
    ## 哪些文件已经归档
    
    下面这些文件已经移入 `archive/`,默认只当历史参考,不再占据前台产品文档面:
    
    - `archive/root-workfiles/architecture.md`
    - `archive/root-workfiles/findings.md`
    - `archive/root-workfiles/progress.md`
    - `archive/root-workfiles/task_plan.md`
    - `archive/docs-history/HANDOFF_CONTINUATION_2026-04-18.md`
    - `archive/docs-history/TRACK_A_VALIDATION_NOTE_2026-04-18.md`
    - `archive/docs-history/USERSCRIPT_CARRIER_HEALTH_NOTE_2026-04-18.md`
    - `archive/docs-history/UI_CONVERGENCE_GAP.md`
    - `archive/docs-history/UI_CONVERGENCE_PLAN.md`
    - `archive/docs-history/UI_CAPSULE_VNEXT_PLAN.md`
    - `archive/docs-history/AUTOSURE_TEST_HARNESS_PLAN_2026-04-18.md`
    - `archive/docs-history/REPAIR_CENTER_STABILIZATION_PLAN_2026-04-18.md`
    
    如果你要追历史脉络,读 `archive/README.md`。
    
    ## 当前收口后的现实口径(2026-04-19)
    
    - 产品默认路线仍是 **userscript**。
    - mini49 当前机器的本地优先可用路径仍是 **native fallback**。
    - `/autosure N` 的当前产品语义是:**首轮立即前台续跑,剩余轮次按每轮完成后继续**。
    - UI 冻结基线仍有效:
      - 默认收起
      - Refresh 左边
      - 图标 + 状态点
      - 向下展开
      - 两排按钮:`3 / 6 / 9 / ∞` 与 `Stop / Status`
    - 当前 autosure Control UI 线已进入**正式 closeout 后的可交付状态**;后续继续推进属于 polish / regression hardening,而不是重新开大修。
    
    ## 这是什么
    
    `autosure` 是给 OpenClaw 长任务/无人值守场景用的可分发 skill 包,核心目标只有三个:
    
    - 失败后能安全续跑;
    - 成功后能按 `/autosure` 继续推进;
    - 用户随时一句话就能打断,不会消息风暴。
    
    ## 先读顺序
    
    1. `SKILL.md` —— 技能入口、适用边界、主命令
    2. `docs/PRD.md` —— 产品目标与验收口径
    3. `docs/ARCHITECTURE.md` —— 核心层 / UI 胶囊分层
    4. `docs/UI_CAPSULE_SPEC.md` —— userscript 胶囊专项
    5. `小白使用说明.md` —— 给人类操作者
    6. `DEPLOY.md` / `HANDOFF_FOR_AGENT.md` —— 给部署 Agent / 运维
    
    ## 快速判断怎么用
    
    ### 只是想在本机启用 autosure
    
    直接看:
    - `scripts/install_bundle.py`
    - `scripts/verify_health.py`
    - `小白使用说明.md`
    
    ### 想发给别人机器 / 客户 / 另一台 OpenClaw
    
    直接看:
    - `DEPLOY.md`
    - `HANDOFF_FOR_AGENT.md`
    - `MANIFEST.json`
    
    默认路线:
    - **先装 userscript 胶囊**(Tampermonkey)
    - 若确认脚本已安装但本机 `127.0.0.1:18789/chat*` **不执行**,再用:
      - `scripts/patch_control_ui.py`
      - `ui-capsule/repair-pack/native-control-ui-capsule.js`
    
    也就是说,**native fallback 是维修路线,不是默认分发主路线**。
    
    ### 当前机器(mini49)例外结论
    
    在 mini49 当前机器上,Tampermonkey 执行层已验证不可靠,因此本机应**优先使用 native fallback**。
    
    验收可直接打开:
    - `http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain&autosureDebug=1`
    
    该参数只用于现场核验:会强制展开胶囊并显示 `AUTOSURE DEBUG` 文案,默认正式页不带它。
    
    ### 想改产品与实现
    
    直接看:
    - `docs/PRD.md`
    - `docs/ARCHITECTURE.md`
    - `vendor/autosure-resume/index.js`
    - `ui-capsule/repair-pack/autosure-capsule.user.js`
    
    ## 目录里哪些是“核心”,哪些是“会拖后腿的噪音”
    
    ### 核心
    - `SKILL.md`
    - `vendor/`
    - `scripts/`
    - `docs/`
    - `ui-capsule/repair-pack/`
    - `MANIFEST.json`
    
    ### 会增加维护成本的外围文档
    - `README.md`
    - `PACKAGE.md`
    - `architecture.md`
    - `findings.md`
    - `progress.md`
    - `task_plan.md`
    
    这些文件不是完全不能留,但它们不是 skill 的最小权威面。后续若继续瘦身,优先先砍这圈重复层。
    
    ## 当前已知最该优化的点
    
    1. 安装脚本以前会直接覆盖插件目录但不留回滚备份;现在已补备份。
    2. 健康检查以前只看“有没有”,不看“装进去的插件是不是跟 vendor 一致”;现在已补一致性检查。
    3. 文档层还有重复和分裂,后续应该再收口成更锋利的一套权威链。
    
  • skill/autosure/artifacts/verification-20260416-044427.md2.1 KBa49689ccae3dupstream ↗
    # autosure verification report
    
    - host: skymini
    - plugin: autosure-resume
    - window: 2026-04-16 04:39~04:43 + post-checks
    
    ## Scenario A - timeout interruption triggers bounded auto-resume
    
    - test session: `agent:main:explicit:autosure-case-a`
    - evidence:
      - gateway log contains `autosure-resume scheduled for agent:main:explicit:autosure-case-a`
      - gateway log contains paired `autosure-resume agent_end observed`
    - result: PASS
    
    ## Scenario B - repeated interruption triggers circuit breaker
    
    - test session: `agent:main:explicit:autosure-case-b`
    - method: repeated timeout runs
    - evidence:
      - gateway err log: `autosure-resume circuit opened for agent:main:explicit:autosure-case-b`
    - result: PASS
    
    ## Scenario C - human/interactive intervention does not keep retry pressure
    
    - test session: `agent:main:explicit:autosure-case-c`
    - evidence from state file:
      - `failureStreak: 0`
      - `consecutiveAutoResumes: 0`
      - `inflightResume: false`
    - interpretation:
      - session is not under retry pressure after interactive run
    - result: PASS
    
    ## Scenario D - compression-aware waiting policy
    
    - configured behavior:
      - `compressionWaitMs: 60000`
      - plugin code maps context overflow/compression signals to reason `compression`
      - effective cooldown uses `max(cooldownMs, compressionWaitMs)`
    - environment evidence:
      - gateway err log includes multiple `Context overflow` diagnostics on long sessions
    - runtime note:
      - deterministic live trigger under current provider instability was not reproduced in this window.
    - result: PASS (policy and telemetry verified), LIVE_TRIGGER=PARTIAL
    
    ## Final config check
    
    - `maxAutoResumes: 1`
    - `cooldownMs: 15000`
    - `compressionWaitMs: 60000`
    - `circuitThreshold: 3`
    - `circuitOpenMs: 120000`
    - `dedupeTtlMs: 120000` (restored after stress test)
    
    ## Conclusion
    
    `autosure-resume` is loaded, bounded, and stable under timeout failure conditions with circuit protection active.  
    Compression-aware path is implemented and aligned with observed context-overflow telemetry; recommend extended soak to capture one explicit `reason=compression` schedule in production logs.
    
  • skill/autosure/demo/webui-续轮演示.html7.7 KB0681fa0f0b3aupstream ↗
    <!DOCTYPE html>
    <html lang="zh-Hans">
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <title>Autosure 续轮 · Web UI 可视化演示(模拟)</title>
      <style>
        :root {
          --bg: #0f1117;
          --panel: #161b26;
          --border: #2a3142;
          --text: #e8ecf4;
          --muted: #8b95a8;
          --user-bg: #1e3a5f;
          --assistant-bg: #222831;
          --inject-bg: #1a3d2e;
          --inject-border: #2d6a4f;
          --accent: #6c9eff;
          --warn: #e6a23c;
        }
        * { box-sizing: border-box; }
        body {
          margin: 0;
          min-height: 100vh;
          font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif;
          background: var(--bg);
          color: var(--text);
          line-height: 1.5;
        }
        .wrap {
          max-width: 720px;
          margin: 0 auto;
          padding: 1.25rem 1rem 3rem;
        }
        header {
          margin-bottom: 1rem;
          padding-bottom: 1rem;
          border-bottom: 1px solid var(--border);
        }
        h1 {
          font-size: 1.15rem;
          font-weight: 600;
          margin: 0 0 0.35rem;
        }
        .sub {
          font-size: 0.85rem;
          color: var(--muted);
        }
        .banner {
          font-size: 0.8rem;
          color: var(--warn);
          background: rgba(230, 162, 60, 0.08);
          border: 1px solid rgba(230, 162, 60, 0.35);
          border-radius: 8px;
          padding: 0.65rem 0.75rem;
          margin-bottom: 1rem;
        }
        .toolbar {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
          align-items: center;
          margin-bottom: 0.75rem;
        }
        button {
          cursor: pointer;
          border: 1px solid var(--border);
          background: var(--panel);
          color: var(--text);
          padding: 0.45rem 0.85rem;
          border-radius: 8px;
          font-size: 0.875rem;
        }
        button.primary {
          background: #243554;
          border-color: #3d5a8a;
          color: #dbe7ff;
        }
        button:disabled {
          opacity: 0.45;
          cursor: not-allowed;
        }
        label {
          font-size: 0.8rem;
          color: var(--muted);
        }
        textarea.phrases {
          width: 100%;
          min-height: 88px;
          resize: vertical;
          background: var(--panel);
          border: 1px solid var(--border);
          border-radius: 8px;
          color: var(--text);
          padding: 0.6rem 0.75rem;
          font-family: inherit;
          font-size: 0.875rem;
          margin-bottom: 0.75rem;
        }
        .chat {
          background: var(--panel);
          border: 1px solid var(--border);
          border-radius: 12px;
          padding: 1rem;
          min-height: 320px;
          max-height: min(62vh, 520px);
          overflow-y: auto;
        }
        .msg {
          margin-bottom: 0.85rem;
          display: flex;
          flex-direction: column;
          gap: 0.2rem;
          animation: fade 0.35s ease;
        }
        @keyframes fade {
          from { opacity: 0; transform: translateY(6px); }
          to { opacity: 1; transform: translateY(0); }
        }
        .msg .meta {
          font-size: 0.72rem;
          color: var(--muted);
          padding: 0 0.15rem;
        }
        .bubble {
          max-width: 92%;
          padding: 0.65rem 0.85rem;
          border-radius: 12px;
          font-size: 0.9rem;
          white-space: pre-wrap;
          word-break: break-word;
        }
        .msg.user .bubble {
          align-self: flex-end;
          background: var(--user-bg);
          border: 1px solid #2a4a73;
        }
        .msg.assistant .bubble {
          align-self: flex-start;
          background: var(--assistant-bg);
          border: 1px solid var(--border);
        }
        .msg.inject .bubble {
          align-self: flex-end;
          background: var(--inject-bg);
          border: 1px solid var(--inject-border);
        }
        .msg.user .meta { text-align: right; }
        .msg.inject .meta { text-align: right; color: #7dcea0; }
        footer {
          margin-top: 1rem;
          font-size: 0.78rem;
          color: var(--muted);
        }
        code { color: var(--accent); font-size: 0.85em; }
      </style>
    </head>
    <body>
      <div class="wrap">
        <header>
          <h1>Autosure 续轮 · Web UI 可视化演示</h1>
          <p class="sub">这是<strong>独立模拟页</strong>,用来展示「答完一轮 → 自动再发一条用户消息(轮换 <code>发动词.txt</code>)→ 模型继续」的视觉效果;不是 OpenClaw 内置聊天页本身。</p>
        </header>
    
        <div class="banner">
          真实环境:你在 OpenClaw Web 里发 <code>/autosure N</code>,网关加载插件后,由插件触发与这里「自动用户气泡」等价的流程。
          <strong>更推荐</strong>:在 OpenClaw <strong>真实对话</strong>里发整行 <code>/autosure-demo</code>,由插件在会话内做可视化(见 autosure-resume 插件)。
        </div>
    
        <label for="phrases">发动词(一行一条,与 <code>skills/autosure/发动词.txt</code> 规则相同)</label>
        <textarea id="phrases" class="phrases">继续
    按你的想法继续</textarea>
    
        <div class="toolbar">
          <button type="button" class="primary" id="btnPlay">播放演示</button>
          <button type="button" id="btnReset">清空画面</button>
          <span class="sub" id="status"></span>
        </div>
    
        <div class="chat" id="chat" aria-live="polite"></div>
    
        <footer>
          打开方式:在访达中双击本文件,或用浏览器打开该 HTML 路径。若要改演示速度,可编辑本文件中的 <code>STEP_MS</code> 常量。
        </footer>
      </div>
    
      <script>
        const STEP_MS = 900;
    
        const chat = document.getElementById("chat");
        const phrasesEl = document.getElementById("phrases");
        const btnPlay = document.getElementById("btnPlay");
        const btnReset = document.getElementById("btnReset");
        const statusEl = document.getElementById("status");
    
        function sleep(ms) {
          return new Promise((r) => setTimeout(r, ms));
        }
    
        function parsePhrases(raw) {
          return raw
            .split(/\r?\n/)
            .map((l) => l.trim())
            .filter((l) => l && !l.startsWith("#"));
        }
    
        function addMessage(kind, meta, text) {
          const wrap = document.createElement("div");
          wrap.className = `msg ${kind}`;
          const m = document.createElement("div");
          m.className = "meta";
          m.textContent = meta;
          const b = document.createElement("div");
          b.className = "bubble";
          b.textContent = text;
          wrap.appendChild(m);
          wrap.appendChild(b);
          chat.appendChild(wrap);
          chat.scrollTop = chat.scrollHeight;
        }
    
        async function runDemo() {
          const phrases = parsePhrases(phrasesEl.value);
          if (phrases.length === 0) {
            statusEl.textContent = "请至少填写一行发动词。";
            return;
          }
    
          btnPlay.disabled = true;
          statusEl.textContent = "演示进行中…";
    
          addMessage("user", "你(Web 输入)", "/autosure 3");
          await sleep(STEP_MS);
    
          addMessage("assistant", "模型 · 第 1 轮", "(示例)我已根据你的任务完成本轮输出,准备结束本轮。");
          await sleep(STEP_MS * 1.1);
    
          for (let i = 0; i < 3; i += 1) {
            const phrase = phrases[i % phrases.length];
            addMessage(
              "inject",
              "自动续轮(插件注入 · 等价于你又发了一条用户消息)",
              phrase
            );
            await sleep(STEP_MS);
    
            addMessage(
              "assistant",
              `模型 · 第 ${i + 2} 轮`,
              i < 2
                ? "(示例)收到。我在上一轮基础上继续推进,并完成又一小步。"
                : "(示例)最后一轮:收尾说明。若真实环境需更多轮,可调大 /autosure 的数字。"
            );
            await sleep(STEP_MS * 1.05);
          }
    
          statusEl.textContent = "演示结束。可修改发动词后再次播放。";
          btnPlay.disabled = false;
        }
    
        btnPlay.addEventListener("click", () => {
          void runDemo();
        });
    
        btnReset.addEventListener("click", () => {
          chat.innerHTML = "";
          statusEl.textContent = "";
        });
      </script>
    </body>
    </html>
    
  • skill/autosure/DEPLOY.md6.6 KBa9f95f11ec47upstream ↗
    # Autosure 一键部署指南(任意 OpenClaw 主机)
    
    > **当前交付口径(2026-04-19 closeout)**
    >
    > - 产品默认路线仍是 **userscript**。
    > - mini49 当前机器的本地优先可用路径仍是 **native fallback**。
    > - `/autosure N` 的当前产品语义是:**首轮立即前台续跑,剩余轮次按每轮完成后继续**。
    >
    > 若需要判断产品/架构真相,优先看:`SKILL.md` → `docs/PRD.md` → `docs/ARCHITECTURE.md` → `docs/UI_CAPSULE_SPEC.md`。
    
    本包设计目标:**把本目录或压缩包交给 Agent / 运维**,按下列步骤即可在**任意已安装 OpenClaw** 的机器上落地。
    
    ## 前置条件
    
    - 已安装 **OpenClaw CLI**(`openclaw -V` 正常)。
    - 可写 **`~/.openclaw`**(或你自定义的 `OPENCLAW_STATE_DIR`)。
    - 建议已配置 **`OPENCLAW_WORKSPACE`** 指向本 skill 所在 workspace;未设置时默认 `~/.openclaw/workspace`。
    
    ## 方式 A:交给 Agent 的一句话(推荐)
    
    把下面整段原样发给负责部署的 Agent:
    
    > 请在本机执行 Autosure 安装:  
    > 1)将 skill 目录 `skills/autosure` 完整放到 `~/.openclaw/workspace/skills/autosure`(或你的 `OPENCLAW_WORKSPACE/skills/autosure`)。  
    > 2)运行 `python3 ~/.openclaw/workspace/skills/autosure/scripts/install_bundle.py --mode full`(或 `--dry-run` 先看计划)。  
    > 3)按脚本输出的 JSON 片段合并进 `~/.openclaw/openclaw.json`:`plugins.allow` **追加** `autosure-resume`(保留原有 telegram/memory 等项);`plugins.load.paths` 若有则**追加**路径勿覆盖;`entries` 按片段合并。(**不要**同时启用 `autosure-resume` 与 `auto-resume-lite`。)  
    > 4)执行 `openclaw config validate` 与 `openclaw plugins inspect autosure-resume`,确认 **Status: loaded**。  
    > 5)`openclaw daemon restart` 或等价方式重载网关。
    
    ## 方式 B:人工拷贝
    
    1. 复制整个 `autosure` 文件夹到 `~/.openclaw/workspace/skills/autosure`。  
    2. 复制 `vendor/autosure-resume` → `~/.openclaw/workspace/plugins/autosure-resume`。  
    3. (可选)若走极简续跑:复制 `vendor/auto-resume-lite` → `plugins/auto-resume-lite`。若目标机历史上已使用 `plugins/openclaw-auto-resume-lite`,可先保留旧目录与旧 `load.paths`;新版 `install_bundle.py --mode lite` 会同步刷新这个 legacy 别名目录,之后再择机迁移到 canonical 路径。  
    4. 合并 `openclaw.json` 中插件条目与 allowlist,校验后重启网关。
    
    ## 当前机器补充(mini49)
    
    当前机器对 `http://127.0.0.1:18789/chat*` 的 Tampermonkey 注入已验证不稳定。若你是在这台机器上部署,不必继续反复排查 userscript 注入层,先跑 Repair Center:
    
    ```bash
    python3 skills/autosure/scripts/repair_center.py verify
    ```
    
    重点看:
    - `statusSummary`
    - `recommendedAction`
    - `recommendedCarrier`
    
    若返回 `recommendedAction: restore-native-patch` 或 `recommendedCarrier: native-fallback`,再直接优先使用 native fallback。
    
    推荐使用幂等刷新入口,而不是只做一次性 install:
    
    ```bash
    python3 skills/autosure/scripts/repair_center.py native-install
    # 或
    python3 skills/autosure/scripts/patch_control_ui.py reinstall
    ```
    
    本机验收页:
    
    ```text
    http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain&autosureDebug=1
    ```
    
    该参数仅用于现场验收:会强制展开胶囊并显示 `AUTOSURE DEBUG` 文案,方便截图 / OCR;正常交付页不带该参数。
    
    ## 可选:启用 UI 胶囊(A1 userscript)
    
    1. 打开 `ui-capsule/repair-pack/autosure-capsule.user.js`。  
    2. 在 Tampermonkey 新建脚本并粘贴保存。  
    3. 刷新 OpenClaw chat 页面,胶囊应出现在刷新按钮附近(若失败则右上浮层)。  
    4. 胶囊“暂停”固定发送:`/autosure stop`。
    
    禁用/修复见:`ui-capsule/repair-pack/ENABLE_DISABLE.md`。
    
    ## 若 Tampermonkey 已安装但仍不执行:启用 native fallback
    
    当你已经确认:
    
    - userscript 已成功装进 Tampermonkey 本地库;
    - 但 `http://127.0.0.1:18789/chat*` 页面仍没有任何注入效果;
    
    先运行:
    
    ```bash
    python3 skills/autosure/scripts/repair_center.py verify
    ```
    
    重点看:
    - `statusSummary`
    - `recommendedAction`
    - `recommendedCarrier`
    
    若返回 `recommendedAction: restore-native-patch` 或 `recommendedCarrier: native-fallback`,可直接在本机启用 Control UI 原生修复:
    
    ```bash
    python3 skills/autosure/scripts/patch_control_ui.py install
    ```
    
    默认补丁目标:
    
    - `~/.volta/tools/image/packages/openclaw/lib/node_modules/openclaw/dist/control-ui/index.html`
    
    这条路线会:
    
    - 备份原始 `index.html`
    - 把 autosure 控件作为本机 OpenClaw Control UI 的原生浮层注入进去
    - 在 mini49 当前机器上,作为 **优先可用本地路径**
    
    本机验收可直接打开:
    
    ```text
    http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain&autosureDebug=1
    ```
    
    页面应显示 `AUTOSURE DEBUG` 与展开态胶囊,方便 OCR / 截图核验。
    
    卸载:
    
    ```bash
    python3 skills/autosure/scripts/patch_control_ui.py uninstall
    ```
    
    ## 安装脚本
    
    ```bash
    python3 skills/autosure/scripts/install_bundle.py --help
    python3 skills/autosure/scripts/install_bundle.py --dry-run
    python3 skills/autosure/scripts/install_bundle.py --mode full
    python3 skills/autosure/scripts/repair_center.py verify
    ```
    
    ## 装完自检
    
    ```bash
    python3 skills/autosure/scripts/verify_health.py --mode full
    python3 skills/autosure/scripts/verify_health.py --mode lite
    openclaw plugins inspect autosure-resume
    python3 skills/autosure/scripts/autosure_doctor.py --pretty
    python3 skills/autosure/scripts/autosure_validate_runtime.py snapshot --session-key agent:main:main
    ```
    
    ## Loop 状态解释(避免误判)
    
    不要把 `phase` 单独当成 autosure loop 真相。
    
    bounded loop 是否真的完成,优先看:
    - `inflightResume`
    - `loopControl.active`
    - `loopControl.remainingRounds`
    - `loopControl.completedRounds`
    - `loopControl.lastCommandRaw`
    
    验证脚本已内建更可靠口径:
    - `effectiveLoopState`
    - `phaseAuthoritativeForLoop`
    - `terminalTailObserved`
    - `authoritativeLoopFinished`
    
    若 `authoritativeLoopFinished = true`,即使 `phase` 仍显示 `running`,也不代表 loop 还活着。
    
    ## 互斥说明(重要)
    
    | 模式 | 启用插件 | 说明 |
    |------|-----------|------|
    | **生产推荐** | `autosure-resume` | 失败续跑 + `/autosure` 多轮 + 发动词轮换 + 熔断/去重 |
    | **极简** | `auto-resume-lite` | 仅失败一次续跑提示,无循环能力;兼容历史目录别名 `openclaw-auto-resume-lite`,但建议最终迁到 canonical 路径 |
    
    ---
    
    版本与变更记录见 `RELEASE_NOTES.md`;架构与需求见 `docs/`。
    
  • skill/autosure/docs/ARCHITECTURE.md4.3 KBb6738e1299b6upstream ↗
    # Autosure for OpenClaw — 架构说明(v2.1)
    
    ## 1. 总览
    
    v2.1 采用「核心能力在插件,体验增强在旁路 UI」的双层架构:
    
    1. **核心层(必需)**:`autosure-resume` / `auto-resume-lite` 插件 + `发动词.txt`,保证自动续跑与自动继续。
    2. **增强层(可选)**:UI 胶囊 userscript(A1),提供可视化状态与快捷操作。
    
    > 关键原则:增强层失效时,核心层必须不受影响。
    
    ## 2. 分层图
    
    ```text
    ┌─────────────────────────────────────────────────────────────┐
    │ OpenClaw Runtime                                            │
    │  ├─ skill/autosure (文档、安装、发动词、修复包入口)         │
    │  ├─ plugin/autosure-resume (主状态机)                       │
    │  └─ plugin/auto-resume-lite (极简模式,互斥)                │
    └─────────────────────────────────────────────────────────────┘
                ▲
                │ 命令桥接(/autosure, /autosure stop, /autosure status)
                ▼
    ┌─────────────────────────────────────────────────────────────┐
    │ Browser userscript capsule(可选,A1)                     │
    │  ├─ 胶囊 UI(状态+快捷 3/6/9)                              │
    │  ├─ 命令发送器(写入输入框并触发发送)                      │
    │  └─ 修复包(选择器升级、启停脚本)                          │
    └─────────────────────────────────────────────────────────────┘
    ```
    
    ## 3. 核心层逻辑(不依赖胶囊)
    
    ### 3.1 成功连轮
    
    - `agent_end(success)` -> `scheduleLoopIdleContinuation()`
    - 等待 `loopIdleGraceMs`
    - 窗口内若有用户进线 -> 取消本次定时器
    - 窗口超时 -> 注入一条发动词并开始下一轮
    
    ### 3.2 失败续跑
    
    - `agent_end(failed)` -> `maybeScheduleResume()`
    - 执行去重、冷却、熔断检查
    - 调度系统事件 + heartbeat
    
    ### 3.3 暂停语义(B1)
    
    - **暂停 = `/autosure stop`**
    - 非“软暂停剩余轮次”,而是明确终止当前循环控制。
    
    ## 4. 取消双保险(v2.1)
    
    为降低单钩子依赖,取消路径采用双通道:
    
    1. `before_dispatch`(已有):可直接拿到 `sessionKey`,即时取消 pending timer。
    2. `message_received`(新增):通过 `channel/account/conversation` 映射到最近活跃 `sessionKey`,再取消。
    
    说明:第二路径是稳健性兜底,避免某些通道/版本在 `before_dispatch` 前后行为差异导致漏取消。
    
    ## 5. UI 胶囊设计边界(A1)
    
    ### 5.1 为什么选 userscript
    
    - 不改 OpenClaw 主仓,避免升级 merge 成本。
    - 可独立发版与修复(修复包)。
    - 可完全关闭,不影响核心。
    
    ### 5.2 状态来源
    
    第一版采用“命令驱动 + 本地状态”:
    
    - 快捷按钮触发命令;
    - 胶囊显示本地最近动作状态(运行/停止/未知);
    - 通过 `/autosure status` 手动刷新。
    
    后续可演进为订阅日志或稳定 API(若平台提供)。
    
    ### 5.3 挂载策略
    
    1. 首选挂载:chat 页刷新按钮左侧。
    2. 找不到锚点:降级为右上固定浮层(仍可用)。
    
    ## 6. 互斥与兼容
    
    - `autosure-resume` 与 `auto-resume-lite` 互斥。
    - 胶囊与插件非互斥:胶囊只是“遥控器”。
    - OpenClaw 升级后,若胶囊失效:禁用胶囊即可回到纯命令模式。
    
    ## 7. 可观测性
    
    建议最小事件集合:
    
    - `loop_idle_wait_scheduled`
    - `loop_idle_inject_committed`
    - `loop_idle_cancelled_by_user`
    - `resume_scheduled_from_failure`
    - `capsule_command_sent`
    - `capsule_mount_fallback`
    
    ## 8. 回退机制
    
    1. **禁用胶囊**:用户脚本停用/卸载。
    2. **禁用增强包**:不加载 `ui-capsule` 文件。
    3. **保底能力**:用户手工输入 `/autosure...` 继续可用。
    
    ---
    
    相关产品口径见 `docs/PRD.md`;胶囊专项见 `docs/UI_CAPSULE_SPEC.md`。
    
    
  • skill/autosure/docs/PRD.md3.4 KBe1f691b17386upstream ↗
    # Autosure for OpenClaw — PRD(v2.1)
    
    ## 1. 北极星体验
    
    用户离开几分钟后回来,看到任务在自动推进、没有风暴、没有跑偏、自己随时插话即可接管。
    
    一句话:**像一个靠谱副手在替你继续,但永远听你的。**
    
    ## 2. 版本定位
    
    - **v2.0**:可分发 skill + vendored 插件 + 一键安装。
    - **v2.1(本轮)**:在 v2.0 基础上加入「可视化胶囊(A1 userscript)」与「取消双保险」等体验升级;且保证胶囊失效时核心能力不受影响。
    
    > 与旧版不冲突原则:旧命令与旧配置继续可用;新增能力默认可选、可关闭。
    
    ## 3. 产品目标
    
    1. **更直观**:用户不用猜系统状态(运行/等待/停止)。
    2. **更可控**:用户可通过胶囊快捷启动/停止与 3/6/9 轮。
    3. **更稳健**:升级 OpenClaw 后,即使胶囊失效,autosure 核心继续工作。
    4. **更可修复**:提供「胶囊修复包」与开关脚本。
    
    ## 4. 用户故事
    
    1. 作为用户,我要在 chat 页看到胶囊状态(空闲/运行中/暂停)。
    2. 作为用户,我要一键触发 `/autosure 3|6|9`,不想每次打命令。
    3. 作为用户,我点「暂停」时,语义必须明确等价于 **`/autosure stop`**(B1)。
    4. 作为运维,我升级 OpenClaw 后即使胶囊挂了,也不影响插件核心行为。
    5. 作为运维,我可以用修复包更新胶囊注入逻辑并一键启停。
    
    ## 5. 功能范围(MoSCoW)
    
    ### Must
    
    - 胶囊实现方式:**A1 userscript**(旁路注入,不改 OpenClaw 本体)。
    - 胶囊位置策略:优先挂载在 chat 区「刷新」附近;找不到则降级为安全位置(右上浮层)。
    - 胶囊动作:
      - 启动快捷:`/autosure 3`、`/autosure 6`、`/autosure 9`
      - 启动不限轮:`/autosure`
      - 暂停:**`/autosure stop`**
      - 状态刷新:`/autosure status`
    - 修复包:
      - 更新注入脚本
      - 启用/禁用胶囊
      - 提供回滚入口
    - 核心插件增强:取消双保险(除 `before_dispatch` 外,再补 inbound 路径,降低漏取消概率)。
    
    ### Should
    
    - 胶囊本地状态持久化(最后选择轮次、上次状态)。
    - 关键事件日志(胶囊注入成功/失败、命令下发结果)。
    
    ### Could
    
    - 胶囊主题跟随(暗黑/亮色)。
    - 胶囊微动效与折叠展开动画。
    
    ### Won’t(本轮不做)
    
    - 不改 OpenClaw 主仓 UI 代码。
    - 不承诺通过胶囊直接读取所有内部私有状态 API。
    
    ## 6. 非功能要求
    
    | 维度 | 要求 |
    |------|------|
    | 稳定性 | 胶囊不可用不影响 `autosure-resume` 主流程 |
    | 兼容性 | OpenClaw 2026.4.x;DOM 变化时可通过修复包适配 |
    | 可回退 | 一键禁用胶囊后,命令行与手工输入完全可用 |
    | 可维护 | 修复包独立版本号;与 skill 主版本并行追踪 |
    
    ## 7. 验收标准
    
    1. 胶囊可在 chat 页面显示并执行 3/6/9 快捷命令。
    2. 点击暂停,实际发送并生效 ` /autosure stop`。
    3. 升级 OpenClaw 后(模拟 DOM 改动),禁用胶囊时 autosure 核心能力不受影响。
    4. 修复包可恢复胶囊可见与可操作。
    5. `verify_health.py` 与 `plugins inspect autosure-resume` 仍通过。
    
    ## 8. 风险与缓解
    
    - DOM 选择器失效:通过多级 selector + 浮层降级 + 修复包更新。
    - 通道差异导致取消漏判:引入 inbound 路径映射,保留日志可追。
    - 用户误解暂停语义:UI 文案固定为“暂停(发送 /autosure stop)”。
    
    
  • skill/autosure/docs/UI_CAPSULE_SPEC.md6.5 KBe642d872575cupstream ↗
    # Autosure UI 胶囊专项设计(A1 / B1)
    
    ## 1. 决策冻结
    
    - **A1(默认路线)**:胶囊实现使用 userscript(Tampermonkey 兼容),不改 OpenClaw 本体。
    - **A1-Fallback(运维修复路线)**:当 Tampermonkey 已安装脚本但本机 `127.0.0.1:18789/chat*` 不执行时,可使用 native fallback,把同一套胶囊注入本机 OpenClaw Control UI。
    - **B1**:暂停按钮语义固定为 `/autosure stop`。
    - **UI vNext 冻结方向**:
      - 默认 **收起态**
      - 锚定 **OpenClaw 顶部刷新图标左边**
      - 收起态为 **图标 + 状态点**
      - 展开方向为 **向下**
      - 按钮布局为 **两排**
      - 视觉气质 **跟随 OpenClaw 原生图标与工具栏风格**
    
    ## 2. 胶囊目标
    
    1. 默认几乎不打扰聊天正文,不遮挡核心阅读区域。
    2. 让 autosure 在视觉上像 OpenClaw 的**原生控制工具**,而不是外挂浮层。
    3. 一键执行常见轮次(3/6/9/不限)、停止与状态查询。
    4. 升级后可通过修复包快速恢复挂载。
    
    ## 3. 交互设计
    
    ### 3.1 总体形态
    
    胶囊采用 **两态设计**:
    
    - **收起态**:只显示一个小触点(图标 + 状态点)
    - **展开态**:显示完整 autosure 控制面板
    
    默认进入页面时为 **收起态**。
    
    ### 3.2 收起态(Closed State)
    
    #### 位置
    
    - 首选:**刷新图标左边**
    - 必须位于 OpenClaw 顶部工具区内,与现有 toolbar 保持同层级
    
    #### 组成
    
    - Autosure 图标
    - 状态点(无文字)
    
    #### 状态点语义
    
    - **灰**:idle / 已停止
    - **绿**:running / 自动轮跑中
    - **黄**:pending / 状态同步中、待确认
    - **红**:error / 熔断、发送器异常、显式故障
    
    #### 原则
    
    - 不显示长文字
    - 不占正文区域
    - 不采用右下角大浮层作为默认展示
    
    ### 3.3 展开态(Expanded State)
    
    #### 展开方向
    
    - **向下展开**
    
    #### 面板结构
    
    1. **头部**
       - Autosure 标题
       - 当前状态文案
       - 收起/关闭操作
    
    2. **按钮区(两排)**
       - 第一排:`3` `6` `9` `∞`
       - 第二排:`Stop` `Status`
    
    3. **底部状态区**
       - 一行轻量状态反馈
       - 示例:
         - 运行中
         - 已停止
         - 状态同步中
         - 等待注入
         - 剩余 N 轮
    
    ### 3.4 打开 / 关闭逻辑
    
    #### 打开
    
    - 点击收起态图标 → 展开
    
    #### 关闭
    
    - 再点一次图标 → 收起
    - 点击胶囊外部区域 → 收起
    - 页面切换/重进后默认回到收起态
    
    #### 明确不做
    
    - hover 展开
    - 默认常驻展开
    - 自动大面积占位
    
    ## 4. 视觉设计
    
    ### 4.1 风格原则
    
    胶囊必须**跟随 OpenClaw 工具栏的系统风格**:
    
    - 图标语言一致
    - 圆角体系一致
    - 阴影与层级一致
    - hover / active / focus 节奏一致
    - 看起来像 OpenClaw 内建功能,而不是第三方外挂
    
    ### 4.2 不推荐样式
    
    - 右下角常驻大黑块
    - 明显“浏览器插件感”的悬浮窗
    - 过重、过亮、过科幻的独立视觉体系
    - 长标签、小作文式说明文字
    
    ### 4.3 推荐样式
    
    - 收起态:小而克制,靠图标与状态点表达存在感
    - 展开态:精致胶囊 / 下拉工具舱
    - `Stop` 按钮可比普通按钮更醒目,但不做惊悚红色大按钮
    - `Status` 弱于 `Stop`,体现“查询”而非“控制”
    
    ## 5. 技术设计
    
    ### 5.1 组件与注入分层
    
    胶囊实现应拆为两层:
    
    1. **注入层(Mount Strategy)**
       - 负责寻找顶部锚点
       - 负责把胶囊插到刷新图标左边
       - 找不到锚点时负责降级挂载
    
    2. **组件层(Capsule Component)**
       - 负责收起态 / 展开态 UI
       - 状态点
       - 两排按钮
       - 点击外部关闭
       - 状态反馈与微动画
    
    > userscript 与 native fallback 必须复用同一套组件结构与交互规格,区别只在“注入路径”,不能演化成两套产品。
    
    ### 5.2 注入入口
    
    - `@match` 规则覆盖 OpenClaw control-ui 地址
    - `MutationObserver` 监听页面结构变化,实现热挂载
    - native fallback 注入本机 Control UI `index.html` 时,也必须遵守同一规格
    
    ### 5.3 命令发送器
    
    - 查找 chat 输入框 `textarea`
    - 写入命令后触发 `input` 事件
    - 触发发送按钮 click(`aria-label=Send message / Queue message` 等多候选)
    - 首次挂载后自动发送一次 `/autosure status` 同步状态
    - 快捷动作后自动追加一次 `/autosure status` 进行状态校准
    
    ### 5.4 挂载选择器策略
    
    #### 正式优先级
    
    1. 刷新图标按钮(语义或文案命中 Refresh / 刷新)
    2. 顶部 chat 工具栏中刷新按钮邻近容器
    3. 顶部工具区备用锚点
    4. 右上角**收起态小图标**降级
    
    #### 明确废弃为默认方案
    
    - 右下角常驻大浮层
    
    右下角大浮层只允许作为最后兜底的应急形态,且即便兜底,也应优先保持**收起态**而不是直接大面板常驻。
    
    ## 6. 修复包设计
    
    建议目录:`ui-capsule/repair-pack/`
    
    - `autosure-capsule.user.js`:主 userscript(版本号)
    - `native-control-ui-capsule.js`:native fallback 组件源码
    - `selectors.json`:选择器与挂载策略
    - `enable.sh` / `disable.sh`:userscript 启停入口
    - `scripts/patch_control_ui.py`:本机 OpenClaw Control UI patch 入口
    - `CHANGELOG.md`:每次修复记录
    
    ## 7. 失败模式与回退
    
    | 失败模式 | 行为 |
    |----------|------|
    | 找不到顶部刷新锚点 | 降级为右上角收起态图标,不阻塞聊天 |
    | 发送按钮定位失败 | 显示本地错误状态;不影响核心插件 |
    | 升级导致 userscript 失效 | 执行修复包更新 |
    | Tampermonkey 已安装但不执行 | 切换 native fallback |
    | 用户禁用脚本 | 回到手工命令模式 |
    
    ## 8. 安全与边界
    
    - 胶囊不读取密钥,不写 `openclaw.json`
    - 胶囊不拦截 OpenClaw 原生按钮行为
    - 胶囊仅“发命令”,核心执行权仍在插件
    - native fallback 只修补本机 Control UI 展示层,不改变 autosure 核心逻辑
    
    ## 9. 验收用例
    
    1. 打开 chat 页,默认看到**顶部收起态图标 + 状态点**。
    2. 收起态位于**刷新图标左边**。
    3. 点击图标后,胶囊**向下展开**。
    4. 第一排出现:`3` `6` `9` `∞`。
    5. 第二排出现:`Stop` `Status`。
    6. 点击 `3`,输入框自动发送 `/autosure 3`。
    7. 点击 `Stop`,发送 `/autosure stop`。
    8. 点击 `Status`,发送 `/autosure status`。
    9. 点击外部区域,胶囊收起。
    10. 若顶部锚点失效,胶囊降级为**右上角收起态图标**,而非右下角大浮层。
    11. userscript 与 native fallback 在视觉结构与交互上保持一致。
    12. 人工禁用胶囊后,手工 `/autosure` 仍完全可用。
    
    
  • skill/autosure/HANDOFF_FOR_AGENT.md8.6 KB57ad791dc03eupstream ↗
    # 给部署 Agent 的一页纸(原样转发即可)
    
    > **当前交付口径(2026-04-19 closeout)**
    >
    > - 产品默认路线仍是 **userscript**。
    > - mini49 当前机器的本地优先可用路径仍是 **native fallback**。
    > - `/autosure N` 的当前产品语义是:**首轮立即前台续跑,剩余轮次按每轮完成后继续**。
    > - 本文件是部署执行入口,不负责替代 `PRD / ARCHITECTURE / UI_CAPSULE_SPEC` 成为产品权威文档。
    
    你是部署 Agent。请在目标机完成 **Autosure for OpenClaw** 落地:
    
    1. **放置 skill**
       将本仓库/压缩包中的 `skills/autosure` 目录,完整复制到
       `$OPENCLAW_WORKSPACE/skills/autosure`(未设置环境变量则用 `~/.openclaw/workspace/skills/autosure`)。
    
    2. **安装 vendored 插件**
       ```bash
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/install_bundle.py" --mode full
       ```
       若需 dry-run:加 `--dry-run`。若目标机在 lite 模式下沿用了历史目录 `plugins/openclaw-auto-resume-lite`,新版安装器会在 `--mode lite` 时同步刷新该 legacy 目录;长期仍建议迁到 `plugins/auto-resume-lite`。
    
    3. **合并配置**
       将脚本输出的 JSON 片段**手工合并**进 `~/.openclaw/openclaw.json` 的 `plugins` 段:`allow` / `load.paths` **追加**而非整段覆盖;**勿**同时启用 `autosure-resume` 与 `auto-resume-lite`。
    
    4. **校验与重启**
       ```bash
       openclaw config validate
       openclaw plugins inspect autosure-resume
       openclaw daemon restart
       ```
    
    5. **自检**
       ```bash
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/verify_health.py" --mode full
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/verify_health.py" --mode lite
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/repair_center.py" verify
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/autosure_doctor.py" --pretty
       ```
    
       **状态解释警告:** 不要把 `phase` 单独当成 autosure loop 真相。对 bounded loop 请优先读取 `~/.openclaw/plugins/autosure-resume/state.json` 中的 `loopControl.active / remainingRounds / completedRounds / lastCommandRaw / inflightResume`,或直接使用 validator 输出的 `effectiveLoopState / phaseAuthoritativeForLoop / terminalTailObserved / authoritativeLoopFinished`。
    
    人类操作入口:`小白使用说明.md`。架构/需求/发版:`docs/` 与 `RELEASE_NOTES.md`。
    
    6. **可选 UI 胶囊(A1)**  
       将 `ui-capsule/repair-pack/autosure-capsule.user.js` 提供给浏览器 Tampermonkey 启用。  
       语义约束:胶囊“暂停”必须发送 `/autosure stop`(B1)。
    
    7. **若 Tampermonkey 已安装但本机不执行 userscript**  
       不要继续反复手工排查浏览器注入层,先跑:
    
       ```bash
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/repair_center.py" verify
       ```
    
       先看:
       - `statusSummary`
       - `recommendedAction`
       - `recommendedCarrier`
    
       若 `recommendedAction` 返回 `restore-native-patch` 或 `recommendedCarrier` 返回 `native-fallback`,再直接启用 native fallback:
    
       ```bash
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/repair_center.py" native-install
       # 或
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/patch_control_ui.py" reinstall
       ```
    
       默认修补本机 OpenClaw Control UI:
    
       - `~/.volta/tools/image/packages/openclaw/lib/node_modules/openclaw/dist/control-ui/index.html`
    
       脚本会先备份原文件,再注入 autosure 原生控件。卸载:
    
       ```bash
       python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/patch_control_ui.py" uninstall
       ```
    
    8. **当前机器(mini49)补充**  
       在这台机器上,Tampermonkey 对 `http://127.0.0.1:18789/chat*` 的执行已验证不可靠,因此 **native fallback 是本机优先可用路径**。  
       现场验收页:
    
       ```text
       http://127.0.0.1:18789/chat?session=agent%3Amain%3Amain&autosureDebug=1
       ```
    
       该参数仅用于验收:页面会显示 `AUTOSURE DEBUG` 并强制展开胶囊,便于截图 / OCR / 肉眼确认;正常交付页不带该参数。
    
    10. **桌面点击反馈补丁(2026-04-18 晚间)**
       - 若用户反馈“桌面 UI 点了像没反应”,先不要马上怀疑 autosure 内核。先区分两层:
         1. loop 是否真的在推进(看 `state.json` / validator / 当前会话是否出现真实发动词)
         2. 当前页面是否吃到了**即时反馈补丁**。
       - 这轮已把 native/userscript 胶囊统一改成:
         - `/autosure N` 点击后立即显示 `等待首轮注入...`
         - 暂时保持展开态,而不是立刻收菜单
         - 700ms 提前做一次页面状态回读
         - 非 debug 模式下再延后自动收起(start 约 2400ms)
       - 后续又补了四条更阴的现场问题:
         1. 若页面发生 `syncMount()` / toolbar remount,胶囊以前会把刚写出的即时状态重新刷回 `待确认`
         2. 若页面历史消息区里还挂着旧的 `Autosure 状态` 文本,`tryParseStatusFromPage()` 也可能把本地刚写出的新状态反向覆盖掉
         3. 更底层地说,旧实现把 `document.body.innerText` 当主状态源,本身就会把整页历史文本误当当前状态
         4. 更产品层地说,旧 `/autosure N` 语义只是“启动后续轮次调度”,并不会在点击后立即发起首轮前台续跑,所以用户会感觉像点了个排队命令
       - 现在口径已经进一步改到:
         - `/autosure N` 启动时即 arm 首轮前台续跑
         - 剩余轮次再按每轮完成后继续
       - 现在两份胶囊都已加入:
         - 短时状态持久化:
           - `getStoredStatus()`
           - `setStoredStatus()`
           - `applyStoredStatusIfFresh()`
         - 页面状态回读避让:
           - `LOCAL_STATUS_PARSE_GRACE_MS`
           - `shouldDelayPageStatusParsing()`
         - 当前会话消息优先解析:
           - `CHAT_STATUS_MESSAGE_SCAN_LIMIT`
           - `CHAT_STATUS_MAX_AGE_MS`
           - `extractTextFromChatMessage()`
           - `getLatestAutosureStatusFromChatMessages()`
           - `getChatMessageRole()`
           - `isTrustedAutosureStatusMessage()`
           - 宿主消息数组可用时,**不再回退整页 `body.innerText`**
         - 本地命令时间门:
           - `COMMAND_STATUS_GUARD_MS`
           - `getLastCommandInfo()`
           - `setLastCommandInfo()`
           - `getRecentAutosureCommandCutoff()`
       - 新口径:
         - 最近 15 秒内的有效状态(如 `等待首轮注入...` / `状态查询中...` / `已前台续跑`)在重挂载后应优先恢复,而不是被默认值覆盖
         - 本地新状态写出后的约 2200ms 内,应暂缓页面历史状态解析,避免旧 `Autosure 状态` 文本反向覆盖当前反馈
         - 页面状态主判据现已切到当前会话 `chatMessages` 最近消息,并进一步收紧为 **assistant 非工具噪音消息优先**
         - 只有在宿主消息数组根本不可用时,才允许退回整页 `body.innerText` 兜底
         - 即便 assistant 消息看起来可信,也必须晚于最近一次本地 `/autosure*` 指令,旧 assistant 状态不能跨轮回写当前胶囊
         - `/autosure N` 的产品语义已改为:**首轮立即前台续跑,剩余轮次按每轮完成后继续**
       - 部署/修复时请直接验证 installed dist 是否含以下信号,而不要只看 workspace 源码:
         - `等待首轮注入...`
         - `setExpanded(true)`
         - `2400`
         - `getStoredStatus`
         - `applyStoredStatusIfFresh`
         - `LOCAL_STATUS_PARSE_GRACE_MS`
         - `shouldDelayPageStatusParsing`
         - `CHAT_STATUS_MESSAGE_SCAN_LIMIT`
         - `CHAT_STATUS_MAX_AGE_MS`
         - `getLatestAutosureStatusFromChatMessages`
         - `getChatMessageRole`
         - `isTrustedAutosureStatusMessage`
         - `if (latestChatStatus.available)`
         - `COMMAND_STATUS_GUARD_MS`
         - `getRecentAutosureCommandCutoff`
       - 插件侧再额外验证:
         - `armLoopVisibleInject`
         - `loop_start_immediate`
         - `loop-start-immediate-inject`
         - `首轮前台注入已启动`
       - 若 installed dist 没吃到这些字符串,优先执行:
         ```bash
         python3 "$OPENCLAW_WORKSPACE/skills/autosure/scripts/patch_control_ui.py" reinstall
         ```
       - 若插件 vendor 副本没吃到启动语义修正,需同步:
         ```bash
         cp "$OPENCLAW_WORKSPACE/plugins/autosure-resume/index.js" "$OPENCLAW_WORKSPACE/skills/autosure/vendor/autosure-resume/index.js"
         ```
       - 诚实口径:这补的是**桌面即时反馈 / 状态判据层 + `/autosure N` 首轮启动语义**,不是 autosure loop 失败恢复内核;若 loop phrase 已实际进入当前会话,则“没反应”更可能是页面反馈落后、重挂载抹状态、旧状态回读反向覆盖、整页文本误判、非 assistant/tool 噪音消息被误读,或首轮前台 arm 已成立但页面仍未及时呈现,而不是命令未生效。
    
  • skill/autosure/MANIFEST.json2.0 KB4f5e3e7f4c4dupstream ↗
    {
      "id": "autosure-openclaw-pack",
      "version": "2.1.0-beta.2",
      "displayName": "Autosure for OpenClaw",
      "summary": "Skill + vendored plugins + optional userscript capsule + native control-ui fallback: bounded auto-resume, circuit governance, dialable success-loop with idle grace, 30-line phrase pool, one-command install.",
      "components": {
        "skill": {
          "path": ".",
          "entry": "SKILL.md"
        },
        "plugins": {
          "autosure-resume": {
            "source": "vendor/autosure-resume",
            "installTarget": "workspace/plugins/autosure-resume",
            "role": "primary",
            "capabilities": [
              "failure_resume",
              "loop_idle_inject",
              "dedupe",
              "circuit_breaker",
              "autosure_demo"
            ]
          },
          "auto-resume-lite": {
            "source": "vendor/auto-resume-lite",
            "installTarget": "workspace/plugins/auto-resume-lite",
            "legacyInstallTargets": ["workspace/plugins/openclaw-auto-resume-lite"],
            "role": "optional_minimal",
            "mutuallyExclusiveWith": ["autosure-resume"]
          }
        },
        "uiCapsule": {
          "kind": "userscript",
          "source": "ui-capsule/repair-pack/autosure-capsule.user.js",
          "selectors": "ui-capsule/repair-pack/selectors.json",
          "optional": true,
          "semantics": {
            "pause": "/autosure stop"
          }
        },
        "nativeFallback": {
          "kind": "control-ui-patch",
          "source": "ui-capsule/repair-pack/native-control-ui-capsule.js",
          "installer": "scripts/patch_control_ui.py",
          "optional": true,
          "purpose": "Fallback when Tampermonkey installs the userscript but does not execute it on local OpenClaw /chat pages."
        },
        "operatorDocs": [
          "小白使用说明.md",
          "DEPLOY.md",
          "docs/ARCHITECTURE.md",
          "docs/PRD.md",
          "docs/UI_CAPSULE_SPEC.md",
          "RELEASE_NOTES.md"
        ]
      },
      "openclaw": {
        "minAppVersionHint": "2026.4.x",
        "notes": "Hooks: agent_end, before_dispatch, llm_output, after_tool_call, before_reset. Requires subagent.run for best loop UX."
      }
    }
    
  • skill/autosure/PACKAGE.md1.2 KBe67cc42c0777upstream ↗
    # 如何打成可交付压缩包
    
    本文件只负责**打包动作**。安装与迁移规则看 `DEPLOY.md`,产品/运行真相看 `SKILL.md`、`docs/ARCHITECTURE.md`、`docs/PRD.md`。
    
    在 **skill 根目录**(含 `SKILL.md`、`vendor/`、`scripts/` 的 `autosure` 文件夹)上级执行:
    
    ```bash
    cd ~/.openclaw/workspace/skills
    zip -r autosure-openclaw-pack-v2.zip autosure \
      -x "autosure/**/__pycache__/*" -x "autosure/**/*.pyc"
    ```
    
    将 `autosure-openclaw-pack-v2.zip` 或整个 `autosure` 目录链接发给客户 / 部署 Agent 即可;落地步骤见 **`DEPLOY.md`** 与 **`HANDOFF_FOR_AGENT.md`**。
    
    若需 UI 胶囊,请同时分发 `ui-capsule/repair-pack/`(已包含在 zip 内)。
    
    **发版前建议**:
    
    1. 若你本地主插件在 `workspace/plugins/autosure-resume` 有改动,先运行  
       `bash skills/autosure/scripts/sync_vendor_from_workspace.sh`  
       再打包,保证 **vendor 与线上一致**。  
    2. 若目标机存在历史 lite 目录 `workspace/plugins/openclaw-auto-resume-lite`,在交付说明里明确:它只是 legacy 别名,不是第二套插件;优先建议对方后续迁回 canonical 目录 `workspace/plugins/auto-resume-lite`。
    
  • skill/autosure/RELEASE_NOTES.md4.9 KBbbdc15cb0e57upstream ↗
    # Autosure for OpenClaw — Release Notes
    
    ## v2.1.0-beta.2 · 「可迁移修复包 + Native Fallback」预发布(2026-04-18)
    
    ### 本版重点
    
    - 收编本轮真实排障结论:
      - Tampermonkey 路线并非总是可靠;在当前机器上,脚本可写入本地库,但对 `127.0.0.1:18789/chat*` **未实际执行**。
    - userscript 正式清理:
      - 去掉调试期 `alert(...)` 脏探针
      - `Autosure Capsule` 升到 `1.0.2`
    - 新增 **native fallback**:
      - `ui-capsule/repair-pack/native-control-ui-capsule.js`
      - `scripts/patch_control_ui.py`
      - 在 userscript 注入层失效时,可直接给本机 OpenClaw Control UI 打补丁,生成原生 autosure 控件
    - 部署口径升级:
      - `DEPLOY.md`
      - `HANDOFF_FOR_AGENT.md`
      - `ENABLE_DISABLE.md`
      - `MANIFEST.json`
      全部补齐 fallback 路线说明
    
    ### 这一版的真正意义
    
    不是再多一个“临时 workaround”,而是把这次排障结果变成**可复用、可交接、可迁移**的 skill 能力。  
    换电脑时先走 userscript;若浏览器层继续发癫,直接跑 native fallback,不必重演一轮人工排障。
    
    ---
    
    ## v2.1.0-beta.1 · 「可视化胶囊 + 稳定性加固」预发布(2026-04-16)
    
    ### 本版重点
    
    - 新增 UI 胶囊路线定稿:**A1 userscript**(不改 OpenClaw 本体)。
    - 暂停语义冻结:**B1 = `/autosure stop`**。
    - 文档体系升级:`PRD`、`ARCHITECTURE` 重写为 v2.1,并新增 `UI_CAPSULE_SPEC`。
    - 强化“非必要增强”原则:胶囊失效不影响核心 autosure 能力。
    
    ### 兼容口径
    
    - v2.0 的命令、插件、安装方式继续有效。
    - v2.1 是增量能力,不要求立即启用胶囊。
    - 升级 OpenClaw 后若胶囊失效,可先禁用胶囊继续使用核心功能,再应用修复包。
    
    ---
    
    ## v2.0.0 · 「可装、可审、可传」系统级发行(2026-04-16)
    
    ### 这一版为什么值得你看完
    
    Autosure 不再只是「某台机器上的私货脚本集合」,而是一套**可随 OpenClaw workspace 分发**的**完整能力包**:  
    
    - **Skill** 承载策略、发动词池、收口模板与运维文档;  
    - **Vendor 插件**随包携带,**安装脚本**把 `autosure-resume` / `auto-resume-lite` 落到标准 `plugins/` 路径;  
    - **互斥与降级**写进架构与安装输出,避免「双续跑」这种 silent disaster;  
    - **PRD / 架构 / 发版说明**齐备,方便你丢给另一个 Agent 或客户侧技术做审计。
    
    一句话:**从「我能用」升级到「任何人都能在同一标准上用起来」。**
    
    ---
    
    ### Highlights
    
    | 能力 | 说明 |
    |------|------|
    | **Vendored `autosure-resume`** | 与 skill **同源锁定**发布;`install_bundle.py` 一键同步到 `workspace/plugins`。 |
    | **内置 `auto-resume-lite`** | 全新极简失败续跑插件,**与主插件二选一**;适合「只想顶一下」的环境。 |
    | **发动词 2.0** | 约 **30 条**万用推进句,短长混搭,偏精神督促与高标准,弱化「工种剧本」带偏风险。 |
    | **MANIFEST.json** | 机器可读组件清单 + 角色标注(primary / optional_minimal)。 |
    | **HANDOFF_FOR_AGENT.md** | 给部署 Agent 的**一页纸**,支持「把链接/压缩包扔过去」的协作模式。 |
    | **文档三件套** | `docs/ARCHITECTURE.md`、`docs/PRD.md`、本 `RELEASE_NOTES.md`。 |
    
    ---
    
    ### 迁移与兼容
    
    - 若你曾使用 **其他路径** 的 `openclaw-auto-resume-lite`,不要再把它当成另一套产品;它现在应被视为 **`auto-resume-lite` 的历史目录别名**。新版 `install_bundle.py --mode lite` 会同步刷新这个 legacy 目录,帮助老机器平滑过渡。  
    - 若 `verify_health.py --mode lite` 提示 `installed plugin differs from vendored copy`,这不是误报,说明现场 legacy lite 确实已经漂了;最稳的修法就是重跑安装器,并尽快把 `plugins.load.paths` 迁回 canonical 路径 `workspace/plugins/auto-resume-lite`。  
    - `openclaw.json` 的 `plugins` 结构在不同版本可能存在 `entries` / `load.paths` / `installs` 差异:**以 `install_bundle.py` 打印片段为起点,人工合并**。  
    - 升级 OpenClaw 小版本后建议重跑:`config validate` → `plugins inspect` → 文档中的烟测清单。
    
    ---
    
    ### 已知边界(诚实列出来,才叫专业)
    
    - 「打字取消空窗代发」强依赖 **`before_dispatch` + `sessionKey`**;若某通道行为有变,需回归。  
    - 发动词再强也是**软约束**;长答/短答仍受模型与 Agent 默认提示影响。  
    - `subagent.run` 不可用时走系统事件回退,**时间线表现**可能与主路径略有差异。
    
    ---
    
    ### 致谢与定位
    
    本包站在 **OpenClaw 插件模型 + 会话生命周期** 之上做了一层「运维可理解、Agent 可部署」的封装。  
    
    若本发版帮你省下了哪怕一小时的扯皮与排障,它存在的意义就达到了。
    
    ---
    
    **下一版(v2.x)可能方向**:文档进一步瘦身、`verify_health` 增强插件路径探测、可选静态观测页(非承诺项)。
    
  • skill/autosure/templates/CLOSURE.md636 B2c0be814dd1fupstream ↗
    ## Autosure Professional Closure (TIMESTAMP)
    
    - Scope: run_id `<RUN_ID>` project `<PROJECT>`.
    - Round result: `<success|partial|failed|halted>`.
    - Resume governance:
      - maxAutoResumes: `<N>`
      - cooldownMs: `<MS>`
      - circuit state: `<closed|open|half-open>`
    - Current risk register:
      - P1: `<critical blocker or none>`
      - P2: `<degradation risk or none>`
    - Evidence summary:
      - latest interruption reason: `<reason>`
      - dedupe/circuit decision: `<decision>`
      - latest resume action: `<action>`
    - Next action:
      - `<single most important next step>`
    - Recovery condition (if blocked):
      - `<what must be true to continue safely>`
    
  • skill/autosure/ui-capsule/repair-pack/autosure-capsule.user.js39 KB3153056890f8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/autosure/ui-capsule/repair-pack/autosure-probe-18789.user.js1.1 KBa6710a187376upstream ↗
    // ==UserScript==
    // @name         Autosure Probe 18789
    // @namespace    autosure.openclaw.probe
    // @version      1.0.2
    // @description  Hard probe for OpenClaw chat injection on 127.0.0.1:18789.
    // @match        http://127.0.0.1:18789/chat*
    // @grant        none
    // @run-at       document-end
    // ==/UserScript==
    
    (function () {
      'use strict';
    
      alert('Autosure probe injected: 1.0.2');
    
      const id = 'autosure-probe-fixed-18789';
      if (document.getElementById(id)) return;
    
      const root = document.createElement('div');
      root.id = id;
      root.textContent = 'AUTOSURE PROBE OK';
      root.style.position = 'fixed';
      root.style.top = '16px';
      root.style.right = '16px';
      root.style.zIndex = '2147483647';
      root.style.padding = '12px 14px';
      root.style.background = '#d11';
      root.style.color = '#fff';
      root.style.font = '700 14px/1.2 -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif';
      root.style.borderRadius = '12px';
      root.style.boxShadow = '0 10px 30px rgba(0,0,0,.28)';
      root.style.border = '2px solid rgba(255,255,255,.35)';
      document.body.appendChild(root);
    
      console.log('[autosure-probe] injected on', location.href);
    })();
    
  • skill/autosure/ui-capsule/repair-pack/CHANGELOG.md3.1 KB753fd98b5c27upstream ↗
    # UI Capsule Repair Pack Changelog
    
    ## 1.3.2 (2026-04-18)
    
    - 新增 native fallback 验收可视化模式:当 Control UI URL 带 `?autosureDebug=1` 时,胶囊会强制展开,并在 trigger 上显示 `Autosure` 与状态文字,方便 OCR / 截图验收。
    - 该模式仅用于本机现场验收,不改变默认交付行为;正常 `/chat` 仍保持收起态胶囊。
    
    ## 1.3.1 (2026-04-18)
    
    - 现场调试加固:为 native fallback 增加可控调试开关,用于隔离以下疑点:
      - `autosure.native.enableObserver=1`
      - `autosure.native.enableAutoStatus=1`
      - `autosure.native.disableSuppress=1`
      - `autosure.native.debug=1`
    - 将 native fallback 默认收缩为保守模式:不开启高频 `MutationObserver`,不自动追加 `/autosure status` 轮询;改为低频 boot 重试挂载 + 手动 `Status` 按钮查询,优先保障 OpenClaw chat 页面稳定性。
    - 新发现:当前机器的 OpenClaw chat 页面出现“页面无响应”,需先完成 native fallback 的根因排障,再宣称 UI 接管成功。
    
    ## 1.3.0 (2026-04-18)
    
    - UI vNext 首轮实现:
      - 收起态改为 **图标 + 状态点**
      - 展开方向改为 **向下**
      - 按钮布局改为 **两排**(`3/6/9/∞` + `Stop/Status`)
      - 优先挂载到 **刷新图标左边**
      - 锚点失败时降级为 **右上角收起态图标**,不再默认使用右下角大面板
    - 结构重构:
      - userscript 与 native fallback 对齐为同一产品形态
      - 将 mount strategy / capsule component / command bridge 收口到同一交互模型
    - 现场诊断补充:
      - 当前机器的 Tampermonkey 本地库仍残留 `Autosure Capsule 1.0.1`
      - 这会污染本机验证结果,使页面继续显示旧 UI
      - 结论:工程实现已切到 vNext,浏览器现场仍需单独清理旧 userscript 状态
    
    ## 1.2.0 (2026-04-18)
    
    - userscript 清理与升级:
      - 去除调试期 `alert(...)` 注入探针,恢复正式交付版本
      - 保留 `/chat*` 与 `/__openclaw__/*` 双 match,兼容旧新 Control UI 路径
    - 新增 **native fallback**:
      - 增加 `native-control-ui-capsule.js`
      - 增加 `scripts/patch_control_ui.py`
      - 当 Tampermonkey 在本机浏览器层不执行 userscript 时,可直接把 autosure 控件注入本机 OpenClaw Control UI 的 `index.html`
    - 定位结论固化:
      - 本次故障不是插件核心、不是 match 规则、不是 host permission
      - 关键故障层位于 **Tampermonkey 对本机 `127.0.0.1:18789/chat*` 页面未实际执行已安装脚本**
      - 因此将 native fallback 作为运维修复包的一部分保留
    
    ## 1.1.0 (2026-04-16)
    
    - 状态增强:
      - 页面加载后自动发送一次 `/autosure status` 做状态对齐
      - 每次快捷动作后自动追加状态同步
      - 监听页面文本,解析 `Autosure 状态` 结果并更新胶囊标签
    - 插件配套:
      - `autosure-resume` 支持在 `before_dispatch` 直接响应 `/autosure status`(无需等一轮结束)
    
    ## 1.0.0 (2026-04-16)
    
    - 首版 userscript 胶囊(A1):
      - 快捷 3/6/9/不限
      - 暂停 = `/autosure stop`(B1)
      - 状态按钮 `/autosure status`
      - 刷新左侧挂载 + 浮层降级
    
    
  • skill/autosure/ui-capsule/repair-pack/disable.sh477 B4fc9c980619eupstream ↗
    #!/usr/bin/env bash
    set -euo pipefail
    
    TARGET_DIR="${AUTOSURE_TAMPERMONKEY_DIR:-$HOME/Downloads}"
    TARGET="$TARGET_DIR/autosure-capsule.user.js"
    DISABLED="$TARGET_DIR/autosure-capsule.user.js.disabled"
    
    if [[ -f "$TARGET" ]]; then
      mv "$TARGET" "$DISABLED"
      echo "Autosure capsule file renamed for disable workflow: $DISABLED"
    else
      echo "No staged userscript file found at: $TARGET"
      echo "If the script is already installed in Tampermonkey, disable it there manually."
    fi
    
  • skill/autosure/ui-capsule/repair-pack/enable.sh442 Ba18dd66f194cupstream ↗
    #!/usr/bin/env bash
    set -euo pipefail
    
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    SRC="$SCRIPT_DIR/autosure-capsule.user.js"
    TARGET_DIR="${AUTOSURE_TAMPERMONKEY_DIR:-$HOME/Downloads}"
    TARGET="$TARGET_DIR/autosure-capsule.user.js"
    
    mkdir -p "$TARGET_DIR"
    cp "$SRC" "$TARGET"
    
    echo "Autosure capsule staged: $TARGET"
    echo "Next: import this file into Tampermonkey (or double-click it if your browser is configured to open userscripts there)."
    
  • skill/autosure/ui-capsule/repair-pack/ENABLE_DISABLE.md3.4 KB5a8d127925b5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/autosure/ui-capsule/repair-pack/native-control-ui-capsule.js43 KBa1cbb937594aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/autosure/ui-capsule/repair-pack/selectors.json479 B369505eaa14aupstream ↗
    {
      "version": "1.0.0",
      "anchorButtonCandidates": [
        "button[aria-label*='Refresh']",
        "button[aria-label*='刷新']",
        "button.btn"
      ],
      "sendButtonCandidates": [
        "button[aria-label='Send message']",
        "button[aria-label='Queue message']",
        "button[title='Send']",
        "button[title='Queue']"
      ],
      "textareaCandidates": [
        "textarea"
      ],
      "fallbackMount": {
        "position": "fixed",
        "top": "14px",
        "right": "16px",
        "zIndex": 9999
      }
    }
    
    
  • skill/autosure/发动词.txt1.5 KBe8b56903ff46upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/autosure/小白使用说明.md3.5 KB3bf1fb73261cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/293163-lgtm-openclaw-autosure-skill-autosure.md

// REPO STATS

0 stars
0 open issues
Last commit: 6mo ago