Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions external_plugins/context-visualizer/.zcode-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "context-visualizer",
"version": "0.6.3",
"description": "Analyze ZCode session logs and visualize context-window occupancy: cross-session tool consumption leaderboard, zero-call tool list, plugin disable advice, per-plugin install cost preview, and a native interactive dashboard.",
"description_i18n": {
"en": "Analyze ZCode session logs and visualize context-window occupancy: cross-session tool consumption leaderboard, zero-call tool list, plugin disable advice, per-plugin install cost preview, and a native interactive dashboard.",
"zh-CN": "分析会话日志,可视化上下文占用:跨会话工具消耗总排行、零调用工具停用候选清单、插件停用建议(使用次数×定义开销综合排名)、插件安装成本预览。侧栏常驻按钮一键打开,窗口大小按模型自动检测。"
},
"author": {
"name": "hangtian"
},
"skills": "./skills",
"commands": "./commands",
"mcpServers": {
"context-visualizer": {
"type": "stdio",
"command": "node",
"args": [
"${CLAUDE_PLUGIN_ROOT}/mcp/server.mjs"
],
"env": {
"ZCODE_PLUGIN_ROOT": "${CLAUDE_PLUGIN_ROOT}"
}
}
},
"ui": {
"surfaces": [
{
"id": "context-visualizer",
"title": {
"zh-CN": "上下文占用",
"en-US": "Context Usage"
},
"icon": "gauge",
"server": "context-visualizer",
"resourceUri": "ui://context-visualizer/panel.html",
"availability": "session"
}
]
},
"slots": {
"nav.primary": [
{
"id": "open-context-panel",
"title": {
"zh-CN": "上下文占用",
"en-US": "Context Usage"
},
"icon": "gauge",
"target": {
"surface": "context-visualizer"
}
}
]
},
"license": "Apache-2.0"
}
190 changes: 190 additions & 0 deletions external_plugins/context-visualizer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

Copyright 2026 hangtian

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
51 changes: 51 additions & 0 deletions external_plugins/context-visualizer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Context Visualizer

English | [简体中文](README.md)

A ZCode plugin that analyzes session model-io logs and the local usage database to answer the questions every ZCode user eventually asks:

- **What is occupying my context window?** How much goes to the system prompt, tool definitions, tool results, reasoning, and injected content?
- **Which tools are zombies?** Their definitions ship with every request (a fixed tax), yet they have never been called once.
- **Which plugin or MCP server should I disable?** Ranked by usage count × definition cost, with the exact per-request token savings.
- **Which model's window should the percentages use?** The window size is auto-detected from ZCode's builtin model rules (GLM-5.3 → 1M, most models → 200k, etc.) — no manual setup.

## Features

- **Persistent sidebar button** (`nav.primary` slot): one click opens the interactive panel
- **Leaderboard view** (default): cross-session tool consumption ranking, full session ranking (from the local usage database, including sessions whose logs were rotated), and plugin disable advice
- **Session detail**: per-request context fill chart (cache vs fresh), category breakdown, top tool results, largest single items, tool cost bill
- **Zero-call tool list**: tools whose definitions are paid for every request but were never invoked, sorted by cost and tagged by source (builtin / plugin / MCP)
- **Pre-install cost preview**: "weigh" a plugin before installing — spawn its MCP server, enumerate tool schemas, estimate per-request occupancy
- **Native interactive view**: embeds the dashboard in chat via the `::visualize` gen-ui channel (no MCP required)
- **`/context-usage` command and skill**: agent-triggered summary plus interactive view

## Usage

1. Open the "Context Usage" sidebar button, or type `/context-usage` in a session
2. The panel opens on the leaderboard; click a session row to drill into details; "Recalculate" refreshes
3. CLI: `node scripts/analyze-context.mjs [--session <prefix>] [--gen-ui] [--list]`

## Data & Accuracy

