@astrosheep/pi-quota 0.9.0 → 0.10.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 +5 -1
- package/package.json +1 -1
- package/src/config.ts +11 -1
- package/src/query/exec.ts +59 -0
package/README.md
CHANGED
|
@@ -32,7 +32,8 @@ Add bindings in global `~/.pi/agent/settings.json` under `quotaUsage` (not proje
|
|
|
32
32
|
"my-new-api": { "adapter": "new-api", "quotaPerUnit": 500000, "currency": "USD" },
|
|
33
33
|
"deepseek": { "adapter": "deepseek" },
|
|
34
34
|
"opencode-go-2": { "adapter": "opencode-go" },
|
|
35
|
-
"yes-vg": { "adapter": "yescode", "username": "you@example.com", "password": "..." }
|
|
35
|
+
"yes-vg": { "adapter": "yescode", "username": "you@example.com", "password": "..." },
|
|
36
|
+
"my-script": { "adapter": "exec", "command": ["my-quota-cli", "--json"], "label": "My Script" }
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
}
|
|
@@ -47,6 +48,7 @@ Use the **exact Pi provider ID**. Built-in providers and explicitly bound provid
|
|
|
47
48
|
| `deepseek` | Official `/user/balance` | Balance only; no invented spend |
|
|
48
49
|
| `opencode-go` | Official `https://opencode.ai/zen/go/v1/usage` | 5h/1w/30d windows, same as the built-in `opencode-go` adapter |
|
|
49
50
|
| `yescode` | `co.yes.vg` login → session → `/api/v1/auth/profile` + `/api/v1/user/balance` | Wallet (subscription + pay-as-you-go) plus daily/weekly subscription windows |
|
|
51
|
+
| `exec` | Runs `command` as argv (no shell), parses stdout as a `QuotaSnapshot` JSON | Whatever the command reports; `fetchedAt` is stamped by the adapter, never by the command |
|
|
50
52
|
|
|
51
53
|
Bind `opencode-go` to a second OpenCode Go account: register it as its own Pi provider in `models.json` with its own `apiKey` (e.g. `opencode-go-2`), then bind that ID here. The built-in `opencode-go` binding is implicit and needs no entry; the reserved IDs `openai-codex`, `kimi-coding` and `opencode-go` cannot be rebound.
|
|
52
54
|
|
|
@@ -56,6 +58,8 @@ For new-api, `quotaPerUnit` defaults to `500000`, `currency` to `USD`. Optionall
|
|
|
56
58
|
|
|
57
59
|
For YesCode, `username` is the account email and `password` the account password; both stay in global `settings.json`, which is the trade-off of this adapter. YesCode rejects API keys on account endpoints ("requires a user session or JWT"), so the adapter logs in via `/api/v1/auth/login`, caches the issued cookie/JWT in memory for ~23 hours, and re-logs in once on an auth failure. The model `cr_` key is never sent to account endpoints; it only pins the provider to the official `co.yes.vg` origin. Balances are summed from subscription and pay-as-you-go; daily/weekly windows appear only when the account actually has those caps.
|
|
58
60
|
|
|
61
|
+
Exec runs the configured argv without a shell and parses stdout as a `QuotaSnapshot` JSON object: `windows`, optional `balance`, `allowance` and `spend` — the same schema every adapter produces, enforced by the controller. `fetchedAt` is stamped by the adapter; a value from the command is ignored. The controller bounds every query (10s default) and kills the child on timeout; non-zero exits, unreadable JSON and output over 256KB become errors, and command output is never logged. The child inherits Pi's environment, so keep secrets in env vars, not in `quotaUsage`.
|
|
62
|
+
|
|
59
63
|
Authenticated quota URLs must use HTTPS, except HTTP loopback for local deployments. URL userinfo, query strings, fragments and HTTP redirects are rejected; credentials never follow redirects. Fixed official endpoints reject custom origins. No browser cookie scraping or credential discovery.
|
|
60
64
|
|
|
61
65
|
## Architecture
|
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createDeepSeekAdapter } from './query/deepseek.ts';
|
|
2
|
+
import { createExecAdapter, validateExecOptions } from './query/exec.ts';
|
|
2
3
|
import { createNewApiAdapter, validateNewApiOptions } from './query/new-api.ts';
|
|
3
4
|
import { createOpenCodeGoAdapter } from './query/opencode-go.ts';
|
|
4
5
|
import { createSub2ApiAdapter } from './query/sub2api.ts';
|
|
@@ -11,6 +12,7 @@ import type { FooterWindows } from './bar/quota.ts';
|
|
|
11
12
|
export type ProviderQuotaConfig =
|
|
12
13
|
| ({ adapter: 'new-api'; quotaPerUnit: number; currency: string } & Pick<NewApiOptions, 'dashboardAccessToken' | 'dashboardUserId'>)
|
|
13
14
|
| ({ adapter: 'yescode' } & YesCodeOptions)
|
|
15
|
+
| { adapter: 'exec'; command: string[]; label: string }
|
|
14
16
|
| { adapter: 'deepseek' | 'sub2api' | 'opencode-go' };
|
|
15
17
|
export interface QuotaConfig { providers: Record<string, ProviderQuotaConfig>; footerWindows?: FooterWindows }
|
|
16
18
|
|
|
@@ -39,7 +41,7 @@ function parseFooterWindows(value: unknown): FooterWindows {
|
|
|
39
41
|
export class QuotaConfigError extends Error {
|
|
40
42
|
constructor() {
|
|
41
43
|
// Settings may accidentally contain secrets. Never echo content/values.
|
|
42
|
-
super('Invalid settings.json quotaUsage. Use providers with adapter "new-api", "deepseek", "sub2api", "opencode-go" or "
|
|
44
|
+
super('Invalid settings.json quotaUsage. Use providers with adapter "new-api", "deepseek", "sub2api", "opencode-go", "yescode" or "exec", and optionally footerWindows as a positive integer or "all".');
|
|
43
45
|
}
|
|
44
46
|
}
|
|
45
47
|
|
|
@@ -74,6 +76,13 @@ export function parseQuotaConfig(value: unknown): QuotaConfig {
|
|
|
74
76
|
} catch { throw new QuotaConfigError(); }
|
|
75
77
|
continue;
|
|
76
78
|
}
|
|
79
|
+
if (item.adapter === 'exec') {
|
|
80
|
+
if (Object.keys(item).some(key => !['adapter', 'command', 'label'].includes(key))) throw new QuotaConfigError();
|
|
81
|
+
try {
|
|
82
|
+
providers[provider] = { adapter: 'exec', ...validateExecOptions(item) };
|
|
83
|
+
} catch { throw new QuotaConfigError(); }
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
77
86
|
if (item.adapter !== 'new-api'
|
|
78
87
|
|| Object.keys(item).some(key => !['adapter', 'quotaPerUnit', 'currency', ...DASHBOARD_KEYS].includes(key))
|
|
79
88
|
|| (item.quotaPerUnit !== undefined && typeof item.quotaPerUnit !== 'number')
|
|
@@ -102,6 +111,7 @@ export function loadQuotaAdaptersFromSettings(settings: unknown): QuotaAdapter[]
|
|
|
102
111
|
case 'sub2api': return createSub2ApiAdapter(provider);
|
|
103
112
|
case 'opencode-go': return createOpenCodeGoAdapter(provider);
|
|
104
113
|
case 'yescode': return createYesCodeAdapter(provider, options);
|
|
114
|
+
case 'exec': return createExecAdapter(provider, options);
|
|
105
115
|
case 'new-api': return createNewApiAdapter(provider, options);
|
|
106
116
|
}
|
|
107
117
|
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { QuotaError } from './types.ts';
|
|
3
|
+
import type { QuotaAdapter, QuotaSnapshot } from './types.ts';
|
|
4
|
+
|
|
5
|
+
export interface ExecOptions { command: string[]; label: string }
|
|
6
|
+
|
|
7
|
+
export function validateExecOptions(options: { command?: unknown; label?: unknown }): ExecOptions {
|
|
8
|
+
const { command, label } = options;
|
|
9
|
+
if (!Array.isArray(command) || command.length === 0 || command.length > 16
|
|
10
|
+
|| command.some(part => typeof part !== 'string' || part.trim() === '' || part.length > 512)) {
|
|
11
|
+
throw new Error('Invalid exec options');
|
|
12
|
+
}
|
|
13
|
+
if (typeof label !== 'string' || label.trim() === '' || label.length > 64) throw new Error('Invalid exec options');
|
|
14
|
+
return { command: [...command] as string[], label };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Same bound as the HTTP clients: quota payloads are small.
|
|
18
|
+
const MAX_OUTPUT_BYTES = 256 * 1024;
|
|
19
|
+
|
|
20
|
+
function runCommand(command: readonly string[], signal: AbortSignal): Promise<string> {
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
let settled = false;
|
|
23
|
+
const fail = (error: unknown) => { if (!settled) { settled = true; reject(error); } };
|
|
24
|
+
const done = (text: string) => { if (!settled) { settled = true; resolve(text); } };
|
|
25
|
+
let child;
|
|
26
|
+
try {
|
|
27
|
+
// No shell: argv passes verbatim; settings.json is the only trust boundary.
|
|
28
|
+
// The controller bounds the wait via the signal even if the child hangs.
|
|
29
|
+
child = spawn(command[0], command.slice(1), { signal, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
30
|
+
} catch { fail(new QuotaError('network')); return; }
|
|
31
|
+
let output = '';
|
|
32
|
+
child.stdout?.setEncoding('utf8');
|
|
33
|
+
child.stdout?.on('data', (chunk: string) => {
|
|
34
|
+
output += chunk;
|
|
35
|
+
if (output.length > MAX_OUTPUT_BYTES) { child.kill(); fail(new QuotaError('schema')); }
|
|
36
|
+
});
|
|
37
|
+
child.on('error', () => fail(signal.aborted ? signal.reason : new QuotaError('network')));
|
|
38
|
+
child.on('close', code => {
|
|
39
|
+
if (signal.aborted) fail(signal.reason);
|
|
40
|
+
else if (code !== 0) fail(new QuotaError('network'));
|
|
41
|
+
else done(output);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function createExecAdapter(provider: string, options: ExecOptions): QuotaAdapter {
|
|
47
|
+
return {
|
|
48
|
+
provider, label: options.label,
|
|
49
|
+
async query(context) {
|
|
50
|
+
const text = await runCommand(options.command, context.signal);
|
|
51
|
+
let payload: unknown;
|
|
52
|
+
try { payload = JSON.parse(text); } catch { throw new QuotaError('schema'); }
|
|
53
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) throw new QuotaError('schema');
|
|
54
|
+
// fetchedAt is stamped here, never trusted from the command; the
|
|
55
|
+
// controller's validateSnapshot performs the real schema check.
|
|
56
|
+
return { ...(payload as Record<string, unknown>), fetchedAt: context.now() } as QuotaSnapshot;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|