@gengjiawen/os-init 1.23.1 → 1.25.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.
@@ -12,57 +12,29 @@ import { writeCodexConfig } from './codex'
12
12
  describe('writeCodexConfig', () => {
13
13
  let tempHome: string
14
14
  let homedirSpy: jest.SpiedFunction<typeof os.homedir>
15
- let originalFetch: typeof global.fetch | undefined
16
-
17
- function getExpectedModelCatalogConfigPath(): string {
18
- return os.platform() === 'win32'
19
- ? path.join(tempHome, '.codex', 'remote-model-catalog.json')
20
- : '~/.codex/remote-model-catalog.json'
21
- }
22
-
23
- function mockCatalogFetch(
24
- catalog: { models: Array<Record<string, unknown>> } = {
25
- models: [{ id: 'gpt-5.5' }],
26
- }
27
- ): jest.Mock {
28
- const fetchMock = jest.fn().mockResolvedValue({
29
- ok: true,
30
- json: async () => catalog,
31
- })
32
- global.fetch = fetchMock as unknown as typeof global.fetch
33
- return fetchMock
34
- }
35
15
 
36
16
  beforeEach(() => {
37
17
  tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'os-init-codex-'))
38
18
  homedirSpy = jest.spyOn(os, 'homedir').mockReturnValue(tempHome)
39
- originalFetch = global.fetch
40
- mockCatalogFetch()
41
19
  })
42
20
 
43
21
  afterEach(() => {
44
22
  homedirSpy.mockRestore()
45
- if (originalFetch === undefined) {
46
- global.fetch = undefined as unknown as typeof global.fetch
47
- } else {
48
- global.fetch = originalFetch
49
- }
50
23
  fs.rmSync(tempHome, { recursive: true, force: true })
51
24
  })
52
25
 
