From 52743813060b07f279a3ef8d0226b0568b898699 Mon Sep 17 00:00:00 2001 From: rebel117 Date: Sat, 5 Dec 2026 17:42:39 +0800 Subject: [PATCH] feat(quota-auto-resume): add quota-aware tool guard with auto-resume --- .../.zcode-plugin/plugin.json | 27 ++ external_plugins/quota-auto-resume/LICENSE | 21 ++ external_plugins/quota-auto-resume/README.md | 66 ++++ .../quota-auto-resume/README_CN.md | 66 ++++ .../commands/quota-auto-resume.md | 20 ++ .../hooks/auto-resume-hook.cjs | 321 ++++++++++++++++++ .../quota-auto-resume/hooks/hooks.json | 42 +++ .../quota-auto-resume/test/run-tests.cjs | 143 ++++++++ marketplace.json | 21 ++ 9 files changed, 727 insertions(+) create mode 100644 external_plugins/quota-auto-resume/.zcode-plugin/plugin.json create mode 100644 external_plugins/quota-auto-resume/LICENSE create mode 100644 external_plugins/quota-auto-resume/README.md create mode 100644 external_plugins/quota-auto-resume/README_CN.md create mode 100644 external_plugins/quota-auto-resume/commands/quota-auto-resume.md create mode 100644 external_plugins/quota-auto-resume/hooks/auto-resume-hook.cjs create mode 100644 external_plugins/quota-auto-resume/hooks/hooks.json create mode 100644 external_plugins/quota-auto-resume/test/run-tests.cjs diff --git a/external_plugins/quota-auto-resume/.zcode-plugin/plugin.json b/external_plugins/quota-auto-resume/.zcode-plugin/plugin.json new file mode 100644 index 00000000..a041fb8d --- /dev/null +++ b/external_plugins/quota-auto-resume/.zcode-plugin/plugin.json @@ -0,0 +1,27 @@ +{ + "name": "quota-auto-resume", + "version": "0.1.0", + "description": "额度恢复后自动恢复任务:套餐额度用到阈值即停用高消耗工具让 Agent 收尾,额度恢复后由定时任务自动续跑。", + "author": { + "name": "tech.leshang" + }, + "hooks": "./hooks/hooks.json", + "commands": "./commands", + "license": "MIT", + "keywords": [ + "quota", + "usage", + "hooks", + "auto-resume", + "coding-plan" + ], + "description_i18n": { + "en": "Auto-resume tasks after quota recovery: stop high-cost tools when the plan quota reaches a threshold so the agent wraps up, then resume automatically through a scheduled task once quota recovers.", + "zh-CN": "额度恢复后自动恢复任务:套餐额度用到阈值即停用高消耗工具让 Agent 收尾,额度恢复后由定时任务自动续跑。" + }, + "displayName": "额度恢复后自动恢复任务", + "displayName_i18n": { + "en": "Auto Resume After Quota Recovery", + "zh-CN": "额度恢复后自动恢复任务" + } +} diff --git a/external_plugins/quota-auto-resume/LICENSE b/external_plugins/quota-auto-resume/LICENSE new file mode 100644 index 00000000..4bb972e2 --- /dev/null +++ b/external_plugins/quota-auto-resume/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 tech.leshang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/quota-auto-resume/README.md b/external_plugins/quota-auto-resume/README.md new file mode 100644 index 00000000..ac94dba2 --- /dev/null +++ b/external_plugins/quota-auto-resume/README.md @@ -0,0 +1,66 @@ +# quota-auto-resume + +Stops high-cost agent tools when your ZCode plan quota hits a threshold, lets the agent wrap up, and resumes the paused session automatically once quota recovers. + +## Why + +Long agent tasks can burn through a daily plan quota mid-task and die without a handoff. quota-auto-resume watches the quota, cuts off the expensive tools at a configurable line (default 80%), and tells the agent to write a handoff and stop. A scheduled probe then resumes the paused session when quota is back. + +## How it works + +The plugin registers three hooks and one command. It reads the quota snapshots that the ZCode desktop client already writes to its local log after each poll. It makes **no network requests** and reads **no credentials**. + +| Trigger | Behavior | +| --- | --- | +| `PreToolUse` | When model quota is at or above the threshold, denies high-cost tools (subagents, image and video generation, browser automation, etc.). When the official MCP call quota is at or above the threshold, denies `mcp__*` tools. Lightweight tools such as file reads, edits and ordinary shell commands stay available so the agent can wrap up. | +| `UserPromptSubmit` | From the warning line (default 60%) on, injects a one-line quota status into each turn. If this session was paused and quota has recovered, it tells the agent to continue from where it stopped. | +| `SessionStart` | Reports quota status on session start. On the first run only, asks the agent to create the 30-minute recovery probe with `CronCreate`. | +| `/quota-auto-resume` | Shows quota status, creates or rebuilds the probe, runs an interception dry run, or changes thresholds. | + +Each denial records a pending-resume marker under `~/.zcode/quota-auto-resume/pending/`. The recovery probe is a recurring automation whose prompt contains the marker text `quota-auto-resume 额度恢复探测`; on each run the `UserPromptSubmit` hook injects what to do: resume the pending sessions through `SendToSession` if quota has recovered, otherwise reply with one line and stop. + +## Configuration + +Optional file `~/.zcode/quota-auto-resume/config.json`. Defaults: + +```json +{ + "threshold": 80, + "warnAt": 60, + "maxAgeMin": 20, + "highCost": "^(Agent|Task)$|image|video|browser|playwright|firefox|devtools|computer|(^|[^a-z])cua([^a-z]|$)|websearch|web_search|webfetch|web_reader|3d|tripo|blender|designcraft|screencast|node_repl" +} +``` + +- `threshold`: usage percentage at which high-cost tools are denied. +- `warnAt`: usage percentage at which the per-turn reminder starts. +- `maxAgeMin`: a snapshot older than this many minutes is treated as unknown and nothing is blocked. +- `highCost`: case-insensitive regular expression matched against tool names. + +Set `threshold` to 100 to disable interception, or disable the plugin under Settings → Plugins. + +## Requirements + +- ZCode desktop client 4.x. The hook script runs on the Node runtime bundled with ZCode; no global Node or Python install is needed. +- The log directory is resolved from `ZCODE_DATA_BASE_DIR` (`.zcode/v2/logs` beneath it) and falls back to `~/.zcode/v2/logs`. Override with the `QUOTA_AUTO_RESUME_LOGS` environment variable. +- Quota snapshots are only written while the desktop client is running. If it has not polled within `maxAgeMin`, quota-auto-resume stays out of the way and blocks nothing. +- The log format is an internal detail of the desktop client and may change between versions. In that case the snapshot goes stale and the plugin fails open. + +## Side effects + +- Reads the tail (last 4 MB) of today's and yesterday's ZCode log files. Read-only. +- Writes `~/.zcode/quota-auto-resume/config.json` (only if you create it), `~/.zcode/quota-auto-resume/setup-notified`, and marker files under `~/.zcode/quota-auto-resume/pending/`. +- No network access, no credential access, no third-party code or services. + +## Testing + +```shell +node test/run-tests.cjs +node hooks/auto-resume-hook.cjs status +``` + +The test suite uses synthetic log fixtures and a temporary state directory; it does not touch your real quota state. + +## License + +MIT diff --git a/external_plugins/quota-auto-resume/README_CN.md b/external_plugins/quota-auto-resume/README_CN.md new file mode 100644 index 00000000..bb8ea66e --- /dev/null +++ b/external_plugins/quota-auto-resume/README_CN.md @@ -0,0 +1,66 @@ +# quota-auto-resume + +ZCode 套餐额度用到阈值时停用高消耗工具,让 Agent 收尾;额度恢复后自动续跑被中断的会话。 + +## 解决什么问题 + +长时间的 Agent 任务可能在半路把每日套餐额度用光,任务直接断掉,没有交接。quota-auto-resume 盯着额度,到设定的线(默认 80%)就停掉高消耗工具,并提示 Agent 写好交接说明后收尾;之后由定时探测在额度恢复时把中断的会话接着跑。 + +## 工作方式 + +插件注册三个 hook 和一个命令。额度数据取自 ZCode 桌面端每次轮询后写在本机日志里的快照,**不联网、不读凭据**。 + +| 触发点 | 行为 | +| --- | --- | +| `PreToolUse` | 模型额度达到阈值时,拒绝高消耗工具(子代理、生图生视频、浏览器自动化等);官方 MCP 调用额度达到阈值时,拒绝 `mcp__*` 工具。读写文件、编辑、普通命令等轻量工具照常可用,Agent 得以收尾。 | +| `UserPromptSubmit` | 从提醒线(默认 60%)起,每轮注入一行额度状态。本会话若曾被中断且额度已恢复,提示 Agent 从中断处继续。 | +| `SessionStart` | 会话开始时报告额度状态;仅首次运行时,请 Agent 用 `CronCreate` 建 30 分钟一次的恢复探测。 | +| `/quota-auto-resume` | 查看额度状态、建或重建探测任务、试跑拦截、修改阈值。 | + +每次拒绝都会在 `~/.zcode/quota-auto-resume/pending/` 记一个待续跑标记。恢复探测是一个循环定时任务,提示词里带有标记文字 `quota-auto-resume 额度恢复探测`;每次运行时由 `UserPromptSubmit` hook 注入该做什么:额度已恢复就用 `SendToSession` 续跑待续会话,否则只回一行并结束。 + +## 配置 + +可选文件 `~/.zcode/quota-auto-resume/config.json`,默认值: + +```json +{ + "threshold": 80, + "warnAt": 60, + "maxAgeMin": 20, + "highCost": "^(Agent|Task)$|image|video|browser|playwright|firefox|devtools|computer|(^|[^a-z])cua([^a-z]|$)|websearch|web_search|webfetch|web_reader|3d|tripo|blender|designcraft|screencast|node_repl" +} +``` + +- `threshold`:用到百分之几停用高消耗工具。 +- `warnAt`:用到百分之几开始每轮提醒。 +- `maxAgeMin`:快照超过多少分钟视为未知,此时不拦截任何工具。 +- `highCost`:匹配工具名的大小写不敏感正则。 + +把 `threshold` 改成 100 即停用拦截,也可在 设置 → 插件 里停用本插件。 + +## 使用条件 + +- ZCode 桌面端 4.x。hook 脚本运行在 ZCode 自带的 Node 上,不需要另装 Node 或 Python。 +- 日志目录取自 `ZCODE_DATA_BASE_DIR`(其下 `.zcode/v2/logs`),找不到时用 `~/.zcode/v2/logs`;可用环境变量 `QUOTA_AUTO_RESUME_LOGS` 指定。 +- 额度快照只在桌面端运行期间写入。若 `maxAgeMin` 分钟内没有新快照,quota-auto-resume 不拦截任何工具。 +- 日志格式属于桌面端内部细节,版本间可能变化;届时快照过期,插件自动放行。 + +## 副作用 + +- 读取今天和昨天 ZCode 日志文件的尾部(各最后 4 MB),只读。 +- 写入 `~/.zcode/quota-auto-resume/config.json`(仅当用户自己创建)、`~/.zcode/quota-auto-resume/setup-notified`,以及 `~/.zcode/quota-auto-resume/pending/` 下的标记文件。 +- 不联网、不读凭据、不包含第三方代码或服务。 + +## 测试 + +```shell +node test/run-tests.cjs +node hooks/auto-resume-hook.cjs status +``` + +测试使用构造的日志样本和临时状态目录,不触碰真实的额度状态。 + +## 许可证 + +MIT diff --git a/external_plugins/quota-auto-resume/commands/quota-auto-resume.md b/external_plugins/quota-auto-resume/commands/quota-auto-resume.md new file mode 100644 index 00000000..b102ea1a --- /dev/null +++ b/external_plugins/quota-auto-resume/commands/quota-auto-resume.md @@ -0,0 +1,20 @@ +--- +description: 查看 quota-auto-resume 额度状态、建或重建恢复探测定时任务、试跑拦截 +--- + +先运行 `node "${ZCODE_PLUGIN_ROOT}/hooks/auto-resume-hook.cjs" status`,把输出口头报告给用户(额度、是否拦截、待续跑会话数、阈值)。 + +再按用户的要求办事: + +- 用户要“建/重建定时任务”:用 CronCreate 建 recurring=true、cron=`*/30 * * * *` 的任务,标题「每30分钟 quota-auto-resume 额度恢复探测」,prompt 为单行:「quota-auto-resume 额度恢复探测。按系统注入的 quota-auto-resume 提示判断:有待续会话且额度已恢复才用 SendToSession 续跑;否则只回复一行,不做任何别的事。」 +- 用户要“改阈值”:编辑 `~/.zcode/quota-auto-resume/config.json`(`threshold` 阈值、`warnAt` 提醒线、`maxAgeMin` 快照有效期分钟、`highCost` 高消耗工具名正则),改完再跑一次 status 核对。改动前先把新值念给用户确认。 +- 用户要“试跑拦截”:在临时目录放一份 config.json 把 `threshold` 设为 0,用 `QUOTA_AUTO_RESUME_HOME=<临时目录>` 跑下面两条,看输出;试完删掉临时目录。 + +```bash +echo '{"toolName":"Agent","sessionId":"test"}' | QUOTA_AUTO_RESUME_HOME=<临时目录> node "${ZCODE_PLUGIN_ROOT}/hooks/auto-resume-hook.cjs" PreToolUse +echo '{"toolName":"Read","sessionId":"test"}' | QUOTA_AUTO_RESUME_HOME=<临时目录> node "${ZCODE_PLUGIN_ROOT}/hooks/auto-resume-hook.cjs" PreToolUse +``` + +预期:第一条输出 deny 及收尾提示,第二条无输出(放行)。 + +- 用户要“停用拦截”:把 config.json 里 `threshold` 改成 100,或在 设置 → 插件 里停用本插件。 diff --git a/external_plugins/quota-auto-resume/hooks/auto-resume-hook.cjs b/external_plugins/quota-auto-resume/hooks/auto-resume-hook.cjs new file mode 100644 index 00000000..5660edee --- /dev/null +++ b/external_plugins/quota-auto-resume/hooks/auto-resume-hook.cjs @@ -0,0 +1,321 @@ +#!/usr/bin/env node +'use strict'; + +// quota-auto-resume:按 ZCode 套餐额度停用高消耗工具,额度恢复后续跑。 +// 额度来源:ZCode 桌面端轮询后写在日志里的快照(不读凭据、不发请求)。 +// 用法:node auto-resume-hook.cjs (hook 输入走 stdin) +// node auto-resume-hook.cjs status (给人看的额度表) + +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const DEFAULTS = { + threshold: 80, // 用到百分之几即停用高消耗工具 + warnAt: 60, // 用到百分之几开始在每轮提示里提醒 + maxAgeMin: 20, // 快照超过多少分钟视为过期(过期不拦) + highCost: '^(Agent|Task)$|image|video|browser|playwright|firefox|devtools|computer|(^|[^a-z])cua([^a-z]|$)|websearch|web_search|webfetch|web_reader|3d|tripo|blender|designcraft|screencast|node_repl', +}; +const CRON_MARK = 'quota-auto-resume 额度恢复探测'; + +function stateDir() { + return process.env.QUOTA_AUTO_RESUME_HOME || path.join(os.homedir(), '.zcode', 'quota-auto-resume'); +} + +function loadConfig() { + const file = path.join(stateDir(), 'config.json'); + try { + return { ...DEFAULTS, ...JSON.parse(fs.readFileSync(file, 'utf8')) }; + } catch { + return { ...DEFAULTS }; + } +} + +function logDir() { + const candidates = []; + if (process.env.QUOTA_AUTO_RESUME_LOGS) candidates.push(process.env.QUOTA_AUTO_RESUME_LOGS); + if (process.env.ZCODE_DATA_BASE_DIR) { + candidates.push(path.join(process.env.ZCODE_DATA_BASE_DIR, '.zcode', 'v2', 'logs')); + } + candidates.push(path.join(os.homedir(), '.zcode', 'v2', 'logs')); + return candidates.find((dir) => { try { return fs.statSync(dir).isDirectory(); } catch { return false; } }) || null; +} + +function dateStamps() { + const out = []; + for (const back of [0, 1]) { + const d = new Date(Date.now() - back * 86400000); + out.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`); + } + return out; +} + +// 只读文件尾部,日志再大也不拖慢 hook。 +function readTail(file, maxBytes = 4 * 1024 * 1024) { + const fd = fs.openSync(file, 'r'); + try { + const size = fs.fstatSync(fd).size; + const length = Math.min(size, maxBytes); + const buf = Buffer.alloc(length); + fs.readSync(fd, buf, 0, length, size - length); + let text = buf.toString('utf8'); + if (size > length) text = text.slice(text.indexOf('\n') + 1); + return text; + } finally { + fs.closeSync(fd); + } +} + +function lineTimeAt(text, index) { + const start = text.lastIndexOf('\n', index) + 1; + const m = /^\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/.exec(text.slice(start, start + 32)); + return m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime() : NaN; +} + +// 快照行形如:... [usage-stats] <文案> {"balanceCount":2,"balances":[...],"code":0,...} +// 只认 JSON 结构,不认文案,客户端换语言不受影响。 +function parseModels(text) { + const key = '{"balanceCount":'; + for (let at = text.lastIndexOf(key); at !== -1; at = text.lastIndexOf(key, at - 1)) { + const end = text.indexOf('\n', at); + try { + const data = JSON.parse(text.slice(at, end === -1 ? undefined : end)); + const seen = new Set(); + const models = []; + for (const b of data.balances || []) { + if (!b.show_name || b.total_units == null || b.used_units == null || seen.has(b.entitlement_id)) continue; + seen.add(b.entitlement_id); + models.push({ name: b.show_name, used: b.used_units, total: b.total_units, remaining: b.remaining_units }); + } + if (models.length) return { at: lineTimeAt(text, at), models }; + } catch { /* 尾部被截断的行,继续往前找 */ } + } + return null; +} + +// MCP 额度行形如:... [usage-stats] <文案> {"body":"{\"code\":0,...\"total_usage\":{\"used\":0,\"limit\":1000}...}","durationMs":...} +function parseMcp(text) { + const key = '{"body":"'; + for (let at = text.lastIndexOf(key); at !== -1; at = text.lastIndexOf(key, at - 1)) { + try { + const end = text.indexOf('","durationMs"', at); + if (end === -1) continue; + const body = JSON.parse(JSON.parse(text.slice(at + key.length - 1, end + 1))); + const usage = body?.data?.total_usage; + if (!usage || usage.limit == null || usage.used == null) continue; + return { at: lineTimeAt(text, at), used: usage.used, limit: usage.limit, nextRefreshAt: body.data.next_refresh_at || null }; + } catch { /* 往前找 */ } + } + return null; +} + +function readSnapshot(now = Date.now()) { + const dir = logDir(); + const snap = { dir, at: NaN, models: [], mcp: null, modelRatio: null, mcpRatio: null }; + if (!dir) return snap; + let models = null; + let mcp = null; + for (const stamp of dateStamps()) { + const file = path.join(dir, `${stamp}.log`); + if (!fs.existsSync(file)) continue; + const tail = readTail(file); + if (!models) models = parseModels(tail); + if (!mcp) mcp = parseMcp(tail); + if (models && mcp) break; + } + if (models) { + snap.at = models.at; + snap.models = models.models; + const ratios = models.models.filter((m) => m.total > 0).map((m) => m.used / m.total); + snap.modelRatio = ratios.length ? Math.max(...ratios) : null; + const newest = models.models.filter((m) => m.total > 0).sort((a, b) => b.used / b.total - a.used / a.total)[0]; + snap.topModel = newest ? newest.name : null; + } + if (mcp) { + snap.mcp = { used: mcp.used, limit: mcp.limit, nextRefreshAt: mcp.nextRefreshAt }; + snap.mcpRatio = mcp.limit > 0 ? mcp.used / mcp.limit : null; + if (Number.isNaN(snap.at) || mcp.at > snap.at) snap.at = mcp.at; + } + snap.ageMin = Number.isNaN(snap.at) ? null : Math.max(0, (now - snap.at) / 60000); + return snap; +} + +function evaluate(snap, config, now = Date.now()) { + const fresh = snap.ageMin != null && snap.ageMin <= config.maxAgeMin; + return { + fresh, + modelTripped: fresh && snap.modelRatio != null && snap.modelRatio >= config.threshold / 100, + mcpTripped: fresh && snap.mcpRatio != null && snap.mcpRatio >= config.threshold / 100, + }; +} + +const pct = (ratio) => (ratio == null ? '未知' : `${(ratio * 100).toFixed(1)}%`); +const line = (snap) => { + const models = snap.models.length + ? snap.models.map((m) => `${m.name} ${pct(m.total > 0 ? m.used / m.total : null)}(${m.used}/${m.total})`).join('、') + : '未知'; + const mcp = snap.mcp ? `${pct(snap.mcpRatio)}(${snap.mcp.used}/${snap.mcp.limit})` : '未知'; + return `模型额度 ${models};官方 MCP 调用额度 ${mcp};快照${snap.ageMin == null ? '无' : `${snap.ageMin.toFixed(0)} 分钟前`}。`; +}; + +function pendingDir() { + return path.join(stateDir(), 'pending'); +} + +function readPending() { + const dir = pendingDir(); + let names = []; + try { names = fs.readdirSync(dir).filter((n) => n.endsWith('.json')); } catch { return []; } + const out = []; + for (const name of names) { + try { + const item = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')); + out.push({ file: path.join(dir, name), ...item }); + } catch { /* 坏文件略过 */ } + } + return out; +} + +function markPending(sessionId, tool, kind, snap) { + if (!sessionId) return; + const dir = pendingDir(); + const file = path.join(dir, `${String(sessionId).replace(/[^A-Za-z0-9._-]/g, '_')}.json`); + const ratio = kind === 'mcp' ? snap.mcpRatio : snap.modelRatio; + const payload = { sessionId, tool, kind, ratio, at: new Date().toISOString() }; + // 同一会话本轮已经记过且内容相同就不反复写盘。 + try { + if (fs.existsSync(file) && fs.readFileSync(file, 'utf8').includes(`"tool":${JSON.stringify(tool)}`)) return; + } catch { /* 写不了就当没记过 */ } + try { + fs.mkdirSync(dir, { recursive: true }); + const tmp = `${file}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(payload)); + fs.renameSync(tmp, file); + } catch { /* 记不下交接标记不影响拦截本身 */ } +} + +function writeOut(obj) { + const bytes = obj ? JSON.stringify(obj) : ''; + if (!bytes) { process.exitCode = 0; return; } + // Windows 下写完 stdout 立刻 exit 会丢输出,等写回调再退出。 + process.stdout.write(bytes, () => { process.exitCode = 0; }); + process.stdout.on('error', () => { process.exitCode = 0; }); +} + +function readStdin() { + try { + if (process.stdin.isTTY) return {}; + const raw = fs.readFileSync(0, 'utf8').trim(); + return raw ? JSON.parse(raw) : {}; + } catch { + return {}; + } +} + +const toolNameOf = (input) => input.toolName ?? input.tool_name ?? input.tool?.name ?? input.name ?? ''; +const sessionIdOf = (input) => input.sessionId ?? input.session_id ?? ''; +const promptOf = (input) => String(input.prompt ?? input.input ?? input.text ?? ''); + +function onPreToolUse(input, config, snap, state) { + const tool = String(toolNameOf(input)); + const deny = (kind, reason) => { + markPending(sessionIdOf(input), tool, kind, snap); + writeOut({ + hookSpecificOutput: { + hookEventName: 'PreToolUse', + permissionDecision: 'deny', + permissionDecisionReason: reason, + }, + }); + }; + if (!state.fresh) return writeOut(null); + if (state.mcpTripped && /^mcp__/i.test(tool)) { + return deny('mcp', `[quota-auto-resume] 官方 MCP 调用额度已用 ${pct(snap.mcpRatio)},达到 ${config.threshold}% 上限,本次已停用「${tool}」。请立即收尾:把当前进度和下一步写成交接说明,告知用户额度恢复后会自动续跑,然后结束本轮。`); + } + if (state.modelTripped && new RegExp(config.highCost, 'i').test(tool)) { + return deny('model', `[quota-auto-resume] 模型额度已用 ${pct(snap.modelRatio)}(${snap.topModel}),达到 ${config.threshold}% 上限,本次已停用高消耗工具「${tool}」。轻量工具(读写文件、普通命令)仍可用。请立即收尾:把当前进度和下一步写成交接说明,告知用户额度恢复后会自动续跑,然后结束本轮。`); + } + return writeOut(null); +} + +function onPrompt(input, config, snap, state) { + const prompt = promptOf(input); + const context = (text) => writeOut(text ? { additionalContext: text } : null); + const recovered = (item) => state.fresh && (item.kind === 'mcp' ? !state.mcpTripped : !state.modelTripped); + + if (prompt.includes(CRON_MARK)) { + const items = readPending(); + if (!items.length) return context('[quota-auto-resume] 没有等待续跑的会话。只回复「无待续」,不要做别的。'); + if (!state.fresh) return context(`[quota-auto-resume] 额度快照已过期(${line(snap)}),无法判断是否恢复。只回复「数据过期」,不要续跑任何会话。`); + const ready = items.filter(recovered); + if (!ready.length) return context(`[quota-auto-resume] 额度尚未恢复(${line(snap)})。只回复「未恢复」,不要续跑任何会话。`); + return context(`[quota-auto-resume] 额度已恢复(${line(snap)})。请依次用 SendToSession 给下列会话发送「额度已恢复,请从中断处继续」,每发成功一个就用 Bash 删除其标记文件;不要在这些会话里做别的事,也不要新建会话:\n${ + ready.map((i) => `- 会话 ${i.sessionId}(上次停在「${i.tool}」,标记文件 ${i.file})`).join('\n')}`); + } + + const sid = sessionIdOf(input); + const mine = readPending().find((i) => i.sessionId && i.sessionId === sid); + if (mine && recovered(mine)) { + try { fs.unlinkSync(mine.file); } catch { /* 删不掉也无碍 */ } + return context(`[quota-auto-resume] 额度已恢复(${line(snap)})。本会话上一轮在「${mine.tool}」处因额度不足中断,请从中断处继续。`); + } + + const highest = Math.max(snap.modelRatio ?? 0, snap.mcpRatio ?? 0); + if (state.fresh && highest * 100 >= config.warnAt) { + return context(`[quota-auto-resume] ${line(snap)} 到 ${config.threshold}% 将停用高消耗工具(子代理、生图生视频、浏览器等),请节省额度、优先完成主线。`); + } + return context(''); +} + +function onSessionStart(config, snap) { + const flag = path.join(stateDir(), 'setup-notified'); + const notified = fs.existsSync(flag); + if (!notified) { + try { + fs.mkdirSync(stateDir(), { recursive: true }); + fs.writeFileSync(flag, new Date().toISOString()); + } catch { /* 下次再提示 */ } + } + const fresh = snap.ageMin != null && snap.ageMin <= config.maxAgeMin; + const status = !snap.dir ? '没有找到 ZCode 日志目录,暂时读不到额度' + : !fresh ? '额度快照缺失或已过期,暂不拦截' + : line(snap); + const setup = notified ? '' : `\n本机还没有额度恢复探测的定时任务。请现在用 CronCreate 建一个: recurring=true,cron=\"*/30 * * * *\",标题「每30分钟 quota-auto-resume 额度恢复探测」,prompt 原样如下(单行):\n「${CRON_MARK}。按系统注入的 quota-auto-resume 提示判断:有待续会话且额度已恢复才用 SendToSession 续跑;否则只回复一行,不做任何别的事。」建好后用一句话告知用户。`; + return writeOut({ additionalContext: `[quota-auto-resume] 已启用。${status}。${config.threshold}% 起停用高消耗工具,配置在 ${path.join(stateDir(), 'config.json')}(阈值 threshold、提醒线 warnAt、快照有效期 maxAgeMin、高消耗工具正则 highCost)。${setup}` }); +} + +function printStatus() { + const config = loadConfig(); + const snap = readSnapshot(); + const state = evaluate(snap, config); + console.log(`日志目录:${snap.dir || '未找到'}`); + console.log(line(snap)); + console.log(`状态:${!state.fresh ? '快照缺失或过期,不拦截' : state.modelTripped || state.mcpTripped ? '已达阈值,高消耗工具已停用' : '正常,未拦截'}`); + console.log(`阈值:${config.threshold}%(提醒线 ${config.warnAt}%,快照有效期 ${config.maxAgeMin} 分钟)`); + console.log(`待续跑会话:${readPending().length} 个`); +} + +function main() { + const event = process.argv[2]; + if (event === 'status') return printStatus(); + const config = loadConfig(); + const snap = readSnapshot(); + const state = evaluate(snap, config); + const input = readStdin(); + if (event === 'PreToolUse') return onPreToolUse(input, config, snap, state); + if (event === 'UserPromptSubmit') return onPrompt(input, config, snap, state); + if (event === 'SessionStart') return onSessionStart(config, snap); + process.exitCode = 2; +} + +if (require.main === module) { + try { + main(); + } catch (error) { + // 自身出错一律放行,不因插件故障卡住用户。 + process.stderr.write(`[quota-auto-resume] hook 内部错误,已放行:${error && error.message}\n`); + writeOut(null); + } +} + +module.exports = { DEFAULTS, parseModels, parseMcp, evaluate, readSnapshot }; diff --git a/external_plugins/quota-auto-resume/hooks/hooks.json b/external_plugins/quota-auto-resume/hooks/hooks.json new file mode 100644 index 00000000..5fc2a633 --- /dev/null +++ b/external_plugins/quota-auto-resume/hooks/hooks.json @@ -0,0 +1,42 @@ +{ + "description": "quota-auto-resume:按套餐额度停用高消耗工具,额度恢复后续跑。", + "hooks": { + "PreToolUse": [ + { + "hooks": [ + { + "type": "process", + "command": "node", + "args": ["${ZCODE_PLUGIN_ROOT}/hooks/auto-resume-hook.cjs", "PreToolUse"], + "timeoutMs": 15000 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "process", + "command": "node", + "args": ["${ZCODE_PLUGIN_ROOT}/hooks/auto-resume-hook.cjs", "UserPromptSubmit"], + "timeoutMs": 15000 + } + ] + } + ], + "SessionStart": [ + { + "matcher": "startup|resume", + "hooks": [ + { + "type": "process", + "command": "node", + "args": ["${ZCODE_PLUGIN_ROOT}/hooks/auto-resume-hook.cjs", "SessionStart"], + "timeoutMs": 15000 + } + ] + } + ] + } +} diff --git a/external_plugins/quota-auto-resume/test/run-tests.cjs b/external_plugins/quota-auto-resume/test/run-tests.cjs new file mode 100644 index 00000000..4e2c501e --- /dev/null +++ b/external_plugins/quota-auto-resume/test/run-tests.cjs @@ -0,0 +1,143 @@ +'use strict'; +// 运行:node test/run-tests.cjs +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const hook = path.join(__dirname, '..', 'hooks', 'auto-resume-hook.cjs'); +const lib = require(hook); + +const logLine = (time, body) => `[${time}] [info] [pid:1] [main] [host-log] (local-1) [host] [${time}.123] [pid:2] [usage-stats] 某文案 ${body}\n`; +const modelsBody = (a, b) => JSON.stringify({ balanceCount: 2, balances: [ + { entitlement_id: 'e1', show_name: 'GLM-5.4', total_units: 3000000, used_units: a, remaining_units: 3000000 - a }, + { entitlement_id: 'e2', show_name: 'GLM-5.3-Flash', total_units: 5000000, used_units: b, remaining_units: 5000000 - b }, +], code: 0, payload: { balances: [{ bucket_id: 'x' }] } }); +const mcpBody = (used) => JSON.stringify({ body: JSON.stringify({ code: 0, data: { server_time: 1, next_refresh_at: 1796486400, total_usage: { used, limit: 1000, remaining: 1000 - used } } }), durationMs: 10, status: 200 }); + +const now = new Date(); +const stamp = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +const clock = (d) => `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`; + +let passed = 0; +const test = (name, fn) => { fn(); passed += 1; console.log(`ok ${passed} - ${name}`); }; + +test('解析模型额度:取最近一条、去重、不收 payload 里的桶', () => { + const text = logLine('2026-12-05 10:00:00', modelsBody(10, 0)) + logLine('2026-12-05 10:05:00', modelsBody(900000, 0)); + const got = lib.parseModels(text); + assert.equal(got.models.length, 2); + assert.equal(got.models[0].used, 900000); + assert.equal(got.at, new Date(2026, 11, 5, 10, 5, 0).getTime()); +}); + +test('解析 MCP 额度:转义 body 能拆出来,无 total_usage 的行跳过', () => { + const text = logLine('2026-12-05 10:00:00', JSON.stringify({ body: '{"code":0,"data":{"other":1}}', durationMs: 5 })) + logLine('2026-12-05 10:06:00', mcpBody(850)); + const got = lib.parseMcp(text); + assert.deepEqual([got.used, got.limit], [850, 1000]); +}); + +test('读快照:日志目录与过期时间', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qg-test-')); + try { + fs.writeFileSync(path.join(dir, `${stamp(now)}.log`), + logLine(`${stamp(now)} ${clock(now)}`, modelsBody(600000, 2000000)) + logLine(`${stamp(now)} ${clock(now)}`, mcpBody(50))); + process.env.QUOTA_AUTO_RESUME_LOGS = dir; + delete process.env.ZCODE_DATA_BASE_DIR; + const snap = lib.readSnapshot(); + assert.equal(snap.modelRatio, 0.4); + assert.equal(snap.mcpRatio, 0.05); + assert.ok(snap.ageMin < 1); + assert.equal(snap.topModel, 'GLM-5.3-Flash'); + } finally { delete process.env.QUOTA_AUTO_RESUME_LOGS; fs.rmSync(dir, { recursive: true, force: true }); } +}); + +test('判定:未到阈值不拦、到阈值拦、快照过期不拦', () => { + const config = { ...lib.DEFAULTS }; + const snap = { ageMin: 1, modelRatio: 0.8, mcpRatio: 0.1 }; + assert.deepEqual(lib.evaluate(snap, config, 0), { fresh: true, modelTripped: true, mcpTripped: false }); + assert.equal(lib.evaluate({ ageMin: 1, modelRatio: 0.799, mcpRatio: 0.99 }, config).mcpTripped, true); + assert.equal(lib.evaluate({ ageMin: 1, modelRatio: 0.99, mcpRatio: null }, config).modelTripped, true); + const stale = lib.evaluate({ ageMin: 21, modelRatio: 0.99, mcpRatio: 0.99 }, config); + assert.equal(stale.fresh, false); + assert.equal(stale.modelTripped, false); +}); + +// 端到端:真跑 hook 进程。 +function run(event, input, env) { + const r = spawnSync(process.execPath, [hook, event], { input: JSON.stringify(input), encoding: 'utf8', env: { ...process.env, ...env } }); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.stderr, '', r.stderr); + return r.stdout.trim() ? JSON.parse(r.stdout) : null; +} +function withLogs(text, fn) { + const logs = fs.mkdtempSync(path.join(os.tmpdir(), 'qg-logs-')); + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'qg-home-')); + try { + fs.writeFileSync(path.join(logs, `${stamp(now)}.log`), text); + fn({ QUOTA_AUTO_RESUME_LOGS: logs, QUOTA_AUTO_RESUME_HOME: home }, home); + } finally { fs.rmSync(logs, { recursive: true, force: true }); fs.rmSync(home, { recursive: true, force: true }); } +} +const freshPair = (a, m) => logLine(`${stamp(now)} ${clock(now)}`, modelsBody(a, 0)) + logLine(`${stamp(now)} ${clock(now)}`, mcpBody(m)); + +test('端到端:额度 90% 时拦 Agent、放 Read,并记下待续跑标记', () => { + withLogs(freshPair(2700000, 10), (env, home) => { + const denied = run('PreToolUse', { toolName: 'Agent', sessionId: 's1' }, env); + assert.equal(denied.hookSpecificOutput.permissionDecision, 'deny'); + assert.match(denied.hookSpecificOutput.permissionDecisionReason, /收尾/); + assert.equal(run('PreToolUse', { toolName: 'Read', sessionId: 's1' }, env), null); + const pending = fs.readdirSync(path.join(home, 'pending')); + assert.deepEqual(pending, ['s1.json']); + }); +}); + +test('端到端:MCP 额度 95% 时只拦 mcp__ 工具,子代理照放', () => { + withLogs(freshPair(100, 950), (env) => { + assert.equal(run('PreToolUse', { toolName: 'mcp__serena__find_symbol', sessionId: 's2' }, env).hookSpecificOutput.permissionDecision, 'deny'); + assert.equal(run('PreToolUse', { toolName: 'Agent', sessionId: 's2' }, env), null); + }); +}); + +test('端到端:额度正常、快照过期、没有日志时一律放行且无输出', () => { + withLogs(freshPair(100, 10), (env) => { + assert.equal(run('PreToolUse', { toolName: 'Agent', sessionId: 's3' }, env), null); + assert.equal(run('UserPromptSubmit', { prompt: '你好', sessionId: 's3' }, env), null); + }); + withLogs(logLine('2020-01-01 08:00:00', modelsBody(2999999, 4999999)) + logLine('2020-01-01 08:00:00', mcpBody(1000)), (env) => { + assert.equal(run('PreToolUse', { toolName: 'Agent', sessionId: 's4' }, env), null); + }); + withLogs('', (env) => { + assert.equal(run('PreToolUse', { toolName: 'Agent', sessionId: 's5' }, { ...env, QUOTA_AUTO_RESUME_LOGS: path.join(os.tmpdir(), 'qg-no-such-dir') }), null); + }); +}); + +test('端到端:额度 70% 时每轮提醒,续跑探测回复未恢复', () => { + withLogs(freshPair(2100000, 10), (env) => { + assert.match(run('UserPromptSubmit', { prompt: '继续', sessionId: 's6' }, env).additionalContext, /70\.0%/); + }); + withLogs(freshPair(2700000, 10), (env, home) => { + fs.mkdirSync(path.join(home, 'pending')); + fs.writeFileSync(path.join(home, 'pending', 's7.json'), JSON.stringify({ sessionId: 's7', tool: 'Agent', kind: 'model' })); + const cron = run('UserPromptSubmit', { prompt: 'quota-auto-resume 额度恢复探测', sessionId: 'cron' }, env); + assert.match(cron.additionalContext, /未恢复/); + // 次日额度清零后的快照:探测应给出续跑指令;原会话自己回来时清掉标记并提示继续。 + const freshLogs = freshPair(0, 0); + const logs = env.QUOTA_AUTO_RESUME_LOGS; + fs.writeFileSync(path.join(logs, `${stamp(now)}.log`), freshLogs); + assert.match(run('UserPromptSubmit', { prompt: 'quota-auto-resume 额度恢复探测', sessionId: 'cron' }, env).additionalContext, /SendToSession[\s\S]*s7/); + assert.match(run('UserPromptSubmit', { prompt: '接着做', sessionId: 's7' }, env).additionalContext, /从中断处继续/); + assert.deepEqual(fs.readdirSync(path.join(home, 'pending')), []); + assert.match(run('UserPromptSubmit', { prompt: 'quota-auto-resume 额度恢复探测', sessionId: 'cron' }, env).additionalContext, /无待续/); + }); +}); + +test('端到端:不认识的字段名和坏输入也不崩', () => { + withLogs(freshPair(2700000, 10), (env) => { + assert.equal(run("PreToolUse", { tool: { name: "Read" } }, env), null); + const r = spawnSync(process.execPath, [hook, 'PreToolUse'], { input: 'not json', encoding: 'utf8', env: { ...process.env, ...env } }); + assert.equal(r.status, 0); + assert.equal(r.stdout, ''); + }); +}); + +console.log(`\n全部通过:${passed} 项`); diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..7db204d0 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,27 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "quota-auto-resume", + "source": "./external_plugins/quota-auto-resume", + "description": "额度恢复后自动恢复任务:套餐额度用到阈值即停用高消耗工具让 Agent 收尾,额度恢复后由定时任务自动续跑。", + "description_i18n": { + "en": "Auto-resume tasks after quota recovery: stop high-cost tools when the plan quota reaches a threshold so the agent wraps up, then resume automatically through a scheduled task once quota recovers.", + "zh-CN": "额度恢复后自动恢复任务:套餐额度用到阈值即停用高消耗工具让 Agent 收尾,额度恢复后由定时任务自动续跑。" + }, + "version": "0.1.0", + "author": { + "name": "tech.leshang" + }, + "category": "productivity", + "keywords": [ + "quota", + "usage", + "hooks", + "auto-resume", + "coding-plan" + ] } ] } \ No newline at end of file