-
Notifications
You must be signed in to change notification settings - Fork 216
Feat/crofai plugin #460
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
briepala
wants to merge
4
commits into
robinebers:main
Choose a base branch
from
briepala:feat/crofai-plugin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/crofai plugin #460
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
529bb1e
feat: add Crof.AI plugin with per-model token usage and plan tracking
briepala 80fa650
fix(crofai): use requests_plan from usage API as progress bar fallback
briepala 8d18e14
fix(crofai): omit negative credits, add extensive test suite
briepala ea4562b
fix(crofai): type-check per-model token values before aggregation
briepala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| # Crof.AI | ||
|
|
||
| > Uses the Crof.AI API to display usage, credits, plan info, and per-model token breakdown. | ||
|
|
||
| ## Overview | ||
|
|
||
| - **Source of truth:** `https://crof.ai/usage_api/`, `https://crof.ai/pricing_api`, `https://crof.ai/user-api/usage` | ||
| - **Auth:** API key (required) + session key (optional, for plan + model breakdown) | ||
| - **Provider ID:** `crofai` | ||
| - **Usage scope:** requests, credits, plan limits, per-model token usage | ||
|
|
||
| ## Setup | ||
|
|
||
| ### Required: API key | ||
|
|
||
| Open [crof.ai/usage_api/](https://crof.ai/usage_api/) while logged in. Copy your API key, then add to your shell config (`~/.zshrc`): | ||
|
|
||
| ```sh | ||
| export CROF_AI_API_KEY="your-api-key-here" | ||
| ``` | ||
|
|
||
| Then `source ~/.zshrc` and restart OpenUsage. | ||
|
|
||
| ### Optional: Session key | ||
|
|
||
| For progress bar (max requests from pricing) and per-model token breakdown, also set: | ||
|
|
||
| ```sh | ||
| export CROF_AI_SESSION_KEY="your-session-cookie-value" | ||
| ``` | ||
|
|
||
| Get it from [crof.ai](https://crof.ai) > DevTools > Application > Cookies > copy the `session` value. | ||
|
|
||
| Or save it to `{appDataDir}/plugins_data/crofai/session-key` (env var takes priority). | ||
|
|
||
| ## Data Sources | ||
|
|
||
| | Endpoint | Auth | Purpose | | ||
| |---|---|---| | ||
| | `GET /usage_api/` | `Authorization: Bearer <API_KEY>` | Requests + credits (required) | | ||
| | `GET /pricing_api` | `Cookie: session=<SESSION_KEY>` | Plan name + max requests (optional) | | ||
| | `GET /user-api/usage` | `Cookie: session=<SESSION_KEY>` | Per-model token breakdown (optional) | | ||
|
|
||
| ## Display | ||
|
|
||
| - **Status badge:** Connected (green) when API responds | ||
| - **Usage progress bar:** Used requests / plan max (shown when both API key + session key available) | ||
| - **Credits:** Dollar-formatted credit balance | ||
| - **Total tokens:** Sum of all models' tokens (shown only with session key) | ||
| - **Top models:** Top 5 models sorted by token usage (shown only with session key) | ||
|
|
||
| ## Failure Behavior | ||
|
|
||
| - **Missing API key:** Error asking to set `CROF_AI_API_KEY` | ||
| - **401/403 on usage_api:** API key invalid or expired | ||
| - **Bad session key:** Only session-backed features drop out, API key data still shows |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,276 @@ | ||
| (function () { | ||
| var PROVIDER_ID = "crofai"; | ||
| var USAGE_API_URL = "https://crof.ai/usage_api/"; | ||
| var USER_USAGE_URL = "https://crof.ai/user-api/usage"; | ||
| var PRICING_URL = "https://crof.ai/pricing_api"; | ||
| var TIMEOUT_MS = 10000; | ||
| var MAX_DISPLAY_MODELS = 5; | ||
|
|
||
| var PLAN_NAMES = { | ||
| hobby: "Hobby", | ||
| pro: "Pro", | ||
| int: "Intermediate", | ||
| scale: "Scale", | ||
| max: "Max", | ||
| }; | ||
| var FALLBACK_MAX_REQUESTS = 15000; | ||
|
|
||
| function readApiKey(ctx) { | ||
| var raw = ctx.host.env.get("CROF_AI_API_KEY"); | ||
| if (typeof raw === "string" && raw.trim()) { | ||
| return raw.trim(); | ||
| } | ||
| throw ( | ||
| "Crof.AI not configured. Set CROF_AI_API_KEY env var.\n" + | ||
| "Get your API key from https://crof.ai/usage_api/" | ||
| ); | ||
| } | ||
|
|
||
| function readSessionKey(ctx) { | ||
| var raw = ctx.host.env.get("CROF_AI_SESSION_KEY"); | ||
| if (typeof raw === "string" && raw.trim()) { | ||
| return raw.trim(); | ||
| } | ||
|
|
||
| var keyPath = ctx.app.pluginDataDir + "/session-key"; | ||
| if (!ctx.host.fs.exists(keyPath)) { | ||
| return null; | ||
| } | ||
| try { | ||
| var key = ctx.host.fs.readText(keyPath).trim(); | ||
| return key || null; | ||
| } catch (e) { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| function requestJson(ctx, opts) { | ||
| var resp; | ||
| try { | ||
| resp = ctx.host.http.request({ | ||
| method: "GET", | ||
| url: opts.url, | ||
| headers: opts.headers || {}, | ||
| Accept: "application/json", | ||
| timeoutMs: TIMEOUT_MS, | ||
| }); | ||
| } catch (e) { | ||
| throw "Crof.AI network error. Check your connection."; | ||
| } | ||
|
|
||
| if (resp.status === 401 || resp.status === 403) { | ||
| throw "Crof.AI auth expired. Check your API key or session key."; | ||
| } | ||
|
|
||
| if (resp.status !== 200) { | ||
| throw "Crof.AI API error (HTTP " + resp.status + "). Try again later."; | ||
| } | ||
|
|
||
| var parsed = ctx.util.tryParseJson(resp.bodyText); | ||
| if (parsed === null) { | ||
| throw "Invalid response from Crof.AI. Try again later."; | ||
| } | ||
| return parsed; | ||
| } | ||
|
|
||
| function planFullName(raw) { | ||
| if (!raw) return null; | ||
| var lower = String(raw).toLowerCase().trim(); | ||
| return PLAN_NAMES[lower] || null; | ||
| } | ||
|
|
||
| function formatTokens(count) { | ||
| if (count >= 1e9) { | ||
| var b = count / 1e9; | ||
| return (Math.round(b * 10) / 10).toFixed(1) + "B"; | ||
| } | ||
| if (count >= 1e6) { | ||
| var m = count / 1e6; | ||
| return (Math.round(m * 10) / 10).toFixed(1) + "M"; | ||
| } | ||
| if (count >= 1e3) { | ||
| var k = count / 1e3; | ||
| return (Math.round(k * 10) / 10).toFixed(1) + "K"; | ||
| } | ||
| return String(count); | ||
| } | ||
|
|
||
| function formatCredits(raw) { | ||
| var num = Number(raw); | ||
| if (!Number.isFinite(num)) return "$0.00"; | ||
| var abs = Math.abs(num); | ||
| if (abs < 0.01) return "$0.00"; | ||
| var sign = num < 0 ? "-" : ""; | ||
| return sign + "$" + abs.toFixed(2); | ||
| } | ||
|
|
||
| function buildLines(ctx, usageData, requestsCount, creditsValue, planInfo, usagePlanRequests) { | ||
| var lines = []; | ||
|
|
||
| var maxRequests = FALLBACK_MAX_REQUESTS; | ||
| if ( | ||
| planInfo && | ||
| typeof planInfo.requests === "number" && | ||
| planInfo.requests > 0 | ||
| ) { | ||
| maxRequests = planInfo.requests; | ||
| } else if ( | ||
| typeof usagePlanRequests === "number" && | ||
| Number.isFinite(usagePlanRequests) && | ||
| usagePlanRequests > 0 | ||
| ) { | ||
| maxRequests = usagePlanRequests; | ||
| } | ||
|
|
||
| var used = 0; | ||
| if (requestsCount !== null) { | ||
| used = maxRequests - requestsCount; | ||
| if (used < 0) used = 0; | ||
| } | ||
|
|
||
| lines.push( | ||
| ctx.line.progress({ | ||
| label: "Requests", | ||
| used: used, | ||
| limit: maxRequests, | ||
| format: { kind: "count", suffix: "requests" }, | ||
| }) | ||
| ); | ||
|
|
||
| if (creditsValue >= 0) { | ||
| lines.push( | ||
| ctx.line.text({ | ||
| label: "Credits", | ||
| value: formatCredits(creditsValue), | ||
| }) | ||
| ); | ||
| } | ||
|
|
||
| var models = []; | ||
| var totalTokens = 0; | ||
|
|
||
| if (usageData && typeof usageData === "object") { | ||
| for (var key in usageData) { | ||
| if (Object.prototype.hasOwnProperty.call(usageData, key)) { | ||
| var model = usageData[key]; | ||
| var tt = model.total_tokens || model.totalTokens || 0; | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Outdated
|
||
| if (tt > 0) { | ||
| totalTokens += tt; | ||
| models.push({ name: key, tokens: tt }); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| lines.push( | ||
| ctx.line.text({ | ||
| label: "Total tokens", | ||
| value: formatTokens(totalTokens), | ||
| subtitle: models.length > 0 ? models.length + " models" : undefined, | ||
| }) | ||
| ); | ||
|
|
||
| models.sort(function (a, b) { | ||
| return b.tokens - a.tokens; | ||
| }); | ||
|
|
||
| var topModels = models.slice(0, MAX_DISPLAY_MODELS); | ||
| for (var i = 0; i < topModels.length; i++) { | ||
| var m = topModels[i]; | ||
| lines.push( | ||
| ctx.line.text({ | ||
| label: m.name, | ||
| value: formatTokens(m.tokens) + " tokens", | ||
| }) | ||
| ); | ||
| } | ||
|
|
||
| return lines; | ||
| } | ||
|
|
||
| function probe(ctx) { | ||
| var apiKey = readApiKey(ctx); | ||
|
|
||
| var usageResp = requestJson(ctx, { | ||
| url: USAGE_API_URL, | ||
| headers: { | ||
| Authorization: "Bearer " + apiKey, | ||
| }, | ||
| }); | ||
|
|
||
| if (!usageResp || typeof usageResp !== "object" || Array.isArray(usageResp)) { | ||
| throw "Invalid response from Crof.AI. Try again later."; | ||
| } | ||
|
|
||
| var hasCredits = "credits" in usageResp; | ||
| var creditsValue = 0; | ||
| if (hasCredits) { | ||
| if (typeof usageResp.credits !== "number" || !Number.isFinite(usageResp.credits)) { | ||
| throw "Invalid response from Crof.AI. Try again later."; | ||
| } | ||
| creditsValue = usageResp.credits; | ||
| } | ||
|
|
||
| var requestsCount = null; | ||
| var hasRequests = "usable_requests" in usageResp; | ||
| if (hasRequests) { | ||
| if (usageResp.usable_requests !== null) { | ||
| if (typeof usageResp.usable_requests !== "number" || !Number.isFinite(usageResp.usable_requests)) { | ||
| throw "Invalid response from Crof.AI. Try again later."; | ||
| } | ||
| requestsCount = usageResp.usable_requests; | ||
| } | ||
| } | ||
|
|
||
| var usagePlanRequests = null; | ||
| if ("requests_plan" in usageResp) { | ||
| if ( | ||
| typeof usageResp.requests_plan === "number" && | ||
| Number.isFinite(usageResp.requests_plan) && | ||
| usageResp.requests_plan > 0 | ||
| ) { | ||
| usagePlanRequests = usageResp.requests_plan; | ||
| } | ||
| } | ||
|
|
||
| var sessionKey = readSessionKey(ctx); | ||
|
|
||
| var userUsageData = null; | ||
| var planInfo = null; | ||
| var planName = null; | ||
|
|
||
| if (sessionKey) { | ||
| try { | ||
| userUsageData = requestJson(ctx, { | ||
| url: USER_USAGE_URL, | ||
| headers: { | ||
| Cookie: "session=" + sessionKey, | ||
| }, | ||
| }); | ||
| } catch (e) { | ||
| ctx.host.log.warn("Crof.AI user usage fetch failed: " + String(e)); | ||
| } | ||
|
|
||
| try { | ||
| planInfo = requestJson(ctx, { | ||
| url: PRICING_URL, | ||
| headers: { | ||
| Cookie: "session=" + sessionKey, | ||
| }, | ||
| }); | ||
| if (planInfo && planInfo.name) { | ||
| planName = planFullName(planInfo.name) || ctx.fmt.planLabel(planInfo.name); | ||
| } | ||
| } catch (e) { | ||
| ctx.host.log.warn("Crof.AI pricing fetch failed: " + String(e)); | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| plan: planName, | ||
| lines: buildLines(ctx, userUsageData, requestsCount, creditsValue, planInfo, usagePlanRequests), | ||
| }; | ||
| } | ||
|
|
||
| globalThis.__openusage_plugin = { id: PROVIDER_ID, probe }; | ||
| })(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| { | ||
| "schemaVersion": 1, | ||
| "id": "crofai", | ||
| "name": "Crof.AI", | ||
| "version": "0.0.1", | ||
| "entry": "plugin.js", | ||
| "icon": "icon.svg", | ||
| "brandColor": "#6B52F2", | ||
| "links": [ | ||
| { | ||
| "label": "Dashboard", | ||
| "url": "https://crof.ai" | ||
| } | ||
| ], | ||
| "lines": [ | ||
| { "type": "badge", "label": "Status", "scope": "overview" }, | ||
| { "type": "progress", "label": "Requests", "scope": "overview", "primaryOrder": 1 }, | ||
| { "type": "text", "label": "Credits", "scope": "overview" }, | ||
| { "type": "text", "label": "Total tokens", "scope": "overview" }, | ||
| { "type": "text", "label": "Models", "scope": "detail" } | ||
| ] | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
Acceptvalue is set at the top level of the request object, not insideheaders, so it is not forwarded by the host HTTP wrapper (which serializes onlyreq.headers). If Crof.AI enforces content negotiation, this can return non-JSON content and trigger the plugin's "Invalid response" path even with valid credentials.Useful? React with 👍 / 👎.