@@ -42,6 +42,27 @@ export interface OpencodeRoutedModel {
4242 displayName ?: string ;
4343}
4444
45+ /** Row shape from authenticated GET /api/models on the running proxy. */
46+ export interface OpencodeProxyModelRow {
47+ provider ?: string ;
48+ id ?: string ;
49+ namespaced ?: string ;
50+ native ?: boolean ;
51+ disabled ?: boolean ;
52+ displayName ?: string ;
53+ contextWindow ?: number ;
54+ }
55+
56+ /** Visible catalog entry keyed by the proxy's canonical namespaced selector. */
57+ export interface OpencodeCatalogModel {
58+ namespaced : string ;
59+ native ?: boolean ;
60+ provider ?: string ;
61+ id ?: string ;
62+ contextWindow ?: number ;
63+ displayName ?: string ;
64+ }
65+
4566export interface OpencodeModelEntry {
4667 name : string ;
4768 limit ?: { context : number ; output : number } ;
@@ -244,33 +265,36 @@ function opencodeProviderOptions(baseURL: string, config: OcxConfig): OpencodePr
244265 return options ;
245266}
246267
268+ function opencodeModelEntryLabel ( model : OpencodeCatalogModel ) : string {
269+ const providerLabel = model . native ? "native" : ( model . provider ?? "routed" ) ;
270+ const id = model . id ?? model . namespaced ;
271+ if ( model . displayName && model . displayName . length > 0 ) {
272+ return `${ model . displayName } (${ providerLabel } )` ;
273+ }
274+ return `${ id } (${ providerLabel } )` ;
275+ }
276+
247277/**
248- * Build the `opencodex` provider block from the proxy's visible catalog.
278+ * Build the `opencodex` provider block from proxy catalog rows keyed by each row's
279+ * canonical `namespaced` selector.
249280 *
250281 * `limit.context` is emitted ONLY from an authoritative context window — never guessed.
251282 * When none is available the whole `limit` block is dropped and opencode keeps its own
252283 * defaults; when one is present, `limit.output` rides along (opencode's schema requires
253284 * the pair) clamped to the context window.
254285 */
255- export function buildOpencodeProviderBlock (
286+ export function buildOpencodeProviderBlockFromCatalog (
256287 port : number ,
257- nativeSlugs : readonly string [ ] ,
258- routedModels : readonly OpencodeRoutedModel [ ] ,
259- nativeContextWindow : ( slug : string ) => number | undefined = ( ) => undefined ,
288+ catalogModels : readonly OpencodeCatalogModel [ ] ,
260289 hostname ?: string ,
261290 config : OcxConfig = OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG ,
262291) : OpencodeProviderBlock {
263292 const models : Record < string , OpencodeModelEntry > = { } ;
264- const candidates : OpencodeRoutedModel [ ] = [
265- ...nativeSlugs . map ( id => ( { provider : "native" , id, contextWindow : nativeContextWindow ( id ) } ) ) ,
266- ...routedModels ,
267- ] ;
268- for ( const { provider, id, contextWindow, displayName } of candidates ) {
269- const key = opencodeModelKey ( provider , id ) ;
270- if ( models [ key ] ) continue ; // first entry wins; native slugs are registered first
271- const entry : OpencodeModelEntry = {
272- name : displayName && displayName . length > 0 ? `${ displayName } (${ provider } )` : `${ id } (${ provider } )` ,
273- } ;
293+ for ( const model of catalogModels ) {
294+ const key = model . namespaced ;
295+ if ( models [ key ] ) continue ; // first entry wins; native rows lead /api/models
296+ const entry : OpencodeModelEntry = { name : opencodeModelEntryLabel ( model ) } ;
297+ const { contextWindow } = model ;
274298 if ( typeof contextWindow === "number" && Number . isFinite ( contextWindow ) && contextWindow > 0 ) {
275299 const context = Math . floor ( contextWindow ) ;
276300 entry . limit = { context, output : Math . min ( SCHEMA_REQUIRED_OUTPUT_BUDGET , context ) } ;
@@ -285,6 +309,102 @@ export function buildOpencodeProviderBlock(
285309 } ;
286310}
287311
312+ /** Back-compat helper for unit tests that assemble slugs/routed rows directly. */
313+ export function buildOpencodeProviderBlock (
314+ port : number ,
315+ nativeSlugs : readonly string [ ] ,
316+ routedModels : readonly OpencodeRoutedModel [ ] ,
317+ nativeContextWindow : ( slug : string ) => number | undefined = ( ) => undefined ,
318+ hostname ?: string ,
319+ config : OcxConfig = OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG ,
320+ ) : OpencodeProviderBlock {
321+ const catalog : OpencodeCatalogModel [ ] = [
322+ ...nativeSlugs . map ( id => ( {
323+ namespaced : id ,
324+ native : true ,
325+ provider : "openai" ,
326+ id,
327+ contextWindow : nativeContextWindow ( id ) ,
328+ } ) ) ,
329+ ...routedModels . map ( model => ( {
330+ namespaced : opencodeModelKey ( model . provider , model . id ) ,
331+ native : false ,
332+ provider : model . provider ,
333+ id : model . id ,
334+ contextWindow : model . contextWindow ,
335+ displayName : model . displayName ,
336+ } ) ) ,
337+ ] ;
338+ return buildOpencodeProviderBlockFromCatalog ( port , catalog , hostname , config ) ;
339+ }
340+
341+ /** Fetch the live model catalog from a running proxy's management API. */
342+ export async function fetchOpencodeProxyModels (
343+ live : LiveProxy ,
344+ apiKey : string ,
345+ deps : { fetchImpl ?: typeof fetch } = { } ,
346+ ) : Promise < OpencodeProxyModelRow [ ] > {
347+ const baseUrl = `http://${ probeHostname ( live . hostname ) } :${ live . port } ` ;
348+ const fetchImpl = deps . fetchImpl ?? fetch ;
349+ const headers = new Headers ( { Accept : "application/json" } ) ;
350+ const token = apiKey . trim ( ) ;
351+ if ( token ) headers . set ( "X-OpenCodex-API-Key" , token ) ;
352+
353+ let response : Response ;
354+ try {
355+ response = await fetchImpl ( `${ baseUrl } /api/models` , { headers } ) ;
356+ } catch ( error ) {
357+ throw new Error (
358+ `Management API is unreachable: ${ error instanceof Error ? error . message : String ( error ) } ` ,
359+ ) ;
360+ }
361+ const text = await response . text ( ) ;
362+ let body : unknown = null ;
363+ if ( text ) {
364+ try { body = JSON . parse ( text ) ; }
365+ catch { body = text ; }
366+ }
367+ if ( ! response . ok ) {
368+ const message = body && typeof body === "object" && typeof ( body as Record < string , unknown > ) . error === "string"
369+ ? ( body as Record < string , string > ) . error
370+ : `Management request failed (${ response . status } )` ;
371+ throw new Error ( message ) ;
372+ }
373+ if ( ! Array . isArray ( body ) ) {
374+ throw new Error ( "Management API returned an unexpected /api/models payload." ) ;
375+ }
376+ return body as OpencodeProxyModelRow [ ] ;
377+ }
378+
379+ /**
380+ * Visible OpenCode catalog entries from proxy /api/models rows. Disabled rows are omitted;
381+ * native rows are omitted in Codex Direct mode.
382+ */
383+ export function opencodeCatalogFromProxyRows (
384+ rows : readonly OpencodeProxyModelRow [ ] ,
385+ config : OcxConfig ,
386+ ) : OpencodeCatalogModel [ ] {
387+ const omitNative = providerCodexAccountMode ( "openai" , config . providers ?. openai ) === "direct" ;
388+ const seen = new Set < string > ( ) ;
389+ const catalog : OpencodeCatalogModel [ ] = [ ] ;
390+ for ( const row of rows ) {
391+ const namespaced = row . namespaced ?. trim ( ) ;
392+ if ( ! namespaced || row . disabled === true ) continue ;
393+ if ( omitNative && row . native === true ) continue ;
394+ if ( seen . has ( namespaced ) ) continue ;
395+ seen . add ( namespaced ) ;
396+ catalog . push ( {
397+ namespaced,
398+ native : row . native === true ,
399+ provider : row . provider ,
400+ id : row . id ,
401+ contextWindow : row . contextWindow ,
402+ displayName : row . displayName ,
403+ } ) ;
404+ }
405+ return catalog ;
406+ }
407+
288408export type OpencodeRuntimeConfigError = { error : string } ;
289409
290410/** True when mergeOpencodeRuntimeConfig rejected inherited inline config. */
@@ -502,42 +622,32 @@ export async function cmdOpencode(args: string[]): Promise<number> {
502622 return 1 ;
503623 }
504624
505- const { fetchAllModels } = await import ( "../server/management-api" ) ;
506- const { filterCatalogVisibleModels, nativeOpenAiContextWindow } = await import ( "../codex/catalog" ) ;
507- let allModels : Awaited < ReturnType < typeof fetchAllModels > > ;
625+ const apiKey = opencodeApiKey ( config ) ;
626+ let proxyModels : OpencodeProxyModelRow [ ] ;
508627 try {
509- allModels = await fetchAllModels ( config ) ;
628+ proxyModels = await fetchOpencodeProxyModels ( live , apiKey ) ;
510629 } catch ( error ) {
511630 const reason = error instanceof Error ? error . message : String ( error ) ;
512631 console . error ( `❌ Could not fetch the model catalog from the proxy: ${ reason } ` ) ;
513632 return 1 ;
514633 }
515- const routed = filterCatalogVisibleModels ( allModels , config ) . map ( m => ( {
516- provider : m . provider ,
517- id : m . id ,
518- contextWindow : m . contextWindow ,
519- displayName : m . displayName ,
520- } ) ) ;
521- const nativeSlugs = opencodeLaunchNativeSlugs ( config ) ;
522-
523- const providerBlock = buildOpencodeProviderBlock (
634+ const catalog = opencodeCatalogFromProxyRows ( proxyModels , config ) ;
635+ const providerBlock = buildOpencodeProviderBlockFromCatalog (
524636 live . port ,
525- nativeSlugs ,
526- routed ,
527- nativeOpenAiContextWindow ,
637+ catalog ,
528638 live . hostname ,
529639 config ,
530640 ) ;
531641 const baseUrl = providerBlock . options . baseURL ;
532- const modelCount = nativeSlugs . length + routed . length ;
642+ const modelCount = catalog . length ;
533643 console . error ( `✅ opencode wired to ${ baseUrl } — ${ modelCount } model(s) under provider \`${ OPENCODE_PROVIDER_ID } \`.` ) ;
534644 console . error ( " Your existing opencode config files are left untouched; only the runtime provider block is injected." ) ;
535645 const providerOverride = opencodeProviderOverridePath ( process . cwd ( ) ) ;
536646 if ( providerOverride ) {
537647 console . error ( `ℹ ${ providerOverride } also defines provider.${ OPENCODE_PROVIDER_ID } ; the runtime layer from ocx opencode overrides it for this launch.` ) ;
538648 }
539649
540- const builtEnv = buildOpencodeEnv ( providerBlock , opencodeApiKey ( config ) , process . env ) ;
650+ const builtEnv = buildOpencodeEnv ( providerBlock , apiKey , process . env ) ;
541651 if ( "error" in builtEnv ) {
542652 console . error ( `❌ ${ builtEnv . error } ` ) ;
543653 return 1 ;
0 commit comments