codex-unlimited 0.0.0-stage → 0.2.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 +27 -2
- package/api-key.mjs +61 -0
- package/cli.mjs +287 -0
- package/config.mjs +160 -0
- package/package.json +9 -4
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# codex-unlimited
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CLI độc lập của HRX để cấu hình Codex bằng khóa API thường hoặc mã gói theo giờ/token. Cần Node.js 20 trở lên và Codex.
|
|
4
|
+
|
|
5
|
+
## Khóa API thường
|
|
6
|
+
|
|
7
|
+
Trong **Khóa API → Sử dụng khóa API → Codex CLI**, chạy lệnh sau, bấm **Sao chép mã thiết lập** rồi dán vào lời nhắc ẩn. Xác nhận địa chỉ dịch vụ và mở lại Codex.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx --yes codex-unlimited@0.2.0 setup
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Để nhập khóa trực tiếp, chạy `npx --yes codex-unlimited@0.2.0 setup https://api.hugorix.com/v1` và dán khóa khi được hỏi. Công cụ đọc danh sách model để kiểm tra kết nối. Với cách cài bằng npx, dùng `npx --yes codex-unlimited@0.2.0 restore` để khôi phục cấu hình trước đó.
|
|
14
|
+
|
|
15
|
+
## Gói HRX
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install -g codex-unlimited
|
|
19
|
+
codex-unlimited
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Dán toàn bộ mã người bán gửi. Công cụ hiển thị địa chỉ nhận yêu cầu trước khi bạn xác nhận kích hoạt. Giờ bắt đầu và số dư do máy chủ xác nhận. Credential của gói được lưu trong thư mục cấu hình Codex của người dùng.
|
|
23
|
+
|
|
24
|
+
- `codex-unlimited status` xem thời hạn và số token còn khả dụng.
|
|
25
|
+
- `codex-unlimited repair` áp dụng lại cấu hình sau khi sửa kết nối.
|
|
26
|
+
- `codex-unlimited restore` khôi phục cấu hình trước khi gỡ công cụ.
|
|
27
|
+
|
|
28
|
+
Sau khi tạo hoặc khôi phục cấu hình, mở lại Codex. Gỡ CLI bằng `npm uninstall -g codex-unlimited`.
|
package/api-key.mjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
function normalizeBase(value) {
|
|
2
|
+
let url
|
|
3
|
+
try {
|
|
4
|
+
url = new URL(value)
|
|
5
|
+
} catch {
|
|
6
|
+
throw Error('Địa chỉ API không hợp lệ.')
|
|
7
|
+
}
|
|
8
|
+
const local = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
|
|
9
|
+
if ((!local && url.protocol !== 'https:') || url.username || url.password || url.search || url.hash)
|
|
10
|
+
throw Error('Dùng địa chỉ API HTTPS, hoặc HTTP trên localhost.')
|
|
11
|
+
const base = url.href.replace(/\/+$/, '')
|
|
12
|
+
return /\/v1$/i.test(base) ? base : base + '/v1'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function apiKeySetup(input, url) {
|
|
16
|
+
let data
|
|
17
|
+
if (url) {
|
|
18
|
+
data = { apiKey: input.trim(), baseUrl: url }
|
|
19
|
+
} else {
|
|
20
|
+
try {
|
|
21
|
+
const match = /^hrxapi1\.([\w-]{1,24000})$/.exec(input.trim())
|
|
22
|
+
if (!match) throw Error()
|
|
23
|
+
data = JSON.parse(Buffer.from(match[1], 'base64url').toString('utf8'))
|
|
24
|
+
} catch {
|
|
25
|
+
throw Error('Sao chép mã thiết lập trong trang Khóa API, hoặc chạy codex-unlimited setup <địa chỉ API> để nhập khóa trực tiếp.')
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (typeof data?.apiKey !== 'string' || !/^[!-~]{1,4096}$/.test(data.apiKey) || /^(hrx1\.|hrxs_|hrxk_)/.test(data.apiKey))
|
|
29
|
+
throw Error('Cần khóa API thường. Với mã gói HRX, dùng codex-unlimited activate.')
|
|
30
|
+
return {
|
|
31
|
+
kind: 'api-key',
|
|
32
|
+
origin: normalizeBase(data.baseUrl),
|
|
33
|
+
key: data.apiKey,
|
|
34
|
+
model: typeof data.model === 'string' ? data.model : '',
|
|
35
|
+
openai: data.openai === true,
|
|
36
|
+
websocket: data.websocket === true,
|
|
37
|
+
localCatalog: data.localCatalog === true,
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function apiKeyCatalog(setup) {
|
|
42
|
+
const res = await fetch(setup.origin + '/models?client_version=0.158.0', {
|
|
43
|
+
headers: { Authorization: 'Bearer ' + setup.key, Accept: 'application/json' },
|
|
44
|
+
redirect: 'error',
|
|
45
|
+
signal: AbortSignal.timeout(20000),
|
|
46
|
+
})
|
|
47
|
+
if (!res.ok) throw Error('Không tải được danh sách model của khóa API (HTTP ' + res.status + ').')
|
|
48
|
+
const text = await res.text()
|
|
49
|
+
let manifest
|
|
50
|
+
try { manifest = JSON.parse(text) } catch { throw Error('Danh sách model Codex không hợp lệ.') }
|
|
51
|
+
const models = Array.isArray(manifest?.models) ? manifest.models.filter(m =>
|
|
52
|
+
typeof m?.slug === 'string' && /^[^\s\x00-\x1f\x7f]+$/u.test(m.slug) && (!m.visibility || m.visibility === 'list')
|
|
53
|
+
) : []
|
|
54
|
+
if (!models.length) throw Error('Khóa này chưa có model Codex khả dụng.')
|
|
55
|
+
const selected = models.find(m => m.slug === setup.model) || models[0]
|
|
56
|
+
const efforts = Array.isArray(selected.supported_reasoning_levels)
|
|
57
|
+
? selected.supported_reasoning_levels.map(level => level?.effort).filter(v => typeof v === 'string') : []
|
|
58
|
+
const effort = efforts.includes(selected.default_reasoning_level)
|
|
59
|
+
? selected.default_reasoning_level : efforts.find(v => v !== 'none')
|
|
60
|
+
return { text, count: models.length, model: selected.slug, effort }
|
|
61
|
+
}
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { stdin, stdout } from 'node:process'
|
|
3
|
+
import { createInterface } from 'node:readline/promises'
|
|
4
|
+
import { Writable } from 'node:stream'
|
|
5
|
+
import { homedir } from 'node:os'
|
|
6
|
+
import { join, dirname, delimiter, resolve } from 'node:path'
|
|
7
|
+
import { access, constants, mkdir, open, readFile, rename, unlink, stat } from 'node:fs/promises'
|
|
8
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
9
|
+
import { parse } from 'smol-toml'
|
|
10
|
+
import { configure, delivery, restore } from './config.mjs'
|
|
11
|
+
import { apiKeySetup, apiKeyCatalog } from './api-key.mjs'
|
|
12
|
+
|
|
13
|
+
const dir = resolve(process.env.CODEX_HOME || join(homedir(), '.codex'))
|
|
14
|
+
const path = join(dir, 'config.toml'),
|
|
15
|
+
dataDir = join(dir, 'hrx'),
|
|
16
|
+
statePath = join(dataDir, 'state.json')
|
|
17
|
+
const arg = process.argv[2]
|
|
18
|
+
if (['-h', '--help'].includes(arg)) {
|
|
19
|
+
console.log(
|
|
20
|
+
'codex-unlimited [activate | setup [URL] | status | repair | restore]\nsetup cấu hình khóa API thường. activate kích hoạt mã gói HRX.',
|
|
21
|
+
)
|
|
22
|
+
process.exit(0)
|
|
23
|
+
}
|
|
24
|
+
const read = async (file, fallback) => {
|
|
25
|
+
try {
|
|
26
|
+
return await readFile(file, 'utf8')
|
|
27
|
+
} catch (e) {
|
|
28
|
+
if (e.code === 'ENOENT') return fallback
|
|
29
|
+
throw e
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const state = async () => JSON.parse(await read(statePath, 'null'))
|
|
33
|
+
async function atomic(file, content) {
|
|
34
|
+
const temp = join(dirname(file), '.hrx-' + randomUUID())
|
|
35
|
+
const f = await open(temp, 'wx', 0o600)
|
|
36
|
+
try {
|
|
37
|
+
await f.writeFile(content)
|
|
38
|
+
await f.sync()
|
|
39
|
+
} finally {
|
|
40
|
+
await f.close()
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
await rename(temp, file)
|
|
44
|
+
} finally {
|
|
45
|
+
await unlink(temp).catch((e) => {
|
|
46
|
+
if (e.code !== 'ENOENT') throw e
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
let muted = false
|
|
51
|
+
const output = new Writable({
|
|
52
|
+
write(chunk, _encoding, done) {
|
|
53
|
+
if (!muted) stdout.write(chunk)
|
|
54
|
+
done()
|
|
55
|
+
},
|
|
56
|
+
})
|
|
57
|
+
const rl = createInterface({ input: stdin, output, terminal: Boolean(stdin.isTTY) })
|
|
58
|
+
async function askSecret(label = 'Dán mã kích hoạt (ẩn khi nhập): ') {
|
|
59
|
+
stdout.write(label)
|
|
60
|
+
muted = true
|
|
61
|
+
try {
|
|
62
|
+
return await rl.question('')
|
|
63
|
+
} finally {
|
|
64
|
+
muted = false
|
|
65
|
+
stdout.write('\n')
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function api(origin, endpoint, key) {
|
|
69
|
+
const res = await fetch(origin + '/api/v1/hrx/' + endpoint, {
|
|
70
|
+
method: endpoint === 'activate' ? 'POST' : 'GET',
|
|
71
|
+
headers: { authorization: 'Bearer ' + key },
|
|
72
|
+
redirect: 'error',
|
|
73
|
+
signal: AbortSignal.timeout(20000),
|
|
74
|
+
})
|
|
75
|
+
const body = await res.json()
|
|
76
|
+
if (!res.ok || body.code !== 0) throw Error(body.message || 'HTTP ' + res.status)
|
|
77
|
+
return body.data
|
|
78
|
+
}
|
|
79
|
+
function show(s) {
|
|
80
|
+
const labels = {
|
|
81
|
+
active: 'Đang dùng',
|
|
82
|
+
expired: 'Hết giờ',
|
|
83
|
+
exhausted: 'Hết token',
|
|
84
|
+
revoked: 'Đã thu hồi',
|
|
85
|
+
pending: 'Chờ kích hoạt',
|
|
86
|
+
}
|
|
87
|
+
console.log(s.name + ' · ' + s.model + ' · ' + (labels[s.state] ?? s.state))
|
|
88
|
+
if (s.expires_at) {
|
|
89
|
+
const end = new Date(s.expires_at)
|
|
90
|
+
console.log(
|
|
91
|
+
'Hết hạn: ' +
|
|
92
|
+
end.toLocaleString('vi-VN', { timeZoneName: 'short' }) +
|
|
93
|
+
' · Còn ' +
|
|
94
|
+
Math.max(0, Math.ceil((end - Date.now()) / 60000)) +
|
|
95
|
+
' phút',
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
if (s.token_limit)
|
|
99
|
+
console.log(
|
|
100
|
+
'Token khả dụng: ' +
|
|
101
|
+
s.tokens_available.toLocaleString('vi-VN') +
|
|
102
|
+
' / ' +
|
|
103
|
+
s.token_limit.toLocaleString('vi-VN'),
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
async function codexAvailable() {
|
|
107
|
+
const win = process.platform === 'win32'
|
|
108
|
+
const paths = (process.env.PATH || '')
|
|
109
|
+
.split(delimiter)
|
|
110
|
+
.flatMap((p) => (win ? ['codex.exe', 'codex.cmd'] : ['codex']).map((n) => join(p, n)))
|
|
111
|
+
if (win && process.env.LOCALAPPDATA)
|
|
112
|
+
paths.push(join(process.env.LOCALAPPDATA, 'Programs', 'OpenAI', 'Codex', 'bin', 'codex.exe'))
|
|
113
|
+
if (process.platform === 'darwin')
|
|
114
|
+
paths.push('/Applications/Codex.app', join(homedir(), 'Applications', 'Codex.app'))
|
|
115
|
+
for (const p of paths) {
|
|
116
|
+
try {
|
|
117
|
+
await access(p)
|
|
118
|
+
return true
|
|
119
|
+
} catch {}
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
await stat(join(dir, 'config.toml'))
|
|
123
|
+
return true
|
|
124
|
+
} catch {
|
|
125
|
+
return false
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function install(old) {
|
|
129
|
+
if (!(await codexAvailable())) throw Error('Cài hoặc mở Codex trước, sau đó chạy lại lệnh.')
|
|
130
|
+
await access(dir, constants.W_OK)
|
|
131
|
+
const existing = await read(path, null)
|
|
132
|
+
const base = old ? restore(existing ?? '', old.patch) : (existing ?? '')
|
|
133
|
+
// Preflight the exact merge and ensure both config and backup can be written before the clock starts.
|
|
134
|
+
configure(base, 'https://preflight.invalid', 'preflight', 'placeholder')
|
|
135
|
+
const probe = join(dir, '.hrx-check-' + randomUUID())
|
|
136
|
+
const f = await open(probe, 'wx', 0o600)
|
|
137
|
+
await f.close()
|
|
138
|
+
await unlink(probe)
|
|
139
|
+
const { origin, code } = delivery(await askSecret())
|
|
140
|
+
if (
|
|
141
|
+
(await rl.question('Yêu cầu Codex sẽ được gửi qua ' + origin + '. Kích hoạt gói bây giờ? [y/N] ')) !== 'y'
|
|
142
|
+
)
|
|
143
|
+
return
|
|
144
|
+
const v = await api(origin, 'activate', code)
|
|
145
|
+
show(v)
|
|
146
|
+
if (v.state !== 'active') return
|
|
147
|
+
try {
|
|
148
|
+
await saveConfiguration(existing, base, old, { origin, key: v.credential, model: v.model })
|
|
149
|
+
} catch (e) {
|
|
150
|
+
throw Error('Gói đã kích hoạt. Nhập lại cùng mã để hoàn tất cấu hình. ' + e.message)
|
|
151
|
+
}
|
|
152
|
+
console.log('Đã cấu hình. Đóng rồi mở lại Codex.')
|
|
153
|
+
}
|
|
154
|
+
async function saveConfiguration(existing, base, old, settings, catalog) {
|
|
155
|
+
let options
|
|
156
|
+
if (catalog) {
|
|
157
|
+
options = { ...settings, effort: catalog.effort }
|
|
158
|
+
if (settings.localCatalog || Buffer.byteLength(catalog.text) > 1024 * 1024 || parse(base).model_catalog_json) {
|
|
159
|
+
const hash = createHash('sha256').update(catalog.text).digest('hex')
|
|
160
|
+
options.catalogPath = join(dataDir, 'models-' + hash + '.json')
|
|
161
|
+
await atomic(options.catalogPath, catalog.text)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const result = configure(base, settings.origin, settings.model, settings.key, options)
|
|
165
|
+
const backup = join(dataDir, 'config-' + randomUUID() + '.toml')
|
|
166
|
+
if (existing !== null && !old) await atomic(backup, base)
|
|
167
|
+
// Staging the old/new document lets a second invocation safely finish an interrupted two-file update.
|
|
168
|
+
const next = {
|
|
169
|
+
...settings,
|
|
170
|
+
patch: result.patch,
|
|
171
|
+
created: old?.created ?? existing === null,
|
|
172
|
+
}
|
|
173
|
+
await persist(existing, result.text, next)
|
|
174
|
+
}
|
|
175
|
+
async function setupRegularKey(old) {
|
|
176
|
+
const url = process.argv[3]
|
|
177
|
+
const input = await askSecret(url ? 'Dán khóa API (ẩn khi nhập): ' : 'Dán mã thiết lập từ trang Khóa API (ẩn khi nhập): ')
|
|
178
|
+
const settings = apiKeySetup(input, url)
|
|
179
|
+
if ((await rl.question('Dùng khóa API tại ' + settings.origin + '? [y/N] ')) !== 'y') return
|
|
180
|
+
const existing = await read(path, null)
|
|
181
|
+
const base = old ? restore(existing ?? '', old.patch) : (existing ?? '')
|
|
182
|
+
const catalog = await apiKeyCatalog(settings)
|
|
183
|
+
await saveConfiguration(existing, base, old, { ...settings, model: catalog.model }, catalog)
|
|
184
|
+
console.log('Đã cấu hình khóa API · ' + catalog.model + '. Mở lại Codex.')
|
|
185
|
+
}
|
|
186
|
+
const journal = join(dataDir, 'pending.json')
|
|
187
|
+
async function recover() {
|
|
188
|
+
const p = JSON.parse(await read(journal, 'null'))
|
|
189
|
+
if (!p) return
|
|
190
|
+
const current = await read(path, null)
|
|
191
|
+
if (current !== p.before && current !== p.after)
|
|
192
|
+
throw Error('Cấu hình đã đổi trong lúc cập nhật. Giữ bản hiện tại và đối chiếu ' + journal)
|
|
193
|
+
if (current !== p.after) {
|
|
194
|
+
if (p.after === null) {
|
|
195
|
+
await unlink(path)
|
|
196
|
+
} else await atomic(path, p.after)
|
|
197
|
+
}
|
|
198
|
+
if (p.next) await atomic(statePath, JSON.stringify(p.next))
|
|
199
|
+
else
|
|
200
|
+
await unlink(statePath).catch((e) => {
|
|
201
|
+
if (e.code !== 'ENOENT') throw e
|
|
202
|
+
})
|
|
203
|
+
await unlink(journal)
|
|
204
|
+
}
|
|
205
|
+
async function persist(before, after, next) {
|
|
206
|
+
await atomic(journal, JSON.stringify({ before, after, next }))
|
|
207
|
+
await recover()
|
|
208
|
+
}
|
|
209
|
+
async function run() {
|
|
210
|
+
await mkdir(dataDir, { recursive: true, mode: 0o700 })
|
|
211
|
+
const lock = join(dataDir, 'cli.lock')
|
|
212
|
+
let f
|
|
213
|
+
try {
|
|
214
|
+
f = await open(lock, 'wx', 0o600)
|
|
215
|
+
} catch (e) {
|
|
216
|
+
if (e.code !== 'EEXIST') throw e
|
|
217
|
+
const pid = Number(await read(lock, '0'))
|
|
218
|
+
if (Number.isInteger(pid) && pid > 0) {
|
|
219
|
+
try {
|
|
220
|
+
process.kill(pid, 0)
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (err.code === 'ESRCH') {
|
|
223
|
+
await unlink(lock)
|
|
224
|
+
return run()
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
throw Error('Một lệnh cấu hình HRX khác đang chạy.')
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
await f.writeFile(String(process.pid))
|
|
232
|
+
await f.close()
|
|
233
|
+
await recover()
|
|
234
|
+
const v = await state()
|
|
235
|
+
let cmd = arg
|
|
236
|
+
if (!cmd && v) {
|
|
237
|
+
console.log('1. Trạng thái\n2. Sửa kết nối\n3. Khôi phục cấu hình\n4. Nhập mã gói HRX\n5. Thiết lập khóa API thường')
|
|
238
|
+
cmd = { 1: 'status', 2: 'repair', 3: 'restore', 4: 'activate', 5: 'setup' }[await rl.question('Chọn: ')] || 'exit'
|
|
239
|
+
}
|
|
240
|
+
cmd ??= 'activate'
|
|
241
|
+
if (cmd === 'exit') return
|
|
242
|
+
if (cmd === 'activate') return await install(v)
|
|
243
|
+
if (cmd === 'setup') return await setupRegularKey(v)
|
|
244
|
+
if (!v) throw Error('Chưa có key trên máy này. Chạy codex-unlimited activate.')
|
|
245
|
+
if (cmd === 'status') {
|
|
246
|
+
if (v.kind === 'api-key') {
|
|
247
|
+
const catalog = await apiKeyCatalog(v)
|
|
248
|
+
console.log(v.origin + ' · ' + catalog.count + ' model khả dụng · Model đã cấu hình: ' + v.model)
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
return show(await api(v.origin, 'status', v.key))
|
|
252
|
+
}
|
|
253
|
+
const current = await read(path, null),
|
|
254
|
+
base = restore(current ?? '', v.patch)
|
|
255
|
+
if (cmd === 'restore') {
|
|
256
|
+
await persist(current, v.created && base === '' ? null : base, null)
|
|
257
|
+
console.log('Đã khôi phục cấu hình.')
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
if (cmd === 'repair') {
|
|
261
|
+
if (v.kind === 'api-key') {
|
|
262
|
+
const catalog = await apiKeyCatalog(v)
|
|
263
|
+
await saveConfiguration(current, base, v, { ...v, model: catalog.model }, catalog)
|
|
264
|
+
console.log('Đã sửa kết nối khóa API · ' + catalog.model + '. Mở lại Codex.')
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
const info = await api(v.origin, 'status', v.key)
|
|
268
|
+
show(info)
|
|
269
|
+
if (info.state !== 'active') return
|
|
270
|
+
const result = configure(base, v.origin, info.model, v.key)
|
|
271
|
+
await persist(current, result.text, { ...v, model: info.model, patch: result.patch })
|
|
272
|
+
console.log('Đã sửa kết nối. Mở lại Codex.')
|
|
273
|
+
return
|
|
274
|
+
}
|
|
275
|
+
throw Error('Xem lệnh bằng codex-unlimited --help')
|
|
276
|
+
} finally {
|
|
277
|
+
await unlink(lock)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
await run()
|
|
282
|
+
} catch (e) {
|
|
283
|
+
console.error(e.message)
|
|
284
|
+
process.exitCode = 1
|
|
285
|
+
} finally {
|
|
286
|
+
rl.close()
|
|
287
|
+
}
|
package/config.mjs
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { parse } from 'smol-toml'
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
3
|
+
|
|
4
|
+
const begin = '# >>> codex-unlimited provider'
|
|
5
|
+
const end = '# <<< codex-unlimited provider'
|
|
6
|
+
const managed = ' # codex-unlimited'
|
|
7
|
+
|
|
8
|
+
export function delivery(text) {
|
|
9
|
+
const m = /^hrx1\.([\w-]+)\.(hrxs_[\w-]{43})$/.exec(text.trim())
|
|
10
|
+
if (!m) throw Error('Mã giao hàng không hợp lệ. Sao chép mã đầy đủ từ người bán.')
|
|
11
|
+
const url = new URL(Buffer.from(m[1], 'base64url').toString('utf8'))
|
|
12
|
+
if (
|
|
13
|
+
url.href !== url.origin + '/' ||
|
|
14
|
+
(url.protocol !== 'https:' &&
|
|
15
|
+
!(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)))
|
|
16
|
+
)
|
|
17
|
+
throw Error('Địa chỉ dịch vụ không hợp lệ.')
|
|
18
|
+
return { origin: url.origin, code: m[2] }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function sameOthers(a, b, fields, features) {
|
|
22
|
+
for (const obj of [a, b]) {
|
|
23
|
+
for (const field of fields) delete obj[field]
|
|
24
|
+
if (obj.features) {
|
|
25
|
+
for (const field of Object.keys(features)) delete obj.features[field]
|
|
26
|
+
if (!Object.keys(obj.features).length) delete obj.features
|
|
27
|
+
}
|
|
28
|
+
if (obj.model_providers) {
|
|
29
|
+
delete obj.model_providers.hrx
|
|
30
|
+
if (!Object.keys(obj.model_providers).length) delete obj.model_providers
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!isDeepStrictEqual(a, b))
|
|
34
|
+
throw Error('Không thể chỉnh cấu hình hiện tại mà vẫn giữ nguyên các tùy chọn khác.')
|
|
35
|
+
}
|
|
36
|
+
function quote(s) {
|
|
37
|
+
return JSON.stringify(s)
|
|
38
|
+
}
|
|
39
|
+
export function configure(text, origin, model, key, apiKeySetup) {
|
|
40
|
+
const original = parse(text)
|
|
41
|
+
if (original.model_providers?.hrx || text.includes(begin) || text.includes(end))
|
|
42
|
+
throw Error('Provider hrx đã tồn tại trong cấu hình.')
|
|
43
|
+
const nl = text.includes('\r\n') ? '\r\n' : '\n'
|
|
44
|
+
const lines = text.split(nl),
|
|
45
|
+
replaced = {}
|
|
46
|
+
const values = { model, model_provider: 'hrx' }
|
|
47
|
+
if (!apiKeySetup || apiKeySetup.openai) values.web_search = apiKeySetup ? 'live' : 'disabled'
|
|
48
|
+
if (apiKeySetup) values.review_model = model
|
|
49
|
+
if (apiKeySetup?.effort) values.model_reasoning_effort = apiKeySetup.effort
|
|
50
|
+
if (apiKeySetup?.catalogPath) values.model_catalog_json = apiKeySetup.catalogPath
|
|
51
|
+
const fields = Object.keys(values)
|
|
52
|
+
const injected = []
|
|
53
|
+
for (const field of fields) {
|
|
54
|
+
const line = field + ' = ' + quote(values[field]) + managed
|
|
55
|
+
const firstTable = lines.findIndex((s) => /^\s*\[/.test(s))
|
|
56
|
+
const idx = lines.findIndex(
|
|
57
|
+
(s, i) => (firstTable < 0 || i < firstTable) && new RegExp('^\\s*' + field + '\\s*=').test(s),
|
|
58
|
+
)
|
|
59
|
+
if (idx >= 0) {
|
|
60
|
+
replaced[field] = { old: lines[idx], line }
|
|
61
|
+
lines[idx] = line
|
|
62
|
+
} else {
|
|
63
|
+
if (Object.hasOwn(original, field))
|
|
64
|
+
throw Error('Không thể tự cập nhật trường ' + field + ' trong TOML.')
|
|
65
|
+
replaced[field] = { old: null, line }
|
|
66
|
+
injected.push(line)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const features = {}
|
|
70
|
+
if (apiKeySetup) {
|
|
71
|
+
if (!apiKeySetup.catalogPath) features.api_key_model_discovery = true
|
|
72
|
+
if (apiKeySetup.openai) features.image_generation = true
|
|
73
|
+
if (apiKeySetup.websocket) features.responses_websockets_v2 = true
|
|
74
|
+
}
|
|
75
|
+
const featureTable = lines.findIndex(s => /^\s*\[features\]\s*(?:#.*)?$/.test(s))
|
|
76
|
+
const firstTable = lines.findIndex(s => /^\s*\[/.test(s))
|
|
77
|
+
const rootEnd = firstTable < 0 ? lines.length : firstTable
|
|
78
|
+
const inline = lines.findIndex((s, i) => i < rootEnd && /^\s*features\s*=/.test(s))
|
|
79
|
+
const changed = Object.entries(features).filter(([field, value]) => original.features?.[field] !== value)
|
|
80
|
+
if (inline >= 0 && changed.length) {
|
|
81
|
+
const entries = Object.entries({ ...original.features, ...features })
|
|
82
|
+
if (entries.some(([, value]) => typeof value !== 'boolean'))
|
|
83
|
+
throw Error('Không thể tự cập nhật bảng features nội tuyến này. Dùng hướng dẫn config.toml trong trang Khóa API.')
|
|
84
|
+
const line = 'features = { ' + entries.map(([k, v]) => quote(k) + ' = ' + v).join(', ') + ' }' + managed
|
|
85
|
+
replaced.features = { old: lines[inline], line }
|
|
86
|
+
lines[inline] = line
|
|
87
|
+
}
|
|
88
|
+
for (const [field, value] of inline >= 0 ? [] : changed) {
|
|
89
|
+
const fieldPath = 'features.' + field
|
|
90
|
+
if (featureTable === -1) {
|
|
91
|
+
const line = fieldPath + ' = ' + value + managed
|
|
92
|
+
const old = lines.findIndex((s, i) => i < rootEnd && new RegExp('^\\s*features\\.' + field + '\\s*=').test(s))
|
|
93
|
+
replaced[fieldPath] = { old: old < 0 ? null : lines[old], line }
|
|
94
|
+
if (old < 0) injected.push(line)
|
|
95
|
+
else lines[old] = line
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
const line = field + ' = ' + value + managed
|
|
99
|
+
let i = featureTable + 1
|
|
100
|
+
while (i < lines.length && !/^\s*\[/.test(lines[i])) {
|
|
101
|
+
if (new RegExp('^\\s*' + field + '\\s*=').test(lines[i])) break
|
|
102
|
+
i++
|
|
103
|
+
}
|
|
104
|
+
const exists = i < lines.length && !/^\s*\[/.test(lines[i])
|
|
105
|
+
replaced[fieldPath] = { old: exists ? lines[i] : null, line }
|
|
106
|
+
if (exists) lines[i] = line
|
|
107
|
+
else lines.splice(featureTable + 1, 0, line)
|
|
108
|
+
}
|
|
109
|
+
const block = [
|
|
110
|
+
begin,
|
|
111
|
+
'[model_providers.hrx]',
|
|
112
|
+
'name = ' + quote(apiKeySetup ? 'HRX API' : 'HRX'),
|
|
113
|
+
'base_url = ' + quote(apiKeySetup ? origin : origin + '/api/v1/hrx/v1'),
|
|
114
|
+
...(apiKeySetup && !apiKeySetup.catalogPath ? ['model_catalog_url = ' + quote(origin + '/models')] : []),
|
|
115
|
+
'wire_api = "responses"',
|
|
116
|
+
'requires_openai_auth = false',
|
|
117
|
+
'supports_websockets = ' + Boolean(apiKeySetup?.websocket),
|
|
118
|
+
'experimental_bearer_token = ' + quote(key),
|
|
119
|
+
...(apiKeySetup?.openai ? ['http_headers = { "x-openai-actor-authorization" = "local-image-extension" }'] : []),
|
|
120
|
+
end,
|
|
121
|
+
].join(nl)
|
|
122
|
+
const base = [...injected, ...lines].join(nl)
|
|
123
|
+
const result = base + nl + block + nl
|
|
124
|
+
const configured = parse(result)
|
|
125
|
+
if (
|
|
126
|
+
configured.model !== model ||
|
|
127
|
+
configured.model_provider !== 'hrx' ||
|
|
128
|
+
configured.model_providers?.hrx?.experimental_bearer_token !== key ||
|
|
129
|
+
Object.entries(features).some(([field, value]) => configured.features?.[field] !== value)
|
|
130
|
+
)
|
|
131
|
+
throw Error('Cấu hình HRX không hợp lệ.')
|
|
132
|
+
sameOthers(original, configured, fields, features)
|
|
133
|
+
return { text: result, patch: { replaced, block } }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function restore(text, patch) {
|
|
137
|
+
const nl = text.includes('\r\n') ? '\r\n' : '\n'
|
|
138
|
+
let result = text
|
|
139
|
+
const block = patch.block.replace(/\r?\n/g, nl)
|
|
140
|
+
if (result.includes(begin) || result.includes(end)) {
|
|
141
|
+
if (!result.includes(block))
|
|
142
|
+
throw Error('Phần provider HRX đã được sửa. Hãy lưu các thay đổi đó trước khi khôi phục.')
|
|
143
|
+
const start = result.indexOf(block)
|
|
144
|
+
const left = result.slice(0, start).replace(/\r?\n$/, '')
|
|
145
|
+
const right = result.slice(start + block.length).replace(/^\r?\n/, '')
|
|
146
|
+
const separator = left && right && !left.endsWith('\n') && !right.startsWith(nl) ? nl : ''
|
|
147
|
+
result = left + separator + right
|
|
148
|
+
}
|
|
149
|
+
const lines = result.split(nl)
|
|
150
|
+
for (const { old, line } of Object.values(patch.replaced)) {
|
|
151
|
+
const index = lines.indexOf(line)
|
|
152
|
+
if (index !== -1) {
|
|
153
|
+
if (old === null) lines.splice(index, 1)
|
|
154
|
+
else lines[index] = old
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
result = lines.join(nl)
|
|
158
|
+
parse(result)
|
|
159
|
+
return result
|
|
160
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-unlimited",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Configure Codex for a regular gateway API key or an independent HRX time or token pass",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": { "codex-unlimited": "cli.mjs" },
|
|
7
|
+
"files": ["cli.mjs", "config.mjs", "api-key.mjs", "README.md"],
|
|
8
|
+
"engines": { "node": ">=20" },
|
|
9
|
+
"scripts": { "test": "node --test" },
|
|
10
|
+
"dependencies": { "smol-toml": "^1.4.2" }
|
|
11
|
+
}
|