aicredits 0.0.0-stage → 0.1.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/LICENSE +22 -0
- package/README.md +55 -2
- package/bin/aicredits.js +10 -0
- package/package.json +35 -4
- package/src/api.js +33 -0
- package/src/cli.js +341 -0
- package/src/constants.js +31 -0
- package/src/files.js +59 -0
- package/src/shell.js +52 -0
- package/src/tools/claude.js +80 -0
- package/src/tools/codex.js +114 -0
- package/src/tools/manual.js +7 -0
- package/src/tools/opencode.js +76 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AICredits
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# aicredits
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use **Claude Code**, **Codex CLI** and **OpenCode** with [AICredits](https://aicredits.in): one API key for Claude, GPT, Gemini, DeepSeek, GLM and 500+ more models, paid in rupees with UPI, cards or net banking, with a GST invoice on every top-up.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npx aicredits init
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
The command asks for your API key, checks it, shows your wallet balance, and configures every supported tool it finds on your machine. Then open a new terminal and run `claude`, `codex` or `opencode` as usual. Every request bills to your AICredits wallet in rupees.
|
|
10
|
+
|
|
11
|
+
Get a key at [aicredits.in/dashboard/keys](https://aicredits.in/dashboard/keys?utm_source=github). Top-ups start at ₹50.
|
|
12
|
+
|
|
13
|
+
## What it changes
|
|
14
|
+
|
|
15
|
+
| Tool | File | What is written |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Claude Code | `~/.claude/settings.json` | `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` and the Opus, Sonnet and Haiku model ids. Removes a conflicting `ANTHROPIC_API_KEY`. |
|
|
18
|
+
| Codex CLI | `~/.codex/config.toml` | An `aicredits` model provider (Responses API), set as the default unless you say no. |
|
|
19
|
+
| Codex CLI | `~/.zshrc`, `~/.bashrc` or fish config | `AICREDITS_API_KEY`, which Codex reads the key from. Asked first. |
|
|
20
|
+
| OpenCode | `~/.config/opencode/opencode.json` | An `aicredits` provider with popular models, set as the default unless you say no. |
|
|
21
|
+
|
|
22
|
+
Every file is backed up next to itself (`*.aicredits-backup-*`) before it changes. Other settings in these files are kept.
|
|
23
|
+
|
|
24
|
+
## Commands
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npx aicredits init # set up your tools
|
|
28
|
+
npx aicredits doctor # check what is set up, spot conflicts, show balance
|
|
29
|
+
npx aicredits remove # undo what init changed
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Options for `init`:
|
|
33
|
+
|
|
34
|
+
| Option | Meaning |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `--key sk-...` | Use this key instead of asking (or set `AICREDITS_API_KEY`) |
|
|
37
|
+
| `--tools claude,codex,opencode` | Configure only these tools |
|
|
38
|
+
| `-y`, `--yes` | Accept every default without asking |
|
|
39
|
+
| `--no-default` | Add AICredits without making it the default in Codex and OpenCode |
|
|
40
|
+
| `--no-shell` | Do not add `AICREDITS_API_KEY` to your shell profile |
|
|
41
|
+
|
|
42
|
+
## Editor tools
|
|
43
|
+
|
|
44
|
+
Cursor, Cline, Continue, Zed and Aider keep keys in their own settings screens, so set them up there. Each has a two-minute guide in the [AICredits docs](https://aicredits.in/docs/community).
|
|
45
|
+
|
|
46
|
+
## Budgets
|
|
47
|
+
|
|
48
|
+
Coding agents send many requests per task. Create a separate key for each tool in the dashboard and give it a rupee budget. When the budget is used up that key stops, and your other keys keep working.
|
|
49
|
+
|
|
50
|
+
## Privacy
|
|
51
|
+
|
|
52
|
+
The CLI talks only to `api.aicredits.in`, to check your key and read the model list. It sends no telemetry. Your key is written only to the files listed above.
|
|
53
|
+
|
|
54
|
+
## License
|
|
55
|
+
|
|
56
|
+
MIT
|
package/bin/aicredits.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aicredits",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Set up Claude Code, Codex CLI and OpenCode to use AICredits (pay for AI APIs in INR) in one command.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"aicredits": "bin/aicredits.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"aicredits",
|
|
23
|
+
"claude-code",
|
|
24
|
+
"codex",
|
|
25
|
+
"opencode",
|
|
26
|
+
"llm",
|
|
27
|
+
"india",
|
|
28
|
+
"upi",
|
|
29
|
+
"inr"
|
|
30
|
+
],
|
|
31
|
+
"homepage": "https://aicredits.in",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/AiCredits-in/cli.git"
|
|
35
|
+
},
|
|
36
|
+
"license": "MIT"
|
|
37
|
+
}
|
package/src/api.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { VERSION } from './constants.js';
|
|
2
|
+
|
|
3
|
+
function headers(key) {
|
|
4
|
+
return {
|
|
5
|
+
Authorization: `Bearer ${key}`,
|
|
6
|
+
'User-Agent': `aicredits-cli/${VERSION}`,
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export async function checkKey(baseUrl, key) {
|
|
11
|
+
let res;
|
|
12
|
+
try {
|
|
13
|
+
res = await fetch(`${baseUrl}/v1/credits`, { headers: headers(key), signal: AbortSignal.timeout(15000) });
|
|
14
|
+
} catch (err) {
|
|
15
|
+
return { ok: false, reason: 'network', message: err.message };
|
|
16
|
+
}
|
|
17
|
+
if (res.status === 401 || res.status === 403) return { ok: false, reason: 'invalid' };
|
|
18
|
+
if (!res.ok) return { ok: false, reason: 'http', message: `HTTP ${res.status}` };
|
|
19
|
+
const body = await res.json().catch(() => ({}));
|
|
20
|
+
const balance = body?.data?.credits_inr;
|
|
21
|
+
return { ok: true, balance: typeof balance === 'number' ? balance : null };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function listModels(baseUrl, key) {
|
|
25
|
+
try {
|
|
26
|
+
const res = await fetch(`${baseUrl}/v1/models`, { headers: headers(key), signal: AbortSignal.timeout(15000) });
|
|
27
|
+
if (!res.ok) return null;
|
|
28
|
+
const body = await res.json();
|
|
29
|
+
return new Set((body?.data ?? []).map((m) => m.id));
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import readline from 'node:readline';
|
|
5
|
+
import { Writable } from 'node:stream';
|
|
6
|
+
import { checkKey, listModels } from './api.js';
|
|
7
|
+
import { BILLING_URL, DEFAULT_BASE_URL, DOCS_URL, ENV_VAR, KEYS_URL, VERSION } from './constants.js';
|
|
8
|
+
import { findAnthropicKeyConflicts, removeEnvVar, shellProfile, writeEnvVar } from './shell.js';
|
|
9
|
+
import { claude } from './tools/claude.js';
|
|
10
|
+
import { codex } from './tools/codex.js';
|
|
11
|
+
import { opencode } from './tools/opencode.js';
|
|
12
|
+
import { MANUAL_TOOLS } from './tools/manual.js';
|
|
13
|
+
|
|
14
|
+
export const TOOLS = [claude, codex, opencode];
|
|
15
|
+
|
|
16
|
+
const HELP = `aicredits ${VERSION}: use Claude Code, Codex CLI and OpenCode with AICredits (pay in INR)
|
|
17
|
+
|
|
18
|
+
Usage:
|
|
19
|
+
npx aicredits init Set up your coding tools with your AICredits key
|
|
20
|
+
npx aicredits doctor Check what is set up and your wallet balance
|
|
21
|
+
npx aicredits remove Undo what init changed
|
|
22
|
+
|
|
23
|
+
Options for init:
|
|
24
|
+
--key <sk-...> API key (otherwise read from ${ENV_VAR} or asked)
|
|
25
|
+
--tools <list> Comma list: ${TOOLS.map((t) => t.id).join(',')} (default: the ones installed)
|
|
26
|
+
-y, --yes Accept every default without asking
|
|
27
|
+
--no-default Add AICredits without making it the default in Codex and OpenCode
|
|
28
|
+
--no-shell Do not add ${ENV_VAR} to your shell profile (Codex needs it)
|
|
29
|
+
--base-url <url> API base URL (default ${DEFAULT_BASE_URL})
|
|
30
|
+
|
|
31
|
+
Every file is backed up next to itself before it is changed.
|
|
32
|
+
Get a key: ${KEYS_URL}
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
export function parseArgs(argv) {
|
|
36
|
+
const opts = { command: null, yes: false, makeDefault: true, shell: true, baseUrl: DEFAULT_BASE_URL };
|
|
37
|
+
for (let i = 0; i < argv.length; i++) {
|
|
38
|
+
const a = argv[i];
|
|
39
|
+
const value = () => {
|
|
40
|
+
const v = argv[++i];
|
|
41
|
+
if (v === undefined) throw new Error(`${a} needs a value`);
|
|
42
|
+
return v;
|
|
43
|
+
};
|
|
44
|
+
if (a === '--key') opts.key = value();
|
|
45
|
+
else if (a === '--tools') opts.tools = value().split(',').map((s) => s.trim()).filter(Boolean);
|
|
46
|
+
else if (a === '--base-url') opts.baseUrl = value().replace(/\/+$/, '').replace(/\/v1$/, '');
|
|
47
|
+
else if (a === '-y' || a === '--yes') opts.yes = true;
|
|
48
|
+
else if (a === '--no-default') opts.makeDefault = false;
|
|
49
|
+
else if (a === '--no-shell') opts.shell = false;
|
|
50
|
+
else if (a === '-h' || a === '--help') opts.command = 'help';
|
|
51
|
+
else if (a === '-v' || a === '--version') opts.command = 'version';
|
|
52
|
+
else if (a.startsWith('-')) throw new Error(`Unknown option ${a}. Run "npx aicredits --help".`);
|
|
53
|
+
else if (!opts.command) opts.command = a;
|
|
54
|
+
else throw new Error(`Unexpected argument ${a}`);
|
|
55
|
+
}
|
|
56
|
+
if (opts.tools) {
|
|
57
|
+
const known = new Set(TOOLS.map((t) => t.id));
|
|
58
|
+
const bad = opts.tools.filter((t) => !known.has(t));
|
|
59
|
+
if (bad.length) throw new Error(`Unknown tool ${bad.join(', ')}. Choose from ${[...known].join(', ')}.`);
|
|
60
|
+
}
|
|
61
|
+
return opts;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function onPath(cmd) {
|
|
65
|
+
const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
|
|
66
|
+
return (process.env.PATH ?? '').split(path.delimiter).some((dir) =>
|
|
67
|
+
exts.some((ext) => {
|
|
68
|
+
try {
|
|
69
|
+
fs.accessSync(path.join(dir, cmd + ext), fs.constants.X_OK);
|
|
70
|
+
return true;
|
|
71
|
+
} catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}),
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function createPrompter() {
|
|
79
|
+
const interactive = Boolean(process.stdin.isTTY);
|
|
80
|
+
let muted = false;
|
|
81
|
+
const rl = interactive
|
|
82
|
+
? readline.createInterface({
|
|
83
|
+
input: process.stdin,
|
|
84
|
+
output: new Writable({
|
|
85
|
+
write(chunk, enc, cb) {
|
|
86
|
+
if (!muted) process.stdout.write(chunk, enc);
|
|
87
|
+
cb();
|
|
88
|
+
},
|
|
89
|
+
}),
|
|
90
|
+
terminal: true,
|
|
91
|
+
})
|
|
92
|
+
: null;
|
|
93
|
+
const ask = (q) =>
|
|
94
|
+
new Promise((resolve) => {
|
|
95
|
+
rl.question(q, (a) => resolve(a.trim()));
|
|
96
|
+
});
|
|
97
|
+
return {
|
|
98
|
+
interactive,
|
|
99
|
+
async confirm(question, def = true) {
|
|
100
|
+
if (!interactive) return def;
|
|
101
|
+
const a = (await ask(`${question} ${def ? '(Y/n)' : '(y/N)'} `)).toLowerCase();
|
|
102
|
+
return a === '' ? def : a.startsWith('y');
|
|
103
|
+
},
|
|
104
|
+
async secret(question) {
|
|
105
|
+
if (!interactive) return '';
|
|
106
|
+
process.stdout.write(question);
|
|
107
|
+
muted = true;
|
|
108
|
+
const a = await ask('');
|
|
109
|
+
muted = false;
|
|
110
|
+
process.stdout.write('\n');
|
|
111
|
+
return a;
|
|
112
|
+
},
|
|
113
|
+
close() {
|
|
114
|
+
rl?.close();
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function rel(file, home) {
|
|
120
|
+
return file.startsWith(home) ? `~${file.slice(home.length)}` : file;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function formatINR(n) {
|
|
124
|
+
return `₹${n.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function runInit(opts, io) {
|
|
128
|
+
const home = os.homedir();
|
|
129
|
+
const log = io.log;
|
|
130
|
+
log(`\nAICredits setup ${VERSION}\n`);
|
|
131
|
+
|
|
132
|
+
let key = opts.key ?? process.env[ENV_VAR] ?? '';
|
|
133
|
+
if (!key) {
|
|
134
|
+
if (!io.prompt.interactive) throw new Error(`No key given. Pass --key sk-... or set ${ENV_VAR}.`);
|
|
135
|
+
log(`Create a key at ${KEYS_URL}`);
|
|
136
|
+
key = await io.prompt.secret('Paste your AICredits API key (hidden): ');
|
|
137
|
+
}
|
|
138
|
+
key = key.trim();
|
|
139
|
+
if (!key.startsWith('sk-')) throw new Error('That does not look like an AICredits key (they start with "sk-").');
|
|
140
|
+
|
|
141
|
+
const check = await io.checkKey(opts.baseUrl, key);
|
|
142
|
+
if (!check.ok && check.reason === 'invalid') {
|
|
143
|
+
throw new Error(`The key was rejected. Check it at ${KEYS_URL}`);
|
|
144
|
+
}
|
|
145
|
+
if (!check.ok) {
|
|
146
|
+
log(`! Could not reach ${opts.baseUrl} to check the key (${check.message}). Continuing anyway.`);
|
|
147
|
+
} else if (check.balance !== null) {
|
|
148
|
+
log(`✓ Key works. Wallet balance: ${formatINR(check.balance)}`);
|
|
149
|
+
if (check.balance <= 0) log(` Your wallet is empty. Top up with UPI: ${BILLING_URL}`);
|
|
150
|
+
} else {
|
|
151
|
+
log('✓ Key works.');
|
|
152
|
+
}
|
|
153
|
+
const models = check.ok ? await io.listModels(opts.baseUrl, key) : null;
|
|
154
|
+
|
|
155
|
+
const detected = TOOLS.filter((t) => t.detect({ home, onPath: io.onPath }));
|
|
156
|
+
let chosen;
|
|
157
|
+
if (opts.tools) chosen = TOOLS.filter((t) => opts.tools.includes(t.id));
|
|
158
|
+
else if (detected.length === 0) chosen = [];
|
|
159
|
+
else if (opts.yes) chosen = detected;
|
|
160
|
+
else {
|
|
161
|
+
chosen = [];
|
|
162
|
+
for (const t of detected) if (await io.prompt.confirm(`Set up ${t.name}?`)) chosen.push(t);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (chosen.length === 0) {
|
|
166
|
+
log('\nNo supported terminal tool found (Claude Code, Codex CLI or OpenCode).');
|
|
167
|
+
log('Install one, then run "npx aicredits init" again:');
|
|
168
|
+
log(' npm install -g @anthropic-ai/claude-code');
|
|
169
|
+
log(' npm install -g @openai/codex');
|
|
170
|
+
printManual(log);
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let makeDefault = opts.makeDefault;
|
|
175
|
+
if (makeDefault && !opts.yes && chosen.some((t) => t !== claude)) {
|
|
176
|
+
makeDefault = await io.prompt.confirm('Make AICredits the default provider in Codex and OpenCode?');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const changed = [];
|
|
180
|
+
let failed = 0;
|
|
181
|
+
for (const t of chosen) {
|
|
182
|
+
try {
|
|
183
|
+
const res = t.configure({ home, baseUrl: opts.baseUrl, key, models, makeDefault });
|
|
184
|
+
changed.push({ tool: t, ...res });
|
|
185
|
+
log(`✓ ${t.name}: updated ${rel(res.file, home)}`);
|
|
186
|
+
for (const n of res.notes) log(` ${n}`);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
failed++;
|
|
189
|
+
log(`✗ ${t.name}: ${err.message}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const codexDone = changed.some((c) => c.tool === codex);
|
|
194
|
+
let shellFile = null;
|
|
195
|
+
if (codexDone) {
|
|
196
|
+
const profile = shellProfile(home);
|
|
197
|
+
if (!profile) {
|
|
198
|
+
log(`\n Codex reads the key from ${ENV_VAR}. On Windows run once, then open a new terminal:`);
|
|
199
|
+
log(` setx ${ENV_VAR} "${key.slice(0, 6)}..." (use your full key)`);
|
|
200
|
+
} else if (process.env[ENV_VAR] === key) {
|
|
201
|
+
log(` ${ENV_VAR} is already set in this shell.`);
|
|
202
|
+
} else if (
|
|
203
|
+
opts.shell &&
|
|
204
|
+
(opts.yes || (await io.prompt.confirm(`Codex needs ${ENV_VAR}. Add it to ${rel(profile.file, home)}?`)))
|
|
205
|
+
) {
|
|
206
|
+
const res = writeEnvVar(profile, key);
|
|
207
|
+
shellFile = res.file;
|
|
208
|
+
log(`✓ Shell: added ${ENV_VAR} to ${rel(res.file, home)}`);
|
|
209
|
+
} else {
|
|
210
|
+
log(` Codex needs this in your shell profile: export ${ENV_VAR}=<your key>`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (changed.some((c) => c.tool === claude)) {
|
|
215
|
+
const hits = findAnthropicKeyConflicts(home);
|
|
216
|
+
if (process.env.ANTHROPIC_API_KEY || hits.length) {
|
|
217
|
+
log('\n! ANTHROPIC_API_KEY is set. Remove it, or Claude Code will send each request twice:');
|
|
218
|
+
for (const h of hits) log(` ${rel(h, home)}`);
|
|
219
|
+
if (process.env.ANTHROPIC_API_KEY && !hits.length) log(' (set in this shell; unset ANTHROPIC_API_KEY)');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const backups = changed.map((c) => c.backup).filter(Boolean);
|
|
224
|
+
if (backups.length) log(`\nBackups saved next to each file (*.aicredits-backup-*). Undo with "npx aicredits remove".`);
|
|
225
|
+
|
|
226
|
+
log('\nNext:');
|
|
227
|
+
if (codexDone || shellFile) log(' Open a new terminal so the settings load.');
|
|
228
|
+
if (changed.some((c) => c.tool === claude)) log(' claude (Claude Code now bills to your AICredits wallet)');
|
|
229
|
+
if (codexDone) log(' codex');
|
|
230
|
+
if (changed.some((c) => c.tool === opencode)) log(' opencode');
|
|
231
|
+
log(` Usage in rupees: https://aicredits.in/dashboard/usage`);
|
|
232
|
+
printManual(log);
|
|
233
|
+
return failed ? 1 : 0;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function printManual(log) {
|
|
237
|
+
log(`\nEditor tools are set up from their settings screen: ${MANUAL_TOOLS.map((t) => t.name).join(', ')}.`);
|
|
238
|
+
log(`Guides: ${DOCS_URL}/community`);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function runDoctor(opts, io) {
|
|
242
|
+
const home = os.homedir();
|
|
243
|
+
const log = io.log;
|
|
244
|
+
log(`\nAICredits doctor ${VERSION}\n`);
|
|
245
|
+
for (const t of TOOLS) {
|
|
246
|
+
let s;
|
|
247
|
+
try {
|
|
248
|
+
s = t.status({ home, baseUrl: opts.baseUrl });
|
|
249
|
+
} catch (err) {
|
|
250
|
+
log(`✗ ${t.name}: ${err.message}`);
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (!s.configured) {
|
|
254
|
+
const installed = t.detect({ home, onPath: io.onPath });
|
|
255
|
+
log(`- ${t.name}: ${installed ? 'installed, not using AICredits' : 'not installed'}`);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const extra = [s.model && `model ${s.model}`, s.isDefault === false && 'not the default provider']
|
|
259
|
+
.filter(Boolean)
|
|
260
|
+
.join(', ');
|
|
261
|
+
log(`✓ ${t.name}: using AICredits${extra ? ` (${extra})` : ''}`);
|
|
262
|
+
if (s.conflict) log(' ! ANTHROPIC_API_KEY is also set in settings.json; remove it.');
|
|
263
|
+
}
|
|
264
|
+
if (codex.status({ home }).configured && !process.env[ENV_VAR]) {
|
|
265
|
+
log(`! ${ENV_VAR} is not set in this shell, so Codex cannot authenticate. Open a new terminal or run init again.`);
|
|
266
|
+
}
|
|
267
|
+
const hits = findAnthropicKeyConflicts(home);
|
|
268
|
+
if (process.env.ANTHROPIC_API_KEY || hits.length) {
|
|
269
|
+
log('! ANTHROPIC_API_KEY is set; Claude Code may send each request twice.');
|
|
270
|
+
for (const h of hits) log(` ${rel(h, home)}`);
|
|
271
|
+
}
|
|
272
|
+
const key = opts.key ?? process.env[ENV_VAR];
|
|
273
|
+
if (key) {
|
|
274
|
+
const check = await io.checkKey(opts.baseUrl, key);
|
|
275
|
+
if (check.ok && check.balance !== null) log(`\nWallet balance: ${formatINR(check.balance)}`);
|
|
276
|
+
else if (!check.ok && check.reason === 'invalid') log(`\n✗ The key in ${ENV_VAR} was rejected.`);
|
|
277
|
+
else if (!check.ok) log(`\n! Could not reach the API: ${check.message}`);
|
|
278
|
+
}
|
|
279
|
+
return 0;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function runRemove(opts, io) {
|
|
283
|
+
const home = os.homedir();
|
|
284
|
+
const log = io.log;
|
|
285
|
+
if (!opts.yes && !(await io.prompt.confirm('Remove AICredits from Claude Code, Codex, OpenCode and your shell profile?'))) {
|
|
286
|
+
return 0;
|
|
287
|
+
}
|
|
288
|
+
let any = false;
|
|
289
|
+
for (const t of TOOLS) {
|
|
290
|
+
try {
|
|
291
|
+
const res = t.remove({ home, baseUrl: opts.baseUrl });
|
|
292
|
+
if (res) {
|
|
293
|
+
any = true;
|
|
294
|
+
log(`✓ ${t.name}: removed from ${rel(res.file, home)}`);
|
|
295
|
+
}
|
|
296
|
+
} catch (err) {
|
|
297
|
+
log(`✗ ${t.name}: ${err.message}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const profile = shellProfile(home);
|
|
301
|
+
const res = profile && removeEnvVar(profile);
|
|
302
|
+
if (res) {
|
|
303
|
+
any = true;
|
|
304
|
+
log(`✓ Shell: removed ${ENV_VAR} from ${rel(res.file, home)}`);
|
|
305
|
+
}
|
|
306
|
+
log(any ? '\nDone. Open a new terminal. Backups of each file were kept.' : 'Nothing to remove.');
|
|
307
|
+
return 0;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export async function main(argv, deps = {}) {
|
|
311
|
+
const opts = parseArgs(argv);
|
|
312
|
+
const io = {
|
|
313
|
+
log: deps.log ?? ((m) => console.log(m)),
|
|
314
|
+
checkKey: deps.checkKey ?? checkKey,
|
|
315
|
+
listModels: deps.listModels ?? listModels,
|
|
316
|
+
onPath: deps.onPath ?? onPath,
|
|
317
|
+
prompt: deps.prompt ?? createPrompter(),
|
|
318
|
+
};
|
|
319
|
+
try {
|
|
320
|
+
switch (opts.command ?? 'init') {
|
|
321
|
+
case 'init':
|
|
322
|
+
return await runInit(opts, io);
|
|
323
|
+
case 'doctor':
|
|
324
|
+
return await runDoctor(opts, io);
|
|
325
|
+
case 'remove':
|
|
326
|
+
case 'uninstall':
|
|
327
|
+
return await runRemove(opts, io);
|
|
328
|
+
case 'help':
|
|
329
|
+
io.log(HELP);
|
|
330
|
+
return 0;
|
|
331
|
+
case 'version':
|
|
332
|
+
io.log(VERSION);
|
|
333
|
+
return 0;
|
|
334
|
+
default:
|
|
335
|
+
io.log(HELP);
|
|
336
|
+
return 1;
|
|
337
|
+
}
|
|
338
|
+
} finally {
|
|
339
|
+
io.prompt.close?.();
|
|
340
|
+
}
|
|
341
|
+
}
|
package/src/constants.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
|
|
3
|
+
export const VERSION = createRequire(import.meta.url)('../package.json').version;
|
|
4
|
+
export const DEFAULT_BASE_URL = 'https://api.aicredits.in';
|
|
5
|
+
export const ENV_VAR = 'AICREDITS_API_KEY';
|
|
6
|
+
export const KEYS_URL = 'https://aicredits.in/dashboard/keys?utm_source=cli';
|
|
7
|
+
export const BILLING_URL = 'https://aicredits.in/dashboard/billing?utm_source=cli';
|
|
8
|
+
export const DOCS_URL = 'https://aicredits.in/docs';
|
|
9
|
+
|
|
10
|
+
export const CLAUDE_MODELS = {
|
|
11
|
+
opus: 'anthropic/claude-opus-5.5',
|
|
12
|
+
sonnet: 'anthropic/claude-sonnet-5.5',
|
|
13
|
+
haiku: 'anthropic/claude-haiku-5.5',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const CODEX_DEFAULT_MODEL = 'openai/gpt-5.3-codex';
|
|
17
|
+
|
|
18
|
+
export const OPENCODE_MODELS = [
|
|
19
|
+
'anthropic/claude-sonnet-5.5',
|
|
20
|
+
'anthropic/claude-opus-5.5',
|
|
21
|
+
'anthropic/claude-haiku-5.5',
|
|
22
|
+
'openai/gpt-5.3-codex',
|
|
23
|
+
'openai/gpt-6-luna',
|
|
24
|
+
'deepseek/deepseek-v4.1-flash',
|
|
25
|
+
'z-ai/glm-5.2',
|
|
26
|
+
'google/gemini-3.8-flash',
|
|
27
|
+
];
|
|
28
|
+
export const OPENCODE_DEFAULT_MODEL = 'anthropic/claude-sonnet-5.5';
|
|
29
|
+
|
|
30
|
+
export const BLOCK_START = '# >>> aicredits >>>';
|
|
31
|
+
export const BLOCK_END = '# <<< aicredits <<<';
|
package/src/files.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
export function readText(file) {
|
|
5
|
+
try {
|
|
6
|
+
return fs.readFileSync(file, 'utf8');
|
|
7
|
+
} catch (err) {
|
|
8
|
+
if (err.code === 'ENOENT') return null;
|
|
9
|
+
throw err;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function readJson(file) {
|
|
14
|
+
const text = readText(file);
|
|
15
|
+
if (text === null || text.trim() === '') return {};
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(text);
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error(`${file} is not valid JSON, so it was left untouched. Fix or move it, then run again.`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function backup(file) {
|
|
24
|
+
if (!fs.existsSync(file)) return null;
|
|
25
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
26
|
+
const dest = `${file}.aicredits-backup-${stamp}`;
|
|
27
|
+
fs.copyFileSync(file, dest);
|
|
28
|
+
fs.chmodSync(dest, 0o600);
|
|
29
|
+
return dest;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function writeText(file, text, { mode } = {}) {
|
|
33
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
34
|
+
const tmp = `${file}.aicredits-tmp`;
|
|
35
|
+
fs.writeFileSync(tmp, text, mode ? { mode } : undefined);
|
|
36
|
+
fs.renameSync(tmp, file);
|
|
37
|
+
if (mode) fs.chmodSync(file, mode);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function writeJson(file, data, opts) {
|
|
41
|
+
writeText(file, `${JSON.stringify(data, null, 2)}\n`, opts);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function replaceBlock(text, start, end, body) {
|
|
45
|
+
const source = text ?? '';
|
|
46
|
+
const block = body === null ? '' : `${start}\n${body}\n${end}\n`;
|
|
47
|
+
const i = source.indexOf(start);
|
|
48
|
+
const j = source.indexOf(end);
|
|
49
|
+
if (i !== -1 && j > i) {
|
|
50
|
+
let after = source.slice(j + end.length);
|
|
51
|
+
if (after.startsWith('\n')) after = after.slice(1);
|
|
52
|
+
let before = source.slice(0, i);
|
|
53
|
+
if (body === null && after === '' && before.endsWith('\n\n')) before = before.slice(0, -1);
|
|
54
|
+
return before + block + after;
|
|
55
|
+
}
|
|
56
|
+
if (body === null) return source;
|
|
57
|
+
const sep = source === '' || source.endsWith('\n\n') ? '' : source.endsWith('\n') ? '\n' : '\n\n';
|
|
58
|
+
return source + sep + block;
|
|
59
|
+
}
|
package/src/shell.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { backup, readText, replaceBlock, writeText } from './files.js';
|
|
4
|
+
import { BLOCK_END, BLOCK_START, ENV_VAR } from './constants.js';
|
|
5
|
+
|
|
6
|
+
export function shellProfile(home, shell = process.env.SHELL ?? '') {
|
|
7
|
+
if (process.platform === 'win32') return null;
|
|
8
|
+
const name = path.basename(shell);
|
|
9
|
+
if (name === 'fish') return { file: path.join(home, '.config', 'fish', 'config.fish'), fish: true };
|
|
10
|
+
if (name === 'zsh') return { file: path.join(home, '.zshrc'), fish: false };
|
|
11
|
+
if (name === 'bash') {
|
|
12
|
+
const bashrc = path.join(home, '.bashrc');
|
|
13
|
+
if (process.platform === 'darwin' && !fs.existsSync(bashrc)) {
|
|
14
|
+
return { file: path.join(home, '.bash_profile'), fish: false };
|
|
15
|
+
}
|
|
16
|
+
return { file: bashrc, fish: false };
|
|
17
|
+
}
|
|
18
|
+
return { file: path.join(home, '.profile'), fish: false };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function quote(value) {
|
|
22
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function writeEnvVar(profile, key) {
|
|
26
|
+
const line = profile.fish ? `set -gx ${ENV_VAR} ${quote(key)}` : `export ${ENV_VAR}=${quote(key)}`;
|
|
27
|
+
const text = replaceBlock(readText(profile.file), BLOCK_START, BLOCK_END, line);
|
|
28
|
+
const saved = backup(profile.file);
|
|
29
|
+
writeText(profile.file, text);
|
|
30
|
+
return { file: profile.file, backup: saved };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function removeEnvVar(profile) {
|
|
34
|
+
const original = readText(profile.file);
|
|
35
|
+
if (!original || !original.includes(BLOCK_START)) return null;
|
|
36
|
+
const saved = backup(profile.file);
|
|
37
|
+
writeText(profile.file, replaceBlock(original, BLOCK_START, BLOCK_END, null));
|
|
38
|
+
return { file: profile.file, backup: saved };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function findAnthropicKeyConflicts(home) {
|
|
42
|
+
const files = ['.zshrc', '.bashrc', '.bash_profile', '.profile', '.zprofile'].map((f) => path.join(home, f));
|
|
43
|
+
const hits = [];
|
|
44
|
+
for (const file of files) {
|
|
45
|
+
const text = readText(file);
|
|
46
|
+
if (!text) continue;
|
|
47
|
+
text.split('\n').forEach((line, i) => {
|
|
48
|
+
if (/^\s*(export\s+)?ANTHROPIC_API_KEY\s*=/.test(line)) hits.push(`${file}:${i + 1}`);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return hits;
|
|
52
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { backup, readJson, writeJson } from '../files.js';
|
|
4
|
+
import { CLAUDE_MODELS } from '../constants.js';
|
|
5
|
+
|
|
6
|
+
function isOurs(url, baseUrl) {
|
|
7
|
+
if (!url) return false;
|
|
8
|
+
if (url === baseUrl) return true;
|
|
9
|
+
try {
|
|
10
|
+
return /(^|\.)aicredits\.in$/.test(new URL(url).hostname);
|
|
11
|
+
} catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const OWNED = [
|
|
17
|
+
'ANTHROPIC_BASE_URL',
|
|
18
|
+
'ANTHROPIC_AUTH_TOKEN',
|
|
19
|
+
'ANTHROPIC_MODEL',
|
|
20
|
+
'ANTHROPIC_DEFAULT_OPUS_MODEL',
|
|
21
|
+
'ANTHROPIC_DEFAULT_SONNET_MODEL',
|
|
22
|
+
'ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
export const claude = {
|
|
26
|
+
id: 'claude',
|
|
27
|
+
name: 'Claude Code',
|
|
28
|
+
docs: 'https://aicredits.in/docs/guides/claude-code',
|
|
29
|
+
|
|
30
|
+
file(home) {
|
|
31
|
+
return path.join(home, '.claude', 'settings.json');
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
detect({ home, onPath }) {
|
|
35
|
+
return onPath('claude') || fs.existsSync(path.join(home, '.claude'));
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
configure({ home, baseUrl, key, models }) {
|
|
39
|
+
const file = this.file(home);
|
|
40
|
+
const settings = readJson(file);
|
|
41
|
+
const env = { ...(settings.env ?? {}) };
|
|
42
|
+
const notes = [];
|
|
43
|
+
if (env.ANTHROPIC_API_KEY) {
|
|
44
|
+
delete env.ANTHROPIC_API_KEY;
|
|
45
|
+
notes.push('Removed ANTHROPIC_API_KEY from settings.json (it makes Claude Code send each request twice).');
|
|
46
|
+
}
|
|
47
|
+
const pick = (id) => (models && !models.has(id) ? null : id);
|
|
48
|
+
Object.assign(env, {
|
|
49
|
+
ANTHROPIC_BASE_URL: baseUrl,
|
|
50
|
+
ANTHROPIC_AUTH_TOKEN: key,
|
|
51
|
+
});
|
|
52
|
+
const sonnet = pick(CLAUDE_MODELS.sonnet);
|
|
53
|
+
if (sonnet) env.ANTHROPIC_MODEL = sonnet;
|
|
54
|
+
for (const [tier, id] of Object.entries(CLAUDE_MODELS)) {
|
|
55
|
+
if (pick(id)) env[`ANTHROPIC_DEFAULT_${tier.toUpperCase()}_MODEL`] = id;
|
|
56
|
+
}
|
|
57
|
+
const saved = backup(file);
|
|
58
|
+
writeJson(file, { ...settings, env }, { mode: 0o600 });
|
|
59
|
+
return { file, backup: saved, notes };
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
status({ home, baseUrl }) {
|
|
63
|
+
const env = readJson(this.file(home)).env ?? {};
|
|
64
|
+
if (env.ANTHROPIC_BASE_URL !== baseUrl) return { configured: false };
|
|
65
|
+
return { configured: true, model: env.ANTHROPIC_MODEL, conflict: Boolean(env.ANTHROPIC_API_KEY) };
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
remove({ home, baseUrl }) {
|
|
69
|
+
const file = this.file(home);
|
|
70
|
+
const settings = readJson(file);
|
|
71
|
+
if (!isOurs(settings.env?.ANTHROPIC_BASE_URL, baseUrl)) return null;
|
|
72
|
+
const env = { ...settings.env };
|
|
73
|
+
for (const k of OWNED) delete env[k];
|
|
74
|
+
const next = { ...settings, env };
|
|
75
|
+
if (Object.keys(env).length === 0) delete next.env;
|
|
76
|
+
const saved = backup(file);
|
|
77
|
+
writeJson(file, next, { mode: 0o600 });
|
|
78
|
+
return { file, backup: saved };
|
|
79
|
+
},
|
|
80
|
+
};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { backup, readText, replaceBlock, writeText } from '../files.js';
|
|
4
|
+
import { BLOCK_END, BLOCK_START, CODEX_DEFAULT_MODEL, ENV_VAR } from '../constants.js';
|
|
5
|
+
|
|
6
|
+
const TAG = '# set by aicredits';
|
|
7
|
+
const PREV = '# aicredits previous:';
|
|
8
|
+
const TABLE = '[model_providers.aicredits]';
|
|
9
|
+
|
|
10
|
+
function splitTopLevel(text) {
|
|
11
|
+
const lines = text.split('\n');
|
|
12
|
+
const first = lines.findIndex((l) => /^\s*\[/.test(l));
|
|
13
|
+
const cut = first === -1 ? lines.length : first;
|
|
14
|
+
return { top: lines.slice(0, cut), rest: lines.slice(cut) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function stripUnmarkedTable(lines) {
|
|
18
|
+
const out = [];
|
|
19
|
+
let skipping = false;
|
|
20
|
+
for (const line of lines) {
|
|
21
|
+
if (/^\s*\[/.test(line)) skipping = line.trim() === TABLE;
|
|
22
|
+
if (!skipping) out.push(line);
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function tomlString(s) {
|
|
28
|
+
return JSON.stringify(s);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const codex = {
|
|
32
|
+
id: 'codex',
|
|
33
|
+
name: 'Codex CLI',
|
|
34
|
+
docs: 'https://aicredits.in/docs/guides/codex-cli',
|
|
35
|
+
needsEnvVar: true,
|
|
36
|
+
|
|
37
|
+
file(home) {
|
|
38
|
+
return path.join(home, '.codex', 'config.toml');
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
detect({ home, onPath }) {
|
|
42
|
+
return onPath('codex') || fs.existsSync(path.join(home, '.codex'));
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
configure({ home, baseUrl, models, makeDefault = true }) {
|
|
46
|
+
const file = this.file(home);
|
|
47
|
+
const original = readText(file) ?? '';
|
|
48
|
+
let text = replaceBlock(original, BLOCK_START, BLOCK_END, null);
|
|
49
|
+
let { top, rest } = splitTopLevel(text);
|
|
50
|
+
rest = stripUnmarkedTable(rest);
|
|
51
|
+
|
|
52
|
+
const model = models && !models.has(CODEX_DEFAULT_MODEL) ? null : CODEX_DEFAULT_MODEL;
|
|
53
|
+
if (makeDefault) {
|
|
54
|
+
const prev = [];
|
|
55
|
+
top = top.filter((l) => {
|
|
56
|
+
if (l.startsWith(PREV)) {
|
|
57
|
+
prev.push(l);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const m = l.match(/^\s*(model_provider|model)\s*=/);
|
|
61
|
+
if (!m) return true;
|
|
62
|
+
if (!l.includes(TAG)) prev.push(`${PREV} ${l.trim()}`);
|
|
63
|
+
return false;
|
|
64
|
+
});
|
|
65
|
+
const head = [...prev, `model_provider = "aicredits" ${TAG}`];
|
|
66
|
+
if (model) head.push(`model = ${tomlString(model)} ${TAG}`);
|
|
67
|
+
top = [...head, ...top];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
text = [...top, ...rest].join('\n');
|
|
71
|
+
const body = [
|
|
72
|
+
TABLE,
|
|
73
|
+
'name = "AICredits"',
|
|
74
|
+
`base_url = ${tomlString(`${baseUrl}/v1`)}`,
|
|
75
|
+
`env_key = "${ENV_VAR}"`,
|
|
76
|
+
'wire_api = "responses"',
|
|
77
|
+
].join('\n');
|
|
78
|
+
text = replaceBlock(text, BLOCK_START, BLOCK_END, body);
|
|
79
|
+
|
|
80
|
+
const saved = backup(file);
|
|
81
|
+
writeText(file, text);
|
|
82
|
+
return { file, backup: saved, notes: [] };
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
status({ home }) {
|
|
86
|
+
const text = readText(this.file(home)) ?? '';
|
|
87
|
+
if (!text.includes(TABLE)) return { configured: false };
|
|
88
|
+
const { top } = splitTopLevel(text);
|
|
89
|
+
const isDefault = top.some((l) => /^\s*model_provider\s*=\s*"aicredits"/.test(l));
|
|
90
|
+
const model = top.map((l) => l.match(/^\s*model\s*=\s*"([^"]+)"/)).find(Boolean)?.[1];
|
|
91
|
+
return { configured: true, isDefault, model };
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
remove({ home }) {
|
|
95
|
+
const file = this.file(home);
|
|
96
|
+
const original = readText(file);
|
|
97
|
+
if (!original || !original.includes(TABLE)) return null;
|
|
98
|
+
let text = replaceBlock(original, BLOCK_START, BLOCK_END, null);
|
|
99
|
+
let { top, rest } = splitTopLevel(text);
|
|
100
|
+
rest = stripUnmarkedTable(rest);
|
|
101
|
+
const restored = [];
|
|
102
|
+
top = top.filter((l) => {
|
|
103
|
+
if (l.startsWith(PREV)) {
|
|
104
|
+
restored.push(l.slice(PREV.length).trim());
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
return !l.includes(TAG);
|
|
108
|
+
});
|
|
109
|
+
text = [...restored, ...top, ...rest].join('\n');
|
|
110
|
+
const saved = backup(file);
|
|
111
|
+
writeText(file, text);
|
|
112
|
+
return { file, backup: saved };
|
|
113
|
+
},
|
|
114
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export const MANUAL_TOOLS = [
|
|
2
|
+
{ name: 'Cursor', docs: 'https://aicredits.in/docs/community/cursor' },
|
|
3
|
+
{ name: 'Cline', docs: 'https://aicredits.in/docs/community/cline' },
|
|
4
|
+
{ name: 'Continue', docs: 'https://aicredits.in/docs/community/continue' },
|
|
5
|
+
{ name: 'Zed', docs: 'https://aicredits.in/docs/community/zed' },
|
|
6
|
+
{ name: 'Aider', docs: 'https://aicredits.in/docs/community/aider' },
|
|
7
|
+
];
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { backup, readJson, writeJson } from '../files.js';
|
|
4
|
+
import { OPENCODE_DEFAULT_MODEL, OPENCODE_MODELS } from '../constants.js';
|
|
5
|
+
|
|
6
|
+
const CANDIDATES = ['opencode.json', 'opencode.jsonc', 'config.json'];
|
|
7
|
+
|
|
8
|
+
function configDir(home) {
|
|
9
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
10
|
+
return path.join(xdg && xdg.startsWith('/') ? xdg : path.join(home, '.config'), 'opencode');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const opencode = {
|
|
14
|
+
id: 'opencode',
|
|
15
|
+
name: 'OpenCode',
|
|
16
|
+
docs: 'https://aicredits.in/docs/community/opencode',
|
|
17
|
+
|
|
18
|
+
file(home) {
|
|
19
|
+
const dir = configDir(home);
|
|
20
|
+
const found = CANDIDATES.map((f) => path.join(dir, f)).find((f) => fs.existsSync(f));
|
|
21
|
+
return found ?? path.join(dir, 'opencode.json');
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
detect({ home, onPath }) {
|
|
25
|
+
return onPath('opencode') || fs.existsSync(configDir(home));
|
|
26
|
+
},
|
|
27
|
+
|
|
28
|
+
configure({ home, baseUrl, key, models, makeDefault = true }) {
|
|
29
|
+
const file = this.file(home);
|
|
30
|
+
if (file.endsWith('.jsonc')) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
`${file} uses JSON with comments, which this tool will not rewrite. Add the provider by hand: ${this.docs}`,
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
const config = readJson(file);
|
|
36
|
+
const ids = OPENCODE_MODELS.filter((id) => !models || models.has(id));
|
|
37
|
+
const provider = {
|
|
38
|
+
npm: '@ai-sdk/openai-compatible',
|
|
39
|
+
name: 'AICredits',
|
|
40
|
+
options: { baseURL: `${baseUrl}/v1`, apiKey: key },
|
|
41
|
+
models: Object.fromEntries(ids.map((id) => [id, {}])),
|
|
42
|
+
};
|
|
43
|
+
const next = {
|
|
44
|
+
...(Object.keys(config).length === 0 ? { $schema: 'https://opencode.ai/config.json' } : {}),
|
|
45
|
+
...config,
|
|
46
|
+
provider: { ...(config.provider ?? {}), aicredits: provider },
|
|
47
|
+
};
|
|
48
|
+
const def = ids.includes(OPENCODE_DEFAULT_MODEL) ? OPENCODE_DEFAULT_MODEL : ids[0];
|
|
49
|
+
if (makeDefault && def) next.model = `aicredits/${def}`;
|
|
50
|
+
const saved = backup(file);
|
|
51
|
+
writeJson(file, next, { mode: 0o600 });
|
|
52
|
+
return { file, backup: saved, notes: [] };
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
status({ home }) {
|
|
56
|
+
const file = this.file(home);
|
|
57
|
+
if (file.endsWith('.jsonc')) return { configured: false };
|
|
58
|
+
const config = readJson(file);
|
|
59
|
+
if (!config.provider?.aicredits) return { configured: false };
|
|
60
|
+
return { configured: true, model: config.model, isDefault: String(config.model ?? '').startsWith('aicredits/') };
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
remove({ home }) {
|
|
64
|
+
const file = this.file(home);
|
|
65
|
+
if (file.endsWith('.jsonc')) return null;
|
|
66
|
+
const config = readJson(file);
|
|
67
|
+
if (!config.provider?.aicredits) return null;
|
|
68
|
+
const { aicredits: _, ...others } = config.provider;
|
|
69
|
+
const next = { ...config, provider: others };
|
|
70
|
+
if (Object.keys(others).length === 0) delete next.provider;
|
|
71
|
+
if (String(next.model ?? '').startsWith('aicredits/')) delete next.model;
|
|
72
|
+
const saved = backup(file);
|
|
73
|
+
writeJson(file, next, { mode: 0o600 });
|
|
74
|
+
return { file, backup: saved };
|
|
75
|
+
},
|
|
76
|
+
};
|