@lumyne/codex-gateway 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.
@@ -0,0 +1,397 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const os = require('node:os');
5
+ const http = require('node:http');
6
+ const crypto = require('node:crypto');
7
+ const { Readable, Transform } = require('node:stream');
8
+ const { execFileSync, spawn } = require('node:child_process');
9
+
10
+ const { readSettings } = require('./settings.cjs');
11
+ const { applyImageLinkGuard } = require('./image-link-response.cjs');
12
+ const { parse } = require('smol-toml');
13
+ const { version } = require('../package.json');
14
+ const entry = path.join(__dirname, '..', 'bin', 'codex-gateway.cjs');
15
+
16
+ const defaultRoot = path.join(os.homedir(), '.codex');
17
+ const root = path.resolve(process.env.CODEX_HOME || defaultRoot);
18
+ const installed = path.join(root, 'company-gateway-three.cjs');
19
+ const vault = path.join(root, 'company-gateway.dpapi');
20
+ const profile = path.join(root, 'company-gateway.config.toml');
21
+ const catalog = path.join(root, 'company-gateway-catalog.json');
22
+ const settingsFile = path.join(root, 'company-gateway-settings.json');
23
+ const port = Number(process.env.CODEX_GATEWAY_PORT || 37649);
24
+ if (!Number.isInteger(port) || port<1024 || port>65535 ||
25
+ (port!==37649 && root.toLowerCase()===defaultRoot.toLowerCase())) {
26
+ throw new Error('An alternate loopback port requires a separate Codex home.');
27
+ }
28
+ const isolated = port!==37649 && root.toLowerCase()!==defaultRoot.toLowerCase();
29
+ const loopback = 'http://127.0.0.1:'+port;
30
+ const ps = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
31
+ const markers = ['# BEGIN Codex company gateway model', '# END Codex company gateway model',
32
+ '# BEGIN Codex company gateway provider', '# END Codex company gateway provider'];
33
+
34
+ function powershell(script, input) {
35
+ const encoded = Buffer.from('[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); '+script, 'utf16le').toString('base64');
36
+ try {
37
+ return execFileSync(ps, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
38
+ { input, encoding: 'utf8', timeout: 20000, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
39
+ } catch (error) {
40
+ throw new Error('Windows PowerShell operation failed ('+(error.code || error.status || 'unknown')+').');
41
+ }
42
+ }
43
+
44
+ function protect(key, file) {
45
+ const target = "'"+file.replace(/'/g,"''")+"'";
46
+ powershell("$ErrorActionPreference='Stop'; Add-Type -AssemblyName System.Security; " +
47
+ "$v=[Convert]::FromBase64String([Console]::In.ReadLine()); try { " +
48
+ "$c=[Security.Cryptography.ProtectedData]::Protect($v,$null,'CurrentUser'); " +
49
+ "$f=[IO.File]::Open("+target+",'CreateNew','Write'); try {$f.Write($c,0,$c.Length)} finally {$f.Dispose()} " +
50
+ "} finally {[Array]::Clear($v,0,$v.Length)}; " +
51
+ "$sid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value; " +
52
+ "& icacls.exe "+target+" /inheritance:r /grant:r ('*'+$sid+':F') | Out-Null; " +
53
+ "if ($LASTEXITCODE -ne 0) {throw 'Could not restrict credential permissions'}", key.toString('base64')+'\n');
54
+ }
55
+
56
+ function key(file) {
57
+ if (!fs.lstatSync(file).isFile()) throw new Error('Invalid credential storage file.');
58
+ const target = "'"+file.replace(/'/g,"''")+"'";
59
+ return powershell("$ErrorActionPreference='Stop'; Add-Type -AssemblyName System.Security; " +
60
+ "$v=[Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes("+target+"),$null,'CurrentUser'); " +
61
+ "try {[Console]::Write([Text.Encoding]::UTF8.GetString($v))} finally {[Array]::Clear($v,0,$v.Length)}").trim();
62
+ }
63
+
64
+ function capability(gatewayKey) {
65
+ return crypto.createHmac('sha256', gatewayKey).update('codex-company-gateway-loopback-37649-v1').digest('base64url');
66
+ }
67
+
68
+ function packageBridge() {
69
+ return require('@petercjl/codex-own/lib/subagent-bridge.cjs');
70
+ }
71
+
72
+ function secretFile(id) {
73
+ return path.join(root, 'gateway-credential-' + id + '.dpapi');
74
+ }
75
+
76
+ function token() {
77
+ const secret = key(path.join(root, 'gateway-loopback.dpapi'));
78
+ return capability(secret);
79
+ }
80
+
81
+ function reply(res, status, body) {
82
+ res.writeHead(status, { 'content-type':'application/json', 'cache-control':'no-store' });
83
+ res.end(JSON.stringify(body));
84
+ }
85
+
86
+ async function runBridge() {
87
+ const settings = readSettings(settingsFile);
88
+ const authorization = token();
89
+ const byId = new Map(settings.models.map(model => [model.id, model]));
90
+ const routes = Object.values(settings.channels).map(channel => {
91
+ const base = new URL(channel.endpoint);
92
+ const prefix = base.pathname.replace(/\/$/, '');
93
+ const messages = prefix.endsWith('/v1') ? prefix + '/messages' : prefix + '/v1/messages';
94
+ return {base, allowed: [prefix + '/responses', prefix + '/responses/compact', messages]};
95
+ });
96
+ const upstream = await packageBridge().startServer({
97
+ authorization,
98
+ resolveRoute(id) {
99
+ const model = byId.get(id);
100
+ if (!model) throw Object.assign(new Error('Model is outside the configured catalogue.'), {code:'MODEL_NOT_CONFIGURED'});
101
+ const channel = settings.channels[model.channel];
102
+ return { model:id, protocol:model.protocol, baseURL:channel.endpoint, apiKey:key(secretFile(channel.credential)),
103
+ spec:{maxOutput:32768,thinking:null} };
104
+ },
105
+ prepareBody(body) {
106
+ if (byId.get(body.model)?.hostedSearch || !Array.isArray(body.tools)) return body;
107
+ const hosted = new Set(['web_search','web_search_preview']);
108
+ return {...body,tools:body.tools.filter(tool=>!hosted.has(tool.type))};
109
+ },
110
+ async fetch(url, options) {
111
+ const target = new URL(url);
112
+ if (!routes.some(({base, allowed}) => target.origin === base.origin && allowed.includes(target.pathname))) {
113
+ throw new Error('Unrecognized upstream route.');
114
+ }
115
+ const selected = new Headers();
116
+ for (const [name, value] of new Headers(options.headers)) {
117
+ if (['authorization','x-api-key','content-type','accept','anthropic-version','anthropic-beta'].includes(name)) {
118
+ selected.set(name,value);
119
+ }
120
+ }
121
+ return fetch(target,{...options,headers:selected,redirect:'error'});
122
+ }
123
+ });
124
+ const outer = http.createServer((req,res) => {
125
+ const supplied = Buffer.from(req.headers.authorization || '');
126
+ const expected = Buffer.from('Bearer '+authorization);
127
+ if (supplied.length!==expected.length || !crypto.timingSafeEqual(supplied,expected)) {
128
+ return reply(res,401,{error:'unauthorized'});
129
+ }
130
+ if (req.method==='GET' && req.url==='/health') return reply(res,200,{bridge:'codex-gateway',version});
131
+ if (req.method==='POST' && req.url==='/stop') {
132
+ reply(res,200,{stopping:true});
133
+ outer.close(); upstream.close().finally(()=>process.exit(0));
134
+ return;
135
+ }
136
+ if (req.method==='GET' && /^\/models(?:\?.*)?$/.test(req.url)) {
137
+ const data=JSON.parse(fs.readFileSync(catalog,'utf8'));
138
+ return reply(res,200,data);
139
+ }
140
+ if (req.method!=='POST' || !/^\/responses(?:\/compact)?(?:\?.*)?$/.test(req.url)) {
141
+ return reply(res,404,{error:'unknown route'});
142
+ }
143
+ const chunks = [];
144
+ let captured = 0;
145
+ const limit = require('@petercjl/codex-own/lib/request-budget.cjs').maxRequestBytes();
146
+ const tap = new Transform({
147
+ transform(chunk, encoding, done) {
148
+ captured += chunk.length;
149
+ if (captured <= limit) chunks.push(chunk);
150
+ else chunks.length = 0;
151
+ done(null, chunk);
152
+ }
153
+ });
154
+ const request=http.request(upstream.url+req.url,{method:'POST',headers:{
155
+ authorization:'Bearer '+authorization,'content-type':'application/json',accept:req.headers.accept||'*/*'}},async source=>{
156
+ try {
157
+ const headers = {'content-type':source.headers['content-type']||'application/json','cache-control':'no-store'};
158
+ let body;
159
+ if (chunks.length && req.url.split('?')[0]==='/responses' && source.statusCode===200) {
160
+ try { body = JSON.parse(Buffer.concat(chunks)); } catch {}
161
+ }
162
+ chunks.length = 0;
163
+ let output = source;
164
+ if (byId.get(body?.model)?.repairImageLinks) {
165
+ const response = new Response(Readable.toWeb(source), {status:source.statusCode, headers});
166
+ const guarded = await applyImageLinkGuard(response, body);
167
+ output = Readable.fromWeb(guarded.body);
168
+ }
169
+ if (res.destroyed) { output.destroy(); return; }
170
+ res.writeHead(source.statusCode,headers);
171
+ output.on('error',()=>res.destroy());
172
+ output.pipe(res);
173
+ } catch {
174
+ source.destroy();
175
+ if(!res.headersSent && !res.destroyed)reply(res,502,{error:'bridge unavailable'});
176
+ else res.destroy();
177
+ }
178
+ });
179
+ request.on('error',()=>{if(!res.headersSent && !res.destroyed)reply(res,502,{error:'bridge unavailable'});else res.destroy();});
180
+ res.on('close',()=>{if(!res.writableEnded){tap.destroy();request.destroy();}});
181
+ req.pipe(tap).pipe(request);
182
+ });
183
+ outer.on('error',()=>upstream.close().finally(()=>process.exit(1)));
184
+ outer.listen(port,'127.0.0.1');
185
+ }
186
+
187
+ async function bridgeControl(route, method='GET') {
188
+ try {
189
+ const res=await fetch(loopback+route,{method,headers:{Authorization:'Bearer '+token()},
190
+ redirect:'error',signal:AbortSignal.timeout(1800)});
191
+ if(!res.ok)return null;
192
+ return await res.json();
193
+ } catch {return null;}
194
+ }
195
+
196
+ async function ensureBridge(restartOlder = false) {
197
+ const active = await bridgeControl('/health');
198
+ if (active?.bridge==='codex-gateway') {
199
+ if (active.version===version || !restartOlder) return;
200
+ await bridgeControl('/stop','POST');
201
+ for (let count=0; count<25; count++) {
202
+ if (!(await bridgeControl('/health'))) break;
203
+ await new Promise(resolve=>setTimeout(resolve,200));
204
+ }
205
+ }
206
+ const proc=spawn(process.execPath,[entry,'bridge'],{stdio:'ignore',windowsHide:true,detached:true});
207
+ proc.unref();
208
+ for(let count=0;count<25;count++) {
209
+ await new Promise(r=>setTimeout(r,200));
210
+ if((await bridgeControl('/health'))?.version===version) return;
211
+ if(proc.exitCode!==null && count>10)break;
212
+ }
213
+ throw new Error('The authenticated loopback bridge did not start. Check the configured loopback port and runtime.');
214
+ }
215
+
216
+ function save(file, data) {
217
+ const bytes=Buffer.isBuffer(data)?data:Buffer.from(data);
218
+ if (!fs.existsSync(file)) {
219
+ fs.writeFileSync(file,bytes,{flag:'wx'});
220
+ if(!fs.readFileSync(file).equals(bytes))throw new Error('Write verification failed.');
221
+ return;
222
+ }
223
+ if(!fs.lstatSync(file).isFile())throw new Error('Invalid configuration target.');
224
+ const old=fs.readFileSync(file);
225
+ if(old.equals(bytes))return;
226
+ const id=crypto.randomUUID();
227
+ const backup=file+'.before-three-'+id;
228
+ const stage=file+'.stage-'+id;
229
+ fs.copyFileSync(file,backup,fs.constants.COPYFILE_EXCL);
230
+ if(!fs.readFileSync(backup).equals(old)||!fs.readFileSync(file).equals(old))throw new Error('Configuration backup verification failed.');
231
+ fs.writeFileSync(stage,bytes,{flag:'wx'});
232
+ fs.renameSync(stage,file);
233
+ if(!fs.readFileSync(file).equals(bytes))throw new Error('Write verification failed.');
234
+ }
235
+
236
+ function makeCatalog(cli, settings) {
237
+ const output=execFileSync(cli,['debug','models','--bundled'],{encoding:'utf8',windowsHide:true,maxBuffer:10*1024*1024});
238
+ const bundled=JSON.parse(output).models;
239
+ const base=bundled.find(item=>item.slug===settings.defaultModel) || bundled.find(item=>item.visibility==='list');
240
+ if(!base)throw new Error('Installed Codex does not bundle the expected baseline model.');
241
+ return {models:settings.models.map((m,index)=>{
242
+ const copy=structuredClone(base);
243
+ Object.assign(copy,{slug:m.id,display_name:m.label,description:settings.label+' / '+m.id,priority:index,
244
+ upgrade:null,availability_nux:null,additional_speed_tiers:[],service_tiers:[]});
245
+ if(m.id!==settings.defaultModel || base.slug!==m.id) Object.assign(copy,{visibility:'list',default_reasoning_level:'low',
246
+ supported_reasoning_levels:[{effort:'low',description:'Default'}],
247
+ context_window:Math.min(base.context_window||128000,128000),max_context_window:128000,
248
+ input_modalities:['text'],supports_search_tool:false,supports_image_detail_original:false,
249
+ experimental_supported_tools:[],
250
+ supports_experimental_context:false,use_responses_lite:false,supports_reasoning_effort_updates:false});
251
+ return copy;
252
+ })};
253
+ }
254
+
255
+ function discoverCli() {
256
+ let exe;
257
+ try {
258
+ exe = powershell(
259
+ "$ProgressPreference='SilentlyContinue'; "+
260
+ "$a=Get-AppxPackage -Name 'OpenAI.Codex' -ErrorAction SilentlyContinue | Select-Object -First 1; "+
261
+ "if($a){$p=Join-Path $a.InstallLocation 'app\\resources\\codex.exe'; "+
262
+ "if(Test-Path -LiteralPath $p -PathType Leaf){[Console]::Write($p); return}}; "+
263
+ "$dir=Join-Path $env:LOCALAPPDATA 'OpenAI\\Codex\\bin'; "+
264
+ "if(Test-Path -LiteralPath $dir -PathType Container){"+
265
+ "$p=Get-ChildItem -LiteralPath $dir -Recurse -Filter codex.exe -ErrorAction SilentlyContinue | "+
266
+ "Sort-Object LastWriteTime -Descending | Select-Object -First 1; if($p){[Console]::Write($p.FullName)}}"
267
+ ).trim();
268
+ } catch {}
269
+ if (!exe) throw new Error('Official Codex CLI not found. Open the official desktop app once or pass --codex-cli.');
270
+ return exe;
271
+ }
272
+
273
+ function requireClosed() {
274
+ const running = execFileSync('tasklist.exe',['/FO','CSV','/NH'],{encoding:'utf8',windowsHide:true});
275
+ if (/^"(?:ChatGPT|Codex)\.exe",/im.test(running)) {
276
+ throw new Error('Quit Codex using File > Quit before changing its gateway settings.');
277
+ }
278
+ }
279
+
280
+ async function install(config, cli, keyFile, shortcuts, json) {
281
+ const settings = readSettings(config);
282
+ const value = makeCatalog(cli || discoverCli(), settings);
283
+ if (!isolated||shortcuts) requireClosed();
284
+ if (isolated&&shortcuts) throw new Error('Isolated configuration requires --no-shortcut.');
285
+ fs.mkdirSync(root, {recursive:true});
286
+ const refs = [...new Set(Object.values(settings.channels).map(channel=>channel.credential))];
287
+ let secrets = {};
288
+ if (keyFile) {
289
+ try { secrets = JSON.parse(fs.readFileSync(keyFile,'utf8').replace(/^\uFEFF/,'')); }
290
+ catch { throw new Error('Could not read the credential file as a JSON object.'); }
291
+ }
292
+ if (!secrets || typeof secrets !== 'object' || Array.isArray(secrets) ||
293
+ Object.keys(secrets).some(id=>!refs.includes(id))) throw new Error('Credential file must map configured references to API keys.');
294
+ const missing = refs.filter(id=>!fs.existsSync(secretFile(id)));
295
+ const legacy = missing.length === 1 && refs.length === 1 && fs.existsSync(vault) && !keyFile;
296
+ for (const id of missing) {
297
+ if (!legacy && (typeof secrets[id]!=='string' || !/^[!-~]{1,4096}$/.test(secrets[id]))) {
298
+ throw new Error('Missing or invalid credential for reference: '+id);
299
+ }
300
+ }
301
+ for (const id of refs) {
302
+ if (Object.hasOwn(secrets,id) && fs.existsSync(secretFile(id)) && key(secretFile(id))!==secrets[id]) {
303
+ throw new Error('Use a new credential reference to rotate this key.');
304
+ }
305
+ }
306
+ if (legacy) {
307
+ const oldToken = capability(key(vault));
308
+ await fetch(loopback+'/stop',{method:'POST',headers:{Authorization:'Bearer '+oldToken},signal:AbortSignal.timeout(1800)}).catch(()=>{});
309
+ } else if (fs.existsSync(path.join(root,'gateway-loopback.dpapi'))) {
310
+ await bridgeControl('/stop','POST');
311
+ }
312
+ for (const id of missing) {
313
+ const secret = Buffer.from(legacy ? key(vault) : secrets[id]);
314
+ try { protect(secret,secretFile(id)); } finally { secret.fill(0); }
315
+ }
316
+ const loopbackFile = path.join(root,'gateway-loopback.dpapi');
317
+ if (!fs.existsSync(loopbackFile)) protect(Buffer.from(crypto.randomBytes(32).toString('base64url')),loopbackFile);
318
+ const toml=[
319
+ 'model = '+JSON.stringify(settings.defaultModel), 'model_provider = "company_gateway"',
320
+ 'model_catalog_json = '+JSON.stringify(catalog.replaceAll('\\','/')), '',
321
+ '[model_providers.company_gateway]', 'name = '+JSON.stringify(settings.label), 'base_url = "'+loopback+'"',
322
+ 'wire_api = "responses"', 'supports_websockets = false', '',
323
+ '[model_providers.company_gateway.capabilities]', 'remote_compaction = "unsupported"', '',
324
+ '[model_providers.company_gateway.auth]', 'command = '+JSON.stringify(process.execPath.replaceAll('\\','/')),
325
+ 'args = '+JSON.stringify([installed.replaceAll('\\','/'),'token']), 'timeout_ms = 15000', ''
326
+ ].join('\n');
327
+ save(settingsFile,JSON.stringify(settings)+'\n');
328
+ save(installed,Buffer.from('process.env.CODEX_HOME='+JSON.stringify(root)+'; process.env.CODEX_GATEWAY_PORT='+JSON.stringify(String(port))+'; require('+JSON.stringify(entry)+');\n'));
329
+ save(catalog,JSON.stringify(value)+'\n');
330
+ save(profile,toml);
331
+ if (shortcuts) createShortcut();
332
+ const models = settings.models.map(model=>model.id);
333
+ console.log(json?JSON.stringify({ok:true,mode:'configured',version,models}):'Installed gateway profile: '+models.join(', '));
334
+ }
335
+
336
+ async function activate(mode,noLaunch,json) {
337
+ if (!isolated||!noLaunch) requireClosed();
338
+ if (isolated&&!noLaunch) throw new Error('Isolated configuration requires --no-launch.');
339
+ const file=path.join(root,'config.toml');
340
+ if(fs.existsSync(file) && !fs.lstatSync(file).isFile())throw new Error('Unexpected Codex configuration file type.');
341
+ const original=fs.existsSync(file)?fs.readFileSync(file,'utf8'):null;
342
+ const bom=(original||'').startsWith('\uFEFF')?'\uFEFF':'';
343
+ let text=(original||'').slice(bom.length);
344
+ const found=markers.filter(m=>text.includes(m)).length;
345
+ if(found!==0 && found!==4)throw new Error('Gateway mode markers were edited.');
346
+ if(found===4) {
347
+ const first=/^# BEGIN Codex company gateway model\r?\n[\s\S]*?^# END Codex company gateway model\r?\n/m;
348
+ const last=/\r?\n# BEGIN Codex company gateway provider\r?\n[\s\S]*?^# END Codex company gateway provider\r?\n?/m;
349
+ if(!first.test(text)||!last.test(text))throw new Error('Could not identify the gateway settings to remove.');
350
+ text=text.replace(first,'').replace(last,'');
351
+ }
352
+ if(mode==='Gateway') {
353
+ const top=text.split(/\r?\n\s*\[/,1)[0];
354
+ if(/^\s*(?:model|model_provider|model_catalog_json)\s*=/m.test(top)||/^\s*\[model_providers\.company_gateway\]/m.test(text)) {
355
+ throw new Error('Found an existing model override. Configuration was preserved.');
356
+ }
357
+ const source=fs.readFileSync(profile,'utf8').trimEnd();
358
+ const split=source.indexOf('[model_providers.company_gateway]');
359
+ if(split<0)throw new Error('Gateway profile is incomplete.');
360
+ await ensureBridge(true);
361
+ text=markers[0]+'\n'+source.slice(0,split).trimEnd()+'\n'+markers[1]+'\n'+text+'\n'+
362
+ markers[2]+'\n'+source.slice(split)+'\n'+markers[3]+'\n';
363
+ }
364
+ parse(text);
365
+ if((fs.existsSync(file)?fs.readFileSync(file,'utf8'):null)!==original)throw new Error('Codex configuration changed during the switch.');
366
+ save(file,bom+text);
367
+ if(mode==='Plus'&&fs.existsSync(vault))await bridgeControl('/stop','POST');
368
+ if(!noLaunch) {
369
+ const app=powershell("$p=Get-AppxPackage -Name 'OpenAI.Codex'; if(!$p){throw 'Official Codex not installed'}; [Console]::Write($p.PackageFamilyName+'!App')").trim();
370
+ if(!/^OpenAI\.Codex_[a-z0-9]+!App$/i.test(app))throw new Error('Unrecognized official Codex application ID.');
371
+ spawn('explorer.exe',['shell:AppsFolder\\'+app],{stdio:'ignore',windowsHide:true,detached:true}).unref();
372
+ }
373
+ console.log(json?JSON.stringify({ok:true,mode,version}):'Codex mode: '+mode);
374
+ }
375
+
376
+ function createShortcut() {
377
+ const psLiteral = value => "'" + value.replaceAll("'", "''") + "'";
378
+ powershell(
379
+ "$ErrorActionPreference='Stop'; $shell=New-Object -ComObject WScript.Shell; " +
380
+ "$desktop=[Environment]::GetFolderPath('Desktop'); $file=Join-Path $desktop 'Codex - Gateway.lnk'; " +
381
+ "if(Test-Path -LiteralPath $file){return}; $link=$shell.CreateShortcut($file); " +
382
+ "$link.TargetPath="+psLiteral(process.execPath)+"; $link.Arguments="+psLiteral('"'+installed+'" Gateway')+"; $link.Save()"
383
+ );
384
+ }
385
+
386
+ async function main(mode, options) {
387
+ if(process.platform!=='win32')throw new Error('Gateway configuration and desktop launching require Windows.');
388
+ if(mode==='install')return install(options.config,options['codex-cli'],options.credentials,!options['no-shortcut'],options.json);
389
+ if(mode==='token'){await ensureBridge();return process.stdout.write(token()+'\n');}
390
+ if(mode==='bridge')return runBridge();
391
+ if(mode==='ensure')return ensureBridge();
392
+ if(mode==='stop')return bridgeControl('/stop','POST');
393
+ if(mode==='Gateway'||mode==='Plus')return activate(mode,options['no-launch'],options.json);
394
+ throw new Error('Unknown Windows gateway operation.');
395
+ }
396
+
397
+ module.exports = {main};
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@lumyne/codex-gateway",
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 an isolated gateway for the official Codex desktop app on Windows",
5
+ "bin": {
6
+ "codex-gateway": "bin/codex-gateway.cjs"
7
+ },
8
+ "engines": {
9
+ "node": ">=22"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "lib",
14
+ "skills",
15
+ "capabilities.json",
16
+ "gateway.example.json",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "prepack": "node bin/codex-gateway.cjs prepack"
22
+ },
23
+ "dependencies": {
24
+ "@petercjl/codex-own": "0.6.17",
25
+ "smol-toml": "1.9.1"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org"
30
+ }
31
+ }
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: codex-gateway
3
+ description: Configure or update the gateway helper for the official Codex desktop application on Windows, or diagnose its local gateway, model catalogue, and generated-image links.
4
+ ---
5
+
6
+ # Configure the Codex gateway
7
+
8
+ Use the installed `codex-gateway` CLI. Run `doctor --json` and `capabilities --json` to discover the version and available operations. The agent may run the CLI on Windows directly or through an authorized Windows session.
9
+
10
+ 1. Confirm the target Windows account owns the Codex configuration. Use the authorized external gateway configuration. Import a separate JSON credential file only when the configured credential references are missing. Follow the package README for the input format.
11
+ 2. Ask the user to finish active Codex work before applying gateway configuration or switching modes. Run `codex-gateway install --config FILE`. Add `--credentials FILE` if needed. A previously installed single-channel gateway can reuse its protected Windows credential.
12
+ 3. Run `codex-gateway Gateway` to launch the official application in gateway mode. `codex-gateway Plus` restores the subscription entry when applicable. Validate the model picker and a minimal response using a configured model. If checking image links, compare the actual generated file with the displayed link.
13
+ 4. For a package upgrade, resolve the current Agent's own Skill directory. Use the CLI's `update install --yes` with its Agent name and exact Skill destination, then verify the CLI version and `skill status --json`. Reapply configuration only when it changes.
14
+
15
+ Handle credentials as private input. Report only whether authentication worked and the resulting mode, model list, and verified operations.
@@ -0,0 +1,6 @@
1
+ {
2
+ "agent": "generic",
3
+ "requirements": ["shell execution", "file access", "resolved Skill directory"],
4
+ "target": {"flag": "--target", "kind": "skill-directory"},
5
+ "cli": "codex-gateway"
6
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "schema_version": 1,
3
+ "skill": "codex-gateway",
4
+ "target_platforms": ["generic"],
5
+ "host_resolution": {"fallback_adapter": "generic"},
6
+ "dependencies": {"cli": "codex-gateway", "node": ">=22"},
7
+ "operation_platform": "windows"
8
+ }