codex-unlimited 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.
Files changed (4) hide show
  1. package/README.md +15 -2
  2. package/cli.mjs +253 -0
  3. package/config.mjs +111 -0
  4. package/package.json +9 -4
package/README.md CHANGED
@@ -1,3 +1,16 @@
1
- # Temporary Holding Version
1
+ # codex-unlimited
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
5
+ ```sh
6
+ npm install -g codex-unlimited
7
+ codex-unlimited
8
+ ```
9
+
10
+ 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.
11
+
12
+ - `codex-unlimited status` xem thời hạn và số token còn khả dụng.
13
+ - `codex-unlimited repair` áp dụng lại cấu hình sau khi sửa kết nối.
14
+ - `codex-unlimited restore` khôi phục cấu hình trước khi gỡ công cụ.
15
+
16
+ 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/cli.mjs ADDED
@@ -0,0 +1,253 @@
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 { randomUUID } from 'node:crypto'
9
+ import { configure, delivery, restore } from './config.mjs'
10
+
11
+ const dir = resolve(process.env.CODEX_HOME || join(homedir(), '.codex'))
12
+ const path = join(dir, 'config.toml'),
13
+ dataDir = join(dir, 'hrx'),
14
+ statePath = join(dataDir, 'state.json')
15
+ const arg = process.argv[2]
16
+ if (['-h', '--help'].includes(arg)) {
17
+ console.log(
18
+ 'codex-unlimited [activate | status | repair | restore]\nGõ codex-unlimited để mở menu. Khôi phục trước khi gỡ package.',
19
+ )
20
+ process.exit(0)
21
+ }
22
+ const read = async (file, fallback) => {
23
+ try {
24
+ return await readFile(file, 'utf8')
25
+ } catch (e) {
26
+ if (e.code === 'ENOENT') return fallback
27
+ throw e
28
+ }
29
+ }
30
+ const state = async () => JSON.parse(await read(statePath, 'null'))
31
+ async function atomic(file, content) {
32
+ const temp = join(dirname(file), '.hrx-' + randomUUID())
33
+ const f = await open(temp, 'wx', 0o600)
34
+ try {
35
+ await f.writeFile(content)
36
+ await f.sync()
37
+ } finally {
38
+ await f.close()
39
+ }
40
+ try {
41
+ await rename(temp, file)
42
+ } finally {
43
+ await unlink(temp).catch((e) => {
44
+ if (e.code !== 'ENOENT') throw e
45
+ })
46
+ }
47
+ }
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
+ }
66
+ async function api(origin, endpoint, key) {
67
+ const res = await fetch(origin + '/api/v1/hrx/' + endpoint, {
68
+ method: endpoint === 'activate' ? 'POST' : 'GET',
69
+ headers: { authorization: 'Bearer ' + key },
70
+ redirect: 'error',
71
+ signal: AbortSignal.timeout(20000),
72
+ })
73
+ const body = await res.json()
74
+ if (!res.ok || body.code !== 0) throw Error(body.message || 'HTTP ' + res.status)
75
+ return body.data
76
+ }
77
+ function show(s) {
78
+ const labels = {
79
+ active: 'Đang dùng',
80
+ expired: 'Hết giờ',
81
+ exhausted: 'Hết token',
82
+ revoked: 'Đã thu hồi',
83
+ pending: 'Chờ kích hoạt',
84
+ }
85
+ console.log(s.name + ' · ' + s.model + ' · ' + (labels[s.state] ?? s.state))
86
+ if (s.expires_at) {
87
+ const end = new Date(s.expires_at)
88
+ console.log(
89
+ 'Hết hạn: ' +
90
+ end.toLocaleString('vi-VN', { timeZoneName: 'short' }) +
91
+ ' · Còn ' +
92
+ Math.max(0, Math.ceil((end - Date.now()) / 60000)) +
93
+ ' phút',
94
+ )
95
+ }
96
+ if (s.token_limit)
97
+ console.log(
98
+ 'Token khả dụng: ' +
99
+ s.tokens_available.toLocaleString('vi-VN') +
100
+ ' / ' +
101
+ s.token_limit.toLocaleString('vi-VN'),
102
+ )
103
+ }
104
+ async function codexAvailable() {
105
+ const win = process.platform === 'win32'
106
+ const paths = (process.env.PATH || '')
107
+ .split(delimiter)
108
+ .flatMap((p) => (win ? ['codex.exe', 'codex.cmd'] : ['codex']).map((n) => join(p, n)))
109
+ if (win && process.env.LOCALAPPDATA)
110
+ paths.push(join(process.env.LOCALAPPDATA, 'Programs', 'OpenAI', 'Codex', 'bin', 'codex.exe'))
111
+ if (process.platform === 'darwin')
112
+ paths.push('/Applications/Codex.app', join(homedir(), 'Applications', 'Codex.app'))
113
+ for (const p of paths) {
114
+ try {
115
+ await access(p)
116
+ return true
117
+ } catch {}
118
+ }
119
+ try {
120
+ await stat(join(dir, 'config.toml'))
121
+ return true
122
+ } catch {
123
+ return false
124
+ }
125
+ }
126
+ async function install(old) {
127
+ if (!(await codexAvailable())) throw Error('Cài hoặc mở Codex trước, sau đó chạy lại lệnh.')
128
+ await access(dir, constants.W_OK)
129
+ const existing = await read(path, null)
130
+ const base = old ? restore(existing ?? '', old.patch) : (existing ?? '')
131
+ // Preflight the exact merge and ensure both config and backup can be written before the clock starts.
132
+ configure(base, 'https://preflight.invalid', 'preflight', 'placeholder')
133
+ const probe = join(dir, '.hrx-check-' + randomUUID())
134
+ const f = await open(probe, 'wx', 0o600)
135
+ await f.close()
136
+ await unlink(probe)
137
+ const { origin, code } = delivery(await askSecret())
138
+ if (
139
+ (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
+ )
141
+ return
142
+ const v = await api(origin, 'activate', code)
143
+ show(v)
144
+ if (v.state !== 'active') return
145
+ try {
146
+ await saveActivation(existing, base, old, origin, v)
147
+ } catch (e) {
148
+ 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
+ }
150
+ console.log('Đã cấu hình. Đóng rồi mở lại Codex.')
151
+ }
152
+ async function saveActivation(existing, base, old, origin, v) {
153
+ const result = configure(base, origin, v.model, v.credential)
154
+ const backup = join(dataDir, 'config-' + randomUUID() + '.toml')
155
+ if (existing !== null) await atomic(backup, base)
156
+ // Staging the old/new document lets a second invocation safely finish an interrupted two-file update.
157
+ const next = {
158
+ origin,
159
+ key: v.credential,
160
+ model: v.model,
161
+ patch: result.patch,
162
+ created: old?.created ?? existing === null,
163
+ }
164
+ await persist(existing, result.text, next)
165
+ }
166
+ const journal = join(dataDir, 'pending.json')
167
+ async function recover() {
168
+ const p = JSON.parse(await read(journal, 'null'))
169
+ if (!p) return
170
+ const current = await read(path, null)
171
+ if (current !== p.before && current !== p.after)
172
+ 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)
173
+ if (current !== p.after) {
174
+ if (p.after === null) {
175
+ await unlink(path)
176
+ } else await atomic(path, p.after)
177
+ }
178
+ if (p.next) await atomic(statePath, JSON.stringify(p.next))
179
+ else
180
+ await unlink(statePath).catch((e) => {
181
+ if (e.code !== 'ENOENT') throw e
182
+ })
183
+ await unlink(journal)
184
+ }
185
+ async function persist(before, after, next) {
186
+ await atomic(journal, JSON.stringify({ before, after, next }))
187
+ await recover()
188
+ }
189
+ async function run() {
190
+ await mkdir(dataDir, { recursive: true, mode: 0o700 })
191
+ const lock = join(dataDir, 'cli.lock')
192
+ let f
193
+ try {
194
+ f = await open(lock, 'wx', 0o600)
195
+ } catch (e) {
196
+ if (e.code !== 'EEXIST') throw e
197
+ const pid = Number(await read(lock, '0'))
198
+ if (Number.isInteger(pid) && pid > 0) {
199
+ try {
200
+ process.kill(pid, 0)
201
+ } catch (err) {
202
+ if (err.code === 'ESRCH') {
203
+ await unlink(lock)
204
+ return run()
205
+ }
206
+ }
207
+ }
208
+ throw Error('Một lệnh cấu hình HRX khác đang chạy.')
209
+ }
210
+ try {
211
+ await f.writeFile(String(process.pid))
212
+ await f.close()
213
+ await recover()
214
+ const v = await state()
215
+ let cmd = arg
216
+ 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
+ }
220
+ cmd ??= 'activate'
221
+ if (cmd === 'exit') return
222
+ if (cmd === 'activate') return await install(v)
223
+ 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))
225
+ const current = await read(path, null),
226
+ base = restore(current ?? '', v.patch)
227
+ if (cmd === 'restore') {
228
+ await persist(current, v.created && base === '' ? null : base, null)
229
+ console.log('Đã khôi phục cấu hình.')
230
+ return
231
+ }
232
+ if (cmd === 'repair') {
233
+ const info = await api(v.origin, 'status', v.key)
234
+ show(info)
235
+ if (info.state !== 'active') return
236
+ const result = configure(base, v.origin, info.model, v.key)
237
+ await persist(current, result.text, { ...v, model: info.model, patch: result.patch })
238
+ console.log('Đã sửa kết nối. Mở lại Codex.')
239
+ return
240
+ }
241
+ throw Error('Xem lệnh bằng codex-unlimited --help')
242
+ } finally {
243
+ await unlink(lock)
244
+ }
245
+ }
246
+ try {
247
+ await run()
248
+ } catch (e) {
249
+ console.error(e.message)
250
+ process.exitCode = 1
251
+ } finally {
252
+ rl.close()
253
+ }
package/config.mjs ADDED
@@ -0,0 +1,111 @@
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
+ const fields = ['model', 'model_provider', 'web_search']
8
+
9
+ export function delivery(text) {
10
+ const m = /^hrx1\.([\w-]+)\.(hrxs_[\w-]{43})$/.exec(text.trim())
11
+ if (!m) throw Error('Mã giao hàng không hợp lệ. Sao chép mã đầy đủ từ người bán.')
12
+ const url = new URL(Buffer.from(m[1], 'base64url').toString('utf8'))
13
+ if (
14
+ url.href !== url.origin + '/' ||
15
+ (url.protocol !== 'https:' &&
16
+ !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)))
17
+ )
18
+ throw Error('Địa chỉ dịch vụ không hợp lệ.')
19
+ return { origin: url.origin, code: m[2] }
20
+ }
21
+
22
+ function sameOthers(a, b) {
23
+ for (const obj of [a, b]) {
24
+ for (const field of fields) delete obj[field]
25
+ if (obj.model_providers) {
26
+ delete obj.model_providers.hrx
27
+ if (!Object.keys(obj.model_providers).length) delete obj.model_providers
28
+ }
29
+ }
30
+ if (!isDeepStrictEqual(a, b))
31
+ 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.')
32
+ }
33
+ function quote(s) {
34
+ return JSON.stringify(s)
35
+ }
36
+ export function configure(text, origin, model, key) {
37
+ const original = parse(text)
38
+ if (original.model_providers?.hrx || text.includes(begin) || text.includes(end))
39
+ throw Error('Provider hrx đã tồn tại trong cấu hình.')
40
+ const nl = text.includes('\r\n') ? '\r\n' : '\n'
41
+ const lines = text.split(nl),
42
+ replaced = {}
43
+ const values = { model, model_provider: 'hrx', web_search: 'disabled' }
44
+ const injected = []
45
+ for (const field of fields) {
46
+ const line = field + ' = ' + quote(values[field]) + managed
47
+ const firstTable = lines.findIndex((s) => /^\s*\[/.test(s))
48
+ const idx = lines.findIndex(
49
+ (s, i) => (firstTable < 0 || i < firstTable) && new RegExp('^\\s*' + field + '\\s*=').test(s),
50
+ )
51
+ if (idx >= 0) {
52
+ replaced[field] = { old: lines[idx], line }
53
+ lines[idx] = line
54
+ } else {
55
+ if (Object.hasOwn(original, field))
56
+ throw Error('Không thể tự cập nhật trường ' + field + ' trong TOML.')
57
+ replaced[field] = { old: null, line }
58
+ injected.push(line)
59
+ }
60
+ }
61
+ const block = [
62
+ begin,
63
+ '[model_providers.hrx]',
64
+ 'name = "HRX"',
65
+ 'base_url = ' + quote(origin + '/api/v1/hrx/v1'),
66
+ 'wire_api = "responses"',
67
+ 'requires_openai_auth = false',
68
+ 'supports_websockets = false',
69
+ 'experimental_bearer_token = ' + quote(key),
70
+ end,
71
+ ].join(nl)
72
+ const base = [...injected, ...lines].join(nl)
73
+ const result = base + nl + block + nl
74
+ const configured = parse(result)
75
+ if (
76
+ configured.model !== model ||
77
+ configured.model_provider !== 'hrx' ||
78
+ configured.model_providers?.hrx?.experimental_bearer_token !== key
79
+ )
80
+ throw Error('Cấu hình HRX không hợp lệ.')
81
+ sameOthers(original, configured)
82
+ return { text: result, patch: { replaced, block } }
83
+ }
84
+
85
+ export function restore(text, patch) {
86
+ const nl = text.includes('\r\n') ? '\r\n' : '\n'
87
+ let result = text
88
+ const block = patch.block.replace(/\r?\n/g, nl)
89
+ if (result.includes(begin) || result.includes(end)) {
90
+ if (!result.includes(block))
91
+ throw Error('Phần provider HRX đã được sửa. Hãy lưu các thay đổi đó trước khi khôi phục.')
92
+ const start = result.indexOf(block)
93
+ const left = result.slice(0, start).replace(/\r?\n$/, '')
94
+ const right = result.slice(start + block.length).replace(/^\r?\n/, '')
95
+ const separator = left && right && !left.endsWith('\n') && !right.startsWith(nl) ? nl : ''
96
+ result = left + separator + right
97
+ }
98
+ const lines = result.split(nl)
99
+ for (const field of fields) {
100
+ if (!patch.replaced[field]) continue
101
+ const { old, line } = patch.replaced[field]
102
+ const index = lines.indexOf(line)
103
+ if (index !== -1) {
104
+ if (old === null) lines.splice(index, 1)
105
+ else lines[index] = old
106
+ }
107
+ }
108
+ result = lines.join(nl)
109
+ parse(result)
110
+ return result
111
+ }
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "codex-unlimited",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Configure Codex for an independent HRX time or token pass",
5
+ "type": "module",
6
+ "bin": { "codex-unlimited": "cli.mjs" },
7
+ "files": ["cli.mjs", "config.mjs", "README.md"],
8
+ "engines": { "node": ">=20" },
9
+ "scripts": { "test": "node --test" },
10
+ "dependencies": { "smol-toml": "^1.4.2" }
11
+ }