iobroker.ai-usage 0.2.0 → 0.4.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/README.md +135 -24
- package/admin/ai-usage.svg +12 -17
- package/admin/custom/assets/Components-Bq1fGAd7.js +1 -0
- package/admin/custom/assets/ConfigPanel-DGMF4_qT.js +1 -0
- package/admin/custom/assets/{_virtual_mf-localSharedImportMap___mfe_internal__AiUsageComponentSet__mf_owner__1-CXmnAfNY.js → _virtual_mf-localSharedImportMap___mfe_internal__AiUsageComponentSet__mf_owner__1-DKcsNxEw.js} +1 -1
- package/admin/custom/assets/{_virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DwHNIjSR.js → _virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DzPBJWNQ.js} +1 -1
- package/admin/custom/assets/{_virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-qu1s07FY.js → _virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-DEdJInQG.js} +3 -3
- package/admin/custom/assets/{_virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-C8-GjKo4.js → _virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-CFn_lBXc.js} +1 -1
- package/admin/custom/assets/{_virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__prebuild___mf_0_iobroker_mf_1_gui_mf_2_components__prebuild__-CQxWwR2r.js → _virtual_mf___mfe_internal__AiUsageComponentSet__mf_owner__1__prebuild___mf_0_iobroker_mf_1_gui_mf_2_components__prebuild__-DeLUTSLT.js} +1 -1
- package/admin/custom/assets/{hostInit-RHMRa462.js → hostInit-DoGxgbHj.js} +1 -1
- package/admin/custom/assets/index-CKngiVu3.js +1 -0
- package/admin/custom/assets/{lib-ByF76TCN.js → lib-MY71LxhX.js} +1 -1
- package/admin/custom/assets/{mf-entry-bootstrap-0-e070fa3e.js → mf-entry-bootstrap-0-eec08a33.js} +2 -2
- package/admin/custom/assets/virtualExposes-Dc9myzsk.js +1 -0
- package/admin/custom/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__AiUsageComponentSet__customComponents_js-l7jtElkM.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__AiUsageComponentSet__customComponents_js-CP4YA3u3.js} +1 -1
- package/admin/custom/assets/virtual_mf-exposes-ssr___mfe_internal__AiUsageComponentSet__customComponents_js-DlNU_Z38.js +2 -0
- package/admin/custom/assets/{virtual_mf-exposes___mfe_internal__AiUsageComponentSet__customComponents_js-BZ-CVpVo.js → virtual_mf-exposes___mfe_internal__AiUsageComponentSet__customComponents_js-CEfffc0D.js} +2 -2
- package/admin/custom/customComponents.js +1 -1
- package/admin/custom/i18n/de.json +24 -15
- package/admin/custom/i18n/en.json +25 -16
- package/admin/custom/i18n/es.json +25 -16
- package/admin/custom/i18n/fr.json +25 -16
- package/admin/custom/i18n/it.json +25 -16
- package/admin/custom/i18n/nl.json +25 -16
- package/admin/custom/i18n/pl.json +25 -16
- package/admin/custom/i18n/pt.json +25 -16
- package/admin/custom/i18n/ru.json +25 -16
- package/admin/custom/i18n/uk.json +25 -16
- package/admin/custom/i18n/zh-cn.json +25 -16
- package/admin/custom/mf-manifest.json +1 -1
- package/build/lib/http.js +33 -4
- package/build/lib/http.js.map +2 -2
- package/build/lib/jwt.js +59 -0
- package/build/lib/jwt.js.map +7 -0
- package/build/lib/poll-engine.js +86 -6
- package/build/lib/poll-engine.js.map +2 -2
- package/build/lib/provider.js.map +2 -2
- package/build/lib/providers/chatgpt-auth.js +125 -0
- package/build/lib/providers/chatgpt-auth.js.map +7 -0
- package/build/lib/providers/chatgpt-sub.js +122 -0
- package/build/lib/providers/chatgpt-sub.js.map +7 -0
- package/build/lib/providers/claude-auth.js.map +2 -2
- package/build/lib/providers/claude-sub.js +9 -5
- package/build/lib/providers/claude-sub.js.map +2 -2
- package/build/lib/providers/gemini-auth.js +135 -0
- package/build/lib/providers/gemini-auth.js.map +7 -0
- package/build/lib/providers/gemini-sub.js +147 -0
- package/build/lib/providers/gemini-sub.js.map +7 -0
- package/build/lib/pure-helpers.js +38 -6
- package/build/lib/pure-helpers.js.map +2 -2
- package/build/lib/sign-in.js +38 -0
- package/build/lib/sign-in.js.map +7 -0
- package/build/lib/snapshot-tree.js +21 -9
- package/build/lib/snapshot-tree.js.map +2 -2
- package/build/main.js +283 -151
- package/build/main.js.map +2 -2
- package/io-package.json +46 -12
- package/package.json +1 -1
- package/admin/custom/assets/Components-Bd545388.js +0 -1
- package/admin/custom/assets/ConfigPanel-qivVprTj.js +0 -1
- package/admin/custom/assets/index-B0J1NbOp.js +0 -1
- package/admin/custom/assets/virtualExposes-BZWQ_oUV.js +0 -1
- package/admin/custom/assets/virtual_mf-exposes-ssr___mfe_internal__AiUsageComponentSet__customComponents_js-CRK-nAdE.js +0 -2
package/build/lib/poll-engine.js
CHANGED
|
@@ -52,7 +52,10 @@ class PollEngine {
|
|
|
52
52
|
skipUntil: 0,
|
|
53
53
|
backoffMs: BACKOFF_START_MS,
|
|
54
54
|
authNotified: false,
|
|
55
|
-
|
|
55
|
+
serviceOnline: false,
|
|
56
|
+
state: "no-connection",
|
|
57
|
+
createdObjects: /* @__PURE__ */ new Set(),
|
|
58
|
+
written: /* @__PURE__ */ new Map()
|
|
56
59
|
});
|
|
57
60
|
}
|
|
58
61
|
}
|
|
@@ -87,6 +90,20 @@ class PollEngine {
|
|
|
87
90
|
get accountIds() {
|
|
88
91
|
return this.runtimes.map((runtime) => runtime.config.id);
|
|
89
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* Poll one account immediately, by id. Used after a successful sign-in: waiting
|
|
95
|
+
* up to a full interval there reads as "the sign-in did not work".
|
|
96
|
+
*
|
|
97
|
+
* @param accountId the account's object id
|
|
98
|
+
*/
|
|
99
|
+
async pollNow(accountId) {
|
|
100
|
+
const runtime = this.runtimes.find((entry) => entry.config.id === accountId);
|
|
101
|
+
if (runtime) {
|
|
102
|
+
runtime.authNotified = false;
|
|
103
|
+
runtime.skipUntil = 0;
|
|
104
|
+
await this.pollAccount(runtime);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
90
107
|
/**
|
|
91
108
|
* Poll one account now (also used by the staggered first run).
|
|
92
109
|
*
|
|
@@ -108,6 +125,8 @@ class PollEngine {
|
|
|
108
125
|
runtime.authNotified = false;
|
|
109
126
|
runtime.status.snapshot = snapshot;
|
|
110
127
|
runtime.status.reachable = true;
|
|
128
|
+
runtime.serviceOnline = true;
|
|
129
|
+
runtime.state = "ok";
|
|
111
130
|
await this.applySnapshot(runtime, snapshot);
|
|
112
131
|
} catch (e) {
|
|
113
132
|
this.handleFailure(runtime, e);
|
|
@@ -135,20 +154,28 @@ class PollEngine {
|
|
|
135
154
|
for (const write of writes) {
|
|
136
155
|
this.deps.setState(write.id, write.value);
|
|
137
156
|
}
|
|
138
|
-
const
|
|
157
|
+
const driver = (0, import_snapshot_tree.limitingWindow)(snapshot);
|
|
158
|
+
const percent = (_a = driver == null ? void 0 : driver.percent) != null ? _a : 0;
|
|
139
159
|
const wasWarning = runtime.status.warning;
|
|
140
160
|
runtime.status.warning = percent >= config.warnThreshold;
|
|
141
161
|
this.deps.setState(`${config.id}.warning`, runtime.status.warning);
|
|
142
162
|
this.deps.setState(`${config.id}.limitReached`, percent >= 100);
|
|
143
163
|
if (runtime.status.warning && !wasWarning) {
|
|
144
|
-
const
|
|
164
|
+
const window = driver ? `${driver.label} ` : "";
|
|
165
|
+
const message = `${config.name}: ${window}at ${Math.round(percent)} % (threshold ${config.warnThreshold} %)`;
|
|
145
166
|
this.deps.log.warn(message);
|
|
146
167
|
(_c = (_b = this.deps).notify) == null ? void 0 : _c.call(_b, config.name, message);
|
|
147
168
|
}
|
|
148
169
|
}
|
|
149
170
|
/**
|
|
150
|
-
* Classify a fetch failure
|
|
151
|
-
*
|
|
171
|
+
* Classify a fetch failure.
|
|
172
|
+
*
|
|
173
|
+
* The split matters for the online indicator: with `auth` and `rate-limit` the AI
|
|
174
|
+
* service ANSWERED — it is online, it just said no — so only our own access is
|
|
175
|
+
* broken. `service` means the service answered with a fault of its own and is
|
|
176
|
+
* reported as down at once (it told us, that is not a flake). A `network` failure
|
|
177
|
+
* is tolerated MAX_NETWORK_FAILURES times before we call the connection gone, so
|
|
178
|
+
* a single hiccup does not make the indicator flap.
|
|
152
179
|
*
|
|
153
180
|
* @param runtime the account's runtime
|
|
154
181
|
* @param error the thrown error
|
|
@@ -159,6 +186,8 @@ class PollEngine {
|
|
|
159
186
|
const message = error instanceof Error ? error.message : String(error);
|
|
160
187
|
if (error instanceof import_provider.FetchError && error.kind === "auth") {
|
|
161
188
|
runtime.status.reachable = false;
|
|
189
|
+
runtime.serviceOnline = true;
|
|
190
|
+
runtime.state = "unauthorized";
|
|
162
191
|
if (!runtime.authNotified) {
|
|
163
192
|
runtime.authNotified = true;
|
|
164
193
|
const text = `${config.name}: credentials rejected \u2014 ${message}`;
|
|
@@ -168,6 +197,8 @@ class PollEngine {
|
|
|
168
197
|
return;
|
|
169
198
|
}
|
|
170
199
|
if (error instanceof import_provider.FetchError && error.kind === "rate-limit") {
|
|
200
|
+
runtime.serviceOnline = true;
|
|
201
|
+
runtime.state = "rate-limited";
|
|
171
202
|
runtime.skipUntil = this.deps.now() + runtime.backoffMs;
|
|
172
203
|
this.deps.log.warn(
|
|
173
204
|
`${config.name}: rate-limited \u2014 backing off for ${Math.round(runtime.backoffMs / 6e4)} min, keeping last values`
|
|
@@ -175,24 +206,55 @@ class PollEngine {
|
|
|
175
206
|
runtime.backoffMs = Math.min(BACKOFF_MAX_MS, runtime.backoffMs * 2);
|
|
176
207
|
return;
|
|
177
208
|
}
|
|
209
|
+
if (error instanceof import_provider.FetchError && error.kind === "service") {
|
|
210
|
+
runtime.status.reachable = false;
|
|
211
|
+
runtime.failCount = 0;
|
|
212
|
+
if (runtime.serviceOnline) {
|
|
213
|
+
this.deps.log.warn(`${config.name}: the service reports a fault (${message}) \u2014 values kept`);
|
|
214
|
+
}
|
|
215
|
+
runtime.serviceOnline = false;
|
|
216
|
+
runtime.state = "service-down";
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
178
219
|
runtime.failCount++;
|
|
179
220
|
this.deps.log.debug(`${config.name}: fetch failed (${message}), attempt ${runtime.failCount}`);
|
|
180
221
|
if (runtime.failCount >= MAX_NETWORK_FAILURES) {
|
|
181
222
|
runtime.status.reachable = false;
|
|
223
|
+
if (runtime.serviceOnline) {
|
|
224
|
+
this.deps.log.warn(`${config.name}: not reachable after ${runtime.failCount} attempts (${message})`);
|
|
225
|
+
}
|
|
226
|
+
runtime.serviceOnline = false;
|
|
227
|
+
runtime.state = "no-connection";
|
|
182
228
|
}
|
|
183
229
|
}
|
|
184
230
|
/**
|
|
185
|
-
* Write one account's info states (
|
|
231
|
+
* Write one account's info states (data received, service online, state, last update).
|
|
186
232
|
*
|
|
187
233
|
* @param runtime the account's runtime
|
|
188
234
|
*/
|
|
189
235
|
writeAccountInfo(runtime) {
|
|
190
236
|
const { config } = runtime;
|
|
191
237
|
this.deps.setState(`${config.id}.info.reachable`, runtime.status.reachable);
|
|
238
|
+
this.setIfChanged(runtime, `${config.id}.info.serviceOnline`, runtime.serviceOnline);
|
|
239
|
+
this.setIfChanged(runtime, `${config.id}.info.state`, runtime.state);
|
|
192
240
|
if (runtime.status.reachable) {
|
|
193
241
|
this.deps.setState(`${config.id}.info.lastUpdate`, new Date(this.deps.now()).toISOString());
|
|
194
242
|
}
|
|
195
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* Write a state only when its value actually changed since the last write.
|
|
246
|
+
*
|
|
247
|
+
* @param runtime the account's runtime (holds the last-written cache)
|
|
248
|
+
* @param id the state id
|
|
249
|
+
* @param value the value
|
|
250
|
+
*/
|
|
251
|
+
setIfChanged(runtime, id, value) {
|
|
252
|
+
if (runtime.written.get(id) === value) {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
runtime.written.set(id, value);
|
|
256
|
+
this.deps.setState(id, value);
|
|
257
|
+
}
|
|
196
258
|
/** Recompute and write the totals + info.connection. */
|
|
197
259
|
async writeTotals() {
|
|
198
260
|
const totals = (0, import_totals.computeTotals)(this.runtimes.map((runtime) => runtime.status));
|
|
@@ -227,6 +289,22 @@ class PollEngine {
|
|
|
227
289
|
type: "state",
|
|
228
290
|
common: { name: "Reachable", type: "boolean", role: "indicator.reachable", read: true, write: false }
|
|
229
291
|
},
|
|
292
|
+
{
|
|
293
|
+
id: `${config.id}.info.serviceOnline`,
|
|
294
|
+
type: "state",
|
|
295
|
+
common: { name: "AI service online", type: "boolean", role: "indicator.connected", read: true, write: false }
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
id: `${config.id}.info.state`,
|
|
299
|
+
type: "state",
|
|
300
|
+
common: {
|
|
301
|
+
name: "State (ok, unauthorized, rate-limited, service-down, no-connection)",
|
|
302
|
+
type: "string",
|
|
303
|
+
role: "text",
|
|
304
|
+
read: true,
|
|
305
|
+
write: false
|
|
306
|
+
}
|
|
307
|
+
},
|
|
230
308
|
{
|
|
231
309
|
id: `${config.id}.info.lastUpdate`,
|
|
232
310
|
type: "state",
|
|
@@ -249,6 +327,8 @@ class PollEngine {
|
|
|
249
327
|
}
|
|
250
328
|
this.deps.setState(`${config.id}.info.provider`, config.provider);
|
|
251
329
|
this.deps.setState(`${config.id}.info.reachable`, false);
|
|
330
|
+
this.setIfChanged(runtime, `${config.id}.info.serviceOnline`, runtime.serviceOnline);
|
|
331
|
+
this.setIfChanged(runtime, `${config.id}.info.state`, runtime.state);
|
|
252
332
|
}
|
|
253
333
|
/** The totals skeleton (channel + states). */
|
|
254
334
|
async createTotalsSkeleton() {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/poll-engine.ts"],
|
|
4
|
-
"sourcesContent": ["import type { AccountConfig } from \"./pure-helpers\";\nimport { FetchError, type UsageProvider, type UsageSnapshot } from \"./provider\";\nimport { mapSnapshot, maxLimitPercent, type ObjectDef } from \"./snapshot-tree\";\nimport { computeTotals, type AccountStatus } from \"./totals\";\n\n/** Consecutive network failures after which an account is judged unreachable. */\nconst MAX_NETWORK_FAILURES = 3;\n/** First backoff after a rate-limit answer (ms); doubles per repeat. */\nconst BACKOFF_START_MS = 10 * 60 * 1000;\n/** Backoff ceiling (ms). */\nconst BACKOFF_MAX_MS = 60 * 60 * 1000;\n/** Stagger between the accounts' first polls (ms) so they never fire in one burst. */\nconst STAGGER_MS = 3000;\n\n/** The adapter callbacks the engine drives \u2014 narrow, so tests need no adapter mock. */\nexport interface EngineDeps {\n /** Create or update an object. */\n upsertObject(def: ObjectDef): Promise<void>;\n /** Write a state value with ack. */\n setState(id: string, value: boolean | number | string): void;\n /** Schedule a repeating callback; returns a cancel handle. */\n schedule(cb: () => void, ms: number): unknown;\n /** Schedule a one-shot callback; returns a cancel handle. */\n scheduleOnce(cb: () => void, ms: number): unknown;\n /** Cancel a handle from schedule/scheduleOnce. */\n cancel(handle: unknown): void;\n /** Current time (ms since epoch) \u2014 injected for tests. */\n now(): number;\n /** Adapter log. */\n log: { debug(m: string): void; info(m: string): void; warn(m: string): void; error(m: string): void };\n /** Raise a user-facing notification (threshold crossing, broken credentials). */\n notify?(accountName: string, message: string): void;\n}\n\n/** One account's runtime state inside the engine. */\ninterface AccountRuntime {\n config: AccountConfig;\n provider: UsageProvider;\n status: AccountStatus;\n /** Consecutive network failures. */\n failCount: number;\n /** Skip polls until this time (rate-limit backoff). */\n skipUntil: number;\n /** Current backoff length (ms). */\n backoffMs: number;\n /** Whether the auth-broken notification has been raised (reset on success). */\n authNotified: boolean;\n /** Object ids already created for this account (create-once cache). */\n createdObjects: Set<string>;\n}\n\n/**\n * Drives the polling of all configured accounts: staggered starts, one independent\n * cycle per account, typed failure handling (auth = immediate + one notification,\n * rate-limit = backoff keeping last values, network = tolerant), warn-threshold\n * transitions and the adapter-wide totals. Pure orchestration \u2014 all IO is injected.\n */\nexport class PollEngine {\n private readonly runtimes: AccountRuntime[] = [];\n private readonly handles: unknown[] = [];\n private stopped = false;\n\n /**\n * @param accounts the validated account configs\n * @param providers each account id's provider (accounts without one are skipped)\n * @param intervalSec the poll interval in seconds\n * @param deps the injected adapter callbacks\n */\n public constructor(\n accounts: readonly AccountConfig[],\n providers: ReadonlyMap<string, UsageProvider>,\n private readonly intervalSec: number,\n private readonly deps: EngineDeps,\n ) {\n for (const config of accounts) {\n const provider = providers.get(config.id);\n if (!provider) {\n deps.log.warn(`${config.name}: provider \"${config.provider}\" is not available \u2014 account skipped`);\n continue;\n }\n this.runtimes.push({\n config,\n provider,\n status: { reachable: false, warning: false },\n failCount: 0,\n skipUntil: 0,\n backoffMs: BACKOFF_START_MS,\n authNotified: false,\n createdObjects: new Set(),\n });\n }\n }\n\n /** Create the static per-account and totals objects, then arm the poll cycles. */\n public async start(): Promise<void> {\n for (const runtime of this.runtimes) {\n await this.createAccountSkeleton(runtime);\n }\n await this.createTotalsSkeleton();\n await this.writeTotals();\n this.runtimes.forEach((runtime, index) => {\n this.handles.push(\n this.deps.scheduleOnce(() => void this.pollAccount(runtime), index * STAGGER_MS),\n this.deps.schedule(() => void this.pollAccount(runtime), this.intervalSec * 1000),\n );\n });\n }\n\n /** Cancel every timer. Synchronous \u2014 safe from onUnload. */\n public stop(): void {\n this.stopped = true;\n for (const handle of this.handles) {\n this.deps.cancel(handle);\n }\n this.handles.length = 0;\n }\n\n /** The account ids the engine drives (for the stale-object cleanup). */\n public get accountIds(): string[] {\n return this.runtimes.map(runtime => runtime.config.id);\n }\n\n /**\n * Poll one account now (also used by the staggered first run).\n *\n * @param runtime the account's runtime\n */\n private async pollAccount(runtime: AccountRuntime): Promise<void> {\n if (this.stopped) {\n return;\n }\n const { config } = runtime;\n if (this.deps.now() < runtime.skipUntil) {\n this.deps.log.debug(`${config.name}: in rate-limit backoff \u2014 poll skipped`);\n return;\n }\n try {\n const snapshot = await runtime.provider.fetch();\n runtime.failCount = 0;\n runtime.backoffMs = BACKOFF_START_MS;\n runtime.authNotified = false;\n runtime.status.snapshot = snapshot;\n runtime.status.reachable = true;\n await this.applySnapshot(runtime, snapshot);\n } catch (e) {\n this.handleFailure(runtime, e);\n }\n this.writeAccountInfo(runtime);\n await this.writeTotals();\n }\n\n /**\n * Write a successful snapshot: upsert new objects (create-once cache), write the\n * values, and run the warn-threshold transition.\n *\n * @param runtime the account's runtime\n * @param snapshot the fetched snapshot\n */\n private async applySnapshot(runtime: AccountRuntime, snapshot: UsageSnapshot): Promise<void> {\n const { config } = runtime;\n const { objects, writes } = mapSnapshot(config.id, config.name, config.provider, snapshot);\n for (const object of objects) {\n if (!runtime.createdObjects.has(object.id)) {\n await this.deps.upsertObject(object);\n runtime.createdObjects.add(object.id);\n }\n }\n for (const write of writes) {\n this.deps.setState(write.id, write.value);\n }\n const percent = maxLimitPercent(snapshot) ?? 0;\n const wasWarning = runtime.status.warning;\n runtime.status.warning = percent >= config.warnThreshold;\n this.deps.setState(`${config.id}.warning`, runtime.status.warning);\n this.deps.setState(`${config.id}.limitReached`, percent >= 100);\n if (runtime.status.warning && !wasWarning) {\n const message = `${config.name}: usage at ${Math.round(percent)} % (threshold ${config.warnThreshold} %)`;\n this.deps.log.warn(message);\n this.deps.notify?.(config.name, message);\n }\n }\n\n /**\n * Classify a fetch failure: auth = unreachable + ONE notification until it recovers;\n * rate-limit = backoff, last values stay; network = tolerated MAX_NETWORK_FAILURES times.\n *\n * @param runtime the account's runtime\n * @param error the thrown error\n */\n private handleFailure(runtime: AccountRuntime, error: unknown): void {\n const { config } = runtime;\n const message = error instanceof Error ? error.message : String(error);\n if (error instanceof FetchError && error.kind === \"auth\") {\n runtime.status.reachable = false;\n if (!runtime.authNotified) {\n runtime.authNotified = true;\n const text = `${config.name}: credentials rejected \u2014 ${message}`;\n this.deps.log.warn(text);\n this.deps.notify?.(config.name, text);\n }\n return;\n }\n if (error instanceof FetchError && error.kind === \"rate-limit\") {\n runtime.skipUntil = this.deps.now() + runtime.backoffMs;\n this.deps.log.warn(\n `${config.name}: rate-limited \u2014 backing off for ${Math.round(runtime.backoffMs / 60000)} min, keeping last values`,\n );\n runtime.backoffMs = Math.min(BACKOFF_MAX_MS, runtime.backoffMs * 2);\n return;\n }\n runtime.failCount++;\n this.deps.log.debug(`${config.name}: fetch failed (${message}), attempt ${runtime.failCount}`);\n if (runtime.failCount >= MAX_NETWORK_FAILURES) {\n runtime.status.reachable = false;\n }\n }\n\n /**\n * Write one account's info states (reachable, last update).\n *\n * @param runtime the account's runtime\n */\n private writeAccountInfo(runtime: AccountRuntime): void {\n const { config } = runtime;\n this.deps.setState(`${config.id}.info.reachable`, runtime.status.reachable);\n if (runtime.status.reachable) {\n this.deps.setState(`${config.id}.info.lastUpdate`, new Date(this.deps.now()).toISOString());\n }\n }\n\n /** Recompute and write the totals + info.connection. */\n private async writeTotals(): Promise<void> {\n const totals = computeTotals(this.runtimes.map(runtime => runtime.status));\n this.deps.setState(\"total.costs.today\", totals.costsToday);\n this.deps.setState(\"total.costs.month\", totals.costsMonth);\n this.deps.setState(\"total.costs.projectedMonth\", totals.costsProjectedMonth);\n this.deps.setState(\"total.maxLimitPercent\", totals.maxLimitPercent);\n this.deps.setState(\"total.warningsActive\", totals.warningsActive);\n this.deps.setState(\"total.limitReached\", totals.limitReached);\n this.deps.setState(\"total.accountsReachable\", totals.accountsReachable);\n this.deps.setState(\"total.accounts\", totals.accounts);\n this.deps.setState(\"info.connection\", totals.accountsReachable > 0);\n return Promise.resolve();\n }\n\n /**\n * The static per-account objects that exist regardless of what the source delivers.\n *\n * @param runtime the account's runtime\n */\n private async createAccountSkeleton(runtime: AccountRuntime): Promise<void> {\n const { config } = runtime;\n const defs: ObjectDef[] = [\n { id: config.id, type: \"device\", common: { name: `${config.name} (${config.provider})` } },\n { id: `${config.id}.info`, type: \"channel\", common: { name: \"Info\" } },\n {\n id: `${config.id}.info.provider`,\n type: \"state\",\n common: { name: \"Provider\", type: \"string\", role: \"text\", read: true, write: false },\n },\n {\n id: `${config.id}.info.reachable`,\n type: \"state\",\n common: { name: \"Reachable\", type: \"boolean\", role: \"indicator.reachable\", read: true, write: false },\n },\n {\n id: `${config.id}.info.lastUpdate`,\n type: \"state\",\n common: { name: \"Last successful update\", type: \"string\", role: \"date\", read: true, write: false },\n },\n {\n id: `${config.id}.warning`,\n type: \"state\",\n common: { name: \"Above warn threshold\", type: \"boolean\", role: \"indicator\", read: true, write: false },\n },\n {\n id: `${config.id}.limitReached`,\n type: \"state\",\n common: { name: \"A limit window is full\", type: \"boolean\", role: \"indicator\", read: true, write: false },\n },\n ];\n for (const def of defs) {\n await this.deps.upsertObject(def);\n runtime.createdObjects.add(def.id);\n }\n this.deps.setState(`${config.id}.info.provider`, config.provider);\n this.deps.setState(`${config.id}.info.reachable`, false);\n }\n\n /** The totals skeleton (channel + states). */\n private async createTotalsSkeleton(): Promise<void> {\n const defs: ObjectDef[] = [\n { id: \"total.costs\", type: \"channel\", common: { name: \"Costs (USD accounts)\" } },\n {\n id: \"total.costs.today\",\n type: \"state\",\n common: {\n name: \"Costs today (all accounts)\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"USD\",\n },\n },\n {\n id: \"total.costs.month\",\n type: \"state\",\n common: {\n name: \"Costs this month (all accounts)\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"USD\",\n },\n },\n {\n id: \"total.costs.projectedMonth\",\n type: \"state\",\n common: {\n name: \"Costs projected month-end (computed)\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"USD\",\n },\n },\n {\n id: \"total.maxLimitPercent\",\n type: \"state\",\n common: {\n name: \"Highest limit utilisation of any account\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"%\",\n },\n },\n {\n id: \"total.warningsActive\",\n type: \"state\",\n common: {\n name: \"Accounts above their warn threshold\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n },\n },\n {\n id: \"total.limitReached\",\n type: \"state\",\n common: { name: \"Any limit window full\", type: \"boolean\", role: \"indicator\", read: true, write: false },\n },\n {\n id: \"total.accountsReachable\",\n type: \"state\",\n common: { name: \"Reachable accounts\", type: \"number\", role: \"value\", read: true, write: false },\n },\n {\n id: \"total.accounts\",\n type: \"state\",\n common: { name: \"Configured accounts\", type: \"number\", role: \"value\", read: true, write: false },\n },\n ];\n for (const def of defs) {\n await this.deps.upsertObject(def);\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,sBAAmE;AACnE,
|
|
4
|
+
"sourcesContent": ["import type { AccountConfig } from \"./pure-helpers\";\nimport { FetchError, type UsageProvider, type UsageSnapshot } from \"./provider\";\nimport { limitingWindow, mapSnapshot, type ObjectDef } from \"./snapshot-tree\";\nimport { computeTotals, type AccountStatus } from \"./totals\";\n\n/**\n * What the adapter currently knows about one account, in one word.\n *\n * `ok` and `rate-limited` mean the AI service is up and talking to us,\n * `unauthorized` means it is up but rejects our sign-in, `service-down` means the\n * service itself answered with a fault, `no-connection` means we never reached it.\n */\nexport type AccountState = \"ok\" | \"unauthorized\" | \"rate-limited\" | \"service-down\" | \"no-connection\";\n\n/** Consecutive network failures after which an account is judged unreachable. */\nconst MAX_NETWORK_FAILURES = 3;\n/** First backoff after a rate-limit answer (ms); doubles per repeat. */\nconst BACKOFF_START_MS = 10 * 60 * 1000;\n/** Backoff ceiling (ms). */\nconst BACKOFF_MAX_MS = 60 * 60 * 1000;\n/** Stagger between the accounts' first polls (ms) so they never fire in one burst. */\nconst STAGGER_MS = 3000;\n\n/** The adapter callbacks the engine drives \u2014 narrow, so tests need no adapter mock. */\nexport interface EngineDeps {\n /** Create or update an object. */\n upsertObject(def: ObjectDef): Promise<void>;\n /** Write a state value with ack. */\n setState(id: string, value: boolean | number | string): void;\n /** Schedule a repeating callback; returns a cancel handle. */\n schedule(cb: () => void, ms: number): unknown;\n /** Schedule a one-shot callback; returns a cancel handle. */\n scheduleOnce(cb: () => void, ms: number): unknown;\n /** Cancel a handle from schedule/scheduleOnce. */\n cancel(handle: unknown): void;\n /** Current time (ms since epoch) \u2014 injected for tests. */\n now(): number;\n /** Adapter log. */\n log: { debug(m: string): void; info(m: string): void; warn(m: string): void; error(m: string): void };\n /** Raise a user-facing notification (threshold crossing, broken credentials). */\n notify?(accountName: string, message: string): void;\n}\n\n/** One account's runtime state inside the engine. */\ninterface AccountRuntime {\n config: AccountConfig;\n provider: UsageProvider;\n status: AccountStatus;\n /** Consecutive network failures. */\n failCount: number;\n /** Skip polls until this time (rate-limit backoff). */\n skipUntil: number;\n /** Current backoff length (ms). */\n backoffMs: number;\n /** Whether the auth-broken notification has been raised (reset on success). */\n authNotified: boolean;\n /** Whether the AI service itself answered on the last attempt. */\n serviceOnline: boolean;\n /** The account's one-word state. */\n state: AccountState;\n /** Object ids already created for this account (create-once cache). */\n createdObjects: Set<string>;\n /** Last written value per state id \u2014 keeps unchanged values out of the history. */\n written: Map<string, boolean | number | string>;\n}\n\n/**\n * Drives the polling of all configured accounts: staggered starts, one independent\n * cycle per account, typed failure handling (auth = immediate + one notification,\n * rate-limit = backoff keeping last values, network = tolerant), warn-threshold\n * transitions and the adapter-wide totals. Pure orchestration \u2014 all IO is injected.\n */\nexport class PollEngine {\n private readonly runtimes: AccountRuntime[] = [];\n private readonly handles: unknown[] = [];\n private stopped = false;\n\n /**\n * @param accounts the validated account configs\n * @param providers each account id's provider (accounts without one are skipped)\n * @param intervalSec the poll interval in seconds\n * @param deps the injected adapter callbacks\n */\n public constructor(\n accounts: readonly AccountConfig[],\n providers: ReadonlyMap<string, UsageProvider>,\n private readonly intervalSec: number,\n private readonly deps: EngineDeps,\n ) {\n for (const config of accounts) {\n const provider = providers.get(config.id);\n if (!provider) {\n deps.log.warn(`${config.name}: provider \"${config.provider}\" is not available \u2014 account skipped`);\n continue;\n }\n this.runtimes.push({\n config,\n provider,\n status: { reachable: false, warning: false },\n failCount: 0,\n skipUntil: 0,\n backoffMs: BACKOFF_START_MS,\n authNotified: false,\n serviceOnline: false,\n state: \"no-connection\",\n createdObjects: new Set(),\n written: new Map(),\n });\n }\n }\n\n /** Create the static per-account and totals objects, then arm the poll cycles. */\n public async start(): Promise<void> {\n for (const runtime of this.runtimes) {\n await this.createAccountSkeleton(runtime);\n }\n await this.createTotalsSkeleton();\n await this.writeTotals();\n this.runtimes.forEach((runtime, index) => {\n this.handles.push(\n this.deps.scheduleOnce(() => void this.pollAccount(runtime), index * STAGGER_MS),\n this.deps.schedule(() => void this.pollAccount(runtime), this.intervalSec * 1000),\n );\n });\n }\n\n /** Cancel every timer. Synchronous \u2014 safe from onUnload. */\n public stop(): void {\n this.stopped = true;\n for (const handle of this.handles) {\n this.deps.cancel(handle);\n }\n this.handles.length = 0;\n }\n\n /** The account ids the engine drives (for the stale-object cleanup). */\n public get accountIds(): string[] {\n return this.runtimes.map(runtime => runtime.config.id);\n }\n\n /**\n * Poll one account immediately, by id. Used after a successful sign-in: waiting\n * up to a full interval there reads as \"the sign-in did not work\".\n *\n * @param accountId the account's object id\n */\n public async pollNow(accountId: string): Promise<void> {\n const runtime = this.runtimes.find(entry => entry.config.id === accountId);\n if (runtime) {\n // A fresh sign-in clears a previous auth failure and any backoff.\n runtime.authNotified = false;\n runtime.skipUntil = 0;\n await this.pollAccount(runtime);\n }\n }\n\n /**\n * Poll one account now (also used by the staggered first run).\n *\n * @param runtime the account's runtime\n */\n private async pollAccount(runtime: AccountRuntime): Promise<void> {\n if (this.stopped) {\n return;\n }\n const { config } = runtime;\n if (this.deps.now() < runtime.skipUntil) {\n this.deps.log.debug(`${config.name}: in rate-limit backoff \u2014 poll skipped`);\n return;\n }\n try {\n const snapshot = await runtime.provider.fetch();\n runtime.failCount = 0;\n runtime.backoffMs = BACKOFF_START_MS;\n runtime.authNotified = false;\n runtime.status.snapshot = snapshot;\n runtime.status.reachable = true;\n runtime.serviceOnline = true;\n runtime.state = \"ok\";\n await this.applySnapshot(runtime, snapshot);\n } catch (e) {\n this.handleFailure(runtime, e);\n }\n this.writeAccountInfo(runtime);\n await this.writeTotals();\n }\n\n /**\n * Write a successful snapshot: upsert new objects (create-once cache), write the\n * values, and run the warn-threshold transition.\n *\n * @param runtime the account's runtime\n * @param snapshot the fetched snapshot\n */\n private async applySnapshot(runtime: AccountRuntime, snapshot: UsageSnapshot): Promise<void> {\n const { config } = runtime;\n const { objects, writes } = mapSnapshot(config.id, config.name, config.provider, snapshot);\n for (const object of objects) {\n if (!runtime.createdObjects.has(object.id)) {\n await this.deps.upsertObject(object);\n runtime.createdObjects.add(object.id);\n }\n }\n for (const write of writes) {\n this.deps.setState(write.id, write.value);\n }\n // Only PLAN-WIDE windows speak for the account \u2014 a per-model bucket at 100 %\n // must not read as \"this AI is full\" (krobi 2026-08-26).\n const driver = limitingWindow(snapshot);\n const percent = driver?.percent ?? 0;\n const wasWarning = runtime.status.warning;\n runtime.status.warning = percent >= config.warnThreshold;\n this.deps.setState(`${config.id}.warning`, runtime.status.warning);\n this.deps.setState(`${config.id}.limitReached`, percent >= 100);\n if (runtime.status.warning && !wasWarning) {\n // Always name the window: \"usage at 100 %\" without it was misleading whenever\n // several windows existed.\n const window = driver ? `${driver.label} ` : \"\";\n const message = `${config.name}: ${window}at ${Math.round(percent)} % (threshold ${config.warnThreshold} %)`;\n this.deps.log.warn(message);\n this.deps.notify?.(config.name, message);\n }\n }\n\n /**\n * Classify a fetch failure.\n *\n * The split matters for the online indicator: with `auth` and `rate-limit` the AI\n * service ANSWERED \u2014 it is online, it just said no \u2014 so only our own access is\n * broken. `service` means the service answered with a fault of its own and is\n * reported as down at once (it told us, that is not a flake). A `network` failure\n * is tolerated MAX_NETWORK_FAILURES times before we call the connection gone, so\n * a single hiccup does not make the indicator flap.\n *\n * @param runtime the account's runtime\n * @param error the thrown error\n */\n private handleFailure(runtime: AccountRuntime, error: unknown): void {\n const { config } = runtime;\n const message = error instanceof Error ? error.message : String(error);\n if (error instanceof FetchError && error.kind === \"auth\") {\n runtime.status.reachable = false;\n runtime.serviceOnline = true;\n runtime.state = \"unauthorized\";\n if (!runtime.authNotified) {\n runtime.authNotified = true;\n const text = `${config.name}: credentials rejected \u2014 ${message}`;\n this.deps.log.warn(text);\n this.deps.notify?.(config.name, text);\n }\n return;\n }\n if (error instanceof FetchError && error.kind === \"rate-limit\") {\n runtime.serviceOnline = true;\n runtime.state = \"rate-limited\";\n runtime.skipUntil = this.deps.now() + runtime.backoffMs;\n this.deps.log.warn(\n `${config.name}: rate-limited \u2014 backing off for ${Math.round(runtime.backoffMs / 60000)} min, keeping last values`,\n );\n runtime.backoffMs = Math.min(BACKOFF_MAX_MS, runtime.backoffMs * 2);\n return;\n }\n if (error instanceof FetchError && error.kind === \"service\") {\n runtime.status.reachable = false;\n runtime.failCount = 0;\n if (runtime.serviceOnline) {\n this.deps.log.warn(`${config.name}: the service reports a fault (${message}) \u2014 values kept`);\n }\n runtime.serviceOnline = false;\n runtime.state = \"service-down\";\n return;\n }\n runtime.failCount++;\n this.deps.log.debug(`${config.name}: fetch failed (${message}), attempt ${runtime.failCount}`);\n if (runtime.failCount >= MAX_NETWORK_FAILURES) {\n runtime.status.reachable = false;\n if (runtime.serviceOnline) {\n this.deps.log.warn(`${config.name}: not reachable after ${runtime.failCount} attempts (${message})`);\n }\n runtime.serviceOnline = false;\n runtime.state = \"no-connection\";\n }\n }\n\n /**\n * Write one account's info states (data received, service online, state, last update).\n *\n * @param runtime the account's runtime\n */\n private writeAccountInfo(runtime: AccountRuntime): void {\n const { config } = runtime;\n this.deps.setState(`${config.id}.info.reachable`, runtime.status.reachable);\n // Written only on change: an indicator rewritten every cycle floods the history\n // and makes a real transition impossible to spot.\n this.setIfChanged(runtime, `${config.id}.info.serviceOnline`, runtime.serviceOnline);\n this.setIfChanged(runtime, `${config.id}.info.state`, runtime.state);\n if (runtime.status.reachable) {\n this.deps.setState(`${config.id}.info.lastUpdate`, new Date(this.deps.now()).toISOString());\n }\n }\n\n /**\n * Write a state only when its value actually changed since the last write.\n *\n * @param runtime the account's runtime (holds the last-written cache)\n * @param id the state id\n * @param value the value\n */\n private setIfChanged(runtime: AccountRuntime, id: string, value: boolean | number | string): void {\n if (runtime.written.get(id) === value) {\n return;\n }\n runtime.written.set(id, value);\n this.deps.setState(id, value);\n }\n\n /** Recompute and write the totals + info.connection. */\n private async writeTotals(): Promise<void> {\n const totals = computeTotals(this.runtimes.map(runtime => runtime.status));\n this.deps.setState(\"total.costs.today\", totals.costsToday);\n this.deps.setState(\"total.costs.month\", totals.costsMonth);\n this.deps.setState(\"total.costs.projectedMonth\", totals.costsProjectedMonth);\n this.deps.setState(\"total.maxLimitPercent\", totals.maxLimitPercent);\n this.deps.setState(\"total.warningsActive\", totals.warningsActive);\n this.deps.setState(\"total.limitReached\", totals.limitReached);\n this.deps.setState(\"total.accountsReachable\", totals.accountsReachable);\n this.deps.setState(\"total.accounts\", totals.accounts);\n this.deps.setState(\"info.connection\", totals.accountsReachable > 0);\n return Promise.resolve();\n }\n\n /**\n * The static per-account objects that exist regardless of what the source delivers.\n *\n * @param runtime the account's runtime\n */\n private async createAccountSkeleton(runtime: AccountRuntime): Promise<void> {\n const { config } = runtime;\n const defs: ObjectDef[] = [\n { id: config.id, type: \"device\", common: { name: `${config.name} (${config.provider})` } },\n { id: `${config.id}.info`, type: \"channel\", common: { name: \"Info\" } },\n {\n id: `${config.id}.info.provider`,\n type: \"state\",\n common: { name: \"Provider\", type: \"string\", role: \"text\", read: true, write: false },\n },\n {\n id: `${config.id}.info.reachable`,\n type: \"state\",\n common: { name: \"Reachable\", type: \"boolean\", role: \"indicator.reachable\", read: true, write: false },\n },\n {\n id: `${config.id}.info.serviceOnline`,\n type: \"state\",\n common: { name: \"AI service online\", type: \"boolean\", role: \"indicator.connected\", read: true, write: false },\n },\n {\n id: `${config.id}.info.state`,\n type: \"state\",\n common: {\n name: \"State (ok, unauthorized, rate-limited, service-down, no-connection)\",\n type: \"string\",\n role: \"text\",\n read: true,\n write: false,\n },\n },\n {\n id: `${config.id}.info.lastUpdate`,\n type: \"state\",\n common: { name: \"Last successful update\", type: \"string\", role: \"date\", read: true, write: false },\n },\n {\n id: `${config.id}.warning`,\n type: \"state\",\n common: { name: \"Above warn threshold\", type: \"boolean\", role: \"indicator\", read: true, write: false },\n },\n {\n id: `${config.id}.limitReached`,\n type: \"state\",\n common: { name: \"A limit window is full\", type: \"boolean\", role: \"indicator\", read: true, write: false },\n },\n ];\n for (const def of defs) {\n await this.deps.upsertObject(def);\n runtime.createdObjects.add(def.id);\n }\n this.deps.setState(`${config.id}.info.provider`, config.provider);\n this.deps.setState(`${config.id}.info.reachable`, false);\n this.setIfChanged(runtime, `${config.id}.info.serviceOnline`, runtime.serviceOnline);\n this.setIfChanged(runtime, `${config.id}.info.state`, runtime.state);\n }\n\n /** The totals skeleton (channel + states). */\n private async createTotalsSkeleton(): Promise<void> {\n const defs: ObjectDef[] = [\n { id: \"total.costs\", type: \"channel\", common: { name: \"Costs (USD accounts)\" } },\n {\n id: \"total.costs.today\",\n type: \"state\",\n common: {\n name: \"Costs today (all accounts)\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"USD\",\n },\n },\n {\n id: \"total.costs.month\",\n type: \"state\",\n common: {\n name: \"Costs this month (all accounts)\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"USD\",\n },\n },\n {\n id: \"total.costs.projectedMonth\",\n type: \"state\",\n common: {\n name: \"Costs projected month-end (computed)\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"USD\",\n },\n },\n {\n id: \"total.maxLimitPercent\",\n type: \"state\",\n common: {\n name: \"Highest limit utilisation of any account\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n unit: \"%\",\n },\n },\n {\n id: \"total.warningsActive\",\n type: \"state\",\n common: {\n name: \"Accounts above their warn threshold\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: false,\n },\n },\n {\n id: \"total.limitReached\",\n type: \"state\",\n common: { name: \"Any limit window full\", type: \"boolean\", role: \"indicator\", read: true, write: false },\n },\n {\n id: \"total.accountsReachable\",\n type: \"state\",\n common: { name: \"Reachable accounts\", type: \"number\", role: \"value\", read: true, write: false },\n },\n {\n id: \"total.accounts\",\n type: \"state\",\n common: { name: \"Configured accounts\", type: \"number\", role: \"value\", read: true, write: false },\n },\n ];\n for (const def of defs) {\n await this.deps.upsertObject(def);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,sBAAmE;AACnE,2BAA4D;AAC5D,oBAAkD;AAYlD,MAAM,uBAAuB;AAE7B,MAAM,mBAAmB,KAAK,KAAK;AAEnC,MAAM,iBAAiB,KAAK,KAAK;AAEjC,MAAM,aAAa;AAmDZ,MAAM,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWf,YACL,UACA,WACiB,aACA,MACjB;AAFiB;AACA;AAEjB,eAAW,UAAU,UAAU;AAC7B,YAAM,WAAW,UAAU,IAAI,OAAO,EAAE;AACxC,UAAI,CAAC,UAAU;AACb,aAAK,IAAI,KAAK,GAAG,OAAO,IAAI,eAAe,OAAO,QAAQ,2CAAsC;AAChG;AAAA,MACF;AACA,WAAK,SAAS,KAAK;AAAA,QACjB;AAAA,QACA;AAAA,QACA,QAAQ,EAAE,WAAW,OAAO,SAAS,MAAM;AAAA,QAC3C,WAAW;AAAA,QACX,WAAW;AAAA,QACX,WAAW;AAAA,QACX,cAAc;AAAA,QACd,eAAe;AAAA,QACf,OAAO;AAAA,QACP,gBAAg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M,UAAU,MAAM,SAAS,MAAM,MAAM,OAAO,MAAM;AAAA,MAChG;AAAA,MACA;AAAA,QACE,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,QAAQ,EAAE,MAAM,uBAAuB,MAAM,UAAU,MAAM,SAAS,MAAM,MAAM,OAAO,MAAM;AAAA,MACjG;AAAA,IACF;AACA,eAAW,OAAO,MAAM;AACtB,YAAM,KAAK,KAAK,aAAa,GAAG;AAAA,IAClC;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/provider.ts"],
|
|
4
|
-
"sourcesContent": ["/** The provider kinds the adapter speaks. */\nexport type ProviderKind
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["/** The provider kinds the adapter speaks. */\nexport type ProviderKind =\n \"claude-sub\" | \"chatgpt-sub\" | \"gemini-sub\" | \"openrouter\" | \"deepseek\" | \"openai\" | \"anthropic-api\";\n\n/**\n * How a subscription account is signed in. Each provider dictates its own flow \u2014\n * the admin panel renders the matching instructions, the adapter drives the rest.\n *\n * - `paste-code`: the user opens a link, signs in and pastes the code shown there (Claude).\n * - `device-code`: the adapter shows a short code the user types on the provider's page,\n * then polls until the user confirmed (ChatGPT/Codex).\n * - `paste-url`: the user opens a link, signs in and lands on a browser error page whose\n * ADDRESS carries the code \u2014 the whole address is pasted back (Gemini, the only redirect\n * Google accepts for the usable client; measured 2026-08-26).\n */\nexport type SignInFlow = \"paste-code\" | \"device-code\" | \"paste-url\";\n\n/** One limit window (session, week, per-model) \u2014 the same shape for every provider. */\nexport interface LimitWindow {\n /** Window name; becomes the object id segment (session, week, a model name, month). */\n name: string;\n /** Human-readable label for the object name. */\n label: string;\n /** Utilisation in percent (0-100+). */\n percent: number;\n /** When the window resets (ISO timestamp), if the source reports it. */\n resetAt?: string;\n /**\n * True when this window covers only a PART of the plan \u2014 a single model or\n * surface that sits next to a plan-wide window of the same period.\n *\n * Such a bucket is reported as its own datapoint but never drives the account's\n * warning: a model the user does not use can sit at 100 % forever, and a counter\n * that never falls is worse than no counter (krobi 2026-08-26: \"das betrifft nur\n * Fable, nicht allgemein\"). Providers whose ONLY buckets are per-model (Google)\n * leave this unset \u2014 there the model buckets are the plan.\n */\n scoped?: boolean;\n}\n\n/** Granted budget (prepaid money or request credits). */\nexport interface CreditInfo {\n /** Used amount. */\n used?: number;\n /** Granted ceiling; undefined = unlimited/unknown. */\n limit?: number;\n /** Remaining amount. */\n remaining?: number;\n /** Utilisation in percent, when both used and limit are known. */\n percent?: number;\n /** Granted (gifted) part of the balance, where the source distinguishes it (DeepSeek). */\n granted?: number;\n /** Topped-up (paid) part of the balance. */\n toppedUp?: number;\n /** Currency code (\"USD\", \"CNY\") \u2014 or a unit word for piece-counters. */\n currency: string;\n /** True when the credits are pieces (requests), not money \u2014 excluded from cost totals. */\n pieces?: boolean;\n}\n\n/** Real money spent. */\nexport interface CostInfo {\n /** Spent today. */\n today?: number;\n /** Spent this month (or billing period). */\n month?: number;\n /** Lifetime counter, where the source only reports that. */\n total?: number;\n /** Projected month-end spend (computed by the provider module, marked in the object name). */\n projectedMonth?: number;\n /** Currency code. */\n currency: string;\n}\n\n/** Token counters (API accounts). */\nexport interface TokenInfo {\n /** Input tokens today. */\n inputToday?: number;\n /** Output tokens today. */\n outputToday?: number;\n /** Per-model breakdown. */\n perModel?: { model: string; tokens?: number; cost?: number }[];\n}\n\n/**\n * A transport-neutral usage snapshot \u2014 one fetch result. Only what the source\n * actually delivered is present; the tree builder creates nothing for absent parts.\n */\nexport interface UsageSnapshot {\n /** Limit windows (subscription accounts). */\n limits?: LimitWindow[];\n /** Granted budget. */\n credits?: CreditInfo;\n /** Real money spent. */\n costs?: CostInfo;\n /** Token counters. */\n tokens?: TokenInfo;\n /** Provider-specific extra flags (e.g. DeepSeek `available`). */\n available?: boolean;\n}\n\n/**\n * Why a fetch failed \u2014 drives reachability, backoff and notifications.\n *\n * `auth` and `rate-limit` mean the AI service ANSWERED (it is online, it just said\n * no), `service` means it answered with a server fault of its own, and `network`\n * means we never reached it. Keeping the last two apart is what lets the adapter\n * say whether the AI service is down or the ioBroker host has no connection.\n */\nexport type FetchErrorKind = \"auth\" | \"rate-limit\" | \"service\" | \"network\";\n\n/** A typed fetch failure. */\nexport class FetchError extends Error {\n /**\n * @param kind the failure class\n * @param message the human-readable reason\n */\n public constructor(\n public readonly kind: FetchErrorKind,\n message: string,\n ) {\n super(message);\n this.name = \"FetchError\";\n }\n}\n\n/** One account's usage source. Implementations are pure fetch+parse \u2014 no ioBroker inside. */\nexport interface UsageProvider {\n /** Which provider this is. */\n readonly kind: ProviderKind;\n /** Fetch the current snapshot; throws {@link FetchError} on failure. */\n fetch(): Promise<UsageSnapshot>;\n}\n\n/** Persisted OAuth tokens of one subscription account. */\nexport interface TokenSet {\n /** The bearer token used for the usage call. */\n accessToken: string;\n /** The token used to obtain a fresh access token. */\n refreshToken: string;\n /** Absolute expiry of {@link accessToken} in ms since epoch. */\n expiresAt: number;\n /** Provider-specific extra the usage call needs (e.g. ChatGPT account id). */\n accountRef?: string;\n}\n\n/** Where a subscription's tokens live. Keyed by PROVIDER, never by account name. */\nexport interface TokenStore {\n /** Read the stored tokens, or null when never signed in. */\n load(): Promise<TokenSet | null>;\n /** Persist tokens (encrypted by the adapter). */\n save(tokens: TokenSet): Promise<void>;\n /** Forget the tokens (sign out / unusable refresh token). */\n clear(): Promise<void>;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgHO,MAAM,mBAAmB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAK7B,YACW,MAChB,SACA;AACA,UAAM,OAAO;AAHG;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var chatgpt_auth_exports = {};
|
|
20
|
+
__export(chatgpt_auth_exports, {
|
|
21
|
+
CHATGPT_OAUTH: () => CHATGPT_OAUTH,
|
|
22
|
+
exchangeDeviceCode: () => exchangeDeviceCode,
|
|
23
|
+
pollDeviceCode: () => pollDeviceCode,
|
|
24
|
+
refreshChatgptTokens: () => refreshChatgptTokens,
|
|
25
|
+
startDeviceCode: () => startDeviceCode
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(chatgpt_auth_exports);
|
|
28
|
+
var import_jwt = require("../jwt");
|
|
29
|
+
var import_provider = require("../provider");
|
|
30
|
+
const CHATGPT_OAUTH = {
|
|
31
|
+
clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
|
|
32
|
+
deviceCodeUrl: "https://auth.openai.com/api/accounts/deviceauth/usercode",
|
|
33
|
+
devicePollUrl: "https://auth.openai.com/api/accounts/deviceauth/token",
|
|
34
|
+
tokenUrl: "https://auth.openai.com/oauth/token",
|
|
35
|
+
deviceRedirectUri: "https://auth.openai.com/deviceauth/callback",
|
|
36
|
+
/** Where the user types the code. */
|
|
37
|
+
verificationUrl: "https://auth.openai.com/codex/device",
|
|
38
|
+
/** The code is valid for 15 minutes (prompt text in the CLI). */
|
|
39
|
+
windowMs: 15 * 6e4,
|
|
40
|
+
/** Fallback lifetime when the access token carries no expiry. */
|
|
41
|
+
fallbackLifetimeMs: 60 * 6e4
|
|
42
|
+
};
|
|
43
|
+
function str(body, key) {
|
|
44
|
+
if (typeof body !== "object" || body === null) {
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
const value = body[key];
|
|
48
|
+
return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
49
|
+
}
|
|
50
|
+
async function startDeviceCode(post, now) {
|
|
51
|
+
const body = await post(CHATGPT_OAUTH.deviceCodeUrl, { client_id: CHATGPT_OAUTH.clientId });
|
|
52
|
+
const userCode = str(body, "user_code");
|
|
53
|
+
const deviceAuthId = str(body, "device_auth_id");
|
|
54
|
+
if (!userCode || !deviceAuthId) {
|
|
55
|
+
throw new import_provider.FetchError("network", "unexpected device-code response");
|
|
56
|
+
}
|
|
57
|
+
const advised = Number(str(body, "interval"));
|
|
58
|
+
return {
|
|
59
|
+
userCode,
|
|
60
|
+
deviceAuthId,
|
|
61
|
+
intervalSec: Number.isFinite(advised) && advised >= 1 ? advised : 5,
|
|
62
|
+
expiresAt: now + CHATGPT_OAUTH.windowMs
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
async function pollDeviceCode(start, post) {
|
|
66
|
+
let body;
|
|
67
|
+
try {
|
|
68
|
+
body = await post(CHATGPT_OAUTH.devicePollUrl, {
|
|
69
|
+
device_auth_id: start.deviceAuthId,
|
|
70
|
+
user_code: start.userCode
|
|
71
|
+
});
|
|
72
|
+
} catch (e) {
|
|
73
|
+
if (e instanceof import_provider.FetchError && e.kind === "auth") {
|
|
74
|
+
return { status: "pending" };
|
|
75
|
+
}
|
|
76
|
+
throw e;
|
|
77
|
+
}
|
|
78
|
+
const code = str(body, "authorization_code");
|
|
79
|
+
const codeVerifier = str(body, "code_verifier");
|
|
80
|
+
if (!code || !codeVerifier) {
|
|
81
|
+
return { status: "pending" };
|
|
82
|
+
}
|
|
83
|
+
return { status: "ready", code, codeVerifier };
|
|
84
|
+
}
|
|
85
|
+
async function exchangeDeviceCode(code, codeVerifier, post, now) {
|
|
86
|
+
const body = await post(CHATGPT_OAUTH.tokenUrl, {
|
|
87
|
+
grant_type: "authorization_code",
|
|
88
|
+
client_id: CHATGPT_OAUTH.clientId,
|
|
89
|
+
code,
|
|
90
|
+
code_verifier: codeVerifier,
|
|
91
|
+
redirect_uri: CHATGPT_OAUTH.deviceRedirectUri
|
|
92
|
+
});
|
|
93
|
+
return toTokenSet(body, now, "");
|
|
94
|
+
}
|
|
95
|
+
async function refreshChatgptTokens(tokens, post, now) {
|
|
96
|
+
const body = await post(CHATGPT_OAUTH.tokenUrl, {
|
|
97
|
+
client_id: CHATGPT_OAUTH.clientId,
|
|
98
|
+
grant_type: "refresh_token",
|
|
99
|
+
refresh_token: tokens.refreshToken
|
|
100
|
+
});
|
|
101
|
+
return toTokenSet(body, now, tokens.refreshToken, tokens.accountRef);
|
|
102
|
+
}
|
|
103
|
+
function toTokenSet(body, now, previousRefresh, previousAccount) {
|
|
104
|
+
var _a;
|
|
105
|
+
const accessToken = str(body, "access_token");
|
|
106
|
+
if (!accessToken) {
|
|
107
|
+
throw new import_provider.FetchError("auth", "no access token in the answer");
|
|
108
|
+
}
|
|
109
|
+
const idToken = str(body, "id_token");
|
|
110
|
+
return {
|
|
111
|
+
accessToken,
|
|
112
|
+
refreshToken: str(body, "refresh_token") || previousRefresh,
|
|
113
|
+
expiresAt: (0, import_jwt.jwtExpiry)(accessToken, CHATGPT_OAUTH.fallbackLifetimeMs, now),
|
|
114
|
+
accountRef: (_a = idToken ? (0, import_jwt.chatgptAccountId)(idToken) : void 0) != null ? _a : previousAccount
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
118
|
+
0 && (module.exports = {
|
|
119
|
+
CHATGPT_OAUTH,
|
|
120
|
+
exchangeDeviceCode,
|
|
121
|
+
pollDeviceCode,
|
|
122
|
+
refreshChatgptTokens,
|
|
123
|
+
startDeviceCode
|
|
124
|
+
});
|
|
125
|
+
//# sourceMappingURL=chatgpt-auth.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/lib/providers/chatgpt-auth.ts"],
|
|
4
|
+
"sourcesContent": ["import { jwtExpiry, chatgptAccountId } from \"../jwt\";\nimport { FetchError, type TokenSet } from \"../provider\";\n\n/** Constants of the Codex device-code sign-in (openai/codex, login/src/auth/manager.rs). */\nexport const CHATGPT_OAUTH = {\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n deviceCodeUrl: \"https://auth.openai.com/api/accounts/deviceauth/usercode\",\n devicePollUrl: \"https://auth.openai.com/api/accounts/deviceauth/token\",\n tokenUrl: \"https://auth.openai.com/oauth/token\",\n deviceRedirectUri: \"https://auth.openai.com/deviceauth/callback\",\n /** Where the user types the code. */\n verificationUrl: \"https://auth.openai.com/codex/device\",\n /** The code is valid for 15 minutes (prompt text in the CLI). */\n windowMs: 15 * 60_000,\n /** Fallback lifetime when the access token carries no expiry. */\n fallbackLifetimeMs: 60 * 60_000,\n} as const;\n\n/** A JSON POST seam (injected so the modules stay testable). */\nexport type JsonPost = (\n url: string,\n body: Record<string, unknown>,\n headers?: Record<string, string>,\n) => Promise<unknown>;\n/** A form POST seam. */\nexport type FormPost = (\n url: string,\n form: Record<string, string>,\n headers?: Record<string, string>,\n) => Promise<unknown>;\n\n/** What the device-code start handed back \u2014 the user-facing half plus the polling handle. */\nexport interface DeviceCodeStart {\n /** The short code the user types on {@link CHATGPT_OAUTH.verificationUrl}. */\n userCode: string;\n /** Opaque handle for the polling calls. */\n deviceAuthId: string;\n /** Seconds between polls, as advised by the server. */\n intervalSec: number;\n /** Absolute end of the sign-in window (ms since epoch). */\n expiresAt: number;\n}\n\n/**\n * Read a field out of an untrusted JSON answer.\n *\n * @param body the parsed answer\n * @param key the field name\n * @returns the string value, or \"\"\n */\nfunction str(body: unknown, key: string): string {\n if (typeof body !== \"object\" || body === null) {\n return \"\";\n }\n const value = (body as Record<string, unknown>)[key];\n return typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : \"\";\n}\n\n/**\n * Start the device-code sign-in: ask OpenAI for a user code.\n *\n * @param post the JSON POST seam\n * @param now current time in ms\n * @returns what the admin panel has to show plus the polling handle\n */\nexport async function startDeviceCode(post: JsonPost, now: number): Promise<DeviceCodeStart> {\n const body = await post(CHATGPT_OAUTH.deviceCodeUrl, { client_id: CHATGPT_OAUTH.clientId });\n const userCode = str(body, \"user_code\");\n const deviceAuthId = str(body, \"device_auth_id\");\n if (!userCode || !deviceAuthId) {\n throw new FetchError(\"network\", \"unexpected device-code response\");\n }\n // The server sends the interval as a STRING; never poll faster than once a second.\n const advised = Number(str(body, \"interval\"));\n return {\n userCode,\n deviceAuthId,\n intervalSec: Number.isFinite(advised) && advised >= 1 ? advised : 5,\n expiresAt: now + CHATGPT_OAUTH.windowMs,\n };\n}\n\n/** One polling result: still waiting, or the authorization code plus its verifier. */\nexport type DevicePollResult = { status: \"pending\" } | { status: \"ready\"; code: string; codeVerifier: string };\n\n/**\n * Ask once whether the user confirmed the code.\n *\n * \"Not confirmed yet\" arrives as an auth failure (403/404 in the CLI) \u2014 that is a\n * WAIT, not an error, so it must not bubble up as a broken sign-in.\n *\n * @param start the handle from {@link startDeviceCode}\n * @param post the JSON POST seam\n * @returns pending or the redeemable code\n */\nexport async function pollDeviceCode(start: DeviceCodeStart, post: JsonPost): Promise<DevicePollResult> {\n let body: unknown;\n try {\n body = await post(CHATGPT_OAUTH.devicePollUrl, {\n device_auth_id: start.deviceAuthId,\n user_code: start.userCode,\n });\n } catch (e) {\n if (e instanceof FetchError && e.kind === \"auth\") {\n return { status: \"pending\" };\n }\n throw e;\n }\n const code = str(body, \"authorization_code\");\n const codeVerifier = str(body, \"code_verifier\");\n if (!code || !codeVerifier) {\n return { status: \"pending\" };\n }\n return { status: \"ready\", code, codeVerifier };\n}\n\n/**\n * Redeem the authorization code for tokens (form-encoded, unlike the refresh call).\n *\n * @param code the authorization code\n * @param codeVerifier the verifier the server handed back\n * @param post the form POST seam\n * @param now current time in ms\n * @returns the token set including the ChatGPT account id\n */\nexport async function exchangeDeviceCode(\n code: string,\n codeVerifier: string,\n post: FormPost,\n now: number,\n): Promise<TokenSet> {\n const body = await post(CHATGPT_OAUTH.tokenUrl, {\n grant_type: \"authorization_code\",\n client_id: CHATGPT_OAUTH.clientId,\n code,\n code_verifier: codeVerifier,\n redirect_uri: CHATGPT_OAUTH.deviceRedirectUri,\n });\n return toTokenSet(body, now, \"\");\n}\n\n/**\n * Get a fresh access token. The answer carries no lifetime \u2014 it comes out of the\n * token itself \u2014 and often no new refresh token, in which case the old one stays.\n *\n * @param tokens the current tokens\n * @param post the JSON POST seam (refresh is JSON, not form-encoded)\n * @param now current time in ms\n * @returns the refreshed token set\n */\nexport async function refreshChatgptTokens(tokens: TokenSet, post: JsonPost, now: number): Promise<TokenSet> {\n const body = await post(CHATGPT_OAUTH.tokenUrl, {\n client_id: CHATGPT_OAUTH.clientId,\n grant_type: \"refresh_token\",\n refresh_token: tokens.refreshToken,\n });\n return toTokenSet(body, now, tokens.refreshToken, tokens.accountRef);\n}\n\n/**\n * Build a token set from a token answer.\n *\n * @param body the parsed answer\n * @param now current time in ms\n * @param previousRefresh refresh token to keep when the answer omits one\n * @param previousAccount account id to keep when no id token came back\n * @returns the token set\n */\nfunction toTokenSet(body: unknown, now: number, previousRefresh: string, previousAccount?: string): TokenSet {\n const accessToken = str(body, \"access_token\");\n if (!accessToken) {\n throw new FetchError(\"auth\", \"no access token in the answer\");\n }\n const idToken = str(body, \"id_token\");\n return {\n accessToken,\n refreshToken: str(body, \"refresh_token\") || previousRefresh,\n expiresAt: jwtExpiry(accessToken, CHATGPT_OAUTH.fallbackLifetimeMs, now),\n accountRef: (idToken ? chatgptAccountId(idToken) : undefined) ?? previousAccount,\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAA4C;AAC5C,sBAA0C;AAGnC,MAAM,gBAAgB;AAAA,EAC3B,UAAU;AAAA,EACV,eAAe;AAAA,EACf,eAAe;AAAA,EACf,UAAU;AAAA,EACV,mBAAmB;AAAA;AAAA,EAEnB,iBAAiB;AAAA;AAAA,EAEjB,UAAU,KAAK;AAAA;AAAA,EAEf,oBAAoB,KAAK;AAC3B;AAkCA,SAAS,IAAI,MAAe,KAAqB;AAC/C,MAAI,OAAO,SAAS,YAAY,SAAS,MAAM;AAC7C,WAAO;AAAA,EACT;AACA,QAAM,QAAS,KAAiC,GAAG;AACnD,SAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;AACzF;AASA,eAAsB,gBAAgB,MAAgB,KAAuC;AAC3F,QAAM,OAAO,MAAM,KAAK,cAAc,eAAe,EAAE,WAAW,cAAc,SAAS,CAAC;AAC1F,QAAM,WAAW,IAAI,MAAM,WAAW;AACtC,QAAM,eAAe,IAAI,MAAM,gBAAgB;AAC/C,MAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,UAAM,IAAI,2BAAW,WAAW,iCAAiC;AAAA,EACnE;AAEA,QAAM,UAAU,OAAO,IAAI,MAAM,UAAU,CAAC;AAC5C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,aAAa,OAAO,SAAS,OAAO,KAAK,WAAW,IAAI,UAAU;AAAA,IAClE,WAAW,MAAM,cAAc;AAAA,EACjC;A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M,eAAe,KAAK;AAAA,IAC5C,eAAW,sBAAU,aAAa,cAAc,oBAAoB,GAAG;AAAA,IACvE,aAAa,mBAAU,6BAAiB,OAAO,IAAI,WAAtC,YAAoD;AAAA,EACnE;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var chatgpt_sub_exports = {};
|
|
20
|
+
__export(chatgpt_sub_exports, {
|
|
21
|
+
CHATGPT_OAUTH: () => import_chatgpt_auth.CHATGPT_OAUTH,
|
|
22
|
+
CHATGPT_USAGE_URL: () => CHATGPT_USAGE_URL,
|
|
23
|
+
chatgptSubProvider: () => chatgptSubProvider,
|
|
24
|
+
parseChatgptUsage: () => parseChatgptUsage
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(chatgpt_sub_exports);
|
|
27
|
+
var import_http = require("../http");
|
|
28
|
+
var import_provider = require("../provider");
|
|
29
|
+
var import_chatgpt_auth = require("./chatgpt-auth");
|
|
30
|
+
const CHATGPT_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
31
|
+
function readWindow(raw, name, label) {
|
|
32
|
+
if (typeof raw !== "object" || raw === null) {
|
|
33
|
+
return void 0;
|
|
34
|
+
}
|
|
35
|
+
const entry = raw;
|
|
36
|
+
const percent = Number(entry.used_percent);
|
|
37
|
+
if (!Number.isFinite(percent)) {
|
|
38
|
+
return void 0;
|
|
39
|
+
}
|
|
40
|
+
const window = { name, label, percent };
|
|
41
|
+
const resetAt = Number(entry.reset_at);
|
|
42
|
+
if (Number.isFinite(resetAt) && resetAt > 0) {
|
|
43
|
+
const ms = resetAt > 1e12 ? resetAt : resetAt * 1e3;
|
|
44
|
+
window.resetAt = new Date(ms).toISOString();
|
|
45
|
+
}
|
|
46
|
+
return window;
|
|
47
|
+
}
|
|
48
|
+
function parseChatgptUsage(body) {
|
|
49
|
+
var _a, _b;
|
|
50
|
+
if (typeof body !== "object" || body === null) {
|
|
51
|
+
throw new import_provider.FetchError("network", "unexpected usage response");
|
|
52
|
+
}
|
|
53
|
+
const raw = body;
|
|
54
|
+
const limits = [];
|
|
55
|
+
const rateLimit = (_a = raw.rate_limit) != null ? _a : {};
|
|
56
|
+
const session = readWindow(rateLimit.primary_window, "session", "Session (5 h)");
|
|
57
|
+
const week = readWindow(rateLimit.secondary_window, "week", "Week");
|
|
58
|
+
if (session) {
|
|
59
|
+
limits.push(session);
|
|
60
|
+
}
|
|
61
|
+
if (week) {
|
|
62
|
+
limits.push(week);
|
|
63
|
+
}
|
|
64
|
+
for (const extra of Array.isArray(raw.additional_rate_limits) ? raw.additional_rate_limits : []) {
|
|
65
|
+
if (typeof extra !== "object" || extra === null) {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const entry = extra;
|
|
69
|
+
const label = typeof entry.limit_name === "string" ? entry.limit_name : "";
|
|
70
|
+
const name = label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
71
|
+
if (!name || limits.some((window2) => window2.name === name)) {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const window = readWindow(entry.rate_limit, name, label);
|
|
75
|
+
if (window) {
|
|
76
|
+
window.scoped = true;
|
|
77
|
+
limits.push(window);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const snapshot = {};
|
|
81
|
+
if (limits.length) {
|
|
82
|
+
snapshot.limits = limits;
|
|
83
|
+
}
|
|
84
|
+
const credits = (_b = raw.credits) != null ? _b : {};
|
|
85
|
+
const balance = Number(credits.balance);
|
|
86
|
+
if (Number.isFinite(balance) && credits.unlimited !== true) {
|
|
87
|
+
snapshot.credits = { remaining: balance, currency: "USD" };
|
|
88
|
+
}
|
|
89
|
+
return snapshot;
|
|
90
|
+
}
|
|
91
|
+
function chatgptSubProvider(store, fetchJson = import_http.getJson, postJson, now = Date.now) {
|
|
92
|
+
let cached = null;
|
|
93
|
+
return {
|
|
94
|
+
kind: "chatgpt-sub",
|
|
95
|
+
fetch: async () => {
|
|
96
|
+
cached != null ? cached : cached = await store.load();
|
|
97
|
+
if (!cached) {
|
|
98
|
+
throw new import_provider.FetchError("auth", "not signed in \u2014 start the ChatGPT sign-in in the instance settings");
|
|
99
|
+
}
|
|
100
|
+
if (now() >= cached.expiresAt - 6e4) {
|
|
101
|
+
cached = await (0, import_chatgpt_auth.refreshChatgptTokens)(cached, postJson, now());
|
|
102
|
+
await store.save(cached);
|
|
103
|
+
}
|
|
104
|
+
const headers = {
|
|
105
|
+
Authorization: `Bearer ${cached.accessToken}`,
|
|
106
|
+
"User-Agent": "ioBroker.ai-usage"
|
|
107
|
+
};
|
|
108
|
+
if (cached.accountRef) {
|
|
109
|
+
headers["ChatGPT-Account-Id"] = cached.accountRef;
|
|
110
|
+
}
|
|
111
|
+
return parseChatgptUsage(await fetchJson(CHATGPT_USAGE_URL, headers));
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
116
|
+
0 && (module.exports = {
|
|
117
|
+
CHATGPT_OAUTH,
|
|
118
|
+
CHATGPT_USAGE_URL,
|
|
119
|
+
chatgptSubProvider,
|
|
120
|
+
parseChatgptUsage
|
|
121
|
+
});
|
|
122
|
+
//# sourceMappingURL=chatgpt-sub.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/lib/providers/chatgpt-sub.ts"],
|
|
4
|
+
"sourcesContent": ["import { getJson, type JsonFetch } from \"../http\";\nimport {\n FetchError,\n type LimitWindow,\n type TokenSet,\n type TokenStore,\n type UsageProvider,\n type UsageSnapshot,\n} from \"../provider\";\nimport { CHATGPT_OAUTH, refreshChatgptTokens, type JsonPost } from \"./chatgpt-auth\";\n\n/** Where the subscription usage lives (the endpoint OpenAI's own Codex client uses). */\nexport const CHATGPT_USAGE_URL = \"https://chatgpt.com/backend-api/wham/usage\";\n\n/**\n * Read one rate-limit window.\n *\n * Both windows may be null when they do not apply to the account, and `reset_at`\n * is in Unix SECONDS \u2014 a value that already looks like milliseconds is passed\n * through, so a future format change cannot produce a year-58000 timestamp.\n *\n * @param raw the window object\n * @param name the object id segment\n * @param label the human-readable label\n * @returns the window, or undefined when unusable\n */\nfunction readWindow(raw: unknown, name: string, label: string): LimitWindow | undefined {\n if (typeof raw !== \"object\" || raw === null) {\n return undefined;\n }\n const entry = raw as Record<string, unknown>;\n const percent = Number(entry.used_percent);\n if (!Number.isFinite(percent)) {\n return undefined;\n }\n const window: LimitWindow = { name, label, percent };\n const resetAt = Number(entry.reset_at);\n if (Number.isFinite(resetAt) && resetAt > 0) {\n const ms = resetAt > 1e12 ? resetAt : resetAt * 1000;\n window.resetAt = new Date(ms).toISOString();\n }\n return window;\n}\n\n/**\n * Parse a `/wham/usage` answer into a snapshot.\n *\n * Fields follow OpenAI's own generated models: `plan_type`, `rate_limit` with a\n * 5-hour `primary_window` and a weekly `secondary_window`, plus `credits` whose\n * balance arrives as a string in the schema but as a number in practice.\n *\n * @param body the parsed answer\n * @returns the snapshot\n */\nexport function parseChatgptUsage(body: unknown): UsageSnapshot {\n if (typeof body !== \"object\" || body === null) {\n throw new FetchError(\"network\", \"unexpected usage response\");\n }\n const raw = body as Record<string, unknown>;\n const limits: LimitWindow[] = [];\n const rateLimit = (raw.rate_limit ?? {}) as Record<string, unknown>;\n const session = readWindow(rateLimit.primary_window, \"session\", \"Session (5 h)\");\n const week = readWindow(rateLimit.secondary_window, \"week\", \"Week\");\n if (session) {\n limits.push(session);\n }\n if (week) {\n limits.push(week);\n }\n for (const extra of Array.isArray(raw.additional_rate_limits) ? raw.additional_rate_limits : []) {\n if (typeof extra !== \"object\" || extra === null) {\n continue;\n }\n const entry = extra as Record<string, unknown>;\n const label = typeof entry.limit_name === \"string\" ? entry.limit_name : \"\";\n // The name becomes an object-id segment, so it must survive sanitizing and must\n // not collide with a window already collected \u2014 a name of \"Session\" would\n // otherwise overwrite the 5-hour window with an unrelated counter.\n const name = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (!name || limits.some(window => window.name === name)) {\n continue;\n }\n const window = readWindow(entry.rate_limit, name, label);\n if (window) {\n // These sit next to the plan-wide session/week windows and cover one model\n // each \u2014 reported, but never the reason for a warning (LimitWindow.scoped).\n window.scoped = true;\n limits.push(window);\n }\n }\n\n const snapshot: UsageSnapshot = {};\n if (limits.length) {\n snapshot.limits = limits;\n }\n\n const credits = (raw.credits ?? {}) as Record<string, unknown>;\n const balance = Number(credits.balance);\n if (Number.isFinite(balance) && credits.unlimited !== true) {\n snapshot.credits = { remaining: balance, currency: \"USD\" };\n }\n return snapshot;\n}\n\n/**\n * The ChatGPT/Codex subscription provider.\n *\n * @param store where the tokens live (keyed by provider, shared by no one else)\n * @param fetchJson the JSON-GET seam\n * @param postJson the JSON-POST seam (token refresh)\n * @param now clock (ms)\n * @returns the provider\n */\nexport function chatgptSubProvider(\n store: TokenStore,\n fetchJson: JsonFetch = getJson,\n postJson: JsonPost,\n now: () => number = Date.now,\n): UsageProvider {\n let cached: TokenSet | null = null;\n return {\n kind: \"chatgpt-sub\",\n fetch: async (): Promise<UsageSnapshot> => {\n cached ??= await store.load();\n if (!cached) {\n throw new FetchError(\"auth\", \"not signed in \u2014 start the ChatGPT sign-in in the instance settings\");\n }\n if (now() >= cached.expiresAt - 60_000) {\n cached = await refreshChatgptTokens(cached, postJson, now());\n await store.save(cached);\n }\n const headers: Record<string, string> = {\n Authorization: `Bearer ${cached.accessToken}`,\n \"User-Agent\": \"ioBroker.ai-usage\",\n };\n // Only send the account id when we have one \u2014 an empty header is rejected.\n if (cached.accountRef) {\n headers[\"ChatGPT-Account-Id\"] = cached.accountRef;\n }\n return parseChatgptUsage(await fetchJson(CHATGPT_USAGE_URL, headers));\n },\n };\n}\n\nexport { CHATGPT_OAUTH };\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAwC;AACxC,sBAOO;AACP,0BAAmE;AAG5D,MAAM,oBAAoB;AAcjC,SAAS,WAAW,KAAc,MAAc,OAAwC;AACtF,MAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AAC3C,WAAO;AAAA,EACT;AACA,QAAM,QAAQ;AACd,QAAM,UAAU,OAAO,MAAM,YAAY;AACzC,MAAI,CAAC,OAAO,SAAS,OAAO,GAAG;AAC7B,WAAO;AAAA,EACT;AACA,QAAM,SAAsB,EAAE,MAAM,OAAO,QAAQ;AACnD,QAAM,UAAU,OAAO,MAAM,QAAQ;AACrC,MAAI,OAAO,SAAS,OAAO,KAAK,UAAU,GAAG;AAC3C,UAAM,KAAK,UAAU,OAAO,UAAU,UAAU;AAChD,WAAO,UAAU,IAAI,KAAK,EAAE,EAAE,YAAY;AAAA,EAC5C;AACA,SAAO;AACT;AAYO,SAAS,kBAA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