openkodo 0.0.0-stage → 0.3.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/CHANGELOG.md +47 -0
- package/LICENSE +21 -0
- package/README.md +55 -2
- package/index.mjs +333 -0
- package/package.json +52 -4
- package/v1.mjs +2 -0
- package/v2.mjs +101 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package. Versioned independently of the OpenKodo
|
|
4
|
+
gateway.
|
|
5
|
+
|
|
6
|
+
## 0.3.0
|
|
7
|
+
|
|
8
|
+
- Show the reasoning levels each model declares in `GET /v1/models`
|
|
9
|
+
(`low`/`medium`/`high`/`max`, and `none` where the model offers an off
|
|
10
|
+
switch) instead of dropping `reasoning.efforts`.
|
|
11
|
+
- Merge the authenticated descriptor with the public catalog so names, limits
|
|
12
|
+
and prices stay available.
|
|
13
|
+
- Move model limits into the `limit: { context, output }` shape Magpie reads,
|
|
14
|
+
while keeping the older top-level fields for OpenCode 1.x.
|
|
15
|
+
- Fix usage windows: `used` is now a percentage, `amount` is the used value,
|
|
16
|
+
`limit` is the cap, `unit` is `USD` or `requests`, and `span` is seconds.
|
|
17
|
+
- Rename the public repository to **OpenKodo Magpie Plugin**; the Magpie row
|
|
18
|
+
still displays **OpenKodo**.
|
|
19
|
+
|
|
20
|
+
## 0.2.3
|
|
21
|
+
|
|
22
|
+
- First public release on npm as `openkodo`.
|
|
23
|
+
- Title the plugin **OpenKodo** through `magpie.name`, which is what magpie
|
|
24
|
+
reads for a package's own row (the npm name must stay lowercase).
|
|
25
|
+
|
|
26
|
+
## 0.2.2
|
|
27
|
+
|
|
28
|
+
- Declare the provider icon on `auth`, which is where magpie reads it. 0.2.1
|
|
29
|
+
set it on the config record, so the card kept the generic provider box.
|
|
30
|
+
|
|
31
|
+
## 0.2.1
|
|
32
|
+
|
|
33
|
+
- Show 5-hour, 7-day, and monthly windows together, each with its reset time.
|
|
34
|
+
- Add the OpenKodo provider icon.
|
|
35
|
+
- Format money in cents so floating-point noise never reaches the card.
|
|
36
|
+
|
|
37
|
+
## 0.1.1
|
|
38
|
+
|
|
39
|
+
- Show the per-model five-hour request window the account is closest to
|
|
40
|
+
filling, instead of the plan-wide anti-abuse counter.
|
|
41
|
+
|
|
42
|
+
# Changelog
|
|
43
|
+
|
|
44
|
+
## 0.1.0
|
|
45
|
+
|
|
46
|
+
- Initial OpenKodo provider for OpenCode and magpie.
|
|
47
|
+
- 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,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OpenKodo Magpie Plugin
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
- Thinking levels for every model that declares them, taken from the
|
|
14
|
+
authenticated `GET /v1/models` descriptor
|
|
15
|
+
- The live catalog from [`/api/public/models`](https://api.openkodo.dev/api/public/models)
|
|
16
|
+
|
|
17
|
+
The 5-hour and 7-day windows are enforced by the gateway, not decoration:
|
|
18
|
+
Go is $25 / 5h and $50 / 7d, Pro is $50 / 5h and $100 / 7d. Reset times are
|
|
19
|
+
rolling — the cap frees up when the oldest spend in the window ages out — so
|
|
20
|
+
they move as new requests arrive.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
From the magpie plugin store, search for **OpenKodo**.
|
|
25
|
+
|
|
26
|
+
From a checkout:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm add openkodo
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Sign in
|
|
33
|
+
|
|
34
|
+
Paste an OpenKodo API key from **Console → API keys**. Keys start with
|
|
35
|
+
`ok_live_`. The plugin validates the key against
|
|
36
|
+
`https://api.openkodo.dev/api/plugin/usage`; it never stores anything except
|
|
37
|
+
the key itself, and it never creates keys, changes plans, or spends credits.
|
|
38
|
+
|
|
39
|
+
## Provider
|
|
40
|
+
|
|
41
|
+
- Base URL: `https://api.openkodo.dev/v1`
|
|
42
|
+
- SDK: `@ai-sdk/openai-compatible`
|
|
43
|
+
- Models: fetched live, with a bundled fallback for offline starts
|
|
44
|
+
|
|
45
|
+
## Development
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npm test # unit tests, no network
|
|
49
|
+
npm run pack:check # what would be published
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The tests stub `fetch`, so they never use a real API key.
|
|
53
|
+
|
|
54
|
+
## License
|
|
55
|
+
|
|
56
|
+
[MIT](./LICENSE)
|
package/index.mjs
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
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 model catalogs are 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, efforts: ["none", "low", "high", "max"] },
|
|
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, efforts: ["none", "low", "high", "max"] },
|
|
23
|
+
"glm-5.3": { name: "GLM-5.3", context: 1_000_000, output: 131_072, input: 1.4, outputPrice: 4.4, cache: 0.26, efforts: ["low", "medium", "high"] },
|
|
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, efforts: ["low", "medium", "high"] },
|
|
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 effortsOf = (m) => {
|
|
31
|
+
const list = m?.reasoning?.efforts ?? m?.reasoning_efforts
|
|
32
|
+
return Array.isArray(list) ? list.map(String).filter(Boolean) : []
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Magpie turns each variant into an OpenCode reasoning level. "none" is a
|
|
36
|
+
// real level for the DeepSeek models, so it stays in the list: selecting it
|
|
37
|
+
// is the off switch.
|
|
38
|
+
const variantsOf = (efforts) =>
|
|
39
|
+
Object.fromEntries(efforts.map((effort) => [effort, { reasoningEffort: effort }]))
|
|
40
|
+
|
|
41
|
+
const modalitiesOf = (m) => {
|
|
42
|
+
const input = m?.architecture?.input_modalities
|
|
43
|
+
return Array.isArray(input) && input.length ? input.map(String) : ["text"]
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const modelRecord = ({ name, context, output, input, outputPrice, cache, efforts, inputModalities, reasoning }) => {
|
|
47
|
+
const levels = efforts ?? []
|
|
48
|
+
const thinks = reasoning ?? levels.length > 0
|
|
49
|
+
return {
|
|
50
|
+
name,
|
|
51
|
+
limit: { context: context || 1_000_000, output: output || 131_072 },
|
|
52
|
+
cost: { input, output: outputPrice, cache: { read: cache } },
|
|
53
|
+
tool_call: true,
|
|
54
|
+
attachment: inputModalities.includes("image"),
|
|
55
|
+
modalities: { input: inputModalities.length ? inputModalities : ["text"], output: ["text"] },
|
|
56
|
+
// OpenCode reads `reasoning`/`variants`; magpie's internalOf folds them
|
|
57
|
+
// into capabilities.reasoning. Both hosts then see the same levels.
|
|
58
|
+
...(thinks ? { reasoning: true } : {}),
|
|
59
|
+
...(levels.length ? { variants: variantsOf(levels) } : {}),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const fallbackModels = () =>
|
|
64
|
+
Object.fromEntries(
|
|
65
|
+
Object.entries(FALLBACK).map(([id, m]) => [
|
|
66
|
+
id,
|
|
67
|
+
modelRecord({
|
|
68
|
+
name: m.name,
|
|
69
|
+
context: m.context,
|
|
70
|
+
output: m.output,
|
|
71
|
+
input: m.input,
|
|
72
|
+
outputPrice: m.outputPrice,
|
|
73
|
+
cache: m.cache,
|
|
74
|
+
efforts: m.efforts,
|
|
75
|
+
inputModalities: ["text"],
|
|
76
|
+
}),
|
|
77
|
+
]),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
const keyOf = (auth) => String(auth?.key ?? auth?.access ?? "").trim()
|
|
81
|
+
|
|
82
|
+
async function fetchUsage(key) {
|
|
83
|
+
const res = await fetch(USAGE, {
|
|
84
|
+
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
85
|
+
})
|
|
86
|
+
const body = await res.json().catch(() => ({}))
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
const error = new Error(body?.error?.message || `OpenKodo usage failed (${res.status})`)
|
|
89
|
+
error.status = res.status
|
|
90
|
+
throw error
|
|
91
|
+
}
|
|
92
|
+
return body
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function fetchModelList(url, headers, signal) {
|
|
96
|
+
const res = await fetch(url, { headers, signal })
|
|
97
|
+
if (!res.ok) throw new Error(`OpenKodo model list failed (${res.status})`)
|
|
98
|
+
const body = await res.json()
|
|
99
|
+
const models = body?.data ?? body?.models
|
|
100
|
+
if (!Array.isArray(models)) throw new Error("OpenKodo model list was not valid")
|
|
101
|
+
return models.filter(m => typeof (m?.code || m?.id) === "string" && (m.code || m.id).trim())
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function fetchModels(key, signal) {
|
|
105
|
+
// The account list supplies efforts and available IDs. The public catalog
|
|
106
|
+
// supplies prices and limits even when /v1/models only gives descriptors.
|
|
107
|
+
const [accountResult, publicResult] = await Promise.allSettled([
|
|
108
|
+
key
|
|
109
|
+
? fetchModelList(`${BASE}/models`, { Authorization: `Bearer ${key}`, Accept: "application/json" }, signal)
|
|
110
|
+
: Promise.resolve([]),
|
|
111
|
+
fetchModelList(PUBLIC_MODELS, { Accept: "application/json" }, signal),
|
|
112
|
+
])
|
|
113
|
+
const account = accountResult.status === "fulfilled" ? accountResult.value : []
|
|
114
|
+
const catalog = publicResult.status === "fulfilled" ? publicResult.value : []
|
|
115
|
+
const byID = new Map(catalog.map(m => [m.code || m.id, m]))
|
|
116
|
+
const models = account.length ? account : catalog
|
|
117
|
+
if (!models.length) throw new Error("OpenKodo model list was empty or unavailable")
|
|
118
|
+
const out = {}
|
|
119
|
+
for (const descriptor of models) {
|
|
120
|
+
const id = descriptor.code || descriptor.id
|
|
121
|
+
const m = { ...byID.get(id), ...descriptor }
|
|
122
|
+
const declared = m.reasoning?.efforts ?? m.reasoning_efforts
|
|
123
|
+
const efforts = Array.isArray(declared) ? [...new Set(declared.filter(e => typeof e === "string" && e.trim()))] : []
|
|
124
|
+
const reasoning = efforts.length > 0 || m.reasoning === true || m.reasoning?.supported === true
|
|
125
|
+
|| m.capabilities?.reasoning === true || (Array.isArray(m.capabilities) && m.capabilities.includes("reasoning"))
|
|
126
|
+
// `limit` is the shape OpenCode/Magpie read. Keep context/output at the
|
|
127
|
+
// top level too: older OpenCode hosts read those.
|
|
128
|
+
const context = m.context_length ?? m.limit?.context ?? m.context_window ?? 1_000_000
|
|
129
|
+
const output = m.max_completion_tokens ?? m.max_output_tokens ?? m.limit?.output ?? m.max_output ?? 131_072
|
|
130
|
+
const inputModalities = modalitiesOf(m)
|
|
131
|
+
out[id] = {
|
|
132
|
+
name: m.name || id,
|
|
133
|
+
context,
|
|
134
|
+
output,
|
|
135
|
+
limit: { context, output },
|
|
136
|
+
// Config readers use the top-level flag. Model hooks use capabilities.
|
|
137
|
+
reasoning,
|
|
138
|
+
capabilities: {
|
|
139
|
+
reasoning,
|
|
140
|
+
toolcall: true,
|
|
141
|
+
attachment: inputModalities.includes("image"),
|
|
142
|
+
input: Object.fromEntries(["text", "image", "audio", "video", "pdf"].map((k) => [k, inputModalities.includes(k)])),
|
|
143
|
+
output: { text: true, image: false, audio: false, video: false, pdf: false },
|
|
144
|
+
},
|
|
145
|
+
modalities: { input: inputModalities, output: ["text"] },
|
|
146
|
+
tool_call: true,
|
|
147
|
+
attachment: inputModalities.includes("image"),
|
|
148
|
+
...(efforts.length ? { variants: variantsOf(efforts) } : {}),
|
|
149
|
+
cost: {
|
|
150
|
+
// Show the standard (off-peak) rate the gateway charges most of the
|
|
151
|
+
// day, not the peak rate stored in the primary columns.
|
|
152
|
+
input: Number(m.offpeak_input_price_micros_per_mtok || m.input_price_micros_per_mtok || 0) / 1_000_000,
|
|
153
|
+
output: Number(m.offpeak_output_price_micros_per_mtok || m.output_price_micros_per_mtok || 0) / 1_000_000,
|
|
154
|
+
cache: { read: Number(m.offpeak_cached_input_price_micros_per_mtok || m.cached_input_price_micros_per_mtok || 0) / 1_000_000 },
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return Object.keys(out).length ? out : fallbackModels()
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export const OpenKodoAuthPlugin = async () => {
|
|
163
|
+
// The last key the host validated. provider.models() has no credential
|
|
164
|
+
// argument, so this is what lets it read the authenticated descriptor (the
|
|
165
|
+
// only source that carries reasoning.efforts) instead of the public
|
|
166
|
+
// catalog. Per plugin instance, so tests and hosts never share a key.
|
|
167
|
+
let sessionKey = ""
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
config: async (cfg) => {
|
|
171
|
+
cfg.provider ??= {}
|
|
172
|
+
const p = (cfg.provider[ID] ??= {})
|
|
173
|
+
p.name ??= "OpenKodo"
|
|
174
|
+
p.icon ??= ICON
|
|
175
|
+
p.npm ??= "@ai-sdk/openai-compatible"
|
|
176
|
+
p.api ??= BASE
|
|
177
|
+
p.models = { ...fallbackModels(), ...(p.models ?? {}) }
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
provider: {
|
|
181
|
+
id: ID,
|
|
182
|
+
async models(provider, { auth, signal } = {}) {
|
|
183
|
+
try {
|
|
184
|
+
return await fetchModels(keyOf(auth) || sessionKey, signal)
|
|
185
|
+
} catch {
|
|
186
|
+
return provider?.models && Object.keys(provider.models).length ? provider.models : fallbackModels()
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
auth: {
|
|
192
|
+
provider: ID,
|
|
193
|
+
// magpie reads the provider mark from auth.icon, not from config.provider.
|
|
194
|
+
// Declaring it here is what turns the generic provider box into our logo.
|
|
195
|
+
icon: ICON,
|
|
196
|
+
|
|
197
|
+
methods: [
|
|
198
|
+
{
|
|
199
|
+
type: "api",
|
|
200
|
+
label: "OpenKodo API key",
|
|
201
|
+
keyless: true,
|
|
202
|
+
prompts: [
|
|
203
|
+
{
|
|
204
|
+
type: "password",
|
|
205
|
+
key: "apiKey",
|
|
206
|
+
message: "OpenKodo API key (Console → API keys)",
|
|
207
|
+
placeholder: "ok_live_...",
|
|
208
|
+
validate: (v) => (String(v ?? "").trim().startsWith("ok_live_") ? undefined : "Enter an OpenKodo API key"),
|
|
209
|
+
},
|
|
210
|
+
],
|
|
211
|
+
async authorize(inputs) {
|
|
212
|
+
const key = String(inputs?.apiKey ?? "").trim()
|
|
213
|
+
if (!key.startsWith("ok_live_")) return { type: "failed", error: "Enter an OpenKodo API key" }
|
|
214
|
+
try {
|
|
215
|
+
const usage = await fetchUsage(key)
|
|
216
|
+
if (!usage?.plan) throw new Error("OpenKodo usage response was not valid")
|
|
217
|
+
sessionKey = key
|
|
218
|
+
return {
|
|
219
|
+
type: "success",
|
|
220
|
+
key,
|
|
221
|
+
metadata: { plan: usage.plan, email: usage.email },
|
|
222
|
+
}
|
|
223
|
+
} catch (e) {
|
|
224
|
+
return { type: "failed", error: e?.message || "OpenKodo rejected this key" }
|
|
225
|
+
}
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
],
|
|
229
|
+
|
|
230
|
+
async loader(getAuth) {
|
|
231
|
+
const auth = await getAuth()
|
|
232
|
+
const key = keyOf(auth)
|
|
233
|
+
if (!key) return {}
|
|
234
|
+
sessionKey = key
|
|
235
|
+
return { baseURL: BASE, apiKey: key }
|
|
236
|
+
},
|
|
237
|
+
|
|
238
|
+
async usage(getAuth) {
|
|
239
|
+
const auth = await getAuth()
|
|
240
|
+
const key = keyOf(auth)
|
|
241
|
+
if (!key) return { error: "not signed in", signIn: "expired" }
|
|
242
|
+
try {
|
|
243
|
+
const d = await fetchUsage(key)
|
|
244
|
+
// Cents, not raw division: $26.599999999999994 must render as $26.60.
|
|
245
|
+
const usd = (micros) => Math.round(Number(micros || 0) / 10_000) / 100
|
|
246
|
+
const remaining = usd(d.credits_remaining_micros)
|
|
247
|
+
const included = usd(d.credits_included_micros)
|
|
248
|
+
const spent = Math.max(0, Math.round((included - remaining) * 100) / 100)
|
|
249
|
+
const used5h = usd(d.cost_5h_micros)
|
|
250
|
+
const cap5h = usd(d.credits_per_5h_micros)
|
|
251
|
+
const used7d = usd(d.cost_7d_micros)
|
|
252
|
+
const cap7d = usd(d.credits_per_week_micros)
|
|
253
|
+
const periodEnd = d.period_end ? new Date(d.period_end).toISOString() : undefined
|
|
254
|
+
// Each window is rolling: the cap frees up when the oldest spend in it
|
|
255
|
+
// ages out. A window with no spend has nothing to expire.
|
|
256
|
+
const rollingReset = (oldest, span) =>
|
|
257
|
+
oldest ? new Date(new Date(oldest).getTime() + span).toISOString() : undefined
|
|
258
|
+
|
|
259
|
+
// Magpie's UsageWindow contract: `used` is a 0–100 percentage,
|
|
260
|
+
// `amount` is the used count in the window's unit, `limit` is the
|
|
261
|
+
// cap, and `span` is in seconds. Sending dollars as `used` made the
|
|
262
|
+
// card print "50 / 50" instead of "48.26 / 50".
|
|
263
|
+
const windowOf = (name, amount, limit, unit, extra = {}) => {
|
|
264
|
+
if (!(limit > 0)) return null
|
|
265
|
+
return {
|
|
266
|
+
name,
|
|
267
|
+
used: Math.round(Math.min(100, Math.max(0, (100 * amount) / limit)) * 100) / 100,
|
|
268
|
+
amount,
|
|
269
|
+
limit,
|
|
270
|
+
unit,
|
|
271
|
+
...extra,
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const window5h = cap5h > 0
|
|
275
|
+
? windowOf("5 hours", used5h, cap5h, "USD", {
|
|
276
|
+
span: FIVE_HOURS / 1000,
|
|
277
|
+
display: `$${used5h.toFixed(2)} / $${cap5h.toFixed(2)}`,
|
|
278
|
+
...(rollingReset(d.oldest_5h, FIVE_HOURS) ? { resetsAt: rollingReset(d.oldest_5h, FIVE_HOURS) } : {}),
|
|
279
|
+
})
|
|
280
|
+
: null
|
|
281
|
+
const window7d = cap7d > 0
|
|
282
|
+
? windowOf("7 days", used7d, cap7d, "USD", {
|
|
283
|
+
span: SEVEN_DAYS / 1000,
|
|
284
|
+
display: `$${used7d.toFixed(2)} / $${cap7d.toFixed(2)}`,
|
|
285
|
+
...(rollingReset(d.oldest_7d, SEVEN_DAYS) ? { resetsAt: rollingReset(d.oldest_7d, SEVEN_DAYS) } : {}),
|
|
286
|
+
})
|
|
287
|
+
: null
|
|
288
|
+
const monthWindow = included > 0
|
|
289
|
+
? windowOf("Month", spent, included, "USD", {
|
|
290
|
+
display: `$${remaining.toFixed(2)} left of $${included.toFixed(2)}`,
|
|
291
|
+
...(periodEnd ? { resetsAt: periodEnd } : {}),
|
|
292
|
+
})
|
|
293
|
+
: {
|
|
294
|
+
// Welcome-credit accounts have no plan pool, so a percentage
|
|
295
|
+
// against $0 would be nonsense. Magpie's balance-shaped window
|
|
296
|
+
// says exactly what is left.
|
|
297
|
+
name: "Month",
|
|
298
|
+
balance: remaining,
|
|
299
|
+
unit: "USD",
|
|
300
|
+
display: `$${remaining.toFixed(2)} remaining`,
|
|
301
|
+
}
|
|
302
|
+
const requestUsed = Number(d.model_window?.used ?? d.requests_5h ?? 0)
|
|
303
|
+
const requestLimit = Number(d.model_window?.limit ?? d.requests_limit_5h ?? 0)
|
|
304
|
+
const requestWindow = windowOf(
|
|
305
|
+
d.model_window?.model ? `Requests / 5h · ${d.model_window.model}` : "Requests / 5h",
|
|
306
|
+
requestUsed,
|
|
307
|
+
requestLimit,
|
|
308
|
+
"requests",
|
|
309
|
+
{
|
|
310
|
+
span: FIVE_HOURS / 1000,
|
|
311
|
+
display: `${requestUsed.toLocaleString()} / ${requestLimit.toLocaleString()}`,
|
|
312
|
+
...(d.model_window?.model ? { models: [d.model_window.model] } : {}),
|
|
313
|
+
},
|
|
314
|
+
)
|
|
315
|
+
return {
|
|
316
|
+
plan: d.plan,
|
|
317
|
+
user: d.email,
|
|
318
|
+
windows: [
|
|
319
|
+
...(window5h ? [window5h] : []),
|
|
320
|
+
...(window7d ? [window7d] : []),
|
|
321
|
+
monthWindow,
|
|
322
|
+
...(requestWindow ? [requestWindow] : []),
|
|
323
|
+
].filter(Boolean),
|
|
324
|
+
}
|
|
325
|
+
} catch (e) {
|
|
326
|
+
return { error: e?.message || "OpenKodo usage unavailable", signIn: e?.status === 401 ? "expired" : "kept" }
|
|
327
|
+
}
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export default OpenKodoAuthPlugin
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openkodo",
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
"magpie": {
|
|
4
|
+
"name": "OpenKodo",
|
|
5
|
+
"summary": {
|
|
6
|
+
"en": "OpenKodo: plans, credits and usage windows",
|
|
7
|
+
"zh": "OpenKodo:套餐、额度与用量窗口"
|
|
8
|
+
},
|
|
9
|
+
"icon": "https://openkodo.dev/openkodo-logo.svg"
|
|
10
|
+
},
|
|
11
|
+
"version": "0.3.0",
|
|
12
|
+
"description": "OpenKodo Magpie plugin: plans, credits, usage windows, and models in Magpie and OpenCode",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"main": "./v1.mjs",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./v2.mjs",
|
|
17
|
+
"./plugin": "./v1.mjs"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"index.mjs",
|
|
21
|
+
"v1.mjs",
|
|
22
|
+
"v2.mjs",
|
|
23
|
+
"README.md",
|
|
24
|
+
"CHANGELOG.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "node --test test/*.test.mjs",
|
|
29
|
+
"pack:check": "npm pack --dry-run"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"openkodo",
|
|
33
|
+
"magpie",
|
|
34
|
+
"opencode-plugin",
|
|
35
|
+
"deepseek",
|
|
36
|
+
"glm",
|
|
37
|
+
"credits",
|
|
38
|
+
"usage",
|
|
39
|
+
"provider",
|
|
40
|
+
"auth"
|
|
41
|
+
],
|
|
42
|
+
"homepage": "https://openkodo.dev",
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git+https://github.com/OpenKodo/OpenKodo-magpie-plugin.git"
|
|
46
|
+
},
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/OpenKodo/OpenKodo-magpie-plugin/issues"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=18"
|
|
52
|
+
},
|
|
53
|
+
"license": "MIT"
|
|
54
|
+
}
|
package/v1.mjs
ADDED
package/v2.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
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, ctx) => {
|
|
23
|
+
let auth
|
|
24
|
+
try {
|
|
25
|
+
auth = await ctx?.auth?.get?.()
|
|
26
|
+
} catch {}
|
|
27
|
+
try {
|
|
28
|
+
const models = await plugin?.provider?.models?.(provider, { auth })
|
|
29
|
+
if (models && Object.keys(models).length) return models
|
|
30
|
+
} catch {}
|
|
31
|
+
return provider?.models ?? {}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function setup(ctx) {
|
|
35
|
+
const plugin = await (v1.OpenKodoAuthPlugin ?? v1.default)()
|
|
36
|
+
const provider = plugin?.provider ?? {}
|
|
37
|
+
const authCfg = plugin?.auth ?? {}
|
|
38
|
+
|
|
39
|
+
// 2.x builds the SDK from this provider record.
|
|
40
|
+
const record = {
|
|
41
|
+
id: ID,
|
|
42
|
+
name: "OpenKodo",
|
|
43
|
+
icon: "https://openkodo.dev/favicon.svg",
|
|
44
|
+
npm: "@ai-sdk/openai-compatible",
|
|
45
|
+
api: BASE,
|
|
46
|
+
models: await modelsOf(plugin, provider, ctx),
|
|
47
|
+
auth: { type: "api" },
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Let the 1.x plugin widen the config the way it does for OpenCode 1.x.
|
|
51
|
+
try {
|
|
52
|
+
const cfg = { provider: { [ID]: record } }
|
|
53
|
+
await plugin?.config?.(cfg)
|
|
54
|
+
await ctx?.provider?.set?.(cfg.provider[ID] ?? record)
|
|
55
|
+
} catch (e) {
|
|
56
|
+
console.error(`${ID}: provider setup failed: ${e?.message ?? e}`)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Publish the sign-in method: paste an API key, validated against the API.
|
|
60
|
+
const method = methodsOf(plugin)[0]
|
|
61
|
+
if (method && ctx?.auth?.method) {
|
|
62
|
+
try {
|
|
63
|
+
await ctx.auth.method({
|
|
64
|
+
id: `${ID}-key`,
|
|
65
|
+
provider: ID,
|
|
66
|
+
label: method.label ?? "OpenKodo API key",
|
|
67
|
+
type: "api",
|
|
68
|
+
async authorize(inputs) {
|
|
69
|
+
const key = String(inputs?.apiKey ?? inputs?.key ?? "").trim()
|
|
70
|
+
if (!key.startsWith("ok_live_")) return { type: "failed", error: "Enter an OpenKodo API key" }
|
|
71
|
+
const result = await method.authorize({ ...inputs, apiKey: key })
|
|
72
|
+
if (result?.type !== "success") return result
|
|
73
|
+
return { type: "success", key, metadata: { ...(result.metadata ?? {}), provider: ID } }
|
|
74
|
+
},
|
|
75
|
+
})
|
|
76
|
+
} catch (e) {
|
|
77
|
+
console.error(`${ID}: auth method failed: ${e?.message ?? e}`)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Per-request credentials: the stored key, on our base URL.
|
|
82
|
+
const loader = loaderOf(plugin)
|
|
83
|
+
if (ctx?.fetch && loader) {
|
|
84
|
+
try {
|
|
85
|
+
const result = await loader(async () => ctx.auth?.get?.())
|
|
86
|
+
if (result?.baseURL) record.api = result.baseURL
|
|
87
|
+
} catch {}
|
|
88
|
+
}
|
|
89
|
+
if (ctx?.auth) {
|
|
90
|
+
ctx.auth.provider?.(ID, {
|
|
91
|
+
async loader() {
|
|
92
|
+
const auth = await ctx.auth.get?.()
|
|
93
|
+
const key = readKey(auth)
|
|
94
|
+
if (!key && loader) return loader(async () => auth)
|
|
95
|
+
return key ? { baseURL: BASE, apiKey: key } : {}
|
|
96
|
+
},
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export default { id: ID, setup }
|