opencode-glm-quota 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +240 -0
  3. package/dist/index.js +95 -0
  4. package/package.json +57 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,240 @@
1
+ # opencode-glm-quota
2
+
3
+ [![npm version](https://badge.fury.io/js/opencode-glm-quota.svg)](https://www.npmjs.com/package/opencode-glm-quota)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Build Status](https://github.com/guyinwonder168/opencode-glm-quota/workflows/Build%20&%20Test/badge.svg)](https://github.com/guyinwonder168/opencode-glm-quota/actions)
6
+
7
+ OpenCode plugin to query Z.ai GLM Coding Plan usage statistics with real-time quota monitoring, model usage tracking, and MCP tool usage.
8
+
9
+ ## Features
10
+
11
+ - 📊 Query current quota limits (5-hour token cycle, monthly MCP usage)
12
+ - 🤖 View model usage statistics (24-hour rolling window)
13
+ - 🔧 View MCP tool usage (web_search, web_reader, etc.)
14
+ - 🌍 Supports both Global (api.z.ai) and CN (open.bigmodel.cn) platforms
15
+ - 🔐 Automatic credential discovery from OpenCode auth.json
16
+ - 📈 Visual progress bars for quota percentages
17
+ - ⚡ Fail-fast error handling (no retry logic - user controls when to retry)
18
+
19
+ ## Installation
20
+
21
+ ### Option 1: npm (Recommended)
22
+
23
+ ```bash
24
+ npm install opencode-glm-quota
25
+ ```
26
+
27
+ Then add to your OpenCode config (`~/.config/opencode/config.json`):
28
+
29
+ ```json
30
+ {
31
+ "plugins": ["opencode-glm-quota"]
32
+ }
33
+ ```
34
+
35
+ ### Option 2: From GitHub
36
+
37
+ ```bash
38
+ npm install github:guyinwonder168/opencode-glm-quota
39
+ ```
40
+
41
+ ### Option 3: Manual Installation
42
+
43
+ 1. Download the latest release from GitHub
44
+ 2. Copy `dist/index.js` to `~/.config/opencode/plugin/glm-quota.js`
45
+
46
+ ## Quick Start
47
+
48
+ Once installed, simply run the plugin command in OpenCode:
49
+
50
+ ```bash
51
+ /glm_quota
52
+ ```
53
+
54
+ The plugin will automatically detect your credentials (from OpenCode authentication) and display your usage statistics.
55
+
56
+ ## Usage
57
+
58
+ ### Authentication Setup
59
+
60
+ This plugin uses OpenCode's built-in authentication system. No manual configuration required.
61
+
62
+ **Primary Method (Recommended):**
63
+
64
+ ```bash
65
+ # In OpenCode TUI
66
+ /connect
67
+ # Select: Z.AI Coding Plan or Z.AI
68
+ # Enter your API key
69
+ ```
70
+
71
+ **Fallback (Development/Testing Only):**
72
+
73
+ ```bash
74
+ # For Global platform (api.z.ai)
75
+ export ZAI_API_KEY="your-api-key"
76
+
77
+ # For CN platform (open.bigmodel.cn)
78
+ export ZHIPU_API_KEY="your-api-key"
79
+ ```
80
+
81
+ ### Running the Plugin
82
+
83
+ After authentication, simply run:
84
+
85
+ ```bash
86
+ /glm_quota
87
+ ```
88
+
89
+ ### Output Example
90
+
91
+ ```
92
+ ╔════════════════════════════════════════════════════════════╗
93
+ ║ Z.ai GLM Coding Plan Usage Statistics ║
94
+ ╠════════════════════════════════════════════════════════════╣
95
+ ║ Platform: ZAI ║
96
+ ║ Period: 2026-01-12 14:00:00 → 2026-01-13 14:59:59 ║
97
+ ╠════════════════════════════════════════════════════════════╣
98
+ ║ 📊 QUOTA LIMITS ║
99
+ ╟────────────────────────────────────────────────────────────╢
100
+ ║ Token usage(5 Hour) [████████████░░░░░░░░░░░░░░░░░░] 40.5% ║
101
+ ║ MCP usage(1 Month) [████░░░░░░░░░░░░░░░░░░░░░░░░░░] 12.3% ║
102
+ ║ Used: 123/1000 ║
103
+ ╠════════════════════════════════════════════════════════════╣
104
+ ║ 🤖 MODEL USAGE (24h) ║
105
+ ╟────────────────────────────────────────────────────────────╢
106
+ ║ { ║
107
+ ║ "requests": 45, ║
108
+ ║ "tokens": 125000 ║
109
+ ║ } ║
110
+ ╠════════════════════════════════════════════════════════════╣
111
+ ║ 🔧 TOOL/MCP USAGE (24h) ║
112
+ ╟────────────────────────────────────────────────────────────╢
113
+ ║ { ║
114
+ ║ "web_search": 15, ║
115
+ ║ "web_reader": 8 ║
116
+ ║ } ║
117
+ ╚════════════════════════════════════════════════════════════╝
118
+ ```
119
+
120
+ ### Error Handling
121
+
122
+ The plugin uses fail-fast error handling. If any API request fails, it will display the error and stop (no automatic retries). This gives you full control over when to retry.
123
+
124
+ **Example Error Output:**
125
+
126
+ ```
127
+ ╔════════════════════════════════════════════════════════════╗
128
+ ║ ❌ Authentication Error ║
129
+ ╠════════════════════════════════════════════════════════════╣
130
+ ║ Not authenticated with Z.AI. Please run `/connect` ║
131
+ ║ command in OpenCode TUI and select "Z.AI Coding Plan". ║
132
+ ╚════════════════════════════════════════════════════════════╝
133
+ ```
134
+
135
+ ## API Reference
136
+
137
+ This plugin queries three Z.ai monitoring endpoints:
138
+
139
+ | Endpoint | Purpose | Query Params |
140
+ |----------|---------|--------------|
141
+ | `/api/monitor/usage/quota/limit` | Current quota percentages | None |
142
+ | `/api/monitor/usage/model-usage` | Model usage (24h window) | `startTime`, `endTime` |
143
+ | `/api/monitor/usage/tool-usage` | MCP tool usage (24h window) | `startTime`, `endTime` |
144
+
145
+ ### Platform Detection
146
+
147
+ The plugin automatically detects the platform based on the provider ID used during authentication:
148
+
149
+ | Provider ID | Platform | API Base URL |
150
+ |-------------|----------|---------------|
151
+ | `zai-coding-plan` | ZAI | `https://api.z.ai` |
152
+ | `zai` | ZAI | `https://api.z.ai` |
153
+ | `zhipu` | ZHIPU | `https://open.bigmodel.cn` |
154
+
155
+ ### Credential Priority
156
+
157
+ The plugin discovers credentials in this order:
158
+
159
+ 1. **OpenCode auth.json** (`~/.local/share/opencode/auth.json`) - PRIMARY
160
+ 2. **Environment variable** `ZAI_API_KEY` (Global) or `ZHIPU_API_KEY` (CN) - FALLBACK (dev/testing only)
161
+
162
+ ### Time Window
163
+
164
+ Usage statistics are queried for a 24-hour rolling window:
165
+ - **Start**: Yesterday at current hour (e.g., 14:00:00)
166
+ - **End**: Today at current hour end (e.g., 14:59:59)
167
+
168
+ ### Authentication
169
+
170
+ **Critical**: The plugin does NOT use "Bearer" prefix in the Authorization header. The token is passed directly:
171
+
172
+ ```http
173
+ Authorization: {token}
174
+ Accept-Language: en-US,en
175
+ Content-Type: application/json
176
+ ```
177
+
178
+ ## Development
179
+
180
+ ### Build Commands
181
+
182
+ ```bash
183
+ # Build TypeScript to JavaScript
184
+ npm run build
185
+
186
+ # Clean build artifacts
187
+ npm run clean
188
+
189
+ # Run all tests
190
+ npm run test
191
+
192
+ # Run specific test file
193
+ npm run test -- path/to/test.test.ts
194
+
195
+ # Watch mode during development
196
+ npm run test -- --watch
197
+
198
+ # Lint source code
199
+ npm run lint
200
+
201
+ # Prepare for npm publish
202
+ npm run prepublishOnly
203
+ ```
204
+
205
+ ### Project Structure
206
+
207
+ ```
208
+ src/
209
+ index.ts # Main plugin entry point
210
+ dist/ # Compiled JavaScript (generated)
211
+ package.json # Dependencies and scripts
212
+ tsconfig.json # TypeScript configuration
213
+ ```
214
+
215
+ ### Code Style Guidelines
216
+
217
+ - Target: ES2022
218
+ - Module: NodeNext
219
+ - Strict mode enabled
220
+ - Always use type annotations for function returns
221
+ - Use `as const` for immutable constants
222
+
223
+ For detailed coding conventions, see [AGENTS.md](AGENTS.md).
224
+
225
+ ## Contributing
226
+
227
+ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
228
+
229
+ ## License
230
+
231
+ MIT © 2026
232
+
233
+ ## Acknowledgments
234
+
235
+ - API specification verified from [zai-org/zai-coding-plugins](https://github.com/zai-org/zai-coding-plugins)
236
+ - Built for [OpenCode](https://opencode.ai)
237
+
238
+ ## Changelog
239
+
240
+ See [CHANGELOG.md](CHANGELOG.md) for version history and detailed changes.
package/dist/index.js ADDED
@@ -0,0 +1,95 @@
1
+ /**
2
+ * OpenCode GLM Quota Plugin
3
+ *
4
+ * Query Z.ai GLM Coding Plan usage statistics including quota limits,
5
+ * model usage, and MCP tool usage.
6
+ */
7
+ import { tool } from "@opencode-ai/plugin/tool";
8
+ /**
9
+ * Provider ID to platform mapping
10
+ */
11
+ const PLATFORM_MAP = {
12
+ 'zai-coding-plan': 'ZAI',
13
+ 'zai': 'ZAI',
14
+ 'zhipu': 'ZHIPU',
15
+ 'zhipuai': 'ZHIPU'
16
+ };
17
+ /**
18
+ * Get provider platform from provider ID
19
+ * @param providerId - The provider ID from OpenCode authentication
20
+ * @returns Platform type or null if unknown
21
+ */
22
+ export function getProviderPlatform(providerId) {
23
+ return PLATFORM_MAP[providerId] || null;
24
+ }
25
+ /**
26
+ * Create error message for missing credentials
27
+ * @returns Error message with setup instructions
28
+ */
29
+ export function createCredentialError() {
30
+ return `No credentials found. Please authenticate by running /connect command in OpenCode.
31
+
32
+ Supported providers:
33
+ - Z.AI Coding Plan (recommended)
34
+ - Z.AI
35
+ - Zhipu
36
+
37
+ For development/testing, you can also set environment variables for appropriate platform.`;
38
+ }
39
+ /**
40
+ * Get credentials from OpenCode auth context or environment variables
41
+ * @param authContext - Optional auth context from OpenCode plugin system
42
+ * @returns Credentials object or null if no credentials found
43
+ */
44
+ export async function getCredentials(authContext) {
45
+ // Priority 1: OpenCode auth context
46
+ if (authContext && authContext.providerId && authContext.token) {
47
+ const platform = getProviderPlatform(authContext.providerId);
48
+ if (platform) {
49
+ return {
50
+ token: authContext.token,
51
+ platform
52
+ };
53
+ }
54
+ }
55
+ // Priority 2: Environment variables (fallback for development/testing)
56
+ if (process.env.ZAI_API_KEY) {
57
+ return {
58
+ token: process.env.ZAI_API_KEY,
59
+ platform: 'ZAI'
60
+ };
61
+ }
62
+ if (process.env.ZHIPU_API_KEY || process.env.ZHIPUAI_API_KEY) {
63
+ return {
64
+ token: (process.env.ZHIPU_API_KEY || process.env.ZHIPUAI_API_KEY),
65
+ platform: 'ZHIPU'
66
+ };
67
+ }
68
+ // No credentials found
69
+ return null;
70
+ }
71
+ /**
72
+ * Main GLM Quota Plugin
73
+ */
74
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
75
+ export const GlmQuotaPlugin = async (_ctx) => {
76
+ return {
77
+ tool: {
78
+ glm_quota: tool({
79
+ description: 'Query Z.ai GLM Coding Plan usage statistics including quota limits, model usage, and MCP tool usage',
80
+ args: {},
81
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
82
+ async execute(_args, _context) {
83
+ // TODO: Implement full feature in subsequent slices
84
+ // For now, verify credential discovery works
85
+ const credentials = await getCredentials();
86
+ if (!credentials) {
87
+ return createCredentialError();
88
+ }
89
+ return `✅ Credentials found for ${credentials.platform} platform\n\nFeature coming soon: quota limits, model usage, and MCP tool usage statistics.`;
90
+ }
91
+ })
92
+ }
93
+ };
94
+ };
95
+ export default GlmQuotaPlugin;
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "opencode-glm-quota",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "OpenCode plugin to query Z.ai GLM Coding Plan usage statistics including quota limits, model usage, and MCP tool usage",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "clean": "rm -rf dist",
16
+ "prepublishOnly": "npm run clean && npm run build",
17
+ "test": "node --test",
18
+ "lint": "eslint src/"
19
+ },
20
+ "keywords": [
21
+ "opencode",
22
+ "opencode-plugin",
23
+ "zai",
24
+ "z.ai",
25
+ "zhipu",
26
+ "glm",
27
+ "quota",
28
+ "usage",
29
+ "coding-plan",
30
+ "ai",
31
+ "llm"
32
+ ],
33
+ "author": "guyinwonder168 <guyinwonder168@gmail.com>",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/guyinwonder168/opencode-glm-quota.git"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/guyinwonder168/opencode-glm-quota/issues"
41
+ },
42
+ "homepage": "https://github.com/guyinwonder168/opencode-glm-quota#readme",
43
+ "peerDependencies": {
44
+ "@opencode-ai/plugin": ">=0.1.0"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "devDependencies": {
50
+ "@opencode-ai/plugin": "latest",
51
+ "@types/node": "^20.0.0",
52
+ "typescript": "^5.0.0",
53
+ "eslint": "^8.0.0",
54
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
55
+ "@typescript-eslint/parser": "^6.0.0"
56
+ }
57
+ }