mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
feat(codex): support explicit local model catalog configuration (#2266)
* fix(codex): reuse local model catalogs by default * fix(codex): verify catalog provenance and native schema before reuse * fix(codex): keep refresh credentials out of discovery homes * refactor(codex): reduce catalog support to explicit configuration * fix(codex): invalidate selected catalogs and resolve shim names
This commit is contained in:
@@ -106,6 +106,22 @@ describe('CodexAppServerClient process cwd', () => {
|
||||
await client.disconnect();
|
||||
});
|
||||
|
||||
it('passes the explicit catalog to a single app-server without preparation processes', async () => {
|
||||
const file = process.platform === 'win32' ? 'C:\\Models with spaces\\catalog.json' : '/Models with spaces/catalog.json';
|
||||
vi.stubEnv('HAPI_CODEX_MODEL_CATALOG_JSON', file);
|
||||
const client = new CodexAppServerClient();
|
||||
try {
|
||||
spawnMock.mockReturnValue(fakeChild());
|
||||
await client.connect();
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
expect(spawnMock).toHaveBeenCalledWith('codex', ['app-server', '-c', `model_catalog_json=${JSON.stringify(file)}`],
|
||||
expect.objectContaining({ shell: false }));
|
||||
} finally {
|
||||
await client.disconnect();
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it('steerTurn resolves dispatch on stdin accept and completes with the turn response', async () => {
|
||||
const child = fakeChild();
|
||||
child.stdin.write = vi.fn((_data: unknown, cb?: (error?: Error | null) => void) => {
|
||||
|
||||
@@ -5,6 +5,8 @@ import { logger } from '@/ui/logger';
|
||||
import { JsonLineParser } from '@/utils/jsonLineParser';
|
||||
import { killProcessByChildProcess } from '@/utils/process';
|
||||
import { CODEX_WEBSOCKET_MAX_PAYLOAD } from './websocketLimits';
|
||||
import { resolveModelCatalogArgs } from './utils/modelCatalog';
|
||||
import { resolveSelectedCodexCommand } from './utils/codexExecutable';
|
||||
import type {
|
||||
CollaborationModeListResponse,
|
||||
InitializeParams,
|
||||
@@ -255,9 +257,10 @@ export class CodexAppServerClient extends JsonLineParser {
|
||||
return;
|
||||
}
|
||||
|
||||
const codexCommand = resolveCodexAppServerCommand();
|
||||
logger.debug(`[CodexAppServer] Starting ${codexCommand} app-server`);
|
||||
const child = spawn(codexCommand, ['app-server'], {
|
||||
const codexCommand = resolveSelectedCodexCommand(resolveCodexAppServerCommand());
|
||||
logger.debug(`[CodexAppServer] Starting ${codexCommand.command} app-server`);
|
||||
const catalogArgs = resolveModelCatalogArgs();
|
||||
const child = spawn(codexCommand.command, [...codexCommand.args, 'app-server', ...catalogArgs], {
|
||||
cwd: this.options.cwd,
|
||||
env: Object.keys(process.env).reduce((acc, key) => {
|
||||
const value = process.env[key];
|
||||
@@ -265,7 +268,7 @@ export class CodexAppServerClient extends JsonLineParser {
|
||||
return acc;
|
||||
}, {} as Record<string, string>),
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: process.platform === 'win32',
|
||||
shell: false,
|
||||
windowsHide: process.platform === 'win32'
|
||||
});
|
||||
this.process = child;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
||||
import { resolveCodexCommand, type CodexCommand } from '../utils/codexExecutable';
|
||||
import { parseCodexCliOverrides, stripCodexCliOverrides } from '../utils/codexCliOverrides';
|
||||
import { resolveCodexPermissionModeConfig } from '../utils/permissionModeConfig';
|
||||
import { resolveModelCatalogArgs } from '../utils/modelCatalog';
|
||||
import { getCodexSystemPrompt } from '../utils/systemPrompt';
|
||||
import type { CodexAppServerClient } from '../codexAppServerClient';
|
||||
|
||||
@@ -136,6 +137,7 @@ export function sharedLaunchConfig(options: SharedLaunchOptions, cwd: string): {
|
||||
// Launch-wide flags also apply to later native /new roots, not just the
|
||||
// initial HAPI-created root. Explicit config layers keep their order.
|
||||
for (const [key, value] of Object.entries(config)) serverArgs.push('-c', `${key}=${JSON.stringify(value)}`);
|
||||
serverArgs.push(...resolveModelCatalogArgs(serverArgs));
|
||||
return {
|
||||
cwd: directory, serverArgs, tuiArgs,
|
||||
threadParams: {
|
||||
|
||||
@@ -93,6 +93,39 @@ describe('resolveCodexCommand', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('resolves an explicitly selected Windows npm shim without a shell', async () => {
|
||||
const shim = 'C:\\Users\\Test User\\AppData\\Roaming\\npm\\codex.cmd';
|
||||
const script = win32.join(win32.dirname(shim), 'node_modules', '@openai', 'codex', 'bin', 'codex.js');
|
||||
existsSyncMock.mockImplementation((candidate: string) => candidate === shim || candidate === script);
|
||||
const { resolveSelectedCodexCommand } = await import('./codexExecutable');
|
||||
expect(resolveSelectedCodexCommand(shim, 'win32')).toEqual({ command: 'node', args: [script] });
|
||||
});
|
||||
|
||||
it('resolves an explicitly selected npm shim name through PATH', async () => {
|
||||
const shim = 'C:\\Elsewhere\\npm\\codex.cmd';
|
||||
const script = win32.join(win32.dirname(shim), 'node_modules', '@openai', 'codex', 'bin', 'codex.js');
|
||||
execFileSyncMock.mockImplementation((command: string, args: string[]) => {
|
||||
if (command === 'where.exe' && args[0] === 'codex.cmd') return `${shim}\r\n`;
|
||||
throw new Error('not found');
|
||||
});
|
||||
existsSyncMock.mockImplementation((candidate: string) => candidate === shim || candidate === script);
|
||||
const { resolveSelectedCodexCommand } = await import('./codexExecutable');
|
||||
expect(resolveSelectedCodexCommand('codex.cmd', 'win32')).toEqual({ command: 'node', args: [script] });
|
||||
expect(execFileSyncMock).toHaveBeenCalledWith('where.exe', ['codex.cmd'], expect.anything());
|
||||
});
|
||||
|
||||
it('rejects unsupported Windows batch launchers instead of shell-interpreting JSON', async () => {
|
||||
const { resolveSelectedCodexCommand } = await import('./codexExecutable');
|
||||
expect(() => resolveSelectedCodexCommand('C:\\custom.cmd', 'win32')).toThrow('Use a Codex executable');
|
||||
});
|
||||
|
||||
it('preserves explicitly selected macOS and Linux executables', async () => {
|
||||
const { resolveSelectedCodexCommand } = await import('./codexExecutable');
|
||||
for (const platform of ['darwin', 'linux'] as const) {
|
||||
expect(resolveSelectedCodexCommand('/custom path/codex', platform)).toEqual({ command: '/custom path/codex', args: [] });
|
||||
}
|
||||
});
|
||||
|
||||
it('resolves a Windows npm codex.cmd shim through the Codex launcher', async () => {
|
||||
setPlatform('win32');
|
||||
const shim = codexShimPath();
|
||||
|
||||
@@ -68,6 +68,21 @@ function resolveWindowsCodexCommand(): CodexCommand {
|
||||
return { command: 'codex', args: [] };
|
||||
}
|
||||
|
||||
/** Resolve a selected app-server executable without passing JSON overrides through cmd.exe. */
|
||||
export function resolveSelectedCodexCommand(command: string, platform: NodeJS.Platform = process.platform): CodexCommand {
|
||||
if (platform !== 'win32') return { command, args: [] };
|
||||
if (command === 'codex') return resolveWindowsCodexCommand();
|
||||
const candidates = windowsPath.basename(command) === command ? findWhereResults(command) : [];
|
||||
for (const candidate of [...candidates, command]) {
|
||||
const resolved = resolveWindowsCandidate(candidate);
|
||||
if (resolved) return resolved;
|
||||
}
|
||||
if (/\.(cmd|bat)$/i.test(command)) {
|
||||
throw new Error('Use a Codex executable or an npm Codex shim with its launcher script on Windows.');
|
||||
}
|
||||
return { command, args: [] };
|
||||
}
|
||||
|
||||
export const MACOS_CODEX_APP_COMMAND = '/Applications/Codex.app/Contents/Resources/codex';
|
||||
|
||||
export function resolveCodexCommand(
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { CodexAppServerClient } from '../codexAppServerClient';
|
||||
import { sharedLaunchConfig } from '../shared/launch';
|
||||
|
||||
// Opt-in native check; no credentials, inference calls, or production config changes.
|
||||
const executable = process.env.HAPI_TEST_CODEX_BIN;
|
||||
const fixture = process.env.HAPI_TEST_CODEX_CATALOG;
|
||||
describe.skipIf(!executable || !fixture)('local model catalog with native Codex', () => {
|
||||
it.each(['standalone', 'shared-resume', 'configured-standalone'])('loads the configured catalog offline for %s', async mode => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'hapi-catalog-native-'));
|
||||
const catalog = JSON.parse(readFileSync(fixture!, 'utf8'));
|
||||
catalog.models[0].display_name = 'HAPI local catalog probe';
|
||||
const path = join(home, 'models_cache.json');
|
||||
writeFileSync(path, JSON.stringify(catalog));
|
||||
vi.stubEnv('CODEX_HOME', home);
|
||||
vi.stubEnv('HAPI_CODEX_MODEL_CATALOG_JSON', mode === 'configured-standalone' ? '' : path);
|
||||
if (mode === 'configured-standalone') writeFileSync(join(home, 'config.toml'), `model_catalog_json=${JSON.stringify(path)}\n`);
|
||||
vi.stubEnv('HAPI_CODEX_APP_SERVER_BIN', executable!);
|
||||
for (const name of ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy']) {
|
||||
vi.stubEnv(name, 'http://127.0.0.1:9');
|
||||
}
|
||||
vi.stubEnv('NO_PROXY', '');
|
||||
vi.stubEnv('no_proxy', '');
|
||||
try {
|
||||
let models: Array<{ displayName?: string }>;
|
||||
if (mode !== 'shared-resume') {
|
||||
const client = new CodexAppServerClient({ cwd: home });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.initialize({ clientInfo: { name: 'hapi-catalog-test', version: '1' }, capabilities: null });
|
||||
models = (await client.listModels()).data ?? [];
|
||||
} finally {
|
||||
await client.disconnect();
|
||||
}
|
||||
} else {
|
||||
const launch = sharedLaunchConfig({ resumeSessionId: 'existing-thread' }, home);
|
||||
const child = spawn(executable!, ['app-server', ...launch.serverArgs], {
|
||||
cwd: home, env: process.env, stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
const lines = createInterface({ input: child.stdout });
|
||||
try {
|
||||
models = await new Promise<Array<{ displayName?: string }>>((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('Native catalog probe timed out')), 10_000);
|
||||
const finish = () => clearTimeout(timer);
|
||||
child.once('error', error => { finish(); reject(error); });
|
||||
child.once('exit', () => { finish(); reject(new Error('Native Codex exited before model/list')); });
|
||||
lines.on('line', line => {
|
||||
const response = JSON.parse(line);
|
||||
if (response.error) { finish(); reject(new Error(JSON.stringify(response.error))); return; }
|
||||
if (response.id === 1) {
|
||||
child.stdin.write(JSON.stringify({ method: 'initialized' }) + '\n');
|
||||
child.stdin.write(JSON.stringify({ id: 2, method: 'model/list', params: {} }) + '\n');
|
||||
} else if (response.id === 2) {
|
||||
finish(); resolve(response.result.data);
|
||||
}
|
||||
});
|
||||
child.stdin.write(JSON.stringify({ id: 1, method: 'initialize', params: {
|
||||
clientInfo: { name: 'hapi-catalog-test', version: '1' }
|
||||
} }) + '\n');
|
||||
});
|
||||
} finally {
|
||||
lines.close();
|
||||
child.kill();
|
||||
await new Promise<void>(resolve => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) resolve();
|
||||
else child.once('exit', () => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(models).toContainEqual(expect.objectContaining({ displayName: 'HAPI local catalog probe' }));
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
}, 20_000);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { resolveModelCatalogArgs } from './modelCatalog';
|
||||
import { sharedLaunchConfig } from '../shared/launch';
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe('explicit Codex model catalog configuration', () => {
|
||||
it.each([undefined, '', ' '])('leaves native configuration intact when unset (%s)', value => {
|
||||
expect(resolveModelCatalogArgs([], { HAPI_CODEX_MODEL_CATALOG_JSON: value })).toEqual([]);
|
||||
});
|
||||
it.each([
|
||||
['linux', '/home/alice', '/catalogs/models with spaces.json', '/catalogs/models with spaces.json'],
|
||||
['darwin', '/Users/alice', '~/Models/catalog.json', '/Users/alice/Models/catalog.json'],
|
||||
['win32', 'C:\\Users\\Alice', 'D:\\Model Data\\catalog.json', 'D:\\Model Data\\catalog.json'],
|
||||
['win32', 'C:\\Users\\Alice', '~\\Models\\catalog.json', 'C:\\Users\\Alice\\Models\\catalog.json'],
|
||||
['win32', 'C:\\Users\\Alice', '\\\\server\\share\\catalog.json', '\\\\server\\share\\catalog.json']
|
||||
] as const)('serializes a single TOML argument on %s', (platform, home, file, expected) => {
|
||||
expect(resolveModelCatalogArgs([], { HAPI_CODEX_MODEL_CATALOG_JSON: file }, home, platform))
|
||||
.toEqual(['-c', `model_catalog_json=${JSON.stringify(expected)}`]);
|
||||
});
|
||||
it('passes through the path without reading or validating a catalog', () => {
|
||||
expect(resolveModelCatalogArgs([], { HAPI_CODEX_MODEL_CATALOG_JSON: '/not-created/catalog.json' }, '/home/alice', 'linux'))
|
||||
.toEqual(['-c', 'model_catalog_json="/not-created/catalog.json"']);
|
||||
});
|
||||
it('rejects relative paths so runner and session working directories cannot change their meaning', () => {
|
||||
expect(() => resolveModelCatalogArgs([], { HAPI_CODEX_MODEL_CATALOG_JSON: 'catalog.json' })).toThrow('absolute path');
|
||||
});
|
||||
it.each(['-c', '--config'])('preserves an explicit %s launch override', flag => {
|
||||
expect(resolveModelCatalogArgs([flag, 'model_catalog_json="explicit.json"'], {
|
||||
HAPI_CODEX_MODEL_CATALOG_JSON: 'ignored-relative-path'
|
||||
})).toEqual([]);
|
||||
});
|
||||
it('does not treat another setting value as a catalog override', () => {
|
||||
expect(resolveModelCatalogArgs(['-c', 'model="model_catalog_json"'], {
|
||||
HAPI_CODEX_MODEL_CATALOG_JSON: '/catalog.json'
|
||||
}, '/home/alice', 'linux')).toHaveLength(2);
|
||||
});
|
||||
it('applies the setting to new and resumed shared launch configurations', () => {
|
||||
const file = process.platform === 'win32' ? 'C:\\Models\\catalog.json' : '/Models/catalog.json';
|
||||
vi.stubEnv('HAPI_CODEX_MODEL_CATALOG_JSON', file);
|
||||
for (const options of [{}, { resumeSessionId: 'existing-thread' }]) {
|
||||
const launch = sharedLaunchConfig(options, process.cwd());
|
||||
expect(launch.serverArgs).toContain(`model_catalog_json=${JSON.stringify(file)}`);
|
||||
expect(launch.tuiArgs).not.toContain(`model_catalog_json=${JSON.stringify(file)}`);
|
||||
}
|
||||
});
|
||||
it('normalizes and preserves an inline shared launch override', () => {
|
||||
vi.stubEnv('HAPI_CODEX_MODEL_CATALOG_JSON', '/ignored.json');
|
||||
const launch = sharedLaunchConfig({ codexArgs: ['--config=model_catalog_json="explicit.json"'] }, process.cwd());
|
||||
expect(launch.serverArgs).toEqual(['--config', 'model_catalog_json="explicit.json"']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { homedir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const CATALOG_KEY = /^\s*(?:model_catalog_json|"model_catalog_json"|'model_catalog_json')\s*=/;
|
||||
|
||||
/** Pass an explicit HAPI setting to Codex. Catalog contents and lifecycle belong to Codex. */
|
||||
export function resolveModelCatalogArgs(
|
||||
args: string[] = [],
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
userHome = homedir(),
|
||||
platform: NodeJS.Platform = process.platform
|
||||
): string[] {
|
||||
// Shared launch flags are normalized before this helper runs.
|
||||
if (args.some((arg, index) => (arg === '-c' || arg === '--config') && CATALOG_KEY.test(args[index + 1] ?? ''))) return [];
|
||||
const configured = env.HAPI_CODEX_MODEL_CATALOG_JSON;
|
||||
if (!configured?.trim()) return [];
|
||||
const paths = platform === 'win32' ? path.win32 : path.posix;
|
||||
const file = configured.startsWith('~/') || configured.startsWith('~\\')
|
||||
? paths.join(userHome, configured.slice(2)) : configured;
|
||||
if (!paths.isAbsolute(file)) {
|
||||
throw new Error('HAPI_CODEX_MODEL_CATALOG_JSON must be an absolute path (or start with ~/).');
|
||||
}
|
||||
return ['-c', `model_catalog_json=${JSON.stringify(file)}`];
|
||||
}
|
||||
Reference in New Issue
Block a user