@nightdread/opencode-go-usage 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Artyom
4
+
5
+ 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:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ 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.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # opencode-go-usage
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenCode Go usage limits as a pill in OpenCode Desktop — no need to open the console.
4
+
5
+ ![The OpenCode Go usage pill menu](docs/pill.png)
6
+
7
+ The pill above your composer shows the three Go allowances: the 5-hour window, the weekly limit and the monthly one, refreshed every minute. Green by default, yellow above 65%, red above 85%; click it for each limit's reset time. The plugin reads your saved OpenCode Go key through the running OpenCode server's API and polls `https://opencode.ai/inference/go/v1/usage` — the key is never written to a config file.
8
+
9
+ ### Install
10
+
11
+ Requires OpenCode Desktop and a saved OpenCode Go key (`/connect` → OpenCode Go).
12
+
13
+ ```sh
14
+ opencode plugin add github:nightdread/opencode-go-usage
15
+ ```
16
+
17
+ or manually: copy the folder with `gui-experimental.cjs` at its root, e.g. `~/.config/opencode/plugins/go-usage`, and add the path to `plugins` in `opencode.json`.
18
+
19
+ ### Build from source
20
+
21
+ ```sh
22
+ npm install
23
+ npm run bundle
24
+ ```
25
+
26
+ MIT licensed. Русская версия README — ниже.
27
+
28
+ ---
29
+
30
+ # opencode-go-usage · Русский
31
+
32
+ GUI-плагин OpenCode Desktop: показывает остаток лимитов OpenCode Go прямо в приложении — пилюлей над строкой ввода, чтобы не открывать консоль.
33
+
34
+ ![Меню пилюли с лимитами OpenCode Go](docs/pill.png)
35
+
36
+ - **5ч** — 5-часовое окно (20% месячной нормы), **нед** — недельный лимит (50%), **мес** — месячная норма.
37
+ - Цвет пилюли: зелёный → жёлтый (>65%) → красный (>85%).
38
+ - Клик открывает меню с каждым лимитом и временем сброса (у недельного и месячного — дата и время).
39
+ - Обновление раз в 5 минут. Ключ никуда не записывается: плагин берёт сохранённый ключ OpenCode Go через API работающего сервера OpenCode (`credential.list`) и опрашивает `https://opencode.ai/inference/go/v1/usage`.
40
+
41
+ ## Установка
42
+
43
+ Нужен OpenCode Desktop и сохранённый ключ OpenCode Go (`/connect` → OpenCode Go).
44
+
45
+ Из этого репозитория одной командой:
46
+
47
+ ```sh
48
+ opencode plugin add github:nightdread/opencode-go-usage
49
+ ```
50
+
51
+ Или вручную: скопируйте папку с `gui-experimental.cjs` в корне, например `~/.config/opencode/plugins/go-usage`, и добавьте путь в `opencode.json`:
52
+
53
+ ```jsonc
54
+ {
55
+ "plugins": [
56
+ "./plugins/go-usage"
57
+ ]
58
+ }
59
+ ```
60
+
61
+ Путь относительный — от каталога с `opencode.json`. На Windows подойдёт и абсолютный путь с прямыми слэшами.
62
+
63
+ Пилюля появляется над строкой ввода после первого опроса (несколько секунд). На сессиях сабагентов пилюля не показывается.
64
+
65
+ ## Сборка из исходников
66
+
67
+ ```sh
68
+ npm install
69
+ npm run bundle
70
+ ```
71
+
72
+ Готовый бандл появится в `dist/gui-experimental.cjs` — скопируйте его в папку плагина.
73
+
74
+ ## Ограничения
75
+
76
+ - Данные берутся из публичного usage-API OpenCode Go; если ключ не сохранён или подписки нет, пилюля показывает «Go: нет данных».
77
+ - GUI-плагины OpenCode — экспериментальные, возможны изменения API между версиями.
78
+
79
+ ## Лицензия
80
+
81
+ MIT
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js"),u=require("@opencode/plugin/gui"),a=[["rolling","pill.short.five","row.five"],["weekly","pill.short.week","row.week"],["monthly","pill.short.month","row.month"]],m=u.Plugin.define({i18n:{en:{"pill.title":"OpenCode Go usage (5-hour / weekly / monthly)","pill.short.five":"5h","pill.short.week":"wk","pill.short.month":"mo","row.five":"5-hour window","row.week":"Weekly limit","row.month":"Monthly limit","row.reset":"resets","pill.nodata":"Go: no data"},ru:{"pill.title":"Использование OpenCode Go (5-часовое окно / неделя / месяц)","pill.short.five":"5ч","pill.short.week":"нед","pill.short.month":"мес","row.five":"5-часовое окно","row.week":"Недельный лимит","row.month":"Месячный лимит","row.reset":"сброс","pill.nodata":"Go: нет данных"}},setup(i){const[c,g]=l.createSignal(),[d,n]=l.createSignal(""),w=async()=>{try{let e=await i.client.credential.list();if(e&&!Array.isArray(e)&&Array.isArray(e.data)&&(e=e.data),!Array.isArray(e))return;const r=e.find(o=>o?.integrationID==="opencode-go"&&o.active!==!1)?.value;return typeof r=="string"?JSON.parse(r).key:r?.key}catch(e){i.log?.write?.("warn","go-usage: credential list failed: "+String(e)),n(String(e))}},s=async()=>{const e=await w();if(e)try{const t=await fetch("https://opencode.ai/inference/go/v1/usage",{headers:{Authorization:"Bearer "+e}});if(!t.ok){n("HTTP "+t.status);return}const r=await t.json();r?.usage&&g(r.usage)}catch(t){i.log?.write?.("warn","go-usage: usage fetch failed: "+String(t)),n(String(t))}},h=(e,t=!0)=>{if(!e?.resetsAt)return"";const r=new Date(e.resetsAt).toDateString()===new Date().toDateString(),o=t||!r?{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"}:{hour:"2-digit",minute:"2-digit"};return new Date(e.resetsAt).toLocaleString([],o)},p=e=>{const t=Math.max(...a.map(([r])=>e?.[r]?.percent??0));return t>85?"danger":t>65?"warning":"success"};i.add(u.ComposerPill,{id:"usage",show:()=>{const e=c();return e?{label:"Go "+a.map(([t,r])=>`${i.t(r)} ${e[t]?.percent??"?"}%`).join(" · "),tone:p(e),title:i.t("pill.title"),rows:a.map(([t,,r])=>({id:t,label:i.t(r)+": "+(e[t]?.percent??"?")+"%",tone:e[t]?.status==="rate-limited"?"danger":"success",detail:e[t]?.resetsAt?i.t("row.reset")+" "+h(e[t],t!=="rolling"):"",icon:e[t]?.status==="rate-limited"?"circle-x":"circle-check"}))}:d()?{label:i.t("pill.nodata"),tone:"warning",title:i.t("pill.title")}:void 0}}),s();const f=setInterval(()=>{s()},6e4);return()=>clearInterval(f)}});exports.default=m;
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@nightdread/opencode-go-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "OpenCode Go usage limits as a pill in OpenCode Desktop",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "files": ["src", "dist"],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/nightdread/opencode-go-usage.git"
11
+ },
12
+ "exports": {
13
+ ".": "./src/index.ts",
14
+ "./tui": "./src/tui.tsx",
15
+ "./gui-experimental": "./dist/gui-experimental.cjs"
16
+ },
17
+ "scripts": {
18
+ "bundle": "vite build"
19
+ },
20
+ "dependencies": {
21
+ "@opencode/plugin": "latest"
22
+ },
23
+ "devDependencies": {
24
+ "solid-js": "^1.9.0",
25
+ "vite": "^7.0.0",
26
+ "vite-plugin-solid": "^2.11.0"
27
+ }
28
+ }
package/src/gui.tsx ADDED
@@ -0,0 +1,117 @@
1
+ import { createSignal } from "solid-js"
2
+ import { ComposerPill, Plugin } from "@opencode/plugin/gui"
3
+
4
+ type Meter = { status?: string; percent?: number; resetsAt?: string }
5
+ type Usage = { rolling?: Meter; weekly?: Meter; monthly?: Meter }
6
+
7
+ const METERS: [keyof Usage, string, string][] = [
8
+ ["rolling", "pill.short.five", "row.five"],
9
+ ["weekly", "pill.short.week", "row.week"],
10
+ ["monthly", "pill.short.month", "row.month"],
11
+ ]
12
+
13
+ export default Plugin.define({
14
+ i18n: {
15
+ en: {
16
+ "pill.title": "OpenCode Go usage (5-hour / weekly / monthly)",
17
+ "pill.short.five": "5h",
18
+ "pill.short.week": "wk",
19
+ "pill.short.month": "mo",
20
+ "row.five": "5-hour window",
21
+ "row.week": "Weekly limit",
22
+ "row.month": "Monthly limit",
23
+ "row.reset": "resets",
24
+ "pill.nodata": "Go: no data",
25
+ },
26
+ ru: {
27
+ "pill.title": "Использование OpenCode Go (5-часовое окно / неделя / месяц)",
28
+ "pill.short.five": "5ч",
29
+ "pill.short.week": "нед",
30
+ "pill.short.month": "мес",
31
+ "row.five": "5-часовое окно",
32
+ "row.week": "Недельный лимит",
33
+ "row.month": "Месячный лимит",
34
+ "row.reset": "сброс",
35
+ "pill.nodata": "Go: нет данных",
36
+ },
37
+ },
38
+ setup(ctx) {
39
+ const [usage, setUsage] = createSignal<Usage>()
40
+ const [gone, setGone] = createSignal("")
41
+
42
+ const apiKey = async (): Promise<string | undefined> => {
43
+ try {
44
+ let list: unknown = await (ctx.client as { credential: { list(): Promise<unknown> } }).credential.list()
45
+ if (list && !Array.isArray(list) && Array.isArray((list as { data: unknown }).data)) {
46
+ list = (list as { data: unknown[] }).data
47
+ }
48
+ if (!Array.isArray(list)) return
49
+ const entry = list.find((c) => c?.integrationID === "opencode-go" && c.active !== false)
50
+ const value = entry?.value
51
+ if (typeof value === "string") return JSON.parse(value).key
52
+ return value?.key
53
+ } catch (error) {
54
+ ctx.log?.write?.("warn", "go-usage: credential list failed: " + String(error))
55
+ setGone(String(error))
56
+ }
57
+ }
58
+
59
+ const refresh = async () => {
60
+ const key = await apiKey()
61
+ if (!key) return
62
+ try {
63
+ const response = await fetch("https://opencode.ai/inference/go/v1/usage", {
64
+ headers: { Authorization: "Bearer " + key },
65
+ })
66
+ if (!response.ok) {
67
+ setGone("HTTP " + response.status)
68
+ return
69
+ }
70
+ const body = await response.json()
71
+ if (body?.usage) setUsage(body.usage)
72
+ } catch (error) {
73
+ ctx.log?.write?.("warn", "go-usage: usage fetch failed: " + String(error))
74
+ setGone(String(error))
75
+ }
76
+ }
77
+
78
+ const when = (meter?: Meter, withDate = true) => {
79
+ if (!meter?.resetsAt) return ""
80
+ const sameDay = new Date(meter.resetsAt).toDateString() === new Date().toDateString()
81
+ const options: Intl.DateTimeFormatOptions = withDate || !sameDay
82
+ ? { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }
83
+ : { hour: "2-digit", minute: "2-digit" }
84
+ return new Date(meter.resetsAt).toLocaleString([], options)
85
+ }
86
+ const tone = (u?: Usage) => {
87
+ const peak = Math.max(...METERS.map(([key]) => u?.[key]?.percent ?? 0))
88
+ return peak > 85 ? "danger" : peak > 65 ? "warning" : "success"
89
+ }
90
+
91
+ ctx.add(ComposerPill, {
92
+ id: "usage",
93
+ show: () => {
94
+ const u = usage()
95
+ if (!u) return gone() ? { label: ctx.t("pill.nodata"), tone: "warning", title: ctx.t("pill.title") } : undefined
96
+ return {
97
+ label: "Go " + METERS.map(([meter, short]) => `${ctx.t(short)} ${u[meter]?.percent ?? "?"}%`).join(" · "),
98
+ tone: tone(u),
99
+ title: ctx.t("pill.title"),
100
+ rows: METERS.map(([key, , row]) => ({
101
+ id: key,
102
+ label: ctx.t(row) + ": " + (u[key]?.percent ?? "?") + "%",
103
+ tone: u[key]?.status === "rate-limited" ? "danger" : "success",
104
+ // 5-часовое окно сбрасывается сегодня — достаточно времени; неделя и месяц — всегда с датой.
105
+ detail: u[key]?.resetsAt ? ctx.t("row.reset") + " " + when(u[key], key !== "rolling") : "",
106
+ icon: u[key]?.status === "rate-limited" ? "circle-x" : "circle-check",
107
+ })),
108
+ }
109
+ },
110
+ })
111
+
112
+ void refresh()
113
+ // Опрос раз в минуту: запрос лёгкий, остаток виден почти живьём.
114
+ const timer = setInterval(() => void refresh(), 60_000)
115
+ return () => clearInterval(timer)
116
+ },
117
+ })
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { Plugin } from "@opencode/plugin"
2
+
3
+ // Пустая серверная часть: без неё `opencode plugin add` в старых версиях
4
+ // не принимает пакет только с GUI-частью (до поддержки GUI-эндпоинтов).
5
+ export default Plugin.define({
6
+ id: "go-usage",
7
+ async setup() {},
8
+ })
package/src/tui.tsx ADDED
@@ -0,0 +1,8 @@
1
+ import { Plugin } from "@opencode/plugin/tui"
2
+
3
+ // Десктоп-приложение грузит только GUI-часть; пустой TUI-эндпоинт нужен,
4
+ // чтобы `opencode plugin add` принял пакет без серверной части.
5
+ export default Plugin.define({
6
+ id: "go-usage",
7
+ setup() {},
8
+ })