- Data: ZCode's local `~/.zcode/cli/rollout/model-io-*.jsonl` (one record per API request) and `~/.zcode/cli/db/db.sqlite` (usage stats). **Local reads only — zero network requests.**
- Totals come from real usage (`input + cache_read`) and are exact.
- Category values are character-ratio estimates calibrated to the real totals; images/videos use flat estimates.
- Window size is detected from ZCode's builtin model rules cache (ordered merge); falls back to 200k with an explicit label.

## Requirements

- ZCode Desktop (the panel needs the desktop sandbox)
- Node.js ≥ 18 (MCP server and CLI)

## Development

```bash
npm install # build-time deps (@modelcontextprotocol/sdk, ext-apps, esbuild)
node build.mjs # produces mcp/server.mjs and ui/panel.html (zero-dependency runtime bundles)
```

The built bundles are committed (`mcp/server.mjs`, `ui/panel.html`), so the plugin runs without node_modules.

## License

Apache-2.0
52 changes: 52 additions & 0 deletions external_plugins/context-visualizer/README_CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Context Visualizer(上下文占用可视化)

[English](README.en.md) | 简体中文

一个 ZCode 插件:分析会话的 model-io 日志与本地使用统计库,回答每个 ZCode 用户都会问的问题——

- **我的上下文窗口被什么占用了?** 系统提示词、工具定义、工具结果、思考推理、注入内容各占多少?
- **哪些工具是"僵尸"?** 定义随每次请求发送(固定税),却从未被调用过一次。
- **该停用哪个插件/MCP server?** 按使用次数 × 定义开销综合排名,直接给出停用后每请求可省多少 tokens。
- **窗口百分比按哪个模型算?** 窗口大小按 ZCode 内置模型规则自动检测(GLM-5.3 → 1M、多数模型 → 200k 等),无需手动设置。

## 功能

- **侧栏常驻按钮**(`nav.primary` 插槽):一键打开交互面板
- **总排行视图**(默认):跨全部会话聚合的工具消耗排行榜、全量会话排行(本地使用统计库,含已轮转日志的会话)、插件停用建议
- **会话明细**:每次请求的上下文填充图(缓存/新输入)、分类占用构成、工具结果 Top、最大单项、工具成本账单
- **零调用工具清单**:定义税照付却从未调用的工具,按开销排序并标注来源(内置 / 插件 / MCP)
- **插件安装成本预览**:安装前"称重"——拉起插件的 MCP server、枚举工具 schema、估算每请求开销
- **原生交互视图**:通过 `::visualize` gen-ui 通道在聊天中内嵌仪表盘卡片(无需 MCP)
- **`/context-usage` 命令与技能**:Agent 触发,返回文字摘要 + 交互视图

## 使用方式

1. 打开侧栏「上下文占用」按钮,或在会话中输入 `/context-usage`
2. 面板默认显示总排行;点击会话行下钻明细;「重算」获取最新数据
3. CLI:`node scripts/analyze-context.mjs [--session <前缀>] [--gen-ui] [--list]`

## 数据来源与口径

- 数据:ZCode 本地的 `~/.zcode/cli/rollout/model-io-*.jsonl`(每次 API 请求记录)与 `~/.zcode/cli/db/db.sqlite`(使用统计)。**纯本地读取,无任何网络请求。**
- 总量:来自请求的真实 usage(input + cache_read),准确。
- 分类值:按字符量比例估算并以真实总量校准;图片/视频按固定值估算。
- 窗口大小:读取 ZCode 内置模型规则缓存按序合并检测;无法识别时回退 200k 并明确标注。

## 安装要求

- ZCode Desktop(面板需要桌面端沙箱)
- Node.js ≥ 18(MCP server 与 CLI)

## 开发

```bash
npm install # 安装构建期依赖(@modelcontextprotocol/sdk、ext-apps、esbuild)
node build.mjs # 产出 mcp/server.mjs 与 ui/panel.html(运行时零依赖的打包产物)
```

源码结构:`scripts/analyze-lib.mjs`(分析核心)→ 三端复用(CLI / MCP 面板 / gen-ui fragment)。
构建产物已随包提交(`mcp/server.mjs`、`ui/panel.html`),运行时不需要 node_modules。

## License

Apache-2.0
Loading