openkodo 0.0.0-stage → 0.2.3

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/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package. Versioned independently of the OpenKodo
4
+ gateway.
5
+
6
+ ## 0.2.3
7
+
8
+ - First public release on npm as `openkodo`.
9
+ - Title the plugin **OpenKodo** through `magpie.name`, which is what magpie
10
+ reads for a package's own row (the npm name must stay lowercase).
11
+
12
+ ## 0.2.2
13
+
14
+ - Declare the provider icon on `auth`, which is where magpie reads it. 0.2.1
15
+ set it on the config record, so the card kept the generic provider box.
16
+
17
+ ## 0.2.1
18
+
19
+ - Show 5-hour, 7-day, and monthly windows together, each with its reset time.
20
+ - Add the OpenKodo provider icon.
21
+ - Format money in cents so floating-point noise never reaches the card.
22
+
23
+ ## 0.1.1
24
+
25
+ - Show the per-model five-hour request window the account is closest to
26
+ filling, instead of the plan-wide anti-abuse counter.
27
+
28
+ # Changelog
29
+
30
+ ## 0.1.0
31
+
32
+ - Initial OpenKodo provider for OpenCode and magpie.
33
+ - API-key sign-in, live model catalog, credit balance, and 5-hour request window.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpenKodo
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 CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # OpenKodo plugin
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
+ Provider plugin that puts [OpenKodo](https://openkodo.dev) into Magpie and
4
+ OpenCode: plans, credits, usage windows, and the live model catalog.
5
+ Provider id: `openkodo`.
6
+
7
+ ## What it shows
8
+
9
+ - Plan name and the OpenKodo mark
10
+ - Three rolling spend windows, shortest first: **5 hours**, **7 days**, and the
11
+ **monthly** pool — each with the amount used, the cap, and when it frees up
12
+ - The per-model 5-hour request guardrail
13
+ - The live catalog from [`/api/public/models`](https://api.openkodo.dev/api/public/models)
14
+
15
+ The 5-hour and 7-day windows are enforced by the gateway, not decoration:
16
+ Go is $25 / 5h and $50 / 7d, Pro is $50 / 5h and $100 / 7d. Reset times are
17
+ rolling — the cap frees up when the oldest spend in the window ages out — so
18
+ they move as new requests arrive.
19
+
20
+ ## Install
21
+
22
+ From the magpie plugin store, search for **OpenKodo**.
23
+
24
+ From a checkout:
25
+
26
+ ```bash
27
+ pnpm add openkodo
28
+ ```
29
+
30
+ ## Sign in
31
+
32
+ Paste an OpenKodo API key from **Console → API keys**. Keys start with
33
+ `ok_live_`. The plugin validates the key against
34
+ `https://api.openkodo.dev/api/plugin/usage`; it never stores anything except
35
+ the key itself, and it never creates keys, changes plans, or spends credits.
36
+
37
+ ## Provider
38
+
39
+ - Base URL: `https://api.openkodo.dev/v1`
40
+ - SDK: `@ai-sdk/openai-compatible`
41
+ - Models: fetched live, with a bundled fallback for offline starts
42
+
43
+ ## Development
44
+
45
+ ```bash
46
+ npm test # unit tests, no network
47
+ npm run pack:check # what would be published
48
+ ```
49
+
50
+ The tests stub `fetch`, so they never use a real API key.
51
+
52
+ ## License
53
+
54
+ [MIT](./LICENSE)
package/index.mjs ADDED
@@ -0,0 +1,219 @@
1
+ // OpenKodo as an OpenCode / magpie provider.
2
+ //
3
+ // An account is an OpenKodo API key (`ok_live_...`). The plugin validates it
4
+ // against /api/plugin/usage, declares the live model catalog, and exposes the
5
+ // credit balance and 5-hour request window to magpie's account card.
6
+
7
+ const ID = "openkodo"
8
+ const BASE = "https://api.openkodo.dev/v1"
9
+ const ICON = "https://openkodo.dev/favicon.svg"
10
+ const PUBLIC_MODELS = "https://api.openkodo.dev/api/public/models"
11
+ const USAGE = "https://api.openkodo.dev/api/plugin/usage"
12
+
13
+ // The gateway's windows are rolling, not calendar-based, so the reset time is
14
+ // when the oldest spend in the window falls out — not a fixed midnight.
15
+ const FIVE_HOURS = 5 * 60 * 60_000
16
+ const SEVEN_DAYS = 7 * 24 * 60 * 60_000
17
+
18
+ // Offline fallback only. The live /api/public/models response is authoritative;
19
+ // these are the official standard (off-peak) USD list rates.
20
+ const FALLBACK = {
21
+ "deepseek-v4.1-flash": { name: "DeepSeek V4.1 Flash", context: 1_000_000, output: 65_536, input: 0.15, outputPrice: 0.6, cache: 0.003 },
22
+ "deepseek-v4.1-pro": { name: "DeepSeek V4 Pro 0813", context: 1_000_000, output: 131_072, input: 0.66, outputPrice: 1.98, cache: 0.022 },
23
+ "glm-5.3": { name: "GLM-5.3", context: 1_000_000, output: 131_072, input: 1.4, outputPrice: 4.4, cache: 0.26 },
24
+ "glm-5.3-flash": { name: "GLM-5.3 Flash", context: 1_000_000, output: 131_072, input: 0.15, outputPrice: 0.5, cache: 0.03 },
25
+ "kimi-k3.1-pro": { name: "Kimi K3.1 Pro", context: 1_000_000, output: 131_072, input: 2.0, outputPrice: 10.0, cache: 0.2 },
26
+ "qwen3.8-max": { name: "Qwen3.8 Max", context: 1_000_000, output: 131_072, input: 2.0, outputPrice: 6.0, cache: 0.25 },
27
+ "MiniMax-M3": { name: "MiniMax M3", context: 1_000_000, output: 131_072, input: 0.6, outputPrice: 2.4, cache: 0.12 },
28
+ }
29
+
30
+ const fallbackModels = () =>
31
+ Object.fromEntries(
32
+ Object.entries(FALLBACK).map(([id, m]) => [
33
+ id,
34
+ {
35
+ name: m.name,
36
+ context: m.context,
37
+ output: m.output,
38
+ cost: { input: m.input, output: m.outputPrice, cache: { read: m.cache } },
39
+ },
40
+ ]),
41
+ )
42
+
43
+ const keyOf = (auth) => String(auth?.key ?? auth?.access ?? "").trim()
44
+
45
+ async function fetchUsage(key) {
46
+ const res = await fetch(USAGE, {
47
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
48
+ })
49
+ const body = await res.json().catch(() => ({}))
50
+ if (!res.ok) {
51
+ const error = new Error(body?.error?.message || `OpenKodo usage failed (${res.status})`)
52
+ error.status = res.status
53
+ throw error
54
+ }
55
+ return body
56
+ }
57
+
58
+ async function fetchModels() {
59
+ const res = await fetch(PUBLIC_MODELS, { headers: { Accept: "application/json" } })
60
+ if (!res.ok) throw new Error(`OpenKodo model list failed (${res.status})`)
61
+ const body = await res.json()
62
+ const out = {}
63
+ for (const m of body.models || []) {
64
+ if (!m?.code) continue
65
+ out[m.code] = {
66
+ name: m.name || m.code,
67
+ context: m.context_window || 1_000_000,
68
+ output: m.max_output || 131_072,
69
+ cost: {
70
+ // Show the standard (off-peak) rate the gateway charges most of the
71
+ // day, not the peak rate stored in the primary columns.
72
+ input: Number(m.offpeak_input_price_micros_per_mtok || m.input_price_micros_per_mtok || 0) / 1_000_000,
73
+ output: Number(m.offpeak_output_price_micros_per_mtok || m.output_price_micros_per_mtok || 0) / 1_000_000,
74
+ cache: { read: Number(m.offpeak_cached_input_price_micros_per_mtok || m.cached_input_price_micros_per_mtok || 0) / 1_000_000 },
75
+ },
76
+ }
77
+ }
78
+ return Object.keys(out).length ? out : fallbackModels()
79
+ }
80
+
81
+ export const OpenKodoAuthPlugin = async () => ({
82
+ config: async (cfg) => {
83
+ cfg.provider ??= {}
84
+ const p = (cfg.provider[ID] ??= {})
85
+ p.name ??= "OpenKodo"
86
+ p.icon ??= ICON
87
+ p.npm ??= "@ai-sdk/openai-compatible"
88
+ p.api ??= BASE
89
+ p.models = { ...fallbackModels(), ...(p.models ?? {}) }
90
+ },
91
+
92
+ provider: {
93
+ id: ID,
94
+ async models(provider) {
95
+ try {
96
+ return await fetchModels()
97
+ } catch {
98
+ return provider?.models && Object.keys(provider.models).length ? provider.models : fallbackModels()
99
+ }
100
+ },
101
+ },
102
+
103
+ auth: {
104
+ provider: ID,
105
+ // magpie reads the provider mark from auth.icon, not from config.provider.
106
+ // Declaring it here is what turns the generic provider box into our logo.
107
+ icon: ICON,
108
+
109
+ methods: [
110
+ {
111
+ type: "api",
112
+ label: "OpenKodo API key",
113
+ keyless: true,
114
+ prompts: [
115
+ {
116
+ type: "password",
117
+ key: "apiKey",
118
+ message: "OpenKodo API key (Console → API keys)",
119
+ placeholder: "ok_live_...",
120
+ validate: (v) => (String(v ?? "").trim().startsWith("ok_live_") ? undefined : "Enter an OpenKodo API key"),
121
+ },
122
+ ],
123
+ async authorize(inputs) {
124
+ const key = String(inputs?.apiKey ?? "").trim()
125
+ if (!key.startsWith("ok_live_")) return { type: "failed", error: "Enter an OpenKodo API key" }
126
+ try {
127
+ const usage = await fetchUsage(key)
128
+ if (!usage?.plan) throw new Error("OpenKodo usage response was not valid")
129
+ return {
130
+ type: "success",
131
+ key,
132
+ metadata: { plan: usage.plan, email: usage.email },
133
+ }
134
+ } catch (e) {
135
+ return { type: "failed", error: e?.message || "OpenKodo rejected this key" }
136
+ }
137
+ },
138
+ },
139
+ ],
140
+
141
+ async loader(getAuth) {
142
+ const auth = await getAuth()
143
+ const key = keyOf(auth)
144
+ if (!key) return {}
145
+ return { baseURL: BASE, apiKey: key }
146
+ },
147
+
148
+ async usage(getAuth) {
149
+ const auth = await getAuth()
150
+ const key = keyOf(auth)
151
+ if (!key) return { error: "not signed in", signIn: "expired" }
152
+ try {
153
+ const d = await fetchUsage(key)
154
+ // Cents, not raw division: $26.599999999999994 must render as $26.60.
155
+ const usd = (micros) => Math.round(Number(micros || 0) / 10_000) / 100
156
+ const remaining = usd(d.credits_remaining_micros)
157
+ const included = usd(d.credits_included_micros)
158
+ const spent = Math.max(0, included - remaining)
159
+ const used5h = usd(d.cost_5h_micros)
160
+ const cap5h = usd(d.credits_per_5h_micros)
161
+ const used7d = usd(d.cost_7d_micros)
162
+ const cap7d = usd(d.credits_per_week_micros)
163
+ const periodEnd = d.period_end ? new Date(d.period_end).toISOString() : undefined
164
+ // Each window is rolling: the cap frees up when the oldest spend in it
165
+ // ages out. A window with no spend has nothing to expire.
166
+ const rollingReset = (oldest, span) =>
167
+ oldest ? new Date(new Date(oldest).getTime() + span).toISOString() : undefined
168
+ return {
169
+ plan: d.plan,
170
+ user: d.email,
171
+ windows: [
172
+ ...(cap5h > 0
173
+ ? [{
174
+ name: "5 hours",
175
+ used: used5h,
176
+ limit: cap5h,
177
+ span: FIVE_HOURS,
178
+ display: `$${used5h.toFixed(2)} / $${cap5h.toFixed(2)}`,
179
+ ...(rollingReset(d.oldest_5h, FIVE_HOURS) ? { resetsAt: rollingReset(d.oldest_5h, FIVE_HOURS) } : {}),
180
+ }]
181
+ : []),
182
+ ...(cap7d > 0
183
+ ? [{
184
+ name: "7 days",
185
+ used: used7d,
186
+ limit: cap7d,
187
+ span: SEVEN_DAYS,
188
+ display: `$${used7d.toFixed(2)} / $${cap7d.toFixed(2)}`,
189
+ ...(rollingReset(d.oldest_7d, SEVEN_DAYS) ? { resetsAt: rollingReset(d.oldest_7d, SEVEN_DAYS) } : {}),
190
+ }]
191
+ : []),
192
+ {
193
+ name: "Month",
194
+ used: spent,
195
+ limit: included,
196
+ // Welcome-credit accounts have no plan pool, so "left of $0.00"
197
+ // would be nonsense. Show what they actually have.
198
+ display: included > 0
199
+ ? `$${remaining.toFixed(2)} left of $${included.toFixed(2)}`
200
+ : `$${remaining.toFixed(2)} remaining`,
201
+ ...(periodEnd ? { resetsAt: periodEnd } : {}),
202
+ },
203
+ {
204
+ name: d.model_window?.model ? `Requests / 5h · ${d.model_window.model}` : "Requests / 5h",
205
+ used: Number(d.model_window?.used ?? d.requests_5h ?? 0),
206
+ limit: Number(d.model_window?.limit ?? d.requests_limit_5h ?? 0),
207
+ display: `${Number(d.model_window?.used ?? d.requests_5h ?? 0).toLocaleString()} / ${Number(d.model_window?.limit ?? d.requests_limit_5h ?? 0).toLocaleString()}`,
208
+ span: FIVE_HOURS,
209
+ },
210
+ ],
211
+ }
212
+ } catch (e) {
213
+ return { error: e?.message || "OpenKodo usage unavailable", signIn: e?.status === 401 ? "expired" : "kept" }
214
+ }
215
+ },
216
+ },
217
+ })
218
+
219
+ export default OpenKodoAuthPlugin
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "openkodo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "magpie": {
4
+ "name": "OpenKodo",
5
+ "summary": {
6
+ "en": "OpenKodo: plans, credits and usage windows",
7
+ "zh": "OpenKodo:套餐、额度与用量窗口"
8
+ }
9
+ },
10
+ "version": "0.2.3",
11
+ "description": "OpenKodo plans, credits, usage windows, and models in OpenCode and magpie",
12
+ "type": "module",
13
+ "main": "./v1.mjs",
14
+ "exports": {
15
+ ".": "./v2.mjs",
16
+ "./plugin": "./v1.mjs"
17
+ },
18
+ "files": [
19
+ "index.mjs",
20
+ "v1.mjs",
21
+ "v2.mjs",
22
+ "README.md",
23
+ "CHANGELOG.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "test": "node --test test/*.test.mjs",
28
+ "pack:check": "npm pack --dry-run"
29
+ },
30
+ "keywords": [
31
+ "openkodo",
32
+ "magpie",
33
+ "opencode-plugin",
34
+ "deepseek",
35
+ "glm",
36
+ "credits",
37
+ "usage",
38
+ "provider",
39
+ "auth"
40
+ ],
41
+ "homepage": "https://openkodo.dev",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/OpenKodo/openkodo.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/OpenKodo/openkodo/issues"
48
+ },
49
+ "engines": {
50
+ "node": ">=18"
51
+ },
52
+ "license": "MIT"
53
+ }
package/v1.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export { OpenKodoAuthPlugin } from "./index.mjs"
2
+ export { OpenKodoAuthPlugin as default } from "./index.mjs"
package/v2.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // v2 host entry point (OpenCode 2.x / magpie).
2
+ //
3
+ // Those hosts load the package's `exports["."]` and require its default to be
4
+ // { id, setup(ctx) }. The 1.x plugin in ./index.mjs is a function returning
5
+ // { config, provider, auth }, which 1.x understands but 2.x does not. This file
6
+ // adapts one to the other: it runs the 1.x plugin against the host context,
7
+ // publishes the provider (id, name, npm package, base URL, models, and the
8
+ // sign-in method) and routes requests through the credential the user stored.
9
+ //
10
+ // Only what 2.x can actually act on is forwarded. Chat hooks that need a
11
+ // session, plus magpie's usage card, are 1.x-only and stay there.
12
+
13
+ import * as v1 from "./index.mjs"
14
+
15
+ const ID = "openkodo"
16
+ const BASE = "https://api.openkodo.dev/v1"
17
+
18
+ const readKey = (auth) => String(auth?.key ?? auth?.access ?? "").trim()
19
+
20
+ const methodsOf = (plugin) => plugin?.auth?.methods ?? []
21
+ const loaderOf = (plugin) => plugin?.auth?.loader
22
+ const modelsOf = async (plugin, provider) => {
23
+ try {
24
+ const models = await plugin?.provider?.models?.(provider)
25
+ if (models && Object.keys(models).length) return models
26
+ } catch {}
27
+ return provider?.models ?? {}
28
+ }
29
+
30
+ export async function setup(ctx) {
31
+ const plugin = await (v1.OpenKodoAuthPlugin ?? v1.default)()
32
+ const provider = plugin?.provider ?? {}
33
+ const authCfg = plugin?.auth ?? {}
34
+
35
+ // 2.x builds the SDK from this provider record.
36
+ const record = {
37
+ id: ID,
38
+ name: "OpenKodo",
39
+ icon: "https://openkodo.dev/favicon.svg",
40
+ npm: "@ai-sdk/openai-compatible",
41
+ api: BASE,
42
+ models: await modelsOf(plugin, provider),
43
+ auth: { type: "api" },
44
+ }
45
+
46
+ // Let the 1.x plugin widen the config the way it does for OpenCode 1.x.
47
+ try {
48
+ const cfg = { provider: { [ID]: record } }
49
+ await plugin?.config?.(cfg)
50
+ await ctx?.provider?.set?.(cfg.provider[ID] ?? record)
51
+ } catch (e) {
52
+ console.error(`${ID}: provider setup failed: ${e?.message ?? e}`)
53
+ }
54
+
55
+ // Publish the sign-in method: paste an API key, validated against the API.
56
+ const method = methodsOf(plugin)[0]
57
+ if (method && ctx?.auth?.method) {
58
+ try {
59
+ await ctx.auth.method({
60
+ id: `${ID}-key`,
61
+ provider: ID,
62
+ label: method.label ?? "OpenKodo API key",
63
+ type: "api",
64
+ async authorize(inputs) {
65
+ const key = String(inputs?.apiKey ?? inputs?.key ?? "").trim()
66
+ if (!key.startsWith("ok_live_")) return { type: "failed", error: "Enter an OpenKodo API key" }
67
+ const result = await method.authorize({ ...inputs, apiKey: key })
68
+ if (result?.type !== "success") return result
69
+ return { type: "success", key, metadata: { ...(result.metadata ?? {}), provider: ID } }
70
+ },
71
+ })
72
+ } catch (e) {
73
+ console.error(`${ID}: auth method failed: ${e?.message ?? e}`)
74
+ }
75
+ }
76
+
77
+ // Per-request credentials: the stored key, on our base URL.
78
+ const loader = loaderOf(plugin)
79
+ if (ctx?.fetch && loader) {
80
+ try {
81
+ const result = await loader(async () => ctx.auth?.get?.())
82
+ if (result?.baseURL) record.api = result.baseURL
83
+ } catch {}
84
+ }
85
+ if (ctx?.auth) {
86
+ ctx.auth.provider?.(ID, {
87
+ async loader() {
88
+ const auth = await ctx.auth.get?.()
89
+ const key = readKey(auth)
90
+ if (!key && loader) return loader(async () => auth)
91
+ return key ? { baseURL: BASE, apiKey: key } : {}
92
+ },
93
+ })
94
+ }
95
+ }
96
+
97
+ export default { id: ID, setup }