codex-unlimited 0.1.0 → 0.2.1

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 CHANGED
@@ -1,6 +1,18 @@
1
1
  # codex-unlimited
2
2
 
3
- CLI độc lập của HRX để dùng gói theo giờ, theo token hoặc kết hợp trên Codex. Cần Node.js 20 trở lên và Codex.
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 → Hướng dẫn npm**, chạy lệnh sau, bấm **Sao chép mã thiết lập** rồi dán vào terminal. Kiểm tra nội dung vừa dán, nhấn Enter, xác nhận địa chỉ dịch vụ và mở lại Codex.
8
+
9
+ ```sh
10
+ npx --yes codex-unlimited@0.2.1 setup
11
+ ```
12
+
13
+ Để nhập khóa trực tiếp, chạy `npx --yes codex-unlimited@0.2.1 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.1 restore` để khôi phục cấu hình trước đó.
14
+
15
+ ## Gói HRX
4
16
 
5
17
  ```sh
6
18
  npm install -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 CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { stdin, stdout } from 'node:process'
3
3
  import { createInterface } from 'node:readline/promises'
4
- import { Writable } from 'node:stream'
5
4
  import { homedir } from 'node:os'
6
5
  import { join, dirname, delimiter, resolve } from 'node:path'
7
6
  import { access, constants, mkdir, open, readFile, rename, unlink, stat } from 'node:fs/promises'
8
- import { randomUUID } from 'node:crypto'
7
+ import { createHash, randomUUID } from 'node:crypto'
8
+ import { parse } from 'smol-toml'
9
9
  import { configure, delivery, restore } from './config.mjs'
10
+ import { apiKeySetup, apiKeyCatalog } from './api-key.mjs'
10
11
 
11
12
  const dir = resolve(process.env.CODEX_HOME || join(homedir(), '.codex'))
12
13
  const path = join(dir, 'config.toml'),
@@ -15,7 +16,7 @@ const path = join(dir, 'config.toml'),
15
16
  const arg = process.argv[2]
16
17
  if (['-h', '--help'].includes(arg)) {
17
18
  console.log(
18
- 'codex-unlimited [activate | status | repair | restore]\nGõ codex-unlimited để mở menu. Khôi phục trước khi gỡ package.',
19
+ '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.',
19
20
  )
20
21
  process.exit(0)
21
22
  }
@@ -45,24 +46,7 @@ async function atomic(file, content) {
45
46
  })
46
47
  }
47
48
  }
48
- let muted = false
49
- const output = new Writable({
50
- write(chunk, _encoding, done) {
51
- if (!muted) stdout.write(chunk)
52
- done()
53
- },
54
- })
55
- const rl = createInterface({ input: stdin, output, terminal: Boolean(stdin.isTTY) })
56
- async function askSecret() {
57
- stdout.write('Dán mã kích hoạt (ẩn khi nhập): ')
58
- muted = true
59
- try {
60
- return await rl.question('')
61
- } finally {
62
- muted = false
63
- stdout.write('\n')
64
- }
65
- }
49
+ const rl = createInterface({ input: stdin, output: stdout, terminal: Boolean(stdin.isTTY && stdout.isTTY), historySize: 0 })
66
50
  async function api(origin, endpoint, key) {
67
51
  const res = await fetch(origin + '/api/v1/hrx/' + endpoint, {
68
52
  method: endpoint === 'activate' ? 'POST' : 'GET',
@@ -134,7 +118,7 @@ async function install(old) {
134
118
  const f = await open(probe, 'wx', 0o600)
135
119
  await f.close()
136
120
  await unlink(probe)
137
- const { origin, code } = delivery(await askSecret())
121
+ const { origin, code } = delivery(await rl.question('Dán mã kích hoạt rồi nhấn Enter: '))
138
122
  if (
139
123
  (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'
140
124
  )
@@ -143,26 +127,44 @@ async function install(old) {
143
127
  show(v)
144
128
  if (v.state !== 'active') return
145
129
  try {
146
- await saveActivation(existing, base, old, origin, v)
130
+ await saveConfiguration(existing, base, old, { origin, key: v.credential, model: v.model })
147
131
  } catch (e) {
148
132
  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)
149
133
  }
150
134
  console.log('Đã cấu hình. Đóng rồi mở lại Codex.')
151
135
  }
152
- async function saveActivation(existing, base, old, origin, v) {
153
- const result = configure(base, origin, v.model, v.credential)
136
+ async function saveConfiguration(existing, base, old, settings, catalog) {
137
+ let options
138
+ if (catalog) {
139
+ options = { ...settings, effort: catalog.effort }
140
+ if (settings.localCatalog || Buffer.byteLength(catalog.text) > 1024 * 1024 || parse(base).model_catalog_json) {
141
+ const hash = createHash('sha256').update(catalog.text).digest('hex')
142
+ options.catalogPath = join(dataDir, 'models-' + hash + '.json')
143
+ await atomic(options.catalogPath, catalog.text)
144
+ }
145
+ }
146
+ const result = configure(base, settings.origin, settings.model, settings.key, options)
154
147
  const backup = join(dataDir, 'config-' + randomUUID() + '.toml')
155
- if (existing !== null) await atomic(backup, base)
148
+ if (existing !== null && !old) await atomic(backup, base)
156
149
  // Staging the old/new document lets a second invocation safely finish an interrupted two-file update.
157
150
  const next = {
158
- origin,
159
- key: v.credential,
160
- model: v.model,
151
+ ...settings,
161
152
  patch: result.patch,
162
153
  created: old?.created ?? existing === null,
163
154
  }
164
155
  await persist(existing, result.text, next)
165
156
  }
157
+ async function setupRegularKey(old) {
158
+ const url = process.argv[3]
159
+ const input = await rl.question(url ? 'Dán khóa API rồi nhấn Enter: ' : 'Dán mã thiết lập từ trang Khóa API rồi nhấn Enter: ')
160
+ const settings = apiKeySetup(input, url)
161
+ if ((await rl.question('Dùng khóa API tại ' + settings.origin + '? [y/N] ')) !== 'y') return
162
+ const existing = await read(path, null)
163
+ const base = old ? restore(existing ?? '', old.patch) : (existing ?? '')
164
+ const catalog = await apiKeyCatalog(settings)
165
+ await saveConfiguration(existing, base, old, { ...settings, model: catalog.model }, catalog)
166
+ console.log('Đã cấu hình khóa API · ' + catalog.model + '. Mở lại Codex.')
167
+ }
166
168
  const journal = join(dataDir, 'pending.json')
167
169
  async function recover() {
168
170
  const p = JSON.parse(await read(journal, 'null'))
@@ -214,14 +216,22 @@ async function run() {
214
216
  const v = await state()
215
217
  let cmd = arg
216
218
  if (!cmd && v) {
217
- 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ã mới')
218
- cmd = { 1: 'status', 2: 'repair', 3: 'restore', 4: 'activate' }[await rl.question('Chọn: ')] || 'exit'
219
+ 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')
220
+ cmd = { 1: 'status', 2: 'repair', 3: 'restore', 4: 'activate', 5: 'setup' }[await rl.question('Chọn: ')] || 'exit'
219
221
  }
220
222
  cmd ??= 'activate'
221
223
  if (cmd === 'exit') return
222
224
  if (cmd === 'activate') return await install(v)
225
+ if (cmd === 'setup') return await setupRegularKey(v)
223
226
  if (!v) throw Error('Chưa có key trên máy này. Chạy codex-unlimited activate.')
224
- if (cmd === 'status') return show(await api(v.origin, 'status', v.key))
227
+ if (cmd === 'status') {
228
+ if (v.kind === 'api-key') {
229
+ const catalog = await apiKeyCatalog(v)
230
+ console.log(v.origin + ' · ' + catalog.count + ' model khả dụng · Model đã cấu hình: ' + v.model)
231
+ return
232
+ }
233
+ return show(await api(v.origin, 'status', v.key))
234
+ }
225
235
  const current = await read(path, null),
226
236
  base = restore(current ?? '', v.patch)
227
237
  if (cmd === 'restore') {
@@ -230,6 +240,12 @@ async function run() {
230
240
  return
231
241
  }
232
242
  if (cmd === 'repair') {
243
+ if (v.kind === 'api-key') {
244
+ const catalog = await apiKeyCatalog(v)
245
+ await saveConfiguration(current, base, v, { ...v, model: catalog.model }, catalog)
246
+ console.log('Đã sửa kết nối khóa API · ' + catalog.model + '. Mở lại Codex.')
247
+ return
248
+ }
233
249
  const info = await api(v.origin, 'status', v.key)
234
250
  show(info)
235
251
  if (info.state !== 'active') return
package/config.mjs CHANGED
@@ -4,7 +4,6 @@ import { isDeepStrictEqual } from 'node:util'
4
4
  const begin = '# >>> codex-unlimited provider'
5
5
  const end = '# <<< codex-unlimited provider'
6
6
  const managed = ' # codex-unlimited'
7
- const fields = ['model', 'model_provider', 'web_search']
8
7
 
9
8
  export function delivery(text) {
10
9
  const m = /^hrx1\.([\w-]+)\.(hrxs_[\w-]{43})$/.exec(text.trim())
@@ -19,9 +18,13 @@ export function delivery(text) {
19
18
  return { origin: url.origin, code: m[2] }
20
19
  }
21
20
 
22
- function sameOthers(a, b) {
21
+ function sameOthers(a, b, fields, features) {
23
22
  for (const obj of [a, b]) {
24
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
+ }
25
28
  if (obj.model_providers) {
26
29
  delete obj.model_providers.hrx
27
30
  if (!Object.keys(obj.model_providers).length) delete obj.model_providers
@@ -33,14 +36,19 @@ function sameOthers(a, b) {
33
36
  function quote(s) {
34
37
  return JSON.stringify(s)
35
38
  }
36
- export function configure(text, origin, model, key) {
39
+ export function configure(text, origin, model, key, apiKeySetup) {
37
40
  const original = parse(text)
38
41
  if (original.model_providers?.hrx || text.includes(begin) || text.includes(end))
39
42
  throw Error('Provider hrx đã tồn tại trong cấu hình.')
40
43
  const nl = text.includes('\r\n') ? '\r\n' : '\n'
41
44
  const lines = text.split(nl),
42
45
  replaced = {}
43
- const values = { model, model_provider: 'hrx', web_search: 'disabled' }
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)
44
52
  const injected = []
45
53
  for (const field of fields) {
46
54
  const line = field + ' = ' + quote(values[field]) + managed
@@ -58,15 +66,57 @@ export function configure(text, origin, model, key) {
58
66
  injected.push(line)
59
67
  }
60
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
+ }
61
109
  const block = [
62
110
  begin,
63
111
  '[model_providers.hrx]',
64
- 'name = "HRX"',
65
- 'base_url = ' + quote(origin + '/api/v1/hrx/v1'),
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')] : []),
66
115
  'wire_api = "responses"',
67
116
  'requires_openai_auth = false',
68
- 'supports_websockets = false',
117
+ 'supports_websockets = ' + Boolean(apiKeySetup?.websocket),
69
118
  'experimental_bearer_token = ' + quote(key),
119
+ ...(apiKeySetup?.openai ? ['http_headers = { "x-openai-actor-authorization" = "local-image-extension" }'] : []),
70
120
  end,
71
121
  ].join(nl)
72
122
  const base = [...injected, ...lines].join(nl)
@@ -75,10 +125,11 @@ export function configure(text, origin, model, key) {
75
125
  if (
76
126
  configured.model !== model ||
77
127
  configured.model_provider !== 'hrx' ||
78
- configured.model_providers?.hrx?.experimental_bearer_token !== key
128
+ configured.model_providers?.hrx?.experimental_bearer_token !== key ||
129
+ Object.entries(features).some(([field, value]) => configured.features?.[field] !== value)
79
130
  )
80
131
  throw Error('Cấu hình HRX không hợp lệ.')
81
- sameOthers(original, configured)
132
+ sameOthers(original, configured, fields, features)
82
133
  return { text: result, patch: { replaced, block } }
83
134
  }
84
135
 
@@ -96,9 +147,7 @@ export function restore(text, patch) {
96
147
  result = left + separator + right
97
148
  }
98
149
  const lines = result.split(nl)
99
- for (const field of fields) {
100
- if (!patch.replaced[field]) continue
101
- const { old, line } = patch.replaced[field]
150
+ for (const { old, line } of Object.values(patch.replaced)) {
102
151
  const index = lines.indexOf(line)
103
152
  if (index !== -1) {
104
153
  if (old === null) lines.splice(index, 1)
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "codex-unlimited",
3
- "version": "0.1.0",
4
- "description": "Configure Codex for an independent HRX time or token pass",
3
+ "version": "0.2.1",
4
+ "description": "Configure Codex for a regular gateway API key or an independent HRX time or token pass",
5
5
  "type": "module",
6
6
  "bin": { "codex-unlimited": "cli.mjs" },
7
- "files": ["cli.mjs", "config.mjs", "README.md"],
7
+ "files": ["cli.mjs", "config.mjs", "api-key.mjs", "README.md"],
8
8
  "engines": { "node": ">=20" },
9
9
  "scripts": { "test": "node --test" },
10
10
  "dependencies": { "smol-toml": "^1.4.2" }