53
- test('writes config with 128k auto compact threshold', async () => {
54
- const result = await writeCodexConfig('test-api-key')
26
+ test('writes config with 128k auto compact threshold', () => {
27
+ const result = writeCodexConfig('test-api-key')
55
28
  const config = TOML.parse(fs.readFileSync(result.configPath, 'utf8')) as {
56
29
  model_auto_compact_token_limit: number
57
- model_catalog_json: string
58
30
  }
59
31
 
60
32
  expect(config.model_auto_compact_token_limit).toBe(131072)
61
- expect(config.model_catalog_json).toBe(getExpectedModelCatalogConfigPath())
62
- expect(fs.existsSync(result.catalogPath)).toBe(true)
33
+ expect(config).not.toHaveProperty('model_catalog_json')
34
+ expect(fs.existsSync(result.authPath)).toBe(true)
63
35
  })
64
36
 
65
- test('merges template keys and keeps custom config', async () => {
37
+ test('merges template keys and keeps custom config', () => {
66
38
  const configDir = path.join(tempHome, '.codex')
67
39
  fs.mkdirSync(configDir, { recursive: true })
68
40
  const configPath = path.join(configDir, 'config.toml')
@@ -78,11 +50,10 @@ custom_model = "keep-me"
78
50
  `
79
51
  )
80
52
 
81
- await writeCodexConfig('test-api-key')
53
+ writeCodexConfig('test-api-key')
82
54
  const config = TOML.parse(fs.readFileSync(configPath, 'utf8')) as {
83
55
  custom_flag: boolean
84
56
  model: string
85
- model_catalog_json: string
86
57
  preferred_auth_method: string
87
58
  model_providers: {
88
59
  jw: {
@@ -94,9 +65,9 @@ custom_model = "keep-me"
94
65
  }
95
66
 
96
67
  expect(config).not.toHaveProperty('service_tier')
68
+ expect(config).not.toHaveProperty('model_catalog_json')
97
69
  expect(config.custom_flag).toBe(true)
98
70
  expect(config.model).toBe('gpt-5.5')
99
- expect(config.model_catalog_json).toBe(getExpectedModelCatalogConfigPath())
100
71
  expect(config.preferred_auth_method).toBe('apikey')
101
72
  expect(config.model_providers.jw.base_url).toBe(
102
73
  'https://ai.gengjiawen.com/api/openai'
@@ -105,7 +76,7 @@ custom_model = "keep-me"
105
76
  expect(config.model_providers.jw.name).toBe('jw')
106
77
  })
107
78
 
108
- test('adds missing keys without removing custom config', async () => {
79
+ test('adds missing keys without removing custom config', () => {
109
80
  const configDir = path.join(tempHome, '.codex')
110
81
  fs.mkdirSync(configDir, { recursive: true })
111
82
  const configPath = path.join(configDir, 'config.toml')
@@ -119,10 +90,9 @@ base_url = "https://example.com"
119
90
  `
120
91
  )
121
92
 
122
- await writeCodexConfig('test-api-key')
93
+ writeCodexConfig('test-api-key')
123
94
  const config = TOML.parse(fs.readFileSync(configPath, 'utf8')) as {
124
95
  model: string
125
- model_catalog_json: string
126
96
  preferred_auth_method: string
127
97
  model_providers: {
128
98
  jw: {
@@ -133,83 +103,34 @@ base_url = "https://example.com"
133
103
  }
134
104
 
135
105
  expect(config.model).toBe('gpt-5.5')
136
- expect(config.model_catalog_json).toBe(getExpectedModelCatalogConfigPath())
106
+ expect(config).not.toHaveProperty('model_catalog_json')
137
107
  expect(config.preferred_auth_method).toBe('apikey')
138
108
  expect(config.model_providers.jw.name).toBe('jw')
139
109
  expect(config).not.toHaveProperty('service_tier')
140
110
  })
141
111
 
142
- test('refreshes remote model catalog after writing config', async () => {
143
- const fetchMock = mockCatalogFetch({
144
- models: [
145
- { id: 'gpt-5.5' },
146
- { id: 'gpt-5.5-mini' },
147
- { id: 'gpt-5.3-codex' },
148
- ],
149
- })
150
-
151
- const result = await writeCodexConfig('test-api-key')
152
-
153
- expect(fetchMock).toHaveBeenCalledWith(
154
- 'https://ai.gengjiawen.com/api/openai/models',
155
- {
156
- headers: {
157
- Accept: 'application/json',
158
- Authorization: 'Bearer test-api-key',
159
- 'User-Agent': '@gengjiawen/os-init',
160
- },
161
- }
162
- )
163
-
164
- const catalog = JSON.parse(fs.readFileSync(result.catalogPath, 'utf8')) as {
165
- models: Array<{ id: string }>
166
- }
167
-
168
- expect(catalog).toEqual({
169
- models: [
170
- { id: 'gpt-5.5' },
171
- { id: 'gpt-5.5-mini' },
172
- { id: 'gpt-5.3-codex' },
173
- ],
174
- })
175
- })
176
-
177
- test('writes an absolute model catalog path on Windows', async () => {
178
- const platformSpy = jest.spyOn(os, 'platform').mockReturnValue('win32')
179
-
180
- try {
181
- const result = await writeCodexConfig('test-api-key')
182
- const config = TOML.parse(fs.readFileSync(result.configPath, 'utf8')) as {
183
- model_catalog_json: string
184
- }
185
-
186
- expect(config.model_catalog_json).toBe(
187
- path.join(tempHome, '.codex', 'remote-model-catalog.json')
188
- )
189
- } finally {
190
- platformSpy.mockRestore()
191
- }
192
- })
112
+ test('drops model_catalog_json when merging existing codex config', () => {
113
+ const configDir = path.join(tempHome, '.codex')
114
+ fs.mkdirSync(configDir, { recursive: true })
115
+ const configPath = path.join(configDir, 'config.toml')
193
116
 
194
- test('throws when refreshing the remote model catalog fails', async () => {
195
- global.fetch = jest.fn().mockResolvedValue({
196
- ok: false,
197
- status: 503,
198
- statusText: 'Service Unavailable',
199
- }) as unknown as typeof global.fetch
117
+ fs.writeFileSync(
118
+ configPath,
119
+ `model_catalog_json = "${path.join(tempHome, '.codex', 'remote-model-catalog.json')}"
120
+ model = "gpt-custom"
200
121
 
201
- await expect(writeCodexConfig('test-api-key')).rejects.toThrow(
202
- 'Failed to refresh Codex model catalog: 503 Service Unavailable'
122
+ [model_providers.jw]
123
+ base_url = "https://example.com"
124
+ `
203
125
  )
204
126
 
205
- expect(fs.existsSync(path.join(tempHome, '.codex', 'config.toml'))).toBe(
206
- false
207
- )
208
- expect(fs.existsSync(path.join(tempHome, '.codex', 'auth.json'))).toBe(
209
- false
210
- )
211
- expect(
212
- fs.existsSync(path.join(tempHome, '.codex', 'remote-model-catalog.json'))
213
- ).toBe(false)
127
+ writeCodexConfig('test-api-key')
128
+ const config = TOML.parse(fs.readFileSync(configPath, 'utf8')) as Record<
129
+ string,
130
+ unknown
131
+ >
132
+
133
+ expect(config).not.toHaveProperty('model_catalog_json')
134
+ expect(config.model).toBe('gpt-5.5')
214
135
  })
215
136
  })
package/libs/codex.ts CHANGED
@@ -6,27 +6,14 @@ import { execa } from 'execa'
6
6
  import { ensureDir, commandExists, PNPM_INSTALL_ENV } from './utils'
7
7
 
8
8
  type TomlTable = ReturnType<typeof TOML.parse>
9
- type CodexModelCatalog = { models: unknown[] }
10
9
 
11
10
  const CODEX_BASE_URL = 'https://ai.gengjiawen.com/api/openai'
12
- const CODEX_MODEL_CATALOG_CONFIG_PATH = '~/.codex/remote-model-catalog.json'
13
- const CODEX_MODEL_CATALOG_FILENAME = 'remote-model-catalog.json'
14
11
 
15
12
  /** Return Codex configuration directory path */
16
13
  function getCodexConfigDir(): string {
17
14
  return path.join(os.homedir(), '.codex')
18
15
  }
19
16
 
20
- function getCodexModelCatalogPath(): string {
21
- return path.join(getCodexConfigDir(), CODEX_MODEL_CATALOG_FILENAME)
22
- }
23
-
24
- function getCodexModelCatalogConfigPath(): string {
25
- return os.platform() === 'win32'
26
- ? getCodexModelCatalogPath()
27
- : CODEX_MODEL_CATALOG_CONFIG_PATH
28
- }
29
-
30
17
  function getCodexConfigTomlTemplate(): string {
31
18
  return `model_provider = "jw"
32
19
  model = "gpt-5.5"
@@ -35,7 +22,6 @@ plan_mode_reasoning_effort = "xhigh"
35
22
  model_auto_compact_token_limit = 131072
36
23
  disable_response_storage = true
37
24
  preferred_auth_method = "apikey"
38
- model_catalog_json = ${JSON.stringify(getCodexModelCatalogConfigPath())}
39
25
 
40
26
  [model_providers.jw]
41
27
  name = "jw"
@@ -71,58 +57,32 @@ function mergeTomlTables(
71
57
  return mergedConfig
72
58
  }
73
59
 
60
+ /** Strip model_catalog_json before parse; Windows paths break TOML string escapes. */
61
+ function stripModelCatalogJsonFromToml(content: string): string {
62
+ return content
63
+ .split('\n')
64
+ .filter((line) => !/^\s*model_catalog_json\s*=/.test(line))
65
+ .join('\n')
66
+ }
67
+
74
68
  function getMergedCodexConfig(existingContent: string): string {
75
- const existingConfig = TOML.parse(existingContent) as TomlTable
69
+ const sanitizedContent = stripModelCatalogJsonFromToml(existingContent)
70
+ const existingConfig = TOML.parse(sanitizedContent) as TomlTable
76
71
  const templateConfig = TOML.parse(getCodexConfigTomlTemplate()) as TomlTable
77
72
  delete existingConfig.service_tier
73
+ delete existingConfig.model_catalog_json
78
74
 
79
75
  return TOML.stringify(mergeTomlTables(existingConfig, templateConfig))
80
76
  }
81
77
 
82
- async function refreshCodexModelCatalog(apiKey: string): Promise<string> {
83
- if (typeof fetch !== 'function') {
84
- throw new Error('Global fetch API is unavailable in this Node.js runtime.')
85
- }
86
-
87
- const response = await fetch(`${CODEX_BASE_URL}/models`, {
88
- headers: {
89
- Accept: 'application/json',
90
- Authorization: `Bearer ${apiKey}`,
91
- 'User-Agent': '@gengjiawen/os-init',
92
- },
93
- })
94
-
95
- if (!response.ok) {
96
- throw new Error(
97
- `Failed to refresh Codex model catalog: ${response.status} ${response.statusText}`
98
- )
99
- }
100
-
101
- const catalog = (await response.json()) as CodexModelCatalog
102
-
103
- if (!Array.isArray(catalog?.models) || catalog.models.length === 0) {
104
- throw new Error(
105
- 'Failed to refresh Codex model catalog: response does not contain any models.'
106
- )
107
- }
108
-
109
- const catalogPath = getCodexModelCatalogPath()
110
- fs.writeFileSync(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`)
111
-
112
- return catalogPath
113
- }
114
-
115
78
  /** Write Codex config.toml and auth.json */
116
- export async function writeCodexConfig(apiKey: string): Promise<{
79
+ export function writeCodexConfig(apiKey: string): {
117
80
  configPath: string
118
81
  authPath: string
119
- catalogPath: string
120
- }> {
82
+ } {
121
83
  const configDir = getCodexConfigDir()
122
84
  ensureDir(configDir)
123
85
 
124
- const catalogPath = await refreshCodexModelCatalog(apiKey)
125
-
126
86
  const configPath = path.join(configDir, 'config.toml')
127
87
  const configContent = fs.existsSync(configPath)
128
88
  ? getMergedCodexConfig(fs.readFileSync(configPath, 'utf8'))
@@ -133,7 +93,7 @@ export async function writeCodexConfig(apiKey: string): Promise<{
133
93
  const authContent = JSON.stringify({ OPENAI_API_KEY: apiKey }, null, 2)
134
94
  fs.writeFileSync(authPath, authContent)
135
95
 
136
- return { configPath, authPath, catalogPath }
96
+ return { configPath, authPath }
137
97
  }
138
98
 
139
99
  /** Install Codex dependency */
@@ -0,0 +1,204 @@
1
+ import * as fs from 'fs'
2
+ import * as os from 'os'
3
+ import * as path from 'path'
4
+ import { Buffer } from 'node:buffer'
5
+ import { DatabaseSync } from 'node:sqlite'
6
+ import {
7
+ CURSOR_TYPESCRIPT_EXTENSION_ID,
8
+ disableCursorTypescriptExtension,
9
+ getCursorStateDbPath,
10
+ mergeDisabledExtension,
11
+ } from './cursor'
12
+
13
+ const DISABLED_EXTENSIONS_STORAGE_KEY = 'extensionsIdentifiers/disabled'
14
+
15
+ interface DisabledExtensionIdentifier {
16
+ id: string
17
+ uuid?: string
18
+ }
19
+
20
+ function readDisabledExtensions(dbPath: string): DisabledExtensionIdentifier[] {
21
+ const db = new DatabaseSync(dbPath)
22
+
23
+ try {
24
+ const row = db
25
+ .prepare('select value from ItemTable where key = ?')
26
+ .get(DISABLED_EXTENSIONS_STORAGE_KEY) as
27
+ | { value: string | Buffer }
28
+ | undefined
29
+
30
+ if (!row) {
31
+ throw new Error('disabled extensions row was not written')
32
+ }
33
+
34
+ const value =
35
+ typeof row.value === 'string'
36
+ ? row.value
37
+ : Buffer.from(row.value).toString('utf8')
38
+
39
+ return JSON.parse(value) as DisabledExtensionIdentifier[]
40
+ } finally {
41
+ db.close()
42
+ }
43
+ }
44
+
45
+ function writeDisabledExtensions(
46
+ dbPath: string,
47
+ disabledExtensions: DisabledExtensionIdentifier[]
48
+ ): void {
49
+ fs.mkdirSync(path.dirname(dbPath), { recursive: true })
50
+
51
+ const db = new DatabaseSync(dbPath)
52
+
53
+ try {
54
+ db.exec(
55
+ 'create table if not exists ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)'
56
+ )
57
+ db.prepare('insert or replace into ItemTable(key,value) values (?, ?)').run(
58
+ DISABLED_EXTENSIONS_STORAGE_KEY,
59
+ JSON.stringify(disabledExtensions)
60
+ )
61
+ } finally {
62
+ db.close()
63
+ }
64
+ }
65
+
66
+ describe('getCursorStateDbPath', () => {
67
+ test('returns macOS Cursor state DB path', () => {
68
+ expect(getCursorStateDbPath('darwin', {}, '/Users/dev')).toBe(
69
+ path.join(
70
+ '/Users/dev',
71
+ 'Library',
72
+ 'Application Support',
73
+ 'Cursor',
74
+ 'User',
75
+ 'globalStorage',
76
+ 'state.vscdb'
77
+ )
78
+ )
79
+ })
80
+
81
+ test('returns Linux Cursor state DB path', () => {
82
+ expect(getCursorStateDbPath('linux', {}, '/home/dev')).toBe(
83
+ path.join(
84
+ '/home/dev',
85
+ '.config',
86
+ 'Cursor',
87
+ 'User',
88
+ 'globalStorage',
89
+ 'state.vscdb'
90
+ )
91
+ )
92
+ })
93
+
94
+ test('returns Windows Cursor state DB path', () => {
95
+ expect(
96
+ getCursorStateDbPath(
97
+ 'win32',
98
+ { APPDATA: 'C:\\Users\\dev\\AppData\\Roaming' },
99
+ 'C:\\Users\\dev'
100
+ )
101
+ ).toBe(
102
+ path.join(
103
+ 'C:\\Users\\dev\\AppData\\Roaming',
104
+ 'Cursor',
105
+ 'User',
106
+ 'globalStorage',
107
+ 'state.vscdb'
108
+ )
109
+ )
110
+ })
111
+ })
112
+
113
+ describe('mergeDisabledExtension', () => {
114
+ test('adds VS Code TypeScript extension to empty storage value', () => {
115
+ const result = mergeDisabledExtension(undefined)
116
+
117
+ expect(result.changed).toBe(true)
118
+ expect(result.disabledExtensions).toEqual([
119
+ { id: CURSOR_TYPESCRIPT_EXTENSION_ID },
120
+ ])
121
+ expect(JSON.parse(result.value)).toEqual([
122
+ { id: CURSOR_TYPESCRIPT_EXTENSION_ID },
123
+ ])
124
+ })
125
+
126
+ test('preserves existing disabled extensions', () => {
127
+ const result = mergeDisabledExtension(
128
+ JSON.stringify([{ id: 'publisher.extension', uuid: 'test-uuid' }])
129
+ )
130
+
131
+ expect(result.changed).toBe(true)
132
+ expect(result.disabledExtensions).toEqual([
133
+ { id: 'publisher.extension', uuid: 'test-uuid' },
134
+ { id: CURSOR_TYPESCRIPT_EXTENSION_ID },
135
+ ])
136
+ })
137
+
138
+ test('is idempotent and matches extension id case-insensitively', () => {
139
+ const result = mergeDisabledExtension(
140
+ JSON.stringify([{ id: CURSOR_TYPESCRIPT_EXTENSION_ID.toUpperCase() }])
141
+ )
142
+
143
+ expect(result.changed).toBe(false)
144
+ expect(result.disabledExtensions).toEqual([
145
+ { id: CURSOR_TYPESCRIPT_EXTENSION_ID.toUpperCase() },
146
+ ])
147
+ })
148
+
149
+ test('rejects non-array storage value', () => {
150
+ expect(() => mergeDisabledExtension(JSON.stringify({ id: 'bad' }))).toThrow(
151
+ `${DISABLED_EXTENSIONS_STORAGE_KEY} must contain a JSON array`
152
+ )
153
+ })
154
+ })
155
+
156
+ describe('disableCursorTypescriptExtension', () => {
157
+ let tempDir: string
158
+
159
+ beforeEach(() => {
160
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'os-init-cursor-'))
161
+ })
162
+
163
+ afterEach(() => {
164
+ fs.rmSync(tempDir, { recursive: true, force: true })
165
+ })
166
+
167
+ test('creates Cursor state DB and disables VS Code TypeScript extension', async () => {
168
+ const dbPath = path.join(
169
+ tempDir,
170
+ 'Cursor',
171
+ 'User',
172
+ 'globalStorage',
173
+ 'state.vscdb'
174
+ )
175
+
176
+ const result = await disableCursorTypescriptExtension({ dbPath })
177
+
178
+ expect(result).toMatchObject({
179
+ dbPath,
180
+ key: DISABLED_EXTENSIONS_STORAGE_KEY,
181
+ extensionId: CURSOR_TYPESCRIPT_EXTENSION_ID,
182
+ changed: true,
183
+ })
184
+ expect(readDisabledExtensions(dbPath)).toEqual([
185
+ { id: CURSOR_TYPESCRIPT_EXTENSION_ID },
186
+ ])
187
+ })
188
+
189
+ test('preserves existing disabled extensions and is idempotent', async () => {
190
+ const dbPath = path.join(tempDir, 'state.vscdb')
191
+
192
+ writeDisabledExtensions(dbPath, [{ id: 'publisher.extension' }])
193
+
194
+ const firstResult = await disableCursorTypescriptExtension({ dbPath })
195
+ const secondResult = await disableCursorTypescriptExtension({ dbPath })
196
+
197
+ expect(firstResult.changed).toBe(true)
198
+ expect(secondResult.changed).toBe(false)
199
+ expect(readDisabledExtensions(dbPath)).toEqual([
200
+ { id: 'publisher.extension' },
201
+ { id: CURSOR_TYPESCRIPT_EXTENSION_ID },
202
+ ])
203
+ })
204
+ })