diff --git a/Cargo.lock b/Cargo.lock index 070c25adb8e..5148183122c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10076,7 +10076,10 @@ dependencies = [ "base64 0.23.1", "bytes", "futures", + "httpdate", + "openssl", "reqwest 0.12.28", + "ring", "serde", "serde_json", "sha2 0.11.1", diff --git a/app/src/components/settings/panels/__tests__/builtinCloudProviders.test.ts b/app/src/components/settings/panels/__tests__/builtinCloudProviders.test.ts index ec3f7dfe187..4f69731b77e 100644 --- a/app/src/components/settings/panels/__tests__/builtinCloudProviders.test.ts +++ b/app/src/components/settings/panels/__tests__/builtinCloudProviders.test.ts @@ -19,6 +19,7 @@ describe('builtinCloudProviders', () => { ['minimax', 'https://api.minimax.io/v1', 'bearer'], ['sumopod', 'https://ai.sumopod.com/v1', 'bearer'], ['modelscope', 'https://api-inference.modelscope.cn/v1', 'bearer'], + ['oci', 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com', 'oci'], ] as const)('maps %s to its endpoint and auth style', (slug, endpoint, authStyle) => { expect(defaultEndpointForBuiltinCloudProvider(slug)).toBe(endpoint); expect(authStyleForBuiltinCloudProvider(slug)).toBe(authStyle); @@ -46,6 +47,7 @@ describe('builtinCloudProviders', () => { 'vercel-ai-gateway', 'sumopod', 'modelscope', + 'oci', ]) ); }); diff --git a/app/src/components/settings/panels/ai/OciSettingsDialog.tsx b/app/src/components/settings/panels/ai/OciSettingsDialog.tsx new file mode 100644 index 00000000000..adf9c80132f --- /dev/null +++ b/app/src/components/settings/panels/ai/OciSettingsDialog.tsx @@ -0,0 +1,317 @@ +/* + * OCI Generative AI settings dialog. + * + * Collects the non-secret settings kept on the provider entry (auth mode, + * profile, region, compartment, project, protocol, dedicated endpoint) plus — + * only in `api_key` mode — the Generative AI API key, which the caller writes + * to the keyring like any other provider key. Profile and principal modes + * store no secret: key material stays in the user's OCI config directory (or + * the runtime environment) and is read by the core when a model is built. + */ +import { Dialog as DialogPrimitive } from 'radix-ui'; +import { useState } from 'react'; + +import { useT } from '../../../../lib/i18n/I18nContext'; +import type { OciAuthMode, OciSettings } from '../../../../utils/tauriCommands/config'; +import Button from '../../../ui/Button'; +import { DialogContent, DialogRoot } from '../../../ui/Dialog'; +import Label from '../../../ui/Label'; +import NativeSelect from '../../../ui/NativeSelect'; +import TextField from '../../../ui/TextField'; +import { presentProviderSetupError, ProviderSetupErrorNotice } from '../ProviderSetupErrorNotice'; +import { + DEFAULT_OCI_SETTINGS, + isOciGatedPrincipalMode, + isOciPrincipalMode, + isOciProfileMode, + normalizeOciSettings, + OCI_AUTH_MODE_OPTIONS, + OCI_PROVIDER_SLUG, + OCI_TRANSPORT_OPTIONS, + ociTransportUsesProject, + validateOciSettings, +} from './ociSettings'; + +const FIELD_PROPS = { + autoComplete: 'off', + autoCorrect: 'off', + autoCapitalize: 'off', + spellCheck: false, + 'data-form-type': 'other', + 'data-lpignore': 'true', + 'data-1p-ignore': 'true', +} as const; + +export const OciSettingsDialog = ({ + label, + initial, + hasStoredKey, + onCancel, + onSubmit, +}: { + label: string; + /** Existing settings when editing a connected OCI provider. */ + initial?: OciSettings; + /** True when a Generative AI API key is already stored for this provider. */ + hasStoredKey: boolean; + onCancel: () => void; + /** Receives the normalised settings and the (possibly empty) API key. */ + onSubmit: (settings: OciSettings, apiKey: string) => Promise | void; +}) => { + const { t } = useT(); + const [settings, setSettings] = useState(initial ?? DEFAULT_OCI_SETTINGS); + const [apiKey, setApiKey] = useState(''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const titleId = 'oci-settings-dialog-title'; + const mode = settings.auth_mode; + + const patch = (next: Partial) => { + setSettings(prev => ({ ...prev, ...next })); + setError(null); + }; + + const handleSave = async () => { + const problem = validateOciSettings(settings, apiKey, hasStoredKey); + if (problem) { + setError(t(problem)); + return; + } + setError(null); + setSaving(true); + console.debug('[ai-settings][oci] saving provider settings', { + auth_mode: mode, + transport: settings.transport, + }); + try { + await onSubmit(normalizeOciSettings(settings), mode === 'api_key' ? apiKey.trim() : ''); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + console.warn('[ai-settings][oci] provider setup failed', { + slug: OCI_PROVIDER_SLUG, + summary: presentProviderSetupError(message, t).summary, + }); + setError(message); + setSaving(false); + } + }; + + return ( + { + if (!next && !saving) onCancel(); + }}> + { + if (saving) event.preventDefault(); + }} + onPointerDownOutside={event => { + if (saving) event.preventDefault(); + }} + onInteractOutside={event => { + if (saving) event.preventDefault(); + }} + className="border border-line p-6 shadow-soft"> +
+ +

+ {`${t('settings.ai.connectProvider')} ${label}`} +

+
+

{t('settings.ai.oci.description')}

+
+ +
+
+ + patch({ auth_mode: event.target.value as OciAuthMode })}> + {OCI_AUTH_MODE_OPTIONS.map(option => ( + + ))} + +
+ + {mode === 'api_key' && ( +
+ + { + setApiKey(event.target.value); + setError(null); + }} + /> +

+ {t('settings.ai.oci.apiKeyKeepHint')} +

+
+ )} + + {isOciProfileMode(mode) && ( + <> +
+ + patch({ config_file: event.target.value })} + /> +
+
+ + patch({ profile: event.target.value })} + /> +

{t('settings.ai.oci.profileHint')}

+
+ + )} + + {isOciPrincipalMode(mode) && ( +

+ {t('settings.ai.oci.principalHint')} + {isOciGatedPrincipalMode(mode) ? ` ${t('settings.ai.oci.principalBuildHint')}` : ''} +

+ )} + +
+ + patch({ region: event.target.value })} + /> +
+ +
+ + + patch({ transport: event.target.value as OciSettings['transport'] }) + }> + {OCI_TRANSPORT_OPTIONS.map(option => ( + + ))} + +
+ +
+ + patch({ compartment_id: event.target.value })} + /> +
+ + {ociTransportUsesProject(settings.transport) && ( +
+ + patch({ project_id: event.target.value })} + /> +
+ )} + +
+ + patch({ dedicated_endpoint_id: event.target.value })} + /> +
+ + {error ? : null} +
+ +
+ + +
+
+
+ ); +}; + +export default OciSettingsDialog; diff --git a/app/src/components/settings/panels/ai/ProviderAuthSection.tsx b/app/src/components/settings/panels/ai/ProviderAuthSection.tsx index db73b6bcca7..6f090295b31 100644 --- a/app/src/components/settings/panels/ai/ProviderAuthSection.tsx +++ b/app/src/components/settings/panels/ai/ProviderAuthSection.tsx @@ -22,6 +22,7 @@ import { useState } from 'react'; import { useManagedInferenceAvailable } from '../../../../hooks/useLocalSession'; import { useT } from '../../../../lib/i18n/I18nContext'; import type { ProviderAuthError } from '../../../../services/api/aiSettingsApi'; +import type { OciSettings } from '../../../../utils/tauriCommands/config'; import Alert, { AlertDescription } from '../../../ui/Alert'; import Badge from '../../../ui/Badge'; import Button from '../../../ui/Button'; @@ -46,6 +47,8 @@ import { providerToggleAriaLabel, } from './aiPanelTypes'; import { ClaudeCodeConnect } from './ClaudeCodeStatusCard'; +import { OCI_PROVIDER_SLUG, ociSettingsSummary } from './ociSettings'; +import { OciSettingsDialog } from './OciSettingsDialog'; import { ProviderCatalog } from './ProviderCatalog'; import { ProviderGroup, ProviderListRow, type ProviderRowAction } from './ProviderListRow'; @@ -127,7 +130,8 @@ export const ProviderAuthSection = ({ slug: string; localLabel?: string | null; value: string; - credentialMode: 'api_key' | 'endpoint' | 'endpoint_key' | 'cli_login' | 'oauth'; + credentialMode: 'api_key' | 'endpoint' | 'endpoint_key' | 'cli_login' | 'oauth' | 'oci'; + oci?: OciSettings; }) => Promise; onOpenKeyDialog: (slug: string, localLabel: string | null) => void; onAddCustomProvider: () => void; @@ -153,6 +157,9 @@ export const ProviderAuthSection = ({ const { t } = useT(); const managedAvailable = useManagedInferenceAvailable(); const [localAddOpen, setLocalAddOpen] = useState(false); + // Slug of the OCI entry whose settings dialog is open: the built-in `oci` + // or a custom slug with `authStyle: 'oci'` (e.g. `oci-cohere`). + const [ociDialogSlug, setOciDialogSlug] = useState(null); const hostControlsAdd = controlledAddOpen !== undefined; const addOpen = controlledAddOpen ?? localAddOpen; const setAddOpen = (open: boolean) => { @@ -245,6 +252,12 @@ export const ProviderAuthSection = ({ void onConnectProvider({ slug, value: 'cli_login', credentialMode: 'cli_login' }); return; } + if (slug === OCI_PROVIDER_SLUG) { + // OCI is configured through its own settings form (auth mode, profile, + // region, compartment), not the single-field key dialog. + setOciDialogSlug(OCI_PROVIDER_SLUG); + return; + } const localLabel = LOCAL_RUNTIME_SLUGS.includes(slug as (typeof LOCAL_RUNTIME_SLUGS)[number]) ? LOCAL_CHIP_LABEL[slug as LocalChipSlug] : null; @@ -336,11 +349,17 @@ export const ProviderAuthSection = ({ const existing = bySlug(slug)!; const meta = BUILTIN_PROVIDER_META[slug]; const label = meta?.label ?? slug; + const isOci = slug === OCI_PROVIDER_SLUG; const actions: ProviderRowAction[] = [ - { - label: t('settings.ai.providers.replaceKey'), - onSelect: () => onOpenKeyDialog(slug, null), - }, + isOci + ? { + label: t('settings.ai.oci.editSettings'), + onSelect: () => setOciDialogSlug(slug), + } + : { + label: t('settings.ai.providers.replaceKey'), + onSelect: () => onOpenKeyDialog(slug, null), + }, ]; return ( {t('settings.ai.providers.custom')}} control={ @@ -387,7 +414,15 @@ export const ProviderAuthSection = ({ /> } actions={[ - { label: t('common.edit'), onSelect: () => onEditCustomProvider(existing) }, + { + label: t('common.edit'), + // OCI entries keep their settings in the `oci` block, which + // only the OCI dialog edits; the generic editor would drop it. + onSelect: () => + existing.authStyle === 'oci' + ? setOciDialogSlug(existing.slug) + : onEditCustomProvider(existing), + }, { label: t('common.remove'), destructive: true, @@ -489,6 +524,28 @@ export const ProviderAuthSection = ({ /> + {ociDialogSlug && ( + setOciDialogSlug(null)} + onSubmit={async (oci, apiKey) => { + await onConnectProvider({ + slug: ociDialogSlug, + value: apiKey, + credentialMode: 'oci', + oci, + }); + setOciDialogSlug(null); + }} + /> + )} + {addOpen && ( > = {}) => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + const onCancel = vi.fn(); + renderWithProviders( + + ); + return { onSubmit, onCancel }; +}; + +const type = (testId: string, value: string) => + fireEvent.change(screen.getByTestId(testId), { target: { value } }); + +describe('OciSettingsDialog', () => { + it('starts in api_key mode with the key field and no profile fields', async () => { + renderDialog(); + expect(await screen.findByTestId('oci-api-key')).toBeInTheDocument(); + expect(screen.queryByTestId('oci-profile')).not.toBeInTheDocument(); + expect(screen.getByTestId('oci-auth-mode')).toHaveValue('api_key'); + }); + + it('refuses to save without a region and reports it inline', async () => { + const { onSubmit } = renderDialog(); + fireEvent.click(await screen.findByTestId('oci-save')); + expect(await screen.findByText(/region is required/i)).toBeInTheDocument(); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('submits normalised api_key settings together with the key', async () => { + const { onSubmit } = renderDialog(); + type('oci-api-key', ' genai-key '); + type('oci-region', ' us-chicago-1 '); + // `/openai/v1` serves requests in a Generative AI project. + fireEvent.click(screen.getByTestId('oci-save')); + expect(await screen.findByText(/project ocid is required/i)).toBeInTheDocument(); + expect(onSubmit).not.toHaveBeenCalled(); + + type('oci-project', ' ocid1.generativeaiproject.oc1..example '); + fireEvent.click(screen.getByTestId('oci-save')); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + expect(onSubmit).toHaveBeenCalledWith( + { + auth_mode: 'api_key', + transport: 'openai', + region: 'us-chicago-1', + project_id: 'ocid1.generativeaiproject.oc1..example', + }, + 'genai-key' + ); + }); + + it('keeps a stored key when the field is left blank on an edit', async () => { + const { onSubmit } = renderDialog({ + hasStoredKey: true, + initial: { + auth_mode: 'api_key', + transport: 'openai', + region: 'us-chicago-1', + project_id: 'ocid1.generativeaiproject.oc1..example', + }, + }); + fireEvent.click(await screen.findByTestId('oci-save')); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + expect(onSubmit.mock.calls[0][1]).toBe(''); + }); + + it('swaps the key field for profile fields in session_token mode and sends no key', async () => { + const { onSubmit } = renderDialog(); + fireEvent.change(await screen.findByTestId('oci-auth-mode'), { + target: { value: 'session_token' }, + }); + expect(screen.queryByTestId('oci-api-key')).not.toBeInTheDocument(); + type('oci-profile', 'SESSION'); + // A signed call names its compartment even on the openai transport. + fireEvent.click(screen.getByTestId('oci-save')); + expect(await screen.findByText(/compartment ocid is required/i)).toBeInTheDocument(); + expect(onSubmit).not.toHaveBeenCalled(); + + type('oci-compartment', 'ocid1.compartment.oc1..example'); + type('oci-project', 'ocid1.generativeaiproject.oc1..example'); + fireEvent.click(screen.getByTestId('oci-save')); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + expect(onSubmit).toHaveBeenCalledWith( + { + auth_mode: 'session_token', + transport: 'openai', + profile: 'SESSION', + compartment_id: 'ocid1.compartment.oc1..example', + project_id: 'ocid1.generativeaiproject.oc1..example', + }, + '' + ); + }); + + it('explains that principal modes store no secret', async () => { + renderDialog(); + fireEvent.change(await screen.findByTestId('oci-auth-mode'), { + target: { value: 'instance_principal' }, + }); + const hint = screen.getByTestId('oci-principal-hint'); + expect(hint).toHaveTextContent(/no secret is stored/i); + expect(hint).toHaveTextContent(/oci principals support/i); + expect(screen.queryByTestId('oci-api-key')).not.toBeInTheDocument(); + }); + + it('requires a compartment for the native transport and hides the project field', async () => { + const { onSubmit } = renderDialog(); + type('oci-api-key', 'genai-key'); + type('oci-region', 'us-chicago-1'); + expect(screen.getByTestId('oci-project')).toBeInTheDocument(); + fireEvent.change(screen.getByTestId('oci-transport'), { target: { value: 'native_cohere' } }); + expect(screen.queryByTestId('oci-project')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByTestId('oci-save')); + expect(await screen.findByText(/compartment ocid is required/i)).toBeInTheDocument(); + expect(onSubmit).not.toHaveBeenCalled(); + + type('oci-compartment', 'ocid1.compartment.oc1..example'); + fireEvent.click(screen.getByTestId('oci-save')); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + expect(onSubmit.mock.calls[0][0]).toMatchObject({ + transport: 'native_cohere', + compartment_id: 'ocid1.compartment.oc1..example', + }); + }); + + it('shows a failed save inline and re-enables the form', async () => { + const onSubmit = vi.fn().mockRejectedValue(new Error('config file not found')); + renderDialog({ onSubmit }); + type('oci-api-key', 'genai-key'); + type('oci-region', 'us-chicago-1'); + type('oci-project', 'ocid1.generativeaiproject.oc1..example'); + fireEvent.click(screen.getByTestId('oci-save')); + expect(await screen.findByText(/config file not found/i)).toBeInTheDocument(); + await waitFor(() => expect(screen.getByTestId('oci-save')).toBeEnabled()); + }); + + it('calls onCancel from the Cancel button', async () => { + const { onCancel } = renderDialog(); + fireEvent.click(await screen.findByRole('button', { name: /^cancel$/i })); + expect(onCancel).toHaveBeenCalled(); + }); +}); diff --git a/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx b/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx index 25e8a45886c..89a5f7642a3 100644 --- a/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx +++ b/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx @@ -1,5 +1,6 @@ import { configureStore } from '@reduxjs/toolkit'; import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import type { ComponentProps } from 'react'; import { Provider } from 'react-redux'; import { describe, expect, it, vi } from 'vitest'; @@ -129,6 +130,76 @@ describe('ProviderAuthSection connected rows', () => { expect(screen.getByTestId('provider-row-openai')).toHaveTextContent('sk-…4f2a'); }); + it('summarizes a connected OCI provider and edits it through the OCI dialog', async () => { + renderSection('header.payload.signature', { + draft: { + ...EMPTY_SETTINGS, + cloudProviders: [ + provider({ + id: 'p_oci', + slug: 'oci', + label: 'OCI Generative AI', + endpoint: 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com', + authStyle: 'oci', + maskedKey: 'Not configured', + oci: { + auth_mode: 'session_token', + transport: 'native_generic', + region: 'us-chicago-1', + compartment_id: 'ocid1.compartment.oc1..example', + }, + }), + ], + }, + }); + + const row = screen.getByTestId('provider-row-oci'); + // Region and sign-in method instead of a key the entry does not hold. + expect(row).toHaveTextContent('us-chicago-1 · Session token'); + + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: /OCI Generative AI/ })); + await user.click(await screen.findByRole('menuitem', { name: 'Edit OCI settings' })); + expect(await screen.findByTestId('oci-auth-mode')).toHaveValue('session_token'); + }); + + it('edits a custom OCI slug through the OCI dialog, not the generic editor', async () => { + const onEditCustomProvider = vi.fn(); + const onConnectProvider = vi.fn().mockResolvedValue(undefined); + renderSection('header.payload.signature', { + onEditCustomProvider, + onConnectProvider, + draft: { + ...EMPTY_SETTINGS, + cloudProviders: [ + provider({ + id: 'p_oci-cohere', + slug: 'oci-cohere', + label: 'OCI Cohere', + endpoint: '', + authStyle: 'oci', + maskedKey: 'Not configured', + oci: { + auth_mode: 'config_profile', + transport: 'native_cohere', + region: 'eu-frankfurt-1', + compartment_id: 'ocid1.compartment.oc1..example', + }, + }), + ], + }, + }); + + expect(screen.getByTestId('provider-row-oci-cohere')).toHaveTextContent( + 'eu-frankfurt-1 · OCI config profile' + ); + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: /OCI Cohere/ })); + await user.click(await screen.findByRole('menuitem', { name: 'Edit' })); + expect(onEditCustomProvider).not.toHaveBeenCalled(); + expect(await screen.findByTestId('oci-auth-mode')).toHaveValue('config_profile'); + }); + it('renders a user-defined custom provider by host, with edit and remove', () => { renderSection('header.payload.signature', { draft: { diff --git a/app/src/components/settings/panels/ai/__tests__/useProviderConnect.test.ts b/app/src/components/settings/panels/ai/__tests__/useProviderConnect.test.ts index 7c467129183..9547471f266 100644 --- a/app/src/components/settings/panels/ai/__tests__/useProviderConnect.test.ts +++ b/app/src/components/settings/panels/ai/__tests__/useProviderConnect.test.ts @@ -5,6 +5,7 @@ import { type AISettings, EMPTY_SETTINGS } from '../aiPanelTypes'; import { useProviderConnect } from '../useProviderConnect'; const api = vi.hoisted(() => ({ + clearCloudProviderKey: vi.fn(), flushCloudProviders: vi.fn(), listProviderModels: vi.fn(), loadProviderAuthErrors: vi.fn(), @@ -13,6 +14,7 @@ const api = vi.hoisted(() => ({ vi.mock('../../../../../services/api/aiSettingsApi', async importOriginal => ({ ...(await importOriginal()), + clearCloudProviderKey: api.clearCloudProviderKey, flushCloudProviders: api.flushCloudProviders, listProviderModels: api.listProviderModels, loadProviderAuthErrors: api.loadProviderAuthErrors, @@ -20,6 +22,8 @@ vi.mock('../../../../../services/api/aiSettingsApi', async importOriginal => ({ })); beforeEach(() => { + api.clearCloudProviderKey.mockReset(); + api.clearCloudProviderKey.mockResolvedValue(undefined); api.flushCloudProviders.mockReset(); api.flushCloudProviders.mockResolvedValue(undefined); api.listProviderModels.mockReset(); @@ -357,4 +361,208 @@ describe('useProviderConnect', () => { ]) ); }); + + describe('OCI Generative AI', () => { + const ociProvider = (maskedKey: string) => ({ + id: 'p_oci', + slug: 'oci', + label: 'OCI Generative AI', + endpoint: 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com', + authStyle: 'oci' as const, + maskedKey, + oci: { + auth_mode: 'api_key' as const, + transport: 'openai' as const, + region: 'us-chicago-1', + project_id: 'p', + }, + }); + const renderConnect = (settings: AISettings, persist = vi.fn().mockResolvedValue(undefined)) => + renderHook(() => + useProviderConnect({ + draft: settings, + saved: settings, + persist, + t: key => key, + onConnected: vi.fn(), + }) + ); + + it('stores the API key after the flush and skips the /models probe', async () => { + const persist = vi.fn().mockResolvedValue(undefined); + const { result } = renderConnect(EMPTY_SETTINGS, persist); + const oci = { + auth_mode: 'api_key' as const, + transport: 'openai' as const, + region: 'us-chicago-1', + }; + + await act(async () => { + await result.current.connectProvider({ + slug: 'oci', + value: ' genai-key ', + credentialMode: 'oci', + oci, + }); + }); + + expect(api.flushCloudProviders).toHaveBeenCalledWith([ + expect.objectContaining({ slug: 'oci', auth_style: 'oci', oci }), + ]); + expect(api.setCloudProviderKey).toHaveBeenCalledWith('oci', 'genai-key'); + expect(api.flushCloudProviders.mock.invocationCallOrder[0]).toBeLessThan( + api.setCloudProviderKey.mock.invocationCallOrder[0] + ); + expect(api.listProviderModels).not.toHaveBeenCalled(); + expect(api.clearCloudProviderKey).not.toHaveBeenCalled(); + expect(persist).toHaveBeenCalledWith( + expect.objectContaining({ cloudProviders: [expect.objectContaining({ slug: 'oci', oci })] }) + ); + }); + + it('keeps the stored API key when an edit leaves the field blank', async () => { + const settings: AISettings = { ...EMPTY_SETTINGS, cloudProviders: [ociProvider('••••key')] }; + const persist = vi.fn().mockResolvedValue(undefined); + const { result } = renderConnect(settings, persist); + + await act(async () => { + await result.current.connectProvider({ + slug: 'oci', + value: '', + credentialMode: 'oci', + oci: { + auth_mode: 'api_key', + transport: 'actions', + region: 'us-chicago-1', + compartment_id: 'c', + }, + }); + }); + + expect(api.setCloudProviderKey).not.toHaveBeenCalled(); + const saved = persist.mock.calls[0][0].cloudProviders[0]; + expect(saved.maskedKey.startsWith('••••')).toBe(true); + expect(saved.oci.transport).toBe('actions'); + }); + + it('drops a stale API key when switching to a signed mode', async () => { + const settings: AISettings = { ...EMPTY_SETTINGS, cloudProviders: [ociProvider('••••key')] }; + const { result } = renderConnect(settings); + + await act(async () => { + await result.current.connectProvider({ + slug: 'oci', + value: '', + credentialMode: 'oci', + oci: { + auth_mode: 'session_token', + transport: 'openai', + profile: 'SESSION', + compartment_id: 'c', + }, + }); + }); + + expect(api.clearCloudProviderKey).toHaveBeenCalledWith('oci'); + expect(api.setCloudProviderKey).not.toHaveBeenCalled(); + expect(api.listProviderModels).not.toHaveBeenCalled(); + }); + + it('aborts the switch and restores the providers when the key cannot be deleted', async () => { + const settings: AISettings = { ...EMPTY_SETTINGS, cloudProviders: [ociProvider('••••key')] }; + const persist = vi.fn().mockResolvedValue(undefined); + api.clearCloudProviderKey.mockRejectedValueOnce(new Error('keyring locked')); + const { result } = renderConnect(settings, persist); + + await expect( + act(async () => { + await result.current.connectProvider({ + slug: 'oci', + value: '', + credentialMode: 'oci', + oci: { + auth_mode: 'config_profile', + transport: 'openai', + compartment_id: 'c', + project_id: 'p', + }, + }); + }) + ).rejects.toThrow('keyring locked'); + + expect(api.flushCloudProviders).toHaveBeenLastCalledWith([ + expect.objectContaining({ + slug: 'oci', + oci: expect.objectContaining({ auth_mode: 'api_key' }), + }), + ]); + expect(persist).not.toHaveBeenCalled(); + }); + + it('persists a blank endpoint so the core routes by region, keeping explicit overrides', async () => { + const oci = { + auth_mode: 'api_key' as const, + transport: 'openai' as const, + region: 'eu-frankfurt-1', + project_id: 'p', + }; + const { result } = renderConnect({ + ...EMPTY_SETTINGS, + cloudProviders: [ociProvider('••••key')], + }); + await act(async () => { + await result.current.connectProvider({ + slug: 'oci', + value: '', + credentialMode: 'oci', + oci, + }); + }); + expect(api.flushCloudProviders).toHaveBeenLastCalledWith([ + expect.objectContaining({ slug: 'oci', endpoint: '' }), + ]); + + const custom = { + ...ociProvider('••••key'), + id: 'p_oci-private', + slug: 'oci-private', + label: 'OCI private', + endpoint: 'https://genai.private.example.oraclecloud.com', + }; + const { result: second } = renderConnect({ ...EMPTY_SETTINGS, cloudProviders: [custom] }); + await act(async () => { + await second.current.connectProvider({ + slug: 'oci-private', + value: '', + credentialMode: 'oci', + oci, + }); + }); + expect(api.flushCloudProviders).toHaveBeenLastCalledWith([ + expect.objectContaining({ + slug: 'oci-private', + label: 'OCI private', + auth_style: 'oci', + endpoint: 'https://genai.private.example.oraclecloud.com', + }), + ]); + }); + + it('rejects a connection without OCI settings and leaves the queue usable', async () => { + const { result } = renderConnect(EMPTY_SETTINGS); + + await expect( + result.current.connectProvider({ slug: 'oci', value: '', credentialMode: 'oci' }) + ).rejects.toThrow('OCI settings are required'); + + await act(async () => { + await result.current.connectProvider({ + slug: 'openai', + value: 'sk-test', + credentialMode: 'api_key', + }); + }); + expect(api.setCloudProviderKey).toHaveBeenCalledWith('openai', 'sk-test'); + }); + }); }); diff --git a/app/src/components/settings/panels/ai/aiPanelTypes.ts b/app/src/components/settings/panels/ai/aiPanelTypes.ts index 9285b40f7ef..44492f21673 100644 --- a/app/src/components/settings/panels/ai/aiPanelTypes.ts +++ b/app/src/components/settings/panels/ai/aiPanelTypes.ts @@ -7,7 +7,11 @@ * stays trivially unit-testable. */ import type { ModelRegistryEntry } from '../../../../services/api/aiSettingsApi'; -import type { AuthStyle } from '../../../../utils/tauriCommands/config'; +import type { + AuthStyle, + CloudProviderCreds, + OciSettings, +} from '../../../../utils/tauriCommands/config'; import { authStyleForBuiltinCloudProvider, BUILTIN_CLOUD_PROVIDER_META, @@ -27,8 +31,26 @@ export type CloudProvider = { authStyle: AuthStyle; maskedKey: string; caCertPem?: string; + /** Non-secret OCI Generative AI settings; present only for `authStyle: 'oci'`. */ + oci?: OciSettings; }; +/** + * The wire shape of a panel provider. Every place that writes `cloud_providers` + * goes through this so the optional `oci` block is never silently dropped. + */ +export function toWireCloudProvider(p: CloudProvider): CloudProviderCreds { + return { + id: p.id, + slug: p.slug, + label: p.label, + endpoint: p.endpoint, + ca_cert_pem: p.caCertPem ?? '', + auth_style: p.authStyle, + ...(p.oci ? { oci: p.oci } : {}), + }; +} + /** * State of the user-run local endpoint. `unreachable` and `stopped` are both * offline; `degraded` is reachable but unhealthy. The app never installs or diff --git a/app/src/components/settings/panels/ai/ociSettings.test.ts b/app/src/components/settings/panels/ai/ociSettings.test.ts new file mode 100644 index 00000000000..4df795454d6 --- /dev/null +++ b/app/src/components/settings/panels/ai/ociSettings.test.ts @@ -0,0 +1,180 @@ +import { describe, expect, it } from 'vitest'; + +import type { OciSettings } from '../../../../utils/tauriCommands/config'; +import { toWireCloudProvider } from './aiPanelTypes'; +import { + DEFAULT_OCI_SETTINGS, + isOciGatedPrincipalMode, + isOciPrincipalMode, + isOciProfileMode, + normalizeOciSettings, + OCI_AUTH_MODE_OPTIONS, + OCI_TRANSPORT_OPTIONS, + ociEndpointOverride, + ociSettingsSummary, + validateOciSettings, +} from './ociSettings'; + +const settings = (patch: Partial = {}): OciSettings => ({ + ...DEFAULT_OCI_SETTINGS, + region: 'us-chicago-1', + project_id: 'ocid1.generativeaiproject.x', + ...patch, +}); + +describe('validateOciSettings', () => { + it('requires a region in api_key mode', () => { + expect(validateOciSettings(settings({ region: ' ' }), 'key', false)).toBe( + 'settings.ai.oci.regionRequired' + ); + }); + + it('requires a key in api_key mode unless one is already stored', () => { + expect(validateOciSettings(settings(), ' ', false)).toBe('settings.ai.apiKeyRequired'); + expect(validateOciSettings(settings(), '', true)).toBeNull(); + expect(validateOciSettings(settings(), 'sk', false)).toBeNull(); + }); + + it('lets a profile or principal supply the region and needs no key', () => { + for (const mode of OCI_AUTH_MODE_OPTIONS.map(o => o.value).filter(v => v !== 'api_key')) { + expect( + validateOciSettings( + settings({ auth_mode: mode, region: '', compartment_id: 'ocid1.compartment.x' }), + '', + false + ) + ).toBeNull(); + } + }); + + it('requires a compartment for signed auth even on openai', () => { + for (const mode of OCI_AUTH_MODE_OPTIONS.map(o => o.value).filter(v => v !== 'api_key')) { + expect( + validateOciSettings(settings({ auth_mode: mode, transport: 'openai' }), '', false) + ).toBe('settings.ai.oci.compartmentRequired'); + } + }); + + it('requires a compartment for every transport but openai with an API key', () => { + for (const { value } of OCI_TRANSPORT_OPTIONS) { + const result = validateOciSettings(settings({ transport: value }), 'key', false); + expect(result).toBe(value === 'openai' ? null : 'settings.ai.oci.compartmentRequired'); + } + expect( + validateOciSettings( + settings({ transport: 'native_cohere', compartment_id: 'ocid1.compartment.x' }), + 'key', + false + ) + ).toBeNull(); + }); +}); + +describe('validateOciSettings project', () => { + it('requires a project only on the openai transport', () => { + expect(validateOciSettings(settings({ project_id: ' ' }), 'key', false)).toBe( + 'settings.ai.oci.projectRequired' + ); + expect( + validateOciSettings( + settings({ transport: 'actions', project_id: '', compartment_id: 'ocid1.compartment.x' }), + 'key', + false + ) + ).toBeNull(); + }); +}); + +describe('ociEndpointOverride', () => { + it('blanks the preset display URL so the core routes by region', () => { + expect(ociEndpointOverride(undefined)).toBe(''); + expect(ociEndpointOverride(' ')).toBe(''); + expect( + ociEndpointOverride('https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/') + ).toBe(''); + }); + + it('keeps an explicit override', () => { + expect(ociEndpointOverride(' https://genai.private.example.oraclecloud.com ')).toBe( + 'https://genai.private.example.oraclecloud.com' + ); + }); +}); + +describe('normalizeOciSettings', () => { + it('trims values and drops empty optional fields', () => { + expect( + normalizeOciSettings( + settings({ region: ' eu-frankfurt-1 ', compartment_id: ' ', project_id: ' ' }) + ) + ).toEqual({ auth_mode: 'api_key', transport: 'openai', region: 'eu-frankfurt-1' }); + }); + + it('drops profile fields that do not apply to the chosen mode', () => { + const base = settings({ config_file: '~/.oci/config', profile: 'DEFAULT' }); + expect(normalizeOciSettings(base)).not.toHaveProperty('profile'); + expect(normalizeOciSettings(base)).not.toHaveProperty('config_file'); + expect(normalizeOciSettings({ ...base, auth_mode: 'session_token' })).toMatchObject({ + config_file: '~/.oci/config', + profile: 'DEFAULT', + }); + }); + + it('drops the project id when the transport does not send it', () => { + const base = settings({ project_id: 'ocid1.project.x', compartment_id: 'ocid1.compartment.x' }); + expect(normalizeOciSettings(base).project_id).toBe('ocid1.project.x'); + expect(normalizeOciSettings({ ...base, transport: 'native_generic' })).not.toHaveProperty( + 'project_id' + ); + }); +}); + +describe('mode classification and summary', () => { + it('classifies every mode exactly once', () => { + for (const { value } of OCI_AUTH_MODE_OPTIONS) { + const kinds = [value === 'api_key', isOciProfileMode(value), isOciPrincipalMode(value)]; + expect(kinds.filter(Boolean)).toHaveLength(1); + } + expect(isOciGatedPrincipalMode('instance_principal')).toBe(true); + expect(isOciGatedPrincipalMode('oke_workload_identity')).toBe(true); + expect(isOciGatedPrincipalMode('resource_principal')).toBe(false); + }); + + it('summarises region and mode for the provider row', () => { + const t = (key: string) => `t:${key}`; + expect(ociSettingsSummary(settings({ auth_mode: 'session_token' }), t)).toBe( + 'us-chicago-1 · t:settings.ai.oci.mode.sessionToken' + ); + expect(ociSettingsSummary(undefined, t)).toBe(''); + }); +}); + +describe('toWireCloudProvider', () => { + const base = { + id: 'p_oci', + slug: 'oci', + label: 'OCI Generative AI', + endpoint: 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com', + authStyle: 'oci' as const, + maskedKey: 'Not configured', + }; + + it('carries the oci block to the wire', () => { + const oci = settings({ auth_mode: 'config_profile' }); + expect(toWireCloudProvider({ ...base, oci })).toEqual({ + id: 'p_oci', + slug: 'oci', + label: 'OCI Generative AI', + endpoint: base.endpoint, + ca_cert_pem: '', + auth_style: 'oci', + oci, + }); + }); + + it('omits the oci key entirely for other providers', () => { + expect( + toWireCloudProvider({ ...base, slug: 'openai', authStyle: 'bearer' }) + ).not.toHaveProperty('oci'); + }); +}); diff --git a/app/src/components/settings/panels/ai/ociSettings.ts b/app/src/components/settings/panels/ai/ociSettings.ts new file mode 100644 index 00000000000..1a51ba36295 --- /dev/null +++ b/app/src/components/settings/panels/ai/ociSettings.ts @@ -0,0 +1,142 @@ +/* + * Pure helpers for the OCI Generative AI provider form: option tables, the + * validation that mirrors the Rust factory (`inference::provider::factory::oci`), + * normalisation of the payload sent to the core, and the one-line row summary. + * + * Kept free of React so the rules are unit-testable on their own. The core is + * the authority; these checks only catch the same mistakes before a round trip. + */ +import type { + OciAuthMode, + OciSettings, + OciTransport, +} from '../../../../utils/tauriCommands/config'; +import { defaultEndpointForBuiltinCloudProvider } from '../builtinCloudProviders'; + +export const OCI_PROVIDER_SLUG = 'oci'; + +export const OCI_AUTH_MODE_OPTIONS: { value: OciAuthMode; labelKey: string }[] = [ + { value: 'api_key', labelKey: 'settings.ai.oci.mode.apiKey' }, + { value: 'config_profile', labelKey: 'settings.ai.oci.mode.configProfile' }, + { value: 'session_token', labelKey: 'settings.ai.oci.mode.sessionToken' }, + { value: 'resource_principal', labelKey: 'settings.ai.oci.mode.resourcePrincipal' }, + { value: 'instance_principal', labelKey: 'settings.ai.oci.mode.instancePrincipal' }, + { value: 'oke_workload_identity', labelKey: 'settings.ai.oci.mode.okeWorkloadIdentity' }, +]; + +export const OCI_TRANSPORT_OPTIONS: { value: OciTransport; labelKey: string }[] = [ + { value: 'openai', labelKey: 'settings.ai.oci.transport.openai' }, + { value: 'actions', labelKey: 'settings.ai.oci.transport.actions' }, + { value: 'native_generic', labelKey: 'settings.ai.oci.transport.nativeGeneric' }, + { value: 'native_cohere', labelKey: 'settings.ai.oci.transport.nativeCohere' }, +]; + +export const DEFAULT_OCI_SETTINGS: OciSettings = { auth_mode: 'api_key', transport: 'openai' }; + +/** Modes whose key material comes from an OCI config-file profile. */ +export const isOciProfileMode = (mode: OciAuthMode): boolean => + mode === 'config_profile' || mode === 'session_token'; + +/** Modes that identify the workload itself and so store no secret. */ +export const isOciPrincipalMode = (mode: OciAuthMode): boolean => + mode === 'resource_principal' || + mode === 'instance_principal' || + mode === 'oke_workload_identity'; + +/** Principal modes that only exist in a build with the `oci-principals` gate. */ +export const isOciGatedPrincipalMode = (mode: OciAuthMode): boolean => + mode === 'instance_principal' || mode === 'oke_workload_identity'; + +/** + * Whether the entry must name a compartment. A Generative AI API key carries + * its own, so only `openai` with `api_key` can omit it; IAM-signed calls need + * one on every transport. Mirrors the core's check. + */ +export const ociNeedsCompartment = (settings: OciSettings): boolean => + settings.transport !== 'openai' || settings.auth_mode !== 'api_key'; + +/** + * Only `/openai/v1` carries the Generative AI project header, and it requires + * one. Mirrors the core's check. + */ +export const ociTransportUsesProject = (transport: OciTransport): boolean => transport === 'openai'; + +/** + * The `endpoint` to persist on an OCI entry: an explicit override (another + * realm, a private endpoint) is kept, while a blank value or the built-in + * preset's display URL becomes blank so the core derives the host from the + * region. + */ +export function ociEndpointOverride(existing: string | undefined): string { + const endpoint = trimmed(existing).replace(/\/+$/, ''); + const preset = defaultEndpointForBuiltinCloudProvider(OCI_PROVIDER_SLUG).replace(/\/+$/, ''); + return endpoint === preset ? '' : endpoint; +} + +type OptionalOciField = + | 'config_file' + | 'profile' + | 'region' + | 'compartment_id' + | 'project_id' + | 'dedicated_endpoint_id'; + +const trimmed = (value: string | undefined): string => (value ?? '').trim(); + +/** + * First problem with the form as an i18n key, or `null` when it can be saved. + * `hasStoredKey` is true when an API key already sits in the keyring, so an + * edit that leaves the key field blank keeps it. + */ +export function validateOciSettings( + settings: OciSettings, + apiKey: string, + hasStoredKey: boolean +): string | null { + // A profile or principal can supply the region; only api_key mode cannot. + if (settings.auth_mode === 'api_key' && !trimmed(settings.region)) { + return 'settings.ai.oci.regionRequired'; + } + if (settings.auth_mode === 'api_key' && !trimmed(apiKey) && !hasStoredKey) { + return 'settings.ai.apiKeyRequired'; + } + if (ociNeedsCompartment(settings) && !trimmed(settings.compartment_id)) { + return 'settings.ai.oci.compartmentRequired'; + } + if (ociTransportUsesProject(settings.transport) && !trimmed(settings.project_id)) { + return 'settings.ai.oci.projectRequired'; + } + return null; +} + +/** + * The payload persisted on the provider entry: values trimmed, empty optional + * fields dropped, and fields that do not apply to the chosen mode / transport + * removed so a stale value cannot ride along after the user switches. + */ +export function normalizeOciSettings(settings: OciSettings): OciSettings { + const out: OciSettings = { auth_mode: settings.auth_mode, transport: settings.transport }; + const set = (key: OptionalOciField) => { + const value = trimmed(settings[key]); + if (value) out[key] = value; + }; + if (isOciProfileMode(settings.auth_mode)) { + set('config_file'); + set('profile'); + } + set('region'); + set('compartment_id'); + if (ociTransportUsesProject(settings.transport)) set('project_id'); + set('dedicated_endpoint_id'); + return out; +} + +/** `region · mode` for the connected-provider row; empty when nothing is set. */ +export function ociSettingsSummary( + settings: OciSettings | undefined, + t: (key: string) => string +): string { + if (!settings) return ''; + const mode = OCI_AUTH_MODE_OPTIONS.find(option => option.value === settings.auth_mode); + return [trimmed(settings.region), mode ? t(mode.labelKey) : ''].filter(Boolean).join(' · '); +} diff --git a/app/src/components/settings/panels/ai/providerIcons.tsx b/app/src/components/settings/panels/ai/providerIcons.tsx index 4695173541a..b0bf5352cd4 100644 --- a/app/src/components/settings/panels/ai/providerIcons.tsx +++ b/app/src/components/settings/panels/ai/providerIcons.tsx @@ -14,7 +14,7 @@ */ import { createElement, type ReactElement } from 'react'; import type { IconType } from 'react-icons'; -import { LuSparkles } from 'react-icons/lu'; +import { LuCloud, LuSparkles } from 'react-icons/lu'; import { SiAnthropic, SiApple, @@ -70,6 +70,9 @@ const PROVIDER_ICONS: Record = { xai: SiX, ollama: SiOllama, omlx: SiApple, + // No Oracle mark ships in the installed icon set; a neutral cloud glyph + // stands in until a licensed brand asset is bundled. + oci: LuCloud, }; /** Locally bundled marks for providers absent from the installed icon set. */ diff --git a/app/src/components/settings/panels/ai/useAISettingsState.ts b/app/src/components/settings/panels/ai/useAISettingsState.ts index 973ed94ad47..762651bb6c6 100644 --- a/app/src/components/settings/panels/ai/useAISettingsState.ts +++ b/app/src/components/settings/panels/ai/useAISettingsState.ts @@ -28,6 +28,7 @@ import { type OllamaState, type ProviderRef, type RoutingMap, + toWireCloudProvider, } from './aiPanelTypes'; /** Providers with no `/models` endpoint, never re-probed at save time. */ @@ -42,6 +43,7 @@ function toPanelProvider(p: CloudProviderView): CloudProvider { caCertPem: p.ca_cert_pem ?? '', authStyle: p.auth_style, maskedKey: maskKeyLabel(p.has_api_key), + ...(p.oci ? { oci: p.oci } : {}), }; } @@ -77,6 +79,7 @@ function toApiSettings(panel: AISettings): ApiAISettings { ca_cert_pem: p.caCertPem ?? '', auth_style: p.authStyle, has_api_key: p.maskedKey.startsWith('••••'), + ...(p.oci ? { oci: p.oci } : {}), })), routing: { chat: panel.routing.chat, @@ -136,14 +139,7 @@ export function useAISettings() { p => !['', 'cloud', 'openhuman', 'pid'].includes(p.slug) ); if (JSON.stringify(userProviders) === JSON.stringify(savedUserProviders)) return; - const wire = userProviders.map(p => ({ - id: p.id, - slug: p.slug, - label: p.label, - endpoint: p.endpoint, - ca_cert_pem: p.caCertPem ?? '', - auth_style: p.authStyle, - })); + const wire = userProviders.map(toWireCloudProvider); flushCloudProviders(wire).catch(err => console.warn('[ai-settings] eager cloud_providers flush failed:', err) ); diff --git a/app/src/components/settings/panels/ai/useCloudProviderEditorSubmit.ts b/app/src/components/settings/panels/ai/useCloudProviderEditorSubmit.ts index c76e9394577..8e4cf27832b 100644 --- a/app/src/components/settings/panels/ai/useCloudProviderEditorSubmit.ts +++ b/app/src/components/settings/panels/ai/useCloudProviderEditorSubmit.ts @@ -17,6 +17,7 @@ import { type CloudProvider, maskKeyLabel, ProviderProbeError, + toWireCloudProvider, } from './aiPanelTypes'; export function useCloudProviderEditorSubmit({ @@ -48,14 +49,7 @@ export function useCloudProviderEditorSubmit({ // Snapshot the prior persisted cloud_providers list so we can restore // it if the live probe fails. - const priorWireProviders = saved.cloudProviders.map(p => ({ - id: p.id, - slug: p.slug, - label: p.label, - endpoint: p.endpoint, - ca_cert_pem: p.caCertPem ?? '', - auth_style: p.authStyle, - })); + const priorWireProviders = saved.cloudProviders.map(toWireCloudProvider); // Live verification — flush the new cloud_providers list and call // `/models` through the Rust controller. Flush first so Rust validates @@ -67,14 +61,7 @@ export function useCloudProviderEditorSubmit({ : draft.cloudProviders.map(p => (p.id === editing.id ? upserted : p)); const nextWireProviders = list .filter(p => !['', 'cloud', 'openhuman', 'pid'].includes(p.slug)) - .map(p => ({ - id: p.id, - slug: p.slug, - label: p.label, - endpoint: p.endpoint, - ca_cert_pem: p.caCertPem ?? '', - auth_style: p.authStyle, - })); + .map(toWireCloudProvider); try { await flushCloudProviders(nextWireProviders); // The provider must be configured before probing, and its CA has now diff --git a/app/src/components/settings/panels/ai/useProviderConnect.ts b/app/src/components/settings/panels/ai/useProviderConnect.ts index fdac3aeec6a..dcb3a2a25ed 100644 --- a/app/src/components/settings/panels/ai/useProviderConnect.ts +++ b/app/src/components/settings/panels/ai/useProviderConnect.ts @@ -19,7 +19,10 @@ import { type ProviderAuthError, setCloudProviderKey, } from '../../../../services/api/aiSettingsApi'; -import { openhumanUpdateLocalAiSettings } from '../../../../utils/tauriCommands/config'; +import { + type OciSettings, + openhumanUpdateLocalAiSettings, +} from '../../../../utils/tauriCommands/config'; import { presentProviderSetupError } from '../ProviderSetupErrorNotice'; import { type AISettings, @@ -28,7 +31,9 @@ import { type CloudProvider, defaultEndpointFor, maskKeyLabel, + toWireCloudProvider, } from './aiPanelTypes'; +import { ociEndpointOverride } from './ociSettings'; const normalizeProviderSlug = (slug: string) => slug.trim().toLowerCase(); const isProviderSlug = (candidate: string, slug: string) => @@ -40,7 +45,10 @@ export type ConnectCredentialMode = | 'codex_oauth' | 'endpoint' | 'endpoint_key' - | 'cli_login'; + | 'cli_login' + | 'oci'; + +const trimmedValue = (value: string): string => value.trim(); export function useProviderConnect({ draft, @@ -97,13 +105,17 @@ export function useProviderConnect({ value, endpoint: endpointOverride, credentialMode, + oci, }: { slug: string; localLabel?: string | null; value: string; endpoint?: string | null; credentialMode: ConnectCredentialMode; + /** OCI Generative AI settings; required when `credentialMode` is `'oci'`. */ + oci?: OciSettings; }) => { + if (credentialMode === 'oci' && !oci) throw new Error('OCI settings are required'); slug = normalizeProviderSlug(slug); const revision = (providerConnectRevisions.current.get(slug) ?? 0) + 1; providerConnectRevisions.current.set(slug, revision); @@ -123,6 +135,16 @@ export function useProviderConnect({ const isEndpointKey = credentialMode === 'endpoint_key'; const isCodexOAuth = credentialMode === 'codex_oauth'; const isCliLogin = credentialMode === 'cli_login'; + const isOci = credentialMode === 'oci'; + // OCI holds a key only in api_key mode, and keeps the stored one when the + // field was left blank on an edit. + const ociKeepsKey = + isOci && + oci?.auth_mode === 'api_key' && + (trimmedValue(value) !== '' || + latestSettings.current.draft.cloudProviders.some( + p => isProviderSlug(p.slug, slug) && p.maskedKey.startsWith('••••') + )); setBusyAction(`toggle-${localLabel ? localLabel.toLowerCase().replace(/\s/g, '') : slug}`); // A fresh attempt on THIS provider clears only its own prior advisory — // an advisory about a different provider must survive (#5341). @@ -151,15 +173,24 @@ export function useProviderConnect({ const initialSavedProvider = initialSettings.saved.cloudProviders.find(provider => isProviderSlug(provider.slug, slug) ); + const existingProvider = initialProvider ?? initialSavedProvider; const upserted: CloudProvider = { id: `p_${slug}_${Math.random().toString(36).slice(2, 7)}`, slug, - label: localLabel ?? BUILTIN_PROVIDER_META[slug]?.label ?? slug, - endpoint, + label: + localLabel ?? + BUILTIN_PROVIDER_META[slug]?.label ?? + (isOci ? existingProvider?.label : undefined) ?? + slug, + // OCI routes by region: keep only an explicit endpoint override, so + // the preset's display URL never pins every region to Chicago. + endpoint: isOci ? ociEndpointOverride(existingProvider?.endpoint) : endpoint, caCertPem: initialProvider?.caCertPem ?? initialSavedProvider?.caCertPem, - authStyle: authStyleForSlug(slug), + // Custom OCI slugs (e.g. `oci-cohere`) are not built-in presets. + authStyle: isOci ? 'oci' : authStyleForSlug(slug), // CLI-login providers hold no API key — reflect that honestly. - maskedKey: maskKeyLabel(!isCliLogin), + maskedKey: maskKeyLabel(isOci ? ociKeepsKey : !isCliLogin), + ...(isOci && oci ? { oci } : {}), }; if (isLocalRuntime && slug === 'ollama') { @@ -203,28 +234,35 @@ export function useProviderConnect({ caCertPem: currentProvider?.caCertPem ?? currentSavedProvider?.caCertPem, }; const priorWireProviders = currentSettings.saved.cloudProviders.map(provider => ({ - id: provider.id, + ...toWireCloudProvider(provider), slug: normalizeProviderSlug(provider.slug), - label: provider.label, - endpoint: provider.endpoint, - ca_cert_pem: provider.caCertPem ?? '', - auth_style: provider.authStyle, })); const nextWireProviders = [ ...priorWireProviders.filter(provider => !isProviderSlug(provider.slug, slug)), - { - id: currentUpserted.id, - slug: currentUpserted.slug, - label: currentUpserted.label, - endpoint: currentUpserted.endpoint, - ca_cert_pem: currentUpserted.caCertPem ?? '', - auth_style: currentUpserted.authStyle, - }, + toWireCloudProvider(currentUpserted), ]; let flushedProviders = nextWireProviders; try { await flushCloudProviders(flushedProviders); - if (!isLocalRuntime && !isCodexOAuth && !isCliLogin) { + if (isOci) { + if (oci?.auth_mode === 'api_key') { + // A blank key on an edit keeps the stored one. + if (trimmed) await setCloudProviderKey(slug, trimmed); + } else { + // Profile / principal modes hold no secret; drop any key left + // over from an earlier api_key configuration. A failed delete + // aborts the switch (the catch below restores the previous + // providers) rather than saving a keyless mode over a key + // that is still stored. + await clearCloudProviderKey(slug).catch(clearErr => { + console.warn( + `[ai-settings] clearing stale oci key failed slug=${slug}`, + clearErr + ); + throw clearErr; + }); + } + } else if (!isLocalRuntime && !isCodexOAuth && !isCliLogin) { await setCloudProviderKey(slug, trimmed); } const latestSettingsAfterKey = latestSettings.current; @@ -253,7 +291,9 @@ export function useProviderConnect({ ); throw writeError; } - if (!isCodexOAuth && !isCliLogin) { + // OCI has no OpenAI-style `/models` listing to probe; the model id is + // typed by the user and validated by the first request. + if (!isCodexOAuth && !isCliLogin && !isOci) { try { await listProviderModels(slug); } catch (probeErr) { diff --git a/app/src/components/settings/panels/builtinCloudProviders.ts b/app/src/components/settings/panels/builtinCloudProviders.ts index f0330236de8..8014579275c 100644 --- a/app/src/components/settings/panels/builtinCloudProviders.ts +++ b/app/src/components/settings/panels/builtinCloudProviders.ts @@ -229,6 +229,17 @@ export const BUILTIN_CLOUD_PROVIDERS: BuiltinCloudProvider[] = [ tone: TONE.indigo, keyPlaceholder: 'ms-...', }, + { + // Native OCI provider: region, auth mode and compartment live in the + // provider's `oci` settings, edited through `OciSettingsDialog`. The URL is + // a display default only, never saved as the entry endpoint; the core + // routes by `oci.region`. + slug: 'oci', + label: 'OCI Generative AI', + endpoint: 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com', + authStyle: 'oci', + tone: TONE.rose, + }, ]; // NOTE: Claude Code CLI is intentionally NOT a builtin chip. It is a diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts index b8be8bb258a..7a41e3dc6d0 100644 --- a/app/src/lib/i18n/ar.ts +++ b/app/src/lib/i18n/ar.ts @@ -5047,6 +5047,40 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'جارٍ الإرسال…', 'keyring.operation.expires': 'ينتهي الطلب خلال {seconds} ثانية.', 'keyring.operation.error': 'تعذر إرسال قرارك. ربما انتهت صلاحية الطلب.', + + 'settings.ai.oci.description': + 'اتصل بـ Oracle Cloud Infrastructure Generative AI. اختر طريقة مصادقة الطلبات والبروتوكول المستخدم.', + 'settings.ai.oci.authMode': 'المصادقة', + 'settings.ai.oci.mode.apiKey': 'مفتاح API', + 'settings.ai.oci.mode.configProfile': 'ملف تعريف تكوين OCI', + 'settings.ai.oci.mode.sessionToken': 'رمز الجلسة', + 'settings.ai.oci.mode.resourcePrincipal': 'هوية المورد', + 'settings.ai.oci.mode.instancePrincipal': 'هوية المثيل', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'هوية حمل عمل OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'محفوظ مشفّرًا على هذا الجهاز. اتركه فارغًا للاحتفاظ بالمفتاح المحفوظ.', + 'settings.ai.oci.configFile': 'ملف تكوين OCI', + 'settings.ai.oci.profile': 'ملف التعريف', + 'settings.ai.oci.profileHint': + 'تُقرأ مفاتيح التوقيع من تكوين OCI عند الحاجة ولا تُنسخ أبدًا إلى OpenHuman.', + 'settings.ai.oci.principalHint': 'لا يتم تخزين أي سر. تأتي بيانات الاعتماد من بيئة تشغيل OCI.', + 'settings.ai.oci.principalBuildHint': + 'يتطلب Instance principal وهوية حمل عمل OKE إصدارًا يدعم OCI principals.', + 'settings.ai.oci.region': 'المنطقة', + 'settings.ai.oci.compartment': 'معرّف OCID للحجرة', + 'settings.ai.oci.project': 'معرّف OCID لمشروع Generative AI', + 'settings.ai.oci.transport': 'البروتوكول', + 'settings.ai.oci.transport.openai': 'متوافق مع OpenAI', + 'settings.ai.oci.transport.actions': 'متوافق مع OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'دردشة أصلية (Meta وxAI وGoogle وOpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'دردشة أصلية (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'معرّف OCID لنقطة النهاية المخصصة (اختياري)', + 'settings.ai.oci.regionRequired': 'المنطقة مطلوبة (مثل us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'معرّف OCID للحجيرة مطلوب لهذا البروتوكول وطريقة تسجيل الدخول هذه.', + 'settings.ai.oci.projectRequired': + 'معرّف OCID لمشروع Generative AI مطلوب للبروتوكول المتوافق مع OpenAI.', + 'settings.ai.oci.editSettings': 'تعديل إعدادات OCI', }; export default messages; diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts index 81f587758cd..6983f1f9a98 100644 --- a/app/src/lib/i18n/bn.ts +++ b/app/src/lib/i18n/bn.ts @@ -5146,6 +5146,41 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'পাঠানো হচ্ছে…', 'keyring.operation.expires': 'অনুরোধটি {seconds} সেকেন্ডে মেয়াদোত্তীর্ণ হবে।', 'keyring.operation.error': 'সিদ্ধান্ত পাঠানো যায়নি। অনুরোধটির মেয়াদ শেষ হয়ে থাকতে পারে।', + + 'settings.ai.oci.description': + 'Oracle Cloud Infrastructure Generative AI-এর সাথে সংযুক্ত হন। অনুরোধ কীভাবে প্রমাণীকৃত হবে এবং কোন প্রোটোকল ব্যবহৃত হবে তা বেছে নিন।', + 'settings.ai.oci.authMode': 'প্রমাণীকরণ', + 'settings.ai.oci.mode.apiKey': 'API কী', + 'settings.ai.oci.mode.configProfile': 'OCI কনফিগ প্রোফাইল', + 'settings.ai.oci.mode.sessionToken': 'সেশন টোকেন', + 'settings.ai.oci.mode.resourcePrincipal': 'রিসোর্স প্রিন্সিপাল', + 'settings.ai.oci.mode.instancePrincipal': 'ইনস্ট্যান্স প্রিন্সিপাল', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE ওয়ার্কলোড আইডেন্টিটি', + 'settings.ai.oci.apiKeyKeepHint': + 'এই ডিভাইসে এনক্রিপ্ট করে সংরক্ষিত। সংরক্ষিত কী রাখতে ফাঁকা রাখুন।', + 'settings.ai.oci.configFile': 'OCI কনফিগ ফাইল', + 'settings.ai.oci.profile': 'প্রোফাইল', + 'settings.ai.oci.profileHint': + 'সাইনিং কী প্রয়োজনে আপনার OCI কনফিগ থেকে পড়া হয় এবং কখনও OpenHuman-এ কপি করা হয় না।', + 'settings.ai.oci.principalHint': + 'কোনো গোপন তথ্য সংরক্ষিত হয় না। ক্রেডেনশিয়াল OCI রানটাইম পরিবেশ থেকে আসে।', + 'settings.ai.oci.principalBuildHint': + 'Instance principal এবং OKE ওয়ার্কলোড আইডেন্টিটির জন্য OCI principals সমর্থন সহ বিল্ড প্রয়োজন।', + 'settings.ai.oci.region': 'অঞ্চল', + 'settings.ai.oci.compartment': 'কম্পার্টমেন্ট OCID', + 'settings.ai.oci.project': 'Generative AI প্রকল্পের OCID', + 'settings.ai.oci.transport': 'প্রোটোকল', + 'settings.ai.oci.transport.openai': 'OpenAI-সামঞ্জস্যপূর্ণ', + 'settings.ai.oci.transport.actions': 'OpenAI-সামঞ্জস্যপূর্ণ (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'নেটিভ চ্যাট (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'নেটিভ চ্যাট (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'ডেডিকেটেড এন্ডপয়েন্টের OCID (ঐচ্ছিক)', + 'settings.ai.oci.regionRequired': 'অঞ্চল আবশ্যক (যেমন us-chicago-1)।', + 'settings.ai.oci.compartmentRequired': + 'এই প্রোটোকল ও সাইন-ইন পদ্ধতির জন্য কম্পার্টমেন্ট OCID প্রয়োজন।', + 'settings.ai.oci.projectRequired': + 'OpenAI-সামঞ্জস্যপূর্ণ প্রোটোকলের জন্য Generative AI প্রকল্পের OCID প্রয়োজন।', + 'settings.ai.oci.editSettings': 'OCI সেটিংস সম্পাদনা করুন', }; export default messages; diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts index 3fdafb3ebb1..cfa98044440 100644 --- a/app/src/lib/i18n/de.ts +++ b/app/src/lib/i18n/de.ts @@ -5300,6 +5300,41 @@ const messages: TranslationMap = { 'keyring.operation.expires': 'Die Anfrage läuft in {seconds}s ab.', 'keyring.operation.error': 'Deine Entscheidung konnte nicht gesendet werden. Die Anfrage ist möglicherweise abgelaufen.', + + 'settings.ai.oci.description': + 'Verbindung zu Oracle Cloud Infrastructure Generative AI herstellen. Legen Sie fest, wie Anfragen authentifiziert werden und welches Protokoll verwendet wird.', + 'settings.ai.oci.authMode': 'Authentifizierung', + 'settings.ai.oci.mode.apiKey': 'API-Schlüssel', + 'settings.ai.oci.mode.configProfile': 'OCI-Konfigurationsprofil', + 'settings.ai.oci.mode.sessionToken': 'Sitzungstoken', + 'settings.ai.oci.mode.resourcePrincipal': 'Resource Principal', + 'settings.ai.oci.mode.instancePrincipal': 'Instance Principal', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE-Workload-Identität', + 'settings.ai.oci.apiKeyKeepHint': + 'Verschlüsselt auf diesem Gerät gespeichert. Leer lassen, um den gespeicherten Schlüssel beizubehalten.', + 'settings.ai.oci.configFile': 'OCI-Konfigurationsdatei', + 'settings.ai.oci.profile': 'Profil', + 'settings.ai.oci.profileHint': + 'Signaturschlüssel werden bei Bedarf aus Ihrer OCI-Konfiguration gelesen und nie in OpenHuman kopiert.', + 'settings.ai.oci.principalHint': + 'Es wird kein Geheimnis gespeichert. Die Anmeldedaten stammen aus der OCI-Laufzeitumgebung.', + 'settings.ai.oci.principalBuildHint': + 'Instance Principal und OKE-Workload-Identität erfordern einen Build mit Unterstützung für OCI-Principals.', + 'settings.ai.oci.region': 'Region', + 'settings.ai.oci.compartment': 'Compartment-OCID', + 'settings.ai.oci.project': 'OCID des Generative-AI-Projekts', + 'settings.ai.oci.transport': 'Protokoll', + 'settings.ai.oci.transport.openai': 'OpenAI-kompatibel', + 'settings.ai.oci.transport.actions': 'OpenAI-kompatibel (Actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Natives Chat-Protokoll (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Natives Chat-Protokoll (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID des dedizierten Endpunkts (optional)', + 'settings.ai.oci.regionRequired': 'Region ist erforderlich (zum Beispiel us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'Für dieses Protokoll und diese Anmeldemethode ist eine Compartment-OCID erforderlich.', + 'settings.ai.oci.projectRequired': + 'Für das OpenAI-kompatible Protokoll ist die OCID des Generative-AI-Projekts erforderlich.', + 'settings.ai.oci.editSettings': 'OCI-Einstellungen bearbeiten', }; export default messages; diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts index 42d629a5d6a..2f9b2246a84 100644 --- a/app/src/lib/i18n/en.ts +++ b/app/src/lib/i18n/en.ts @@ -5419,6 +5419,41 @@ const en: TranslationMap = { 'keyring.operation.submitting': 'Sending…', 'keyring.operation.expires': 'Request expires in {seconds}s.', 'keyring.operation.error': 'Could not send your decision. The request may have expired.', + + 'settings.ai.oci.description': + 'Connect to Oracle Cloud Infrastructure Generative AI. Choose how requests are authenticated and which protocol to use.', + 'settings.ai.oci.authMode': 'Authentication', + 'settings.ai.oci.mode.apiKey': 'API key', + 'settings.ai.oci.mode.configProfile': 'OCI config profile', + 'settings.ai.oci.mode.sessionToken': 'Session token', + 'settings.ai.oci.mode.resourcePrincipal': 'Resource principal', + 'settings.ai.oci.mode.instancePrincipal': 'Instance principal', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE workload identity', + 'settings.ai.oci.apiKeyKeepHint': + 'Stored encrypted on this device. Leave blank to keep the saved key.', + 'settings.ai.oci.configFile': 'OCI config file', + 'settings.ai.oci.profile': 'Profile', + 'settings.ai.oci.profileHint': + 'Signing keys are read from your OCI config when needed and are never copied into OpenHuman.', + 'settings.ai.oci.principalHint': + 'No secret is stored. Credentials come from the OCI runtime environment.', + 'settings.ai.oci.principalBuildHint': + 'Instance principal and OKE workload identity need a build with OCI principals support.', + 'settings.ai.oci.region': 'Region', + 'settings.ai.oci.compartment': 'Compartment OCID', + 'settings.ai.oci.project': 'Generative AI project OCID', + 'settings.ai.oci.transport': 'Protocol', + 'settings.ai.oci.transport.openai': 'OpenAI-compatible', + 'settings.ai.oci.transport.actions': 'OpenAI-compatible (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Native chat (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Native chat (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'Dedicated endpoint OCID (optional)', + 'settings.ai.oci.regionRequired': 'Region is required (for example us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'Compartment OCID is required for this protocol and sign-in method.', + 'settings.ai.oci.projectRequired': + 'Generative AI project OCID is required for the OpenAI-compatible protocol.', + 'settings.ai.oci.editSettings': 'Edit OCI settings', }; export default en; diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts index bf101f262d4..8d9c17839b5 100644 --- a/app/src/lib/i18n/es.ts +++ b/app/src/lib/i18n/es.ts @@ -5252,6 +5252,41 @@ const messages: TranslationMap = { 'keyring.operation.expires': 'La solicitud vence en {seconds}s.', 'keyring.operation.error': 'No se pudo enviar tu decisión. Es posible que la solicitud haya vencido.', + + 'settings.ai.oci.description': + 'Conéctate a Oracle Cloud Infrastructure Generative AI. Elige cómo se autentican las solicitudes y qué protocolo usar.', + 'settings.ai.oci.authMode': 'Autenticación', + 'settings.ai.oci.mode.apiKey': 'Clave de API', + 'settings.ai.oci.mode.configProfile': 'Perfil de configuración de OCI', + 'settings.ai.oci.mode.sessionToken': 'Token de sesión', + 'settings.ai.oci.mode.resourcePrincipal': 'Entidad principal de recurso', + 'settings.ai.oci.mode.instancePrincipal': 'Entidad principal de instancia', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Identidad de carga de trabajo de OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Almacenada cifrada en este dispositivo. Déjalo en blanco para conservar la clave guardada.', + 'settings.ai.oci.configFile': 'Archivo de configuración de OCI', + 'settings.ai.oci.profile': 'Perfil', + 'settings.ai.oci.profileHint': + 'Las claves de firma se leen de tu configuración de OCI cuando hacen falta y nunca se copian a OpenHuman.', + 'settings.ai.oci.principalHint': + 'No se almacena ningún secreto. Las credenciales provienen del entorno de ejecución de OCI.', + 'settings.ai.oci.principalBuildHint': + 'Instance principal y la identidad de carga de trabajo de OKE requieren una compilación con compatibilidad con principals de OCI.', + 'settings.ai.oci.region': 'Región', + 'settings.ai.oci.compartment': 'OCID del compartimento', + 'settings.ai.oci.project': 'OCID del proyecto de Generative AI', + 'settings.ai.oci.transport': 'Protocolo', + 'settings.ai.oci.transport.openai': 'Compatible con OpenAI', + 'settings.ai.oci.transport.actions': 'Compatible con OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Chat nativo (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Chat nativo (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID del endpoint dedicado (opcional)', + 'settings.ai.oci.regionRequired': 'La región es obligatoria (por ejemplo, us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'Se requiere el OCID del compartimento para este protocolo y método de inicio de sesión.', + 'settings.ai.oci.projectRequired': + 'Se requiere el OCID del proyecto de Generative AI para el protocolo compatible con OpenAI.', + 'settings.ai.oci.editSettings': 'Editar ajustes de OCI', }; export default messages; diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts index e512ab66b0d..4c13ce151aa 100644 --- a/app/src/lib/i18n/fr.ts +++ b/app/src/lib/i18n/fr.ts @@ -5273,6 +5273,41 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'Envoi…', 'keyring.operation.expires': 'La demande expire dans {seconds}s.', 'keyring.operation.error': 'Impossible d’envoyer votre décision. La demande a peut-être expiré.', + + 'settings.ai.oci.description': + 'Connectez-vous à Oracle Cloud Infrastructure Generative AI. Choisissez comment les requêtes sont authentifiées et quel protocole utiliser.', + 'settings.ai.oci.authMode': 'Authentification', + 'settings.ai.oci.mode.apiKey': 'Clé API', + 'settings.ai.oci.mode.configProfile': 'Profil de configuration OCI', + 'settings.ai.oci.mode.sessionToken': 'Jeton de session', + 'settings.ai.oci.mode.resourcePrincipal': 'Principal de ressource', + 'settings.ai.oci.mode.instancePrincipal': 'Principal d’instance', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Identité de charge de travail OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Stockée chiffrée sur cet appareil. Laissez vide pour conserver la clé enregistrée.', + 'settings.ai.oci.configFile': 'Fichier de configuration OCI', + 'settings.ai.oci.profile': 'Profil', + 'settings.ai.oci.profileHint': + 'Les clés de signature sont lues dans votre configuration OCI au besoin et ne sont jamais copiées dans OpenHuman.', + 'settings.ai.oci.principalHint': + "Aucun secret n'est stocké. Les identifiants proviennent de l'environnement d'exécution OCI.", + 'settings.ai.oci.principalBuildHint': + "Instance principal et l'identité de charge de travail OKE nécessitent une version compilée avec la prise en charge des principals OCI.", + 'settings.ai.oci.region': 'Région', + 'settings.ai.oci.compartment': 'OCID du compartiment', + 'settings.ai.oci.project': 'OCID du projet Generative AI', + 'settings.ai.oci.transport': 'Protocole', + 'settings.ai.oci.transport.openai': 'Compatible OpenAI', + 'settings.ai.oci.transport.actions': 'Compatible OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Chat natif (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Chat natif (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID du point de terminaison dédié (facultatif)', + 'settings.ai.oci.regionRequired': 'La région est obligatoire (par exemple us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'L’OCID du compartiment est requis pour ce protocole et cette méthode de connexion.', + 'settings.ai.oci.projectRequired': + 'L’OCID du projet Generative AI est requis pour le protocole compatible OpenAI.', + 'settings.ai.oci.editSettings': 'Modifier les paramètres OCI', }; export default messages; diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts index 1471b9561ac..14864996ed7 100644 --- a/app/src/lib/i18n/hi.ts +++ b/app/src/lib/i18n/hi.ts @@ -5146,6 +5146,41 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'भेजा जा रहा है…', 'keyring.operation.expires': 'अनुरोध {seconds} सेकंड में समाप्त होगा।', 'keyring.operation.error': 'निर्णय भेजा नहीं जा सका। अनुरोध समाप्त हो चुका हो सकता है।', + + 'settings.ai.oci.description': + 'Oracle Cloud Infrastructure Generative AI से कनेक्ट करें। चुनें कि अनुरोध कैसे प्रमाणित हों और कौन सा प्रोटोकॉल उपयोग हो।', + 'settings.ai.oci.authMode': 'प्रमाणीकरण', + 'settings.ai.oci.mode.apiKey': 'API कुंजी', + 'settings.ai.oci.mode.configProfile': 'OCI कॉन्फ़िग प्रोफ़ाइल', + 'settings.ai.oci.mode.sessionToken': 'सेशन टोकन', + 'settings.ai.oci.mode.resourcePrincipal': 'संसाधन प्रिंसिपल', + 'settings.ai.oci.mode.instancePrincipal': 'इंस्टेंस प्रिंसिपल', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE वर्कलोड आइडेंटिटी', + 'settings.ai.oci.apiKeyKeepHint': + 'इस डिवाइस पर एन्क्रिप्टेड रूप में स्टोर है। सहेजी हुई key रखने के लिए खाली छोड़ें।', + 'settings.ai.oci.configFile': 'OCI कॉन्फ़िग फ़ाइल', + 'settings.ai.oci.profile': 'प्रोफ़ाइल', + 'settings.ai.oci.profileHint': + 'साइनिंग keys ज़रूरत पड़ने पर आपके OCI कॉन्फ़िग से पढ़ी जाती हैं और OpenHuman में कभी कॉपी नहीं होतीं।', + 'settings.ai.oci.principalHint': + 'कोई सीक्रेट स्टोर नहीं होता। क्रेडेंशियल OCI रनटाइम परिवेश से आते हैं।', + 'settings.ai.oci.principalBuildHint': + 'Instance principal और OKE वर्कलोड आइडेंटिटी के लिए OCI principals सपोर्ट वाला बिल्ड चाहिए।', + 'settings.ai.oci.region': 'रीजन', + 'settings.ai.oci.compartment': 'कम्पार्टमेंट OCID', + 'settings.ai.oci.project': 'Generative AI प्रोजेक्ट OCID', + 'settings.ai.oci.transport': 'प्रोटोकॉल', + 'settings.ai.oci.transport.openai': 'OpenAI-संगत', + 'settings.ai.oci.transport.actions': 'OpenAI-संगत (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'नेटिव चैट (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'नेटिव चैट (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'डेडिकेटेड एंडपॉइंट OCID (वैकल्पिक)', + 'settings.ai.oci.regionRequired': 'रीजन आवश्यक है (उदाहरण: us-chicago-1)।', + 'settings.ai.oci.compartmentRequired': + 'इस प्रोटोकॉल और साइन-इन तरीके के लिए कम्पार्टमेंट OCID आवश्यक है।', + 'settings.ai.oci.projectRequired': + 'OpenAI-संगत प्रोटोकॉल के लिए Generative AI प्रोजेक्ट OCID आवश्यक है।', + 'settings.ai.oci.editSettings': 'OCI सेटिंग्स संपादित करें', }; export default messages; diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts index 0edcf737a17..a68ad553fa8 100644 --- a/app/src/lib/i18n/id.ts +++ b/app/src/lib/i18n/id.ts @@ -5192,6 +5192,41 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'Mengirim…', 'keyring.operation.expires': 'Permintaan berakhir dalam {seconds} dtk.', 'keyring.operation.error': 'Keputusan tidak dapat dikirim. Permintaan mungkin sudah kedaluwarsa.', + + 'settings.ai.oci.description': + 'Hubungkan ke Oracle Cloud Infrastructure Generative AI. Pilih cara permintaan diautentikasi dan protokol yang digunakan.', + 'settings.ai.oci.authMode': 'Autentikasi', + 'settings.ai.oci.mode.apiKey': 'Kunci API', + 'settings.ai.oci.mode.configProfile': 'Profil konfigurasi OCI', + 'settings.ai.oci.mode.sessionToken': 'Token sesi', + 'settings.ai.oci.mode.resourcePrincipal': 'Prinsipal sumber daya', + 'settings.ai.oci.mode.instancePrincipal': 'Prinsipal instans', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Identitas workload OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Disimpan terenkripsi di perangkat ini. Biarkan kosong untuk mempertahankan key yang tersimpan.', + 'settings.ai.oci.configFile': 'File konfigurasi OCI', + 'settings.ai.oci.profile': 'Profil', + 'settings.ai.oci.profileHint': + 'Key penandatanganan dibaca dari konfigurasi OCI Anda saat dibutuhkan dan tidak pernah disalin ke OpenHuman.', + 'settings.ai.oci.principalHint': + 'Tidak ada rahasia yang disimpan. Kredensial berasal dari lingkungan runtime OCI.', + 'settings.ai.oci.principalBuildHint': + 'Instance principal dan identitas workload OKE memerlukan build dengan dukungan principal OCI.', + 'settings.ai.oci.region': 'Region', + 'settings.ai.oci.compartment': 'OCID compartment', + 'settings.ai.oci.project': 'OCID proyek Generative AI', + 'settings.ai.oci.transport': 'Protokol', + 'settings.ai.oci.transport.openai': 'Kompatibel dengan OpenAI', + 'settings.ai.oci.transport.actions': 'Kompatibel dengan OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Chat native (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Chat native (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID endpoint khusus (opsional)', + 'settings.ai.oci.regionRequired': 'Region wajib diisi (misalnya us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'OCID compartment wajib diisi untuk protokol dan metode masuk ini.', + 'settings.ai.oci.projectRequired': + 'OCID proyek Generative AI wajib diisi untuk protokol yang kompatibel dengan OpenAI.', + 'settings.ai.oci.editSettings': 'Edit pengaturan OCI', }; export default messages; diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts index 233a153cd7c..dd0483ed570 100644 --- a/app/src/lib/i18n/it.ts +++ b/app/src/lib/i18n/it.ts @@ -5225,6 +5225,41 @@ const messages: TranslationMap = { 'keyring.operation.expires': 'La richiesta scade tra {seconds}s.', 'keyring.operation.error': 'Impossibile inviare la decisione. La richiesta potrebbe essere scaduta.', + + 'settings.ai.oci.description': + 'Collegati a Oracle Cloud Infrastructure Generative AI. Scegli come vengono autenticate le richieste e quale protocollo usare.', + 'settings.ai.oci.authMode': 'Autenticazione', + 'settings.ai.oci.mode.apiKey': 'Chiave API', + 'settings.ai.oci.mode.configProfile': 'Profilo di configurazione OCI', + 'settings.ai.oci.mode.sessionToken': 'Token di sessione', + 'settings.ai.oci.mode.resourcePrincipal': 'Principal di risorsa', + 'settings.ai.oci.mode.instancePrincipal': 'Principal di istanza', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Identità del carico di lavoro OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Memorizzata cifrata su questo dispositivo. Lascia vuoto per mantenere la chiave salvata.', + 'settings.ai.oci.configFile': 'File di configurazione OCI', + 'settings.ai.oci.profile': 'Profilo', + 'settings.ai.oci.profileHint': + 'Le chiavi di firma vengono lette dalla configurazione OCI quando servono e non vengono mai copiate in OpenHuman.', + 'settings.ai.oci.principalHint': + "Nessun segreto viene memorizzato. Le credenziali provengono dall'ambiente di runtime OCI.", + 'settings.ai.oci.principalBuildHint': + "Instance principal e l'identità del carico di lavoro OKE richiedono una build con supporto per i principal OCI.", + 'settings.ai.oci.region': 'Regione', + 'settings.ai.oci.compartment': 'OCID del compartimento', + 'settings.ai.oci.project': 'OCID del progetto Generative AI', + 'settings.ai.oci.transport': 'Protocollo', + 'settings.ai.oci.transport.openai': 'Compatibile con OpenAI', + 'settings.ai.oci.transport.actions': 'Compatibile con OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Chat nativa (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Chat nativa (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': "OCID dell'endpoint dedicato (facoltativo)", + 'settings.ai.oci.regionRequired': 'La regione è obbligatoria (ad esempio us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'L’OCID del compartimento è obbligatorio per questo protocollo e metodo di accesso.', + 'settings.ai.oci.projectRequired': + 'L’OCID del progetto Generative AI è obbligatorio per il protocollo compatibile con OpenAI.', + 'settings.ai.oci.editSettings': 'Modifica impostazioni OCI', }; export default messages; diff --git a/app/src/lib/i18n/ja.ts b/app/src/lib/i18n/ja.ts index fc7237fccc7..87c5763639c 100644 --- a/app/src/lib/i18n/ja.ts +++ b/app/src/lib/i18n/ja.ts @@ -5501,6 +5501,41 @@ const messages: TranslationMap = { 'keyring.operation.expires': 'リクエストは {seconds} 秒後に期限切れになります。', 'keyring.operation.error': '判断を送信できませんでした。リクエストの期限が切れた可能性があります。', + + 'settings.ai.oci.description': + 'Oracle Cloud Infrastructure Generative AI に接続します。リクエストの認証方法と使用するプロトコルを選択してください。', + 'settings.ai.oci.authMode': '認証', + 'settings.ai.oci.mode.apiKey': 'API キー', + 'settings.ai.oci.mode.configProfile': 'OCI 構成プロファイル', + 'settings.ai.oci.mode.sessionToken': 'セッショントークン', + 'settings.ai.oci.mode.resourcePrincipal': 'リソースプリンシパル', + 'settings.ai.oci.mode.instancePrincipal': 'インスタンスプリンシパル', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE ワークロードアイデンティティ', + 'settings.ai.oci.apiKeyKeepHint': + 'このデバイスに暗号化して保存されます。保存済みのキーを使い続ける場合は空欄のままにしてください。', + 'settings.ai.oci.configFile': 'OCI 構成ファイル', + 'settings.ai.oci.profile': 'プロファイル', + 'settings.ai.oci.profileHint': + '署名キーは必要なときに OCI 構成から読み込まれ、OpenHuman にコピーされることはありません。', + 'settings.ai.oci.principalHint': + 'シークレットは保存されません。認証情報は OCI のランタイム環境から取得されます。', + 'settings.ai.oci.principalBuildHint': + 'インスタンスプリンシパルと OKE ワークロードアイデンティティには、OCI プリンシパル対応のビルドが必要です。', + 'settings.ai.oci.region': 'リージョン', + 'settings.ai.oci.compartment': 'コンパートメント OCID', + 'settings.ai.oci.project': 'Generative AI プロジェクト OCID', + 'settings.ai.oci.transport': 'プロトコル', + 'settings.ai.oci.transport.openai': 'OpenAI 互換', + 'settings.ai.oci.transport.actions': 'OpenAI 互換(actions)', + 'settings.ai.oci.transport.nativeGeneric': 'ネイティブチャット(Meta、xAI、Google、OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'ネイティブチャット(Cohere)', + 'settings.ai.oci.dedicatedEndpoint': '専用エンドポイント OCID(任意)', + 'settings.ai.oci.regionRequired': 'リージョンは必須です(例: us-chicago-1)。', + 'settings.ai.oci.compartmentRequired': + 'このプロトコルとサインイン方法にはコンパートメント OCID が必要です。', + 'settings.ai.oci.projectRequired': + 'OpenAI 互換プロトコルには Generative AI プロジェクト OCID が必要です。', + 'settings.ai.oci.editSettings': 'OCI 設定を編集', }; export default messages; diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts index f61f2166914..238e4aeccb5 100644 --- a/app/src/lib/i18n/ko.ts +++ b/app/src/lib/i18n/ko.ts @@ -5095,6 +5095,40 @@ const messages: TranslationMap = { 'keyring.operation.submitting': '전송 중…', 'keyring.operation.expires': '요청이 {seconds}초 후 만료됩니다.', 'keyring.operation.error': '결정을 보내지 못했습니다. 요청이 만료되었을 수 있습니다.', + + 'settings.ai.oci.description': + 'Oracle Cloud Infrastructure Generative AI에 연결합니다. 요청 인증 방식과 사용할 프로토콜을 선택하세요.', + 'settings.ai.oci.authMode': '인증', + 'settings.ai.oci.mode.apiKey': 'API 키', + 'settings.ai.oci.mode.configProfile': 'OCI 구성 프로필', + 'settings.ai.oci.mode.sessionToken': '세션 토큰', + 'settings.ai.oci.mode.resourcePrincipal': '리소스 프린시펄', + 'settings.ai.oci.mode.instancePrincipal': '인스턴스 프린시펄', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE 워크로드 ID', + 'settings.ai.oci.apiKeyKeepHint': + '이 기기에 암호화되어 저장됩니다. 비워 두면 저장된 키를 유지합니다.', + 'settings.ai.oci.configFile': 'OCI 구성 파일', + 'settings.ai.oci.profile': '프로필', + 'settings.ai.oci.profileHint': + '서명 키는 필요할 때 OCI 구성에서 읽으며 OpenHuman에 복사되지 않습니다.', + 'settings.ai.oci.principalHint': + '저장되는 비밀 정보가 없습니다. 자격 증명은 OCI 런타임 환경에서 가져옵니다.', + 'settings.ai.oci.principalBuildHint': + '인스턴스 프린시펄과 OKE 워크로드 ID는 OCI 프린시펄을 지원하는 빌드가 필요합니다.', + 'settings.ai.oci.region': '리전', + 'settings.ai.oci.compartment': '구획 OCID', + 'settings.ai.oci.project': 'Generative AI 프로젝트 OCID', + 'settings.ai.oci.transport': '프로토콜', + 'settings.ai.oci.transport.openai': 'OpenAI 호환', + 'settings.ai.oci.transport.actions': 'OpenAI 호환(actions)', + 'settings.ai.oci.transport.nativeGeneric': '네이티브 채팅(Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': '네이티브 채팅(Cohere)', + 'settings.ai.oci.dedicatedEndpoint': '전용 엔드포인트 OCID(선택 사항)', + 'settings.ai.oci.regionRequired': '리전은 필수입니다(예: us-chicago-1).', + 'settings.ai.oci.compartmentRequired': '이 프로토콜과 로그인 방식에는 구획 OCID가 필요합니다.', + 'settings.ai.oci.projectRequired': + 'OpenAI 호환 프로토콜에는 Generative AI 프로젝트 OCID가 필요합니다.', + 'settings.ai.oci.editSettings': 'OCI 설정 편집', }; export default messages; diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts index 266e9493210..514e03d4b96 100644 --- a/app/src/lib/i18n/pl.ts +++ b/app/src/lib/i18n/pl.ts @@ -5219,6 +5219,40 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'Wysyłanie…', 'keyring.operation.expires': 'Prośba wygaśnie za {seconds}s.', 'keyring.operation.error': 'Nie udało się wysłać decyzji. Prośba mogła wygasnąć.', + + 'settings.ai.oci.description': + 'Połącz się z Oracle Cloud Infrastructure Generative AI. Wybierz sposób uwierzytelniania żądań i używany protokół.', + 'settings.ai.oci.authMode': 'Uwierzytelnianie', + 'settings.ai.oci.mode.apiKey': 'Klucz API', + 'settings.ai.oci.mode.configProfile': 'Profil konfiguracji OCI', + 'settings.ai.oci.mode.sessionToken': 'Token sesji', + 'settings.ai.oci.mode.resourcePrincipal': 'Podmiot zasobu', + 'settings.ai.oci.mode.instancePrincipal': 'Podmiot instancji', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Tożsamość obciążenia OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Przechowywany w postaci zaszyfrowanej na tym urządzeniu. Pozostaw puste, aby zachować zapisany klucz.', + 'settings.ai.oci.configFile': 'Plik konfiguracji OCI', + 'settings.ai.oci.profile': 'Profil', + 'settings.ai.oci.profileHint': + 'Klucze podpisywania są odczytywane z konfiguracji OCI w razie potrzeby i nigdy nie są kopiowane do OpenHuman.', + 'settings.ai.oci.principalHint': + 'Żaden sekret nie jest przechowywany. Poświadczenia pochodzą ze środowiska uruchomieniowego OCI.', + 'settings.ai.oci.principalBuildHint': + 'Instance principal i tożsamość obciążenia OKE wymagają kompilacji z obsługą principali OCI.', + 'settings.ai.oci.region': 'Region', + 'settings.ai.oci.compartment': 'OCID przedziału', + 'settings.ai.oci.project': 'OCID projektu Generative AI', + 'settings.ai.oci.transport': 'Protokół', + 'settings.ai.oci.transport.openai': 'Zgodny z OpenAI', + 'settings.ai.oci.transport.actions': 'Zgodny z OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Natywny czat (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Natywny czat (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID dedykowanego punktu końcowego (opcjonalnie)', + 'settings.ai.oci.regionRequired': 'Region jest wymagany (na przykład us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'Ten protokół i ta metoda logowania wymagają OCID przedziału.', + 'settings.ai.oci.projectRequired': 'Protokół zgodny z OpenAI wymaga OCID projektu Generative AI.', + 'settings.ai.oci.editSettings': 'Edytuj ustawienia OCI', }; export default messages; diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts index 3fd39f4abfd..acd40032843 100644 --- a/app/src/lib/i18n/pt.ts +++ b/app/src/lib/i18n/pt.ts @@ -5221,6 +5221,41 @@ const messages: TranslationMap = { 'keyring.operation.expires': 'A solicitação expira em {seconds}s.', 'keyring.operation.error': 'Não foi possível enviar sua decisão. A solicitação pode ter expirado.', + + 'settings.ai.oci.description': + 'Conecte-se ao Oracle Cloud Infrastructure Generative AI. Escolha como as solicitações são autenticadas e qual protocolo usar.', + 'settings.ai.oci.authMode': 'Autenticação', + 'settings.ai.oci.mode.apiKey': 'Chave de API', + 'settings.ai.oci.mode.configProfile': 'Perfil de configuração do OCI', + 'settings.ai.oci.mode.sessionToken': 'Token de sessão', + 'settings.ai.oci.mode.resourcePrincipal': 'Principal de recurso', + 'settings.ai.oci.mode.instancePrincipal': 'Principal de instância', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Identidade de carga de trabalho do OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Armazenada criptografada neste dispositivo. Deixe em branco para manter a chave salva.', + 'settings.ai.oci.configFile': 'Arquivo de configuração do OCI', + 'settings.ai.oci.profile': 'Perfil', + 'settings.ai.oci.profileHint': + 'As chaves de assinatura são lidas da sua configuração do OCI quando necessário e nunca são copiadas para o OpenHuman.', + 'settings.ai.oci.principalHint': + 'Nenhum segredo é armazenado. As credenciais vêm do ambiente de execução do OCI.', + 'settings.ai.oci.principalBuildHint': + 'Instance principal e a identidade de carga de trabalho do OKE exigem uma compilação com suporte a principals do OCI.', + 'settings.ai.oci.region': 'Região', + 'settings.ai.oci.compartment': 'OCID do compartimento', + 'settings.ai.oci.project': 'OCID do projeto do Generative AI', + 'settings.ai.oci.transport': 'Protocolo', + 'settings.ai.oci.transport.openai': 'Compatível com OpenAI', + 'settings.ai.oci.transport.actions': 'Compatível com OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Chat nativo (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Chat nativo (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID do endpoint dedicado (opcional)', + 'settings.ai.oci.regionRequired': 'A região é obrigatória (por exemplo, us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'O OCID do compartimento é obrigatório para este protocolo e método de login.', + 'settings.ai.oci.projectRequired': + 'O OCID do projeto do Generative AI é obrigatório para o protocolo compatível com OpenAI.', + 'settings.ai.oci.editSettings': 'Editar configurações do OCI', }; export default messages; diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts index 26bc30af418..38f6547626c 100644 --- a/app/src/lib/i18n/ru.ts +++ b/app/src/lib/i18n/ru.ts @@ -5202,6 +5202,41 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'Отправка…', 'keyring.operation.expires': 'Срок действия запроса истечёт через {seconds} с.', 'keyring.operation.error': 'Не удалось отправить решение. Возможно, срок запроса истёк.', + + 'settings.ai.oci.description': + 'Подключитесь к Oracle Cloud Infrastructure Generative AI. Выберите способ аутентификации запросов и используемый протокол.', + 'settings.ai.oci.authMode': 'Аутентификация', + 'settings.ai.oci.mode.apiKey': 'API-ключ', + 'settings.ai.oci.mode.configProfile': 'Профиль конфигурации OCI', + 'settings.ai.oci.mode.sessionToken': 'Токен сеанса', + 'settings.ai.oci.mode.resourcePrincipal': 'Субъект ресурса', + 'settings.ai.oci.mode.instancePrincipal': 'Субъект экземпляра', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'Идентификация рабочей нагрузки OKE', + 'settings.ai.oci.apiKeyKeepHint': + 'Хранится в зашифрованном виде на этом устройстве. Оставьте поле пустым, чтобы сохранить текущий ключ.', + 'settings.ai.oci.configFile': 'Файл конфигурации OCI', + 'settings.ai.oci.profile': 'Профиль', + 'settings.ai.oci.profileHint': + 'Ключи подписи читаются из вашей конфигурации OCI по мере необходимости и никогда не копируются в OpenHuman.', + 'settings.ai.oci.principalHint': + 'Секреты не хранятся. Учётные данные берутся из среды выполнения OCI.', + 'settings.ai.oci.principalBuildHint': + 'Для Instance principal и идентификации рабочей нагрузки OKE нужна сборка с поддержкой принципалов OCI.', + 'settings.ai.oci.region': 'Регион', + 'settings.ai.oci.compartment': 'OCID компартмента', + 'settings.ai.oci.project': 'OCID проекта Generative AI', + 'settings.ai.oci.transport': 'Протокол', + 'settings.ai.oci.transport.openai': 'Совместимый с OpenAI', + 'settings.ai.oci.transport.actions': 'Совместимый с OpenAI (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Нативный чат (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Нативный чат (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'OCID выделенной конечной точки (необязательно)', + 'settings.ai.oci.regionRequired': 'Укажите регион (например, us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'Для этого протокола и способа входа требуется OCID компартмента.', + 'settings.ai.oci.projectRequired': + 'Для протокола, совместимого с OpenAI, требуется OCID проекта Generative AI.', + 'settings.ai.oci.editSettings': 'Изменить настройки OCI', }; export default messages; diff --git a/app/src/lib/i18n/tr.ts b/app/src/lib/i18n/tr.ts index c6f900caaef..b388434a017 100644 --- a/app/src/lib/i18n/tr.ts +++ b/app/src/lib/i18n/tr.ts @@ -5148,6 +5148,41 @@ const messages: TranslationMap = { 'keyring.operation.submitting': 'Gönderiliyor…', 'keyring.operation.expires': 'İstek {seconds} sn içinde sona erecek.', 'keyring.operation.error': 'Kararınız gönderilemedi. İsteğin süresi dolmuş olabilir.', + + 'settings.ai.oci.description': + 'Oracle Cloud Infrastructure Generative AI hizmetine bağlanın. İsteklerin nasıl doğrulanacağını ve hangi protokolün kullanılacağını seçin.', + 'settings.ai.oci.authMode': 'Kimlik doğrulama', + 'settings.ai.oci.mode.apiKey': 'API anahtarı', + 'settings.ai.oci.mode.configProfile': 'OCI yapılandırma profili', + 'settings.ai.oci.mode.sessionToken': 'Oturum belirteci', + 'settings.ai.oci.mode.resourcePrincipal': 'Kaynak sorumlusu', + 'settings.ai.oci.mode.instancePrincipal': 'Örnek sorumlusu', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE iş yükü kimliği', + 'settings.ai.oci.apiKeyKeepHint': + 'Bu cihazda şifrelenmiş olarak saklanır. Kayıtlı anahtarı korumak için boş bırakın.', + 'settings.ai.oci.configFile': 'OCI yapılandırma dosyası', + 'settings.ai.oci.profile': 'Profil', + 'settings.ai.oci.profileHint': + 'İmzalama anahtarları gerektiğinde OCI yapılandırmanızdan okunur ve OpenHuman içine asla kopyalanmaz.', + 'settings.ai.oci.principalHint': + 'Hiçbir gizli bilgi saklanmaz. Kimlik bilgileri OCI çalışma ortamından gelir.', + 'settings.ai.oci.principalBuildHint': + 'Örnek sorumlusu ve OKE iş yükü kimliği, OCI sorumlusu desteği içeren bir derleme gerektirir.', + 'settings.ai.oci.region': 'Bölge', + 'settings.ai.oci.compartment': 'Bölme OCID’si', + 'settings.ai.oci.project': 'Generative AI proje OCID’si', + 'settings.ai.oci.transport': 'Protokol', + 'settings.ai.oci.transport.openai': 'OpenAI uyumlu', + 'settings.ai.oci.transport.actions': 'OpenAI uyumlu (actions)', + 'settings.ai.oci.transport.nativeGeneric': 'Yerel sohbet (Meta, xAI, Google, OpenAI)', + 'settings.ai.oci.transport.nativeCohere': 'Yerel sohbet (Cohere)', + 'settings.ai.oci.dedicatedEndpoint': 'Ayrılmış uç nokta OCID’si (isteğe bağlı)', + 'settings.ai.oci.regionRequired': 'Bölge gereklidir (örneğin us-chicago-1).', + 'settings.ai.oci.compartmentRequired': + 'Bu protokol ve oturum açma yöntemi için bölme OCID’si gereklidir.', + 'settings.ai.oci.projectRequired': + 'OpenAI uyumlu protokol için Generative AI proje OCID’si gereklidir.', + 'settings.ai.oci.editSettings': 'OCI ayarlarını düzenle', }; export default messages; diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts index 966f53a9ecd..ea818715032 100644 --- a/app/src/lib/i18n/zh-CN.ts +++ b/app/src/lib/i18n/zh-CN.ts @@ -4860,6 +4860,36 @@ const messages: TranslationMap = { 'keyring.operation.submitting': '正在发送…', 'keyring.operation.expires': '请求将在 {seconds} 秒后过期。', 'keyring.operation.error': '无法发送你的决定。请求可能已过期。', + + 'settings.ai.oci.description': + '连接到 Oracle Cloud Infrastructure Generative AI。选择请求的认证方式和使用的协议。', + 'settings.ai.oci.authMode': '认证', + 'settings.ai.oci.mode.apiKey': 'API 密钥', + 'settings.ai.oci.mode.configProfile': 'OCI 配置文件配置集', + 'settings.ai.oci.mode.sessionToken': '会话令牌', + 'settings.ai.oci.mode.resourcePrincipal': '资源主体', + 'settings.ai.oci.mode.instancePrincipal': '实例主体', + 'settings.ai.oci.mode.okeWorkloadIdentity': 'OKE 工作负载身份', + 'settings.ai.oci.apiKeyKeepHint': '已加密存储在此设备上。留空则保留已保存的密钥。', + 'settings.ai.oci.configFile': 'OCI 配置文件', + 'settings.ai.oci.profile': '配置集', + 'settings.ai.oci.profileHint': + '签名密钥仅在需要时从您的 OCI 配置中读取,绝不会复制到 OpenHuman。', + 'settings.ai.oci.principalHint': '不存储任何机密。凭据来自 OCI 运行时环境。', + 'settings.ai.oci.principalBuildHint': '实例主体和 OKE 工作负载身份需要支持 OCI 主体的构建版本。', + 'settings.ai.oci.region': '区域', + 'settings.ai.oci.compartment': '隔离区 OCID', + 'settings.ai.oci.project': 'Generative AI 项目 OCID', + 'settings.ai.oci.transport': '协议', + 'settings.ai.oci.transport.openai': '兼容 OpenAI', + 'settings.ai.oci.transport.actions': '兼容 OpenAI(actions)', + 'settings.ai.oci.transport.nativeGeneric': '原生聊天(Meta、xAI、Google、OpenAI)', + 'settings.ai.oci.transport.nativeCohere': '原生聊天(Cohere)', + 'settings.ai.oci.dedicatedEndpoint': '专用终端节点 OCID(可选)', + 'settings.ai.oci.regionRequired': '区域为必填项(例如 us-chicago-1)。', + 'settings.ai.oci.compartmentRequired': '此协议和登录方式需要区间 OCID。', + 'settings.ai.oci.projectRequired': 'OpenAI 兼容协议需要 Generative AI 项目 OCID。', + 'settings.ai.oci.editSettings': '编辑 OCI 设置', }; export default messages; diff --git a/app/src/services/api/aiSettingsApi.ts b/app/src/services/api/aiSettingsApi.ts index 15848935429..efadb05f54e 100644 --- a/app/src/services/api/aiSettingsApi.ts +++ b/app/src/services/api/aiSettingsApi.ts @@ -370,19 +370,21 @@ export async function saveAISettings(prev: AISettings, next: AISettings): Promis n.label !== p.label || n.endpoint !== p.endpoint || n.ca_cert_pem !== p.ca_cert_pem || - n.auth_style !== p.auth_style + n.auth_style !== p.auth_style || + JSON.stringify(n.oci ?? null) !== JSON.stringify(p.oci ?? null) ); }) ) { patch.cloud_providers = next.cloudProviders .filter(p => !['', 'cloud', 'openhuman', 'pid'].includes(p.slug.trim())) - .map(({ id, slug, label, endpoint, auth_style, ca_cert_pem }) => ({ + .map(({ id, slug, label, endpoint, auth_style, ca_cert_pem, oci }) => ({ id, slug, label, endpoint, auth_style, ca_cert_pem, + ...(oci ? { oci } : {}), })); } diff --git a/app/src/utils/tauriCommands/config.ts b/app/src/utils/tauriCommands/config.ts index 1ca215fb243..ce71c96620f 100644 --- a/app/src/utils/tauriCommands/config.ts +++ b/app/src/utils/tauriCommands/config.ts @@ -23,7 +23,39 @@ export interface ModelRoute { } /** Authentication header style. Matches Rust AuthStyle enum. */ -export type AuthStyle = 'bearer' | 'anthropic' | 'openhuman_jwt' | 'none'; +export type AuthStyle = 'bearer' | 'anthropic' | 'openhuman_jwt' | 'none' | 'oci'; + +/** How OCI Generative AI requests authenticate. Matches Rust `OciAuthMode`. */ +export type OciAuthMode = + | 'api_key' + | 'config_profile' + | 'session_token' + | 'resource_principal' + | 'instance_principal' + | 'oke_workload_identity'; + +/** Wire protocol to OCI Generative AI. Matches Rust `OciTransportKind`. */ +export type OciTransport = 'openai' | 'actions' | 'native_generic' | 'native_cohere'; + +/** + * Non-secret OCI Generative AI settings carried on an `auth_style: 'oci'` + * provider entry. Matches Rust `OciProviderSettings`. The only secret an OCI + * provider owns is the GenAI API key for `api_key` mode, which is stored in + * the keyring like every other provider key (never here). + */ +export interface OciSettings { + auth_mode: OciAuthMode; + /** OCI config file for the profile modes; empty ⇒ `~/.oci/config`. */ + config_file?: string; + /** Profile inside the config file; empty ⇒ `DEFAULT`. */ + profile?: string; + region?: string; + compartment_id?: string; + project_id?: string; + transport: OciTransport; + /** Dedicated AI cluster endpoint OCID; empty ⇒ on-demand serving. */ + dedicated_endpoint_id?: string; +} /** * Endpoint config for one cloud LLM provider (new slug-keyed shape). @@ -41,6 +73,8 @@ export interface CloudProviderCreds { auth_style: AuthStyle; /** Optional PEM CA bundle trusted only for this provider. */ ca_cert_pem?: string | null; + /** Present only on `auth_style: 'oci'` entries. */ + oci?: OciSettings; } /** @@ -89,7 +123,7 @@ export interface ModelSettingsUpdate { /** * When present, REPLACES `config.cloud_providers` wholesale. API keys are * NOT carried here — store them via `authStoreProviderCredentials`. - * Each entry: { id?, slug, label?, endpoint, auth_style? } + * Each entry: { id?, slug, label?, endpoint, auth_style?, oci? } */ cloud_providers?: CloudProviderCreds[] | null; /** diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock index 0a750c9effa..5b0cf352bf4 100644 --- a/crates/openhuman-app/Cargo.lock +++ b/crates/openhuman-app/Cargo.lock @@ -8120,7 +8120,9 @@ dependencies = [ "base64 0.23.1", "bytes", "futures", + "httpdate", "reqwest 0.12.28", + "ring", "serde", "serde_json", "sha2 0.11.1", diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml index 62166467e5d..2bd0d6d908b 100644 --- a/crates/openhuman-cli/Cargo.toml +++ b/crates/openhuman-cli/Cargo.toml @@ -638,6 +638,7 @@ http-server = ["openhuman-rpc/http-server"] inference = ["openhuman-rpc/inference"] documents = ["openhuman-rpc/documents"] hosting = ["openhuman-rpc/hosting"] +oci-principals = ["openhuman-rpc/oci-principals"] inbound-queues = ["openhuman-rpc/inbound-queues"] modules = ["openhuman-rpc/modules"] security-module = ["openhuman-rpc/security-module"] diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml index 6a03db7e91b..5fcef4bba18 100644 --- a/crates/openhuman-core/Cargo.toml +++ b/crates/openhuman-core/Cargo.toml @@ -671,6 +671,17 @@ hosting = ["modules", "dep:tinyhosts-bus"] # triage. Runtime switches: `[components] eventqueues` and `[inbound] enabled`; # off (or with the module unavailable) the direct triage path runs as before. inbound-queues = ["modules", "dep:tinyeventqueues-bus"] +# OCI Generative AI instance-principal and OKE workload-identity auth +# (`tinyinference-llm/oci-principals`). Default-OFF and product-OFF: both flows +# only exist on OCI compute / OKE, never on a desktop, and the gate pulls +# OpenSSL (RSA session keys, X.509 parsing) into the build, which is a native +# toolchain cost the shipped Windows/macOS/Linux app should not pay. Headless +# and server builds that run on OCI opt in with +# `--features oci-principals`. Off, the `instance_principal` / +# `oke_workload_identity` auth modes fail with an explicit "unsupported in this +# build" error naming this gate; every other OCI auth mode works regardless. +# Leaf gate; building it needs `OPENSSL_DIR` (e.g. `/opt/homebrew/opt/openssl@3`). +oci-principals = ["tinyinference-llm/oci-principals"] # The dynamic module host (`openhuman::modules`): the loader that admits a # compiled `cdylib` through tinybus's ABI descriptor, manifest, dependency and # SHA-256 gates, plus the `modules` RPC namespace and the registry of modules diff --git a/crates/openhuman-core/src/channels/routes_provider_tests.rs b/crates/openhuman-core/src/channels/routes_provider_tests.rs index 263f779ef7a..635bae80e4f 100644 --- a/crates/openhuman-core/src/channels/routes_provider_tests.rs +++ b/crates/openhuman-core/src/channels/routes_provider_tests.rs @@ -25,6 +25,7 @@ async fn handle_runtime_command_routes_configured_provider_slug_and_alias() { endpoint: "https://provider.example.test/v1".into(), auth_style: AuthStyle::Bearer, default_model: None, + oci: None, }, CloudProviderCreds { id: "p_managed_123".into(), @@ -33,6 +34,7 @@ async fn handle_runtime_command_routes_configured_provider_slug_and_alias() { endpoint: "https://api.openhuman.ai/v1".into(), auth_style: AuthStyle::OpenhumanJwt, default_model: None, + oci: None, }, ]; ctx.config = Some(Arc::new(config)); diff --git a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs index 7021e083a11..0083eb3c80a 100644 --- a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs +++ b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs @@ -145,6 +145,7 @@ async fn process_channel_message_handles_models_command_without_llm_call() { endpoint: "https://api.openhuman.ai/v1".to_string(), auth_style: crate::config::schema::AuthStyle::OpenhumanJwt, default_model: Some("default-model".to_string()), + oci: None, }); } let runtime_ctx = Arc::new(runtime_ctx); diff --git a/crates/openhuman-core/src/config/migrations/retire_cloud_provider_type.rs b/crates/openhuman-core/src/config/migrations/retire_cloud_provider_type.rs index 8e56b2d68c6..569c3ef3e72 100644 --- a/crates/openhuman-core/src/config/migrations/retire_cloud_provider_type.rs +++ b/crates/openhuman-core/src/config/migrations/retire_cloud_provider_type.rs @@ -52,19 +52,7 @@ pub(crate) fn rewrite_document(document: &mut toml::Value) -> anyhow::Result<()> if let Some(provider) = builtin { entry.insert( "auth_style".into(), - toml::Value::String( - match provider.auth_style { - crate::config::schema::cloud_providers::AuthStyle::Bearer => "bearer", - crate::config::schema::cloud_providers::AuthStyle::Anthropic => { - "anthropic" - } - crate::config::schema::cloud_providers::AuthStyle::OpenhumanJwt => { - "openhuman_jwt" - } - crate::config::schema::cloud_providers::AuthStyle::None => "none", - } - .into(), - ), + toml::Value::String(provider.auth_style.as_str().into()), ); } } diff --git a/crates/openhuman-core/src/config/ops/cloud_providers.rs b/crates/openhuman-core/src/config/ops/cloud_providers.rs index a5882463d3f..2981a8027cc 100644 --- a/crates/openhuman-core/src/config/ops/cloud_providers.rs +++ b/crates/openhuman-core/src/config/ops/cloud_providers.rs @@ -22,6 +22,9 @@ pub struct CloudProviderUpdate { pub(crate) legacy_type: Option, #[serde(default)] pub(crate) default_model: Option, + /// OCI Generative AI settings (`auth_style = "oci"` only). + #[serde(default)] + pub(crate) oci: Option, } /// Convert cloud-provider settings RPC inputs into validated config entries. @@ -92,6 +95,7 @@ pub fn build_cloud_provider_creds( endpoint, auth_style, default_model: entry.default_model, + oci: entry.oci, }) }) .collect() diff --git a/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs b/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs index e685f98343a..eeeda119ca0 100644 --- a/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs +++ b/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs @@ -10,6 +10,7 @@ fn update(slug: &str) -> CloudProviderUpdate { ca_cert_pem: None, legacy_type: None, default_model: None, + oci: None, } } @@ -77,14 +78,14 @@ fn builder_preserves_auth_aliases_and_unknown_error() { entry.auth_style = Some("OddAuth".to_string()); assert_eq!( build_cloud_provider_creds(vec![entry]).unwrap_err(), - "unknown auth_style 'oddauth'; valid: bearer, anthropic, openhuman_jwt, none" + "unknown auth_style 'oddauth'; valid: bearer, anthropic, openhuman_jwt, none, oci" ); let mut padded = update("custom"); padded.auth_style = Some(" anthropic ".to_string()); assert_eq!( build_cloud_provider_creds(vec![padded]).unwrap_err(), - "unknown auth_style ' anthropic '; valid: bearer, anthropic, openhuman_jwt, none" + "unknown auth_style ' anthropic '; valid: bearer, anthropic, openhuman_jwt, none, oci" ); } diff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rs index 054d1eddf64..8aa7c412c5e 100644 --- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs +++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs @@ -230,14 +230,23 @@ pub async fn client_config_json(config: &Config) -> serde_json::Value { .cloud_providers .iter() .map(|c| { - serde_json::json!({ + let mut entry = serde_json::json!({ "id": c.id, "slug": c.slug, "label": c.label, "endpoint": c.endpoint, "auth_style": c.auth_style.as_str(), "ca_cert_pem": config.cloud_provider_ca_certs.get(&c.slug), - }) + }); + // Non-secret OCI settings only; present solely on OCI entries so + // every other provider's snapshot shape is unchanged. + if let (Some(oci), Some(map)) = (c.oci.as_ref(), entry.as_object_mut()) { + map.insert( + "oci".to_string(), + serde_json::to_value(oci).unwrap_or(serde_json::Value::Null), + ); + } + entry }) .collect(); let model_registry: Vec = config diff --git a/crates/openhuman-core/src/config/ops/model_byok_route.rs b/crates/openhuman-core/src/config/ops/model_byok_route.rs index 7c45897e2e9..0ec76367054 100644 --- a/crates/openhuman-core/src/config/ops/model_byok_route.rs +++ b/crates/openhuman-core/src/config/ops/model_byok_route.rs @@ -112,6 +112,7 @@ pub(super) fn complete_byok_route(config: &mut Config, explicit: &ExplicitRolePi endpoint: endpoint.clone(), auth_style: AuthStyle::Bearer, default_model: Some(model.clone()), + oci: None, }); BYOK_INFERENCE_SLUG.to_string() } diff --git a/crates/openhuman-core/src/config/ops/model_byok_tests.rs b/crates/openhuman-core/src/config/ops/model_byok_tests.rs index 4b203836374..937f87ba2b0 100644 --- a/crates/openhuman-core/src/config/ops/model_byok_tests.rs +++ b/crates/openhuman-core/src/config/ops/model_byok_tests.rs @@ -36,6 +36,7 @@ fn entry(slug: &str, endpoint: &str) -> CloudProviderCreds { endpoint: endpoint.to_string(), auth_style: AuthStyle::Bearer, default_model: None, + oci: None, } } diff --git a/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs b/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs index e09b12796aa..9f45998fccf 100644 --- a/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs +++ b/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs @@ -18,6 +18,7 @@ fn provider(id: &str, slug: &str, endpoint: &str, auth_style: AuthStyle) -> Clou endpoint: endpoint.to_string(), auth_style, default_model: Some("provider-model".to_string()), + oci: None, } } diff --git a/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs b/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs index b57bd015f6d..da5f2cd538a 100644 --- a/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs +++ b/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs @@ -394,6 +394,42 @@ async fn snapshot_config_json_redacts_the_inbound_queue_url_credentials() { ); } +#[tokio::test] +async fn client_config_json_exposes_oci_settings_only_on_oci_entries() { + use crate::config::schema::cloud_providers::{ + AuthStyle, CloudProviderCreds, OciAuthMode, OciProviderSettings, + }; + let mut cfg = Config::default(); + cfg.cloud_providers = vec![ + CloudProviderCreds { + id: "p_oci".into(), + slug: "oci".into(), + auth_style: AuthStyle::Oci, + oci: Some(OciProviderSettings { + auth_mode: OciAuthMode::SessionToken, + profile: Some("DEFAULT".into()), + ..Default::default() + }), + ..Default::default() + }, + CloudProviderCreds { + id: "p_openai".into(), + slug: "openai".into(), + ..Default::default() + }, + ]; + let value = client_config_json(&cfg).await; + let providers = value["cloud_providers"] + .as_array() + .expect("cloud_providers"); + let oci = providers.iter().find(|p| p["slug"] == "oci").unwrap(); + assert_eq!(oci["auth_style"], "oci"); + assert_eq!(oci["oci"]["auth_mode"], "session_token"); + assert_eq!(oci["oci"]["profile"], "DEFAULT"); + let openai = providers.iter().find(|p| p["slug"] == "openai").unwrap(); + assert!(openai.get("oci").is_none()); +} + // ── agent_server_status ──────────────────────────────────────── #[test] diff --git a/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs b/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs index 9f0b3b24dbc..a1987b93c7c 100644 --- a/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs +++ b/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs @@ -214,6 +214,7 @@ async fn apply_model_settings_preserves_existing_reserved_slug_cloud_providers() endpoint: "https://api.tinyhumans.ai".into(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("reasoning-v1".into()), + oci: None, }, CloudProviderCreds { id: "myopenai-1".into(), @@ -222,6 +223,7 @@ async fn apply_model_settings_preserves_existing_reserved_slug_cloud_providers() endpoint: "https://api.openai.com".into(), auth_style: AuthStyle::Bearer, default_model: Some("gpt-4o".into()), + oci: None, }, ]; @@ -237,6 +239,7 @@ async fn apply_model_settings_preserves_existing_reserved_slug_cloud_providers() endpoint: "https://api.openai.com/v1".into(), auth_style: AuthStyle::Bearer, default_model: Some("gpt-4o-mini".into()), + oci: None, }]), ..Default::default() }; @@ -278,6 +281,7 @@ async fn apply_model_settings_does_not_double_add_reserved_entries() { endpoint: "https://api.tinyhumans.ai".into(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("reasoning-v1".into()), + oci: None, }]; let patch = ModelSettingsPatch { @@ -288,6 +292,7 @@ async fn apply_model_settings_does_not_double_add_reserved_entries() { endpoint: "https://api.tinyhumans.ai".into(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("reasoning-v1".into()), + oci: None, }]), ..Default::default() }; diff --git a/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs b/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs index 88bcc027946..5a8adaf7c3e 100644 --- a/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs +++ b/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs @@ -10,6 +10,7 @@ fn provider() -> CloudProviderCreds { endpoint: "https://api.openai.com/v1".into(), auth_style: AuthStyle::Bearer, default_model: Some("gpt-default".into()), + oci: None, } } diff --git a/crates/openhuman-core/src/config/schema/cloud_providers.rs b/crates/openhuman-core/src/config/schema/cloud_providers.rs index 4841f28f71f..ba6dc01edd9 100644 --- a/crates/openhuman-core/src/config/schema/cloud_providers.rs +++ b/crates/openhuman-core/src/config/schema/cloud_providers.rs @@ -69,6 +69,7 @@ fn seed_legacy_custom_provider(config: &mut Config, stats: &mut MigrationStats) endpoint: trimmed.to_string(), auth_style: AuthStyle::Bearer, default_model, + oci: None, }); stats.cloud_providers_seeded += 1; log::info!( @@ -123,6 +124,8 @@ static HOSTED_CLOUD_IDENTITY: HookSlot = static HOSTED_AUTH_STYLE: HookSlot = HookSlot::new("config::hosted_auth_style"); +pub use super::oci_settings::{OciAuthMode, OciProviderSettings, OciTransportKind}; + /// A built-in cloud provider preset in the host's [`AuthStyle`] vocabulary. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BuiltinCloudProvider { @@ -199,6 +202,7 @@ impl From<&tinyinference_providers::builtin::BuiltinCloudProvider> for BuiltinCl auth_style: match preset.auth_style { BuiltinAuthStyle::Bearer => AuthStyle::Bearer, BuiltinAuthStyle::Anthropic => AuthStyle::Anthropic, + BuiltinAuthStyle::Oci => AuthStyle::Oci, }, } } @@ -243,6 +247,7 @@ pub fn builtin_presets() -> BuiltinPresets { // converted into runtime bearer authentication. auth_style: match preset.auth_style { AuthStyle::Anthropic => BuiltinAuthStyle::Anthropic, + AuthStyle::Oci => BuiltinAuthStyle::Oci, AuthStyle::Bearer | AuthStyle::OpenhumanJwt | AuthStyle::None => { BuiltinAuthStyle::Bearer } @@ -283,6 +288,9 @@ pub enum AuthStyle { OpenhumanJwt, /// No auth header — e.g. local Ollama. None, + /// OCI Generative AI. Authentication (API key, signed profile, session + /// token, or a principal) is described by [`CloudProviderCreds::oci`]. + Oci, } impl AuthStyle { @@ -293,8 +301,9 @@ impl AuthStyle { "anthropic" => Ok(Self::Anthropic), "openhuman_jwt" | "openhumanjwt" => Ok(Self::OpenhumanJwt), "none" => Ok(Self::None), + "oci" => Ok(Self::Oci), other => Err(format!( - "unknown auth_style '{}'; valid: bearer, anthropic, openhuman_jwt, none", + "unknown auth_style '{}'; valid: bearer, anthropic, openhuman_jwt, none, oci", other )), } @@ -306,6 +315,7 @@ impl AuthStyle { Self::Anthropic => "anthropic", Self::OpenhumanJwt => "openhuman_jwt", Self::None => "none", + Self::Oci => "oci", } } } @@ -341,6 +351,12 @@ pub struct CloudProviderCreds { // inference settings RPC depend on this field; replacement needs route migration. #[serde(default, skip_serializing_if = "Option::is_none")] pub default_model: Option, + + /// OCI Generative AI settings; only meaningful when + /// `auth_style == AuthStyle::Oci`. Non-secret: the API key (api_key mode) + /// stays in the credential store. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oci: Option, } impl Default for CloudProviderCreds { @@ -352,6 +368,7 @@ impl Default for CloudProviderCreds { endpoint: String::new(), auth_style: AuthStyle::Bearer, default_model: None, + oci: None, } } } diff --git a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs index 346b4a76037..2dd9ce433cc 100644 --- a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs +++ b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs @@ -1,6 +1,9 @@ //! Tests for the surrounding module. -use super::{builtin_cloud_providers, builtin_presets, is_slug_reserved, AuthStyle}; +use super::{ + builtin_cloud_providers, builtin_presets, is_slug_reserved, AuthStyle, CloudProviderCreds, + OciAuthMode, OciTransportKind, +}; use tinyinference_providers::builtin::endpoint_host; #[test] @@ -23,7 +26,7 @@ fn auth_style_parse_accepts_rpc_spellings_and_preserves_unknown_error() { } assert_eq!( AuthStyle::parse("Strange").unwrap_err(), - "unknown auth_style 'strange'; valid: bearer, anthropic, openhuman_jwt, none" + "unknown auth_style 'strange'; valid: bearer, anthropic, openhuman_jwt, none, oci" ); } @@ -376,7 +379,111 @@ fn builtin_table_is_only_the_upstream_provider_catalog() { let expected = match upstream.auth_style { tinyinference_providers::builtin::BuiltinAuthStyle::Bearer => AuthStyle::Bearer, tinyinference_providers::builtin::BuiltinAuthStyle::Anthropic => AuthStyle::Anthropic, + tinyinference_providers::builtin::BuiltinAuthStyle::Oci => AuthStyle::Oci, }; assert_eq!(mapped.auth_style, expected, "{}", mapped.slug); } } + +#[test] +fn auth_style_parse_accepts_oci_and_the_existing_styles() { + for (wire, style) in [ + ("oci", AuthStyle::Oci), + ("OCI", AuthStyle::Oci), + ("bearer", AuthStyle::Bearer), + ("anthropic", AuthStyle::Anthropic), + ("openhumanjwt", AuthStyle::OpenhumanJwt), + ("none", AuthStyle::None), + ] { + assert_eq!(AuthStyle::parse(wire), Ok(style), "{wire}"); + } + assert_eq!(AuthStyle::Oci.as_str(), "oci"); +} + +#[test] +fn auth_style_parse_error_lists_oci_among_the_valid_values() { + let error = AuthStyle::parse("Basic").unwrap_err(); + assert!(error.contains("unknown auth_style 'basic'"), "{error}"); + assert!(error.contains("oci"), "{error}"); +} + +#[test] +fn oci_provider_entry_survives_the_rpc_payload_shape() { + // The settings panel echoes the whole entry back on every save; the OCI + // block must deserialize into the entry type unchanged. + let entry: CloudProviderCreds = serde_json::from_value(serde_json::json!({ + "id": "p_oci_1", + "slug": "oci", + "label": "OCI Generative AI", + "endpoint": "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", + "auth_style": "oci", + "oci": { + "auth_mode": "config_profile", + "profile": "DEFAULT", + "region": "us-chicago-1", + "compartment_id": "ocid1.compartment.oc1..example", + "transport": "native_cohere" + } + })) + .expect("entry deserializes"); + let oci = entry.oci.expect("oci block"); + assert_eq!(oci.auth_mode, OciAuthMode::ConfigProfile); + assert_eq!(oci.transport, OciTransportKind::NativeCohere); + assert_eq!(oci.profile.as_deref(), Some("DEFAULT")); +} + +#[test] +fn documented_toml_oci_entries_deserialize() { + #[derive(serde::Deserialize)] + struct Doc { + cloud_providers: Vec, + } + let doc: Doc = toml::from_str( + r#" +[[cloud_providers]] +slug = "oci-cohere" +auth_style = "oci" +[cloud_providers.oci] +auth_mode = "config_profile" +config_file = "~/.oci/config" +profile = "DEFAULT" +compartment_id = "ocid1.compartment.oc1..example" +transport = "native_cohere" + +[[cloud_providers]] +slug = "oci-principal" +auth_style = "oci" +[cloud_providers.oci] +auth_mode = "instance_principal" +region = "us-ashburn-1" +"#, + ) + .expect("documented config parses"); + assert_eq!(doc.cloud_providers.len(), 2); + assert_eq!(doc.cloud_providers[0].auth_style, AuthStyle::Oci); + let first = doc.cloud_providers[0].oci.as_ref().unwrap(); + assert_eq!(first.transport, OciTransportKind::NativeCohere); + let second = doc.cloud_providers[1].oci.as_ref().unwrap(); + assert_eq!(second.auth_mode, OciAuthMode::InstancePrincipal); + assert_eq!(second.transport, OciTransportKind::Openai); +} + +#[test] +fn oci_builtin_preset_maps_to_the_oci_auth_style() { + let preset = builtin_cloud_providers() + .into_iter() + .find(|p| p.slug == "oci") + .expect("oci preset"); + assert_eq!(preset.label, "OCI Generative AI"); + assert_eq!(preset.auth_style, AuthStyle::Oci); + for style in [ + AuthStyle::Bearer, + AuthStyle::Anthropic, + AuthStyle::OpenhumanJwt, + AuthStyle::None, + AuthStyle::Oci, + ] { + assert_eq!(AuthStyle::parse(style.as_str()), Ok(style)); + } + assert!(AuthStyle::parse("bogus").is_err()); +} diff --git a/crates/openhuman-core/src/config/schema/ephemeral_route.rs b/crates/openhuman-core/src/config/schema/ephemeral_route.rs index 21962090a01..89a234547fc 100644 --- a/crates/openhuman-core/src/config/schema/ephemeral_route.rs +++ b/crates/openhuman-core/src/config/schema/ephemeral_route.rs @@ -202,6 +202,7 @@ pub fn apply(config: &mut crate::config::Config, route: EphemeralRoute) { endpoint: route.endpoint.clone(), auth_style: AuthStyle::Bearer, default_model: Some(model.clone()), + oci: None, }); config.chat_provider = Some(provider_string.clone()); diff --git a/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs b/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs index 80a1bda5c81..a4468f79b9e 100644 --- a/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs @@ -21,6 +21,7 @@ async fn a_brand_new_workspace_persists_and_reopens_generic_config() { endpoint: "https://fixture.example/v1".to_string(), auth_style: crate::config::schema::AuthStyle::Bearer, default_model: None, + oci: None, }); true }), diff --git a/crates/openhuman-core/src/config/schema/load_migration_tests.rs b/crates/openhuman-core/src/config/schema/load_migration_tests.rs index 83a982d94b8..1dd043b33e5 100644 --- a/crates/openhuman-core/src/config/schema/load_migration_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_migration_tests.rs @@ -386,6 +386,7 @@ fn migrate_cloud_provider_slugs_routes_cloud_to_legacy_custom_when_primary_is_op endpoint: "https://api.example.com/v1/".into(), auth_style: crate::config::schema::AuthStyle::Bearer, default_model: Some("gpt-4o-mini".into()), + oci: None, }, ]; diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index 225358cb698..a02c6db1ea8 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -3,6 +3,7 @@ //! Split into submodules; this module re-exports the main `Config` and all public types. pub mod cloud_providers; +pub mod oci_settings; pub use cloud_providers::{generate_provider_id, is_slug_reserved, AuthStyle, CloudProviderCreds}; fn generate_provider_id_with_prefix(prefix: &str, slug: &str) -> String { diff --git a/crates/openhuman-core/src/config/schema/oci_settings.rs b/crates/openhuman-core/src/config/schema/oci_settings.rs new file mode 100644 index 00000000000..b6aea0a724c --- /dev/null +++ b/crates/openhuman-core/src/config/schema/oci_settings.rs @@ -0,0 +1,126 @@ +//! Non-secret settings for the OCI Generative AI cloud provider +//! ([`AuthStyle::Oci`](super::cloud_providers::AuthStyle::Oci)). +//! +//! These live on the `cloud_providers` entry (`CloudProviderCreds::oci`) and +//! are persisted in `config.toml`. The only secret an OCI entry can own is the +//! Generative AI API key used by [`OciAuthMode::ApiKey`]; it stays in the +//! credential store under `provider:`. Key material for the profile and +//! principal modes is never copied here: it is read from the OCI config +//! directory or the runtime environment when the model is built. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// How requests to OCI Generative AI authenticate. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum OciAuthMode { + /// Generative AI API key (`Authorization: Bearer`), stored in the keyring. + #[default] + ApiKey, + /// API-signing-key profile from the OCI config file (`~/.oci/config`). + ConfigProfile, + /// Session-token profile (`oci session authenticate`); token refreshes are + /// picked up without a restart. + SessionToken, + /// OCI resource principal (Functions, Container Instances, ...). + ResourcePrincipal, + /// OCI instance principal (compute instances). Needs `oci-principals`. + InstancePrincipal, + /// OKE workload identity. Needs `oci-principals`. + OkeWorkloadIdentity, +} + +impl OciAuthMode { + /// Stable wire / log name. + pub fn as_str(&self) -> &'static str { + match self { + Self::ApiKey => "api_key", + Self::ConfigProfile => "config_profile", + Self::SessionToken => "session_token", + Self::ResourcePrincipal => "resource_principal", + Self::InstancePrincipal => "instance_principal", + Self::OkeWorkloadIdentity => "oke_workload_identity", + } + } + + /// Whether this mode needs a key stored in the credential store. + pub fn needs_stored_key(&self) -> bool { + matches!(self, Self::ApiKey) + } + + /// Whether this mode reads a profile from the OCI config file. + pub fn uses_config_file(&self) -> bool { + matches!(self, Self::ConfigProfile | Self::SessionToken) + } +} + +/// Which wire protocol to speak to OCI Generative AI. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum OciTransportKind { + /// OpenAI-compatible `/openai/v1`. + #[default] + Openai, + /// OpenAI-compatible `/20231130/actions/v1`. + Actions, + /// Native chat API, `apiFormat: GENERIC` (Meta, xAI, Google, ...). + NativeGeneric, + /// Native chat API, `apiFormat: COHERE`. + NativeCohere, +} + +impl OciTransportKind { + /// Stable wire / log name. + pub fn as_str(&self) -> &'static str { + match self { + Self::Openai => "openai", + Self::Actions => "actions", + Self::NativeGeneric => "native_generic", + Self::NativeCohere => "native_cohere", + } + } + + /// Whether the transport is the native chat API (requires a compartment). + pub fn is_native(&self) -> bool { + matches!(self, Self::NativeGeneric | Self::NativeCohere) + } +} + +/// OCI-specific settings for an `auth_style = "oci"` provider entry. +/// +/// Every field is optional on the wire; the factory reports the first missing +/// required field by name when the model is built. +#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(default)] +pub struct OciProviderSettings { + /// Authentication mode. Defaults to `api_key`. + pub auth_mode: OciAuthMode, + /// OCI config file for the profile modes. Defaults to `$OCI_CLI_CONFIG_FILE` + /// or `~/.oci/config`. + #[serde(skip_serializing_if = "Option::is_none")] + pub config_file: Option, + /// Profile name inside the config file. Defaults to `DEFAULT`. + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, + /// OCI region, e.g. `us-chicago-1`. Falls back to the profile's region. + #[serde(skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Compartment OCID. Required for every transport except `openai` with + /// `api_key` auth, whose key already names one. + #[serde(skip_serializing_if = "Option::is_none")] + pub compartment_id: Option, + /// Generative AI project OCID, sent as `OpenAI-Project` on `/openai/v1`. + #[serde(skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Wire protocol. Defaults to `openai`. + pub transport: OciTransportKind, + /// Dedicated AI cluster endpoint OCID; when set the model is addressed + /// through it instead of on-demand by model id. + #[serde(skip_serializing_if = "Option::is_none")] + pub dedicated_endpoint_id: Option, +} + +#[cfg(test)] +#[path = "oci_settings_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/config/schema/oci_settings_tests.rs b/crates/openhuman-core/src/config/schema/oci_settings_tests.rs new file mode 100644 index 00000000000..6fc4a551c9f --- /dev/null +++ b/crates/openhuman-core/src/config/schema/oci_settings_tests.rs @@ -0,0 +1,83 @@ +use super::*; +use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds}; + +#[test] +fn defaults_are_api_key_over_openai() { + let settings = OciProviderSettings::default(); + assert_eq!(settings.auth_mode, OciAuthMode::ApiKey); + assert_eq!(settings.transport, OciTransportKind::Openai); + assert!(settings.auth_mode.needs_stored_key()); + assert!(!settings.transport.is_native()); +} + +#[test] +fn wire_names_round_trip_for_every_variant() { + for mode in [ + OciAuthMode::ApiKey, + OciAuthMode::ConfigProfile, + OciAuthMode::SessionToken, + OciAuthMode::ResourcePrincipal, + OciAuthMode::InstancePrincipal, + OciAuthMode::OkeWorkloadIdentity, + ] { + let json = serde_json::to_string(&mode).unwrap(); + assert_eq!(json, format!("\"{}\"", mode.as_str())); + assert_eq!(serde_json::from_str::(&json).unwrap(), mode); + } + for transport in [ + OciTransportKind::Openai, + OciTransportKind::Actions, + OciTransportKind::NativeGeneric, + OciTransportKind::NativeCohere, + ] { + let json = serde_json::to_string(&transport).unwrap(); + assert_eq!(json, format!("\"{}\"", transport.as_str())); + assert_eq!( + serde_json::from_str::(&json).unwrap(), + transport + ); + } +} + +#[test] +fn only_profile_modes_read_the_config_file() { + assert!(OciAuthMode::ConfigProfile.uses_config_file()); + assert!(OciAuthMode::SessionToken.uses_config_file()); + assert!(!OciAuthMode::ApiKey.uses_config_file()); + assert!(!OciAuthMode::ResourcePrincipal.uses_config_file()); +} + +#[test] +fn provider_entry_round_trips_with_oci_settings() { + let entry = CloudProviderCreds { + id: "p_oci_1".into(), + slug: "oci".into(), + label: "OCI Generative AI".into(), + endpoint: String::new(), + auth_style: AuthStyle::Oci, + oci: Some(OciProviderSettings { + auth_mode: OciAuthMode::SessionToken, + profile: Some("SESSION".into()), + region: Some("us-chicago-1".into()), + compartment_id: Some("ocid1.compartment.oc1..example".into()), + transport: OciTransportKind::NativeGeneric, + ..Default::default() + }), + ..Default::default() + }; + let json = serde_json::to_value(&entry).unwrap(); + assert_eq!(json["auth_style"], "oci"); + assert_eq!(json["oci"]["auth_mode"], "session_token"); + assert_eq!(json["oci"]["transport"], "native_generic"); + assert!(json["oci"].get("project_id").is_none()); + let back: CloudProviderCreds = serde_json::from_value(json).unwrap(); + assert_eq!(back, entry); +} + +#[test] +fn legacy_entries_without_oci_deserialize_to_none() { + let entry: CloudProviderCreds = + serde_json::from_str(r#"{"id":"a","slug":"openai","endpoint":"https://x/v1"}"#).unwrap(); + assert!(entry.oci.is_none()); + assert!(serde_json::to_value(&entry).unwrap().get("oci").is_none()); +} diff --git a/crates/openhuman-core/src/config/schema/types/config.rs b/crates/openhuman-core/src/config/schema/types/config.rs index f1df89bbbc6..c424193aa4b 100644 --- a/crates/openhuman-core/src/config/schema/types/config.rs +++ b/crates/openhuman-core/src/config/schema/types/config.rs @@ -425,6 +425,8 @@ pub struct Config { // "openrouter:" → type=openrouter; Bearer auth // "orcarouter:" → type=orcarouter; Bearer auth (e.g. "orcarouter:orcarouter/auto") // "custom:" → type=custom; Bearer auth + // "oci:" → auth_style=oci; OCI Generative AI native provider + // (settings in `CloudProviderCreds::oci`, e.g. "oci:xai.grok-4") // "ollama:" → local Ollama at config.local_ai.base_url // // Per-workload fields default to None, which the factory treats as "cloud". diff --git a/crates/openhuman-core/src/config/schemas/controllers/inference.rs b/crates/openhuman-core/src/config/schemas/controllers/inference.rs index d94181acbc0..5c5c7fa92e8 100644 --- a/crates/openhuman-core/src/config/schemas/controllers/inference.rs +++ b/crates/openhuman-core/src/config/schemas/controllers/inference.rs @@ -119,24 +119,7 @@ pub(super) fn handle_update_model_settings( } else { e.endpoint }; - let auth_style = match e - .auth_style - .as_deref() - .unwrap_or(legacy_auth) - .to_ascii_lowercase() - .as_str() - { - "bearer" => AuthStyle::Bearer, - "anthropic" => AuthStyle::Anthropic, - "openhuman_jwt" | "openhumanjwt" => AuthStyle::OpenhumanJwt, - "none" => AuthStyle::None, - other => { - return Err(format!( - "unknown auth_style '{}'; valid: bearer, anthropic, openhuman_jwt, none", - other - )) - } - }; + let auth_style = AuthStyle::parse(e.auth_style.as_deref().unwrap_or(legacy_auth))?; let id = e .id .filter(|s| !s.trim().is_empty()) @@ -152,6 +135,7 @@ pub(super) fn handle_update_model_settings( endpoint, auth_style, default_model: e.default_model, + oci: e.oci, }; Ok(entry) }) diff --git a/crates/openhuman-core/src/config/schemas/helpers.rs b/crates/openhuman-core/src/config/schemas/helpers.rs index c8caa55c922..203b690dfb9 100644 --- a/crates/openhuman-core/src/config/schemas/helpers.rs +++ b/crates/openhuman-core/src/config/schemas/helpers.rs @@ -22,7 +22,7 @@ pub(super) struct CloudProviderUpdate { #[serde(default)] pub(super) label: Option, pub(super) endpoint: String, - /// Auth style: "bearer" | "anthropic" | "openhuman_jwt" | "none". + /// Auth style: "bearer" | "anthropic" | "openhuman_jwt" | "none" | "oci". #[serde(default)] pub(super) auth_style: Option, /// Optional PEM CA bundle for this provider. Empty string removes it. @@ -36,6 +36,9 @@ pub(super) struct CloudProviderUpdate { /// Legacy field — tolerated on read. #[serde(default)] pub(super) default_model: Option, + /// OCI Generative AI settings (`auth_style = "oci"` only). + #[serde(default)] + pub(super) oci: Option, } #[derive(Debug, Deserialize)] diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs index d12c8e4bc8b..d390aac4bda 100644 --- a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs +++ b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs @@ -96,7 +96,7 @@ pub(super) fn lookup(function: &str) -> Option { FieldSchema { name: "cloud_providers", ty: TypeSchema::Option(Box::new(TypeSchema::Json)), - comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style, ca_cert_pem}. The optional PEM CA bundle is trusted only for this provider; an empty string clears it. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.", + comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style, ca_cert_pem, oci?}. auth_style is one of bearer, anthropic, openhuman_jwt, none, oci; `oci` carries the non-secret OCI Generative AI settings {auth_mode, config_file, profile, region, compartment_id, project_id, transport, dedicated_endpoint_id}. The optional PEM CA bundle is trusted only for this provider; an empty string clears it. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.", required: false, }, optional_string( diff --git a/crates/openhuman-core/src/doctor/checks/inference_catalog.rs b/crates/openhuman-core/src/doctor/checks/inference_catalog.rs index abe93ac581f..5cab6133442 100644 --- a/crates/openhuman-core/src/doctor/checks/inference_catalog.rs +++ b/crates/openhuman-core/src/doctor/checks/inference_catalog.rs @@ -68,6 +68,7 @@ fn configured_entries(config: &crate::config::Config) -> Vec endpoint: config.api_url.clone().unwrap_or_default(), auth_style: AuthStyle::OpenhumanJwt, default_model: None, + oci: None, }); } entries @@ -115,6 +116,10 @@ async fn prepare( if entry.auth_style == AuthStyle::OpenhumanJwt { return Err(InspectionCatalogError::Unavailable); } + // OCI Generative AI has no OpenAI-style `/models` listing. + if entry.auth_style == AuthStyle::Oci { + return Err(InspectionCatalogError::NoCatalog); + } let endpoint = entry.endpoint.trim_end_matches('/'); let Ok(url) = reqwest::Url::parse(&format!("{endpoint}/models")) else { return Err(InspectionCatalogError::Unavailable); @@ -151,7 +156,7 @@ async fn prepare( .header("x-api-key", token) .header("anthropic-version", "2023-06-01"), AuthStyle::Bearer => request.bearer_auth(token), - AuthStyle::None | AuthStyle::OpenhumanJwt => request, + AuthStyle::None | AuthStyle::OpenhumanJwt | AuthStyle::Oci => request, }; } let response = request.send().await.map_err(|error| { diff --git a/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs index a568c544937..3cd20b581b1 100644 --- a/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs @@ -69,6 +69,7 @@ fn add_cloud_provider(config: &mut Config, slug: &str, endpoint: &str, model: &s endpoint: endpoint.to_string(), auth_style: AuthStyle::Bearer, default_model: Some(model.to_string()), + oci: None, }); } diff --git a/crates/openhuman-core/src/doctor/checks/inference_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_tests.rs index 333153a25ae..3f820a8746c 100644 --- a/crates/openhuman-core/src/doctor/checks/inference_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/inference_tests.rs @@ -203,6 +203,7 @@ async fn a_byok_cloud_fallback_without_a_key_reports_construction_failure() { endpoint: "https://doctor-test.invalid/v1".to_owned(), auth_style: AuthStyle::Bearer, default_model: Some("test-model".to_owned()), + oci: None, }]; config.vision_provider = Some("cloud".to_owned()); @@ -327,6 +328,7 @@ async fn inspection_reports_refresh_required_without_refreshing_or_publishing_se endpoint: "https://api.openai.invalid/v1".to_owned(), auth_style: AuthStyle::Bearer, default_model: Some("gpt-4o".to_owned()), + oci: None, }]; config.resolved_endpoints.control_plane_url = Some("https://api.openhuman.invalid".to_owned()); @@ -509,6 +511,7 @@ async fn a_fully_configured_managed_default_constructs_cleanly() { endpoint: "https://api.openhuman.invalid/v1".to_owned(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("managed-test-model".to_owned()), + oci: None, }]; let before = filesystem_snapshot(temp.path()); let core_context = crate::core::runtime::CoreContext::for_test_with_extensions( @@ -558,6 +561,7 @@ async fn missing_byok_model_is_reported_by_the_native_construct_check() { endpoint: "https://provider.example.invalid/v1".to_owned(), auth_style: AuthStyle::Bearer, default_model: None, + oci: None, }]; let findings = run_only(config, CONSTRUCT).await; diff --git a/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs b/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs index 77b218e0f71..7de368c31f7 100644 --- a/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs @@ -114,6 +114,7 @@ fn config_for_catalog( endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }]; (root, config) } diff --git a/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs b/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs index 89b2fb998e7..929993f65de 100644 --- a/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs +++ b/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs @@ -119,6 +119,7 @@ pub(super) fn config_for_catalog( endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }]; (root, config) } diff --git a/crates/openhuman-core/src/doctor/inference_catalog_tests.rs b/crates/openhuman-core/src/doctor/inference_catalog_tests.rs index b18043fe8a9..ba40116acc6 100644 --- a/crates/openhuman-core/src/doctor/inference_catalog_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_catalog_tests.rs @@ -119,6 +119,7 @@ fn config_for_catalog( endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }]; (root, config) } @@ -416,6 +417,7 @@ async fn prepared_catalog_identity_changes_when_managed_credential_rotates_in_pl endpoint: endpoint.clone(), auth_style: AuthStyle::OpenhumanJwt, default_model: None, + oci: None, }]; let mut config_b = config_a.clone(); config_b.api_key = Some("fixture-managed-credential-b".into()); @@ -479,6 +481,7 @@ async fn a_slow_provider_times_out_without_blocking_the_other_catalog() { endpoint: slow_endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }, CloudProviderCreds { id: "p_doctor_497_fast".into(), @@ -487,6 +490,7 @@ async fn a_slow_provider_times_out_without_blocking_the_other_catalog() { endpoint: fast_endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }, ]; diff --git a/crates/openhuman-core/src/doctor/inference_config_tests.rs b/crates/openhuman-core/src/doctor/inference_config_tests.rs index c8a41016e41..b6861d271bb 100644 --- a/crates/openhuman-core/src/doctor/inference_config_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_config_tests.rs @@ -118,6 +118,7 @@ async fn a_byok_cloud_fallback_without_a_key_reports_construction_failure() { endpoint: "https://doctor-test.invalid/v1".to_owned(), auth_style: AuthStyle::Bearer, default_model: Some("test-model".to_owned()), + oci: None, }]; config.vision_provider = Some("cloud".to_owned()); @@ -248,6 +249,7 @@ async fn a_fully_configured_managed_default_constructs_cleanly() { endpoint: "https://api.openhuman.invalid/v1".to_owned(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("managed-test-model".to_owned()), + oci: None, }]; let before = filesystem_snapshot(temp.path()); let core_context = crate::core::runtime::CoreContext::for_test_with_extensions( diff --git a/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs b/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs index 01b41a718e2..3a04f4cb0ab 100644 --- a/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs @@ -120,6 +120,7 @@ fn config_for_catalog( endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }]; (root, config) } diff --git a/crates/openhuman-core/src/doctor/tools_tests.rs b/crates/openhuman-core/src/doctor/tools_tests.rs index a761e4c28f1..771a0063521 100644 --- a/crates/openhuman-core/src/doctor/tools_tests.rs +++ b/crates/openhuman-core/src/doctor/tools_tests.rs @@ -202,6 +202,7 @@ async fn models_tool_reports_each_configured_catalog_outcome() { endpoint: format!("{}/available/v1", server.uri()), auth_style: crate::config::schema::cloud_providers::AuthStyle::None, default_model: None, + oci: None, }, crate::config::schema::cloud_providers::CloudProviderCreds { id: "p_doctor_tool_models_missing".into(), @@ -210,6 +211,7 @@ async fn models_tool_reports_each_configured_catalog_outcome() { endpoint: format!("{}/missing/v1", server.uri()), auth_style: crate::config::schema::cloud_providers::AuthStyle::None, default_model: None, + oci: None, }, ]; diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rs index 5745824cbd9..72a10165a2b 100644 --- a/crates/openhuman-core/src/inference/provider/factory.rs +++ b/crates/openhuman-core/src/inference/provider/factory.rs @@ -19,6 +19,7 @@ mod credentials; mod inspection; mod local_runtime; mod managed_backend; +mod oci; mod routing; mod subprocess_providers; diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs index 9d9700e1af8..e8af641ec93 100644 --- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs +++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs @@ -259,7 +259,7 @@ pub(super) fn resolve_cloud_slug_with_access<'a>( // never trip this. if (implicit_fallback || credential_access.is_inspection()) && key.trim().is_empty() - && matches!(entry.auth_style, AuthStyle::Bearer | AuthStyle::Anthropic) + && super::oci::entry_requires_stored_key(entry) { anyhow::bail!("{}", missing_credentials()); } @@ -592,6 +592,35 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too ); } AuthStyle::Anthropic | AuthStyle::None => {} + AuthStyle::Oci => { + // OCI Generative AI: the native provider (API key, signed + // profile, session token, or principal), not the OpenAI-compatible + // builder below. Disclose the egress like every other BYOK slug. + crate::security::egress::emit_external_transfer_in( + egress, + crate::security::egress::EgressDescriptor::inference(&slug, &effective_model, true), + ); + return Some( + super::oci::build_oci_chat_model( + &slug, + entry, + key.as_str(), + &effective_model, + temperature_override, + ) + .map(|(chat, endpoint)| { + if let Some(identity) = inspection_identity { + *identity = Some(( + endpoint, + key.clone(), + effective_model.clone(), + InspectionOutputBudgetCapability::Bounded, + )); + } + (chat, effective_model.clone()) + }), + ); + } style if crate::config::schema::cloud_providers::is_hosted_auth_style_for( extensions, style, @@ -701,7 +730,7 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too None => None, }; let auth_style = cloud_spec::registry_auth_style(entry.auth_style) - .expect("managed JWT entries returned above"); + .expect("managed JWT and OCI entries returned above"); let chat = cloud_spec::build_cloud_model(cloud_spec::CloudBuild { spec: cloud_spec::cloud_provider_spec(entry, &effective_model), auth_style, diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_spec.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_spec.rs index 15af5e2e6d3..a2f0991548c 100644 --- a/crates/openhuman-core/src/inference/provider/factory/cloud_spec.rs +++ b/crates/openhuman-core/src/inference/provider/factory/cloud_spec.rs @@ -49,7 +49,9 @@ impl From for CompatAuthStyle { match style { AuthStyle::Bearer => Self::Bearer, AuthStyle::Anthropic => Self::Anthropic, - AuthStyle::None | AuthStyle::OpenhumanJwt => Self::None, + // OCI never reaches the compatible registry; its listing and + // models go through the native provider. + AuthStyle::None | AuthStyle::OpenhumanJwt | AuthStyle::Oci => Self::None, } } } @@ -61,7 +63,7 @@ pub(super) fn registry_auth_style(style: AuthStyle) -> Option { AuthStyle::Bearer => Some(CompatAuthStyle::Bearer), AuthStyle::Anthropic => Some(CompatAuthStyle::Anthropic), AuthStyle::None => Some(CompatAuthStyle::None), - AuthStyle::OpenhumanJwt => None, + AuthStyle::OpenhumanJwt | AuthStyle::Oci => None, } } diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_spec_tests.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_spec_tests.rs index e77502eb88b..29bc57b1cba 100644 --- a/crates/openhuman-core/src/inference/provider/factory/cloud_spec_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory/cloud_spec_tests.rs @@ -59,7 +59,9 @@ fn managed_jwt_style_never_maps_onto_the_registry() { #[test] fn registry_builds_a_model_for_every_unmanaged_builtin_preset() { for preset in crate::config::schema::cloud_providers::builtin_cloud_providers().iter() { - if preset.auth_style == AuthStyle::OpenhumanJwt { + // The managed route and OCI (its own native provider) never reach the + // compatible registry. + if matches!(preset.auth_style, AuthStyle::OpenhumanJwt | AuthStyle::Oci) { continue; } let creds = entry(preset.slug, preset.endpoint, preset.auth_style); @@ -104,3 +106,10 @@ fn discovery_request_uses_x_api_key_for_anthropic_and_skips_codex_oauth() { with_oauth.codex = Some(&oauth); assert!(cloud_discovery_request(&with_oauth).is_none()); } + +#[test] +fn oci_has_no_compatible_registry_auth_style() { + assert_eq!(registry_auth_style(AuthStyle::Oci), None); + assert_eq!(registry_auth_style(AuthStyle::OpenhumanJwt), None); + assert!(registry_auth_style(AuthStyle::Bearer).is_some()); +} diff --git a/crates/openhuman-core/src/inference/provider/factory/oci.rs b/crates/openhuman-core/src/inference/provider/factory/oci.rs new file mode 100644 index 00000000000..48db00d0948 --- /dev/null +++ b/crates/openhuman-core/src/inference/provider/factory/oci.rs @@ -0,0 +1,294 @@ +//! OCI Generative AI cloud slug (`auth_style = "oci"`): maps the non-secret +//! [`OciProviderSettings`] on a `cloud_providers` entry, plus the optional +//! keyring API key, onto a crate-native [`OciConfig`] and builds the model. +//! +//! Secrets: only `api_key` mode carries one, and it arrives as the `key` +//! argument (read from the credential store by `lookup_key_for_slug`). The +//! profile modes read key material from the OCI config directory when the +//! model is built and never copy it into OpenHuman config. Nothing here logs +//! a key, a token, or a key-file's contents. + +use super::*; +use crate::config::schema::cloud_providers::{ + builtin_cloud_provider, CloudProviderCreds, OciAuthMode, OciProviderSettings, OciTransportKind, +}; +use std::path::PathBuf; +use tinyinference_llm::providers::oci::{ + build_oci_model, default_config_path, load_profile, OciApiFormat, OciAuth, OciConfig, + OciOpenAiBase, OciServing, OciTransport, +}; + +/// Whether `entry` needs a key in the credential store to be usable. +/// +/// `Bearer` / `Anthropic` always do; `Oci` only in `api_key` mode (an entry +/// with no `oci` block defaults to `api_key`). Drives the implicit-fallback +/// missing-key diagnostic in `resolve_cloud_slug`. +pub(super) fn entry_requires_stored_key(entry: &CloudProviderCreds) -> bool { + match entry.auth_style { + AuthStyle::Bearer | AuthStyle::Anthropic => true, + AuthStyle::Oci => entry + .oci + .as_ref() + .map_or(OciAuthMode::default(), |s| s.auth_mode) + .needs_stored_key(), + AuthStyle::OpenhumanJwt | AuthStyle::None => false, + } +} + +fn non_empty(value: &Option) -> Option { + value + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(str::to_string) +} + +/// Expands a leading `~`, `~/` or `~\` from `$HOME`, or `%USERPROFILE%` on +/// Windows, where `HOME` is usually unset. (Core code does not call +/// `dirs::home_dir()`: see `scripts/ci/check-saas-ambient.mjs`.) +fn expand_home(path: &str) -> PathBuf { + let rest = path + .strip_prefix("~/") + .or_else(|| path.strip_prefix("~\\")) + .or((path == "~").then_some("")); + let home = std::env::var_os("HOME") + .filter(|home| !home.is_empty()) + .or_else(|| std::env::var_os("USERPROFILE").filter(|home| !home.is_empty())) + .map(PathBuf::from); + match (rest, home) { + (Some(""), Some(home)) => home, + (Some(rest), Some(home)) => home.join(rest), + _ => PathBuf::from(path), + } +} + +fn config_path(slug: &str, settings: &OciProviderSettings) -> Result { + if let Some(path) = non_empty(&settings.config_file) { + return Ok(expand_home(&path)); + } + default_config_path().ok_or_else(|| { + format!( + "OCI provider '{slug}': cannot locate the OCI config file (no HOME); \ + set oci.config_file on the cloud_providers entry" + ) + }) +} + +/// Resolves credentials for `settings.auth_mode` into an [`OciAuth`] plus the +/// region the credential implies (profile region), if any. +fn resolve_auth( + slug: &str, + settings: &OciProviderSettings, + key: &str, +) -> Result<(OciAuth, Option), String> { + let mode = settings.auth_mode; + match mode { + OciAuthMode::ApiKey => { + let key = key.trim(); + if key.is_empty() { + return Err(format!( + "OCI provider '{slug}' (auth_mode=api_key) has no API key stored; \ + add the OCI Generative AI API key for this provider in Settings, \ + or switch oci.auth_mode to config_profile / session_token / a principal" + )); + } + Ok(( + OciAuth::ApiKey { + bearer: key.to_string(), + }, + None, + )) + } + OciAuthMode::ConfigProfile | OciAuthMode::SessionToken => { + let path = config_path(slug, settings)?; + let profile_name = + non_empty(&settings.profile).unwrap_or_else(|| "DEFAULT".to_string()); + log::debug!( + "[providers][oci] loading profile slug={slug} auth_mode={} profile={profile_name} config_file={}", + mode.as_str(), + path.display() + ); + let profile = load_profile(&path, &profile_name) + .map_err(|e| format!("OCI provider '{slug}' (auth_mode={}): {e}", mode.as_str()))?; + let is_session = matches!(profile.auth, OciAuth::SessionTokenFile { .. }); + match (mode, is_session) { + (OciAuthMode::SessionToken, false) => Err(format!( + "OCI provider '{slug}': profile '{profile_name}' has no security_token_file, \ + so it is not a session-token profile; run `oci session authenticate` or \ + set oci.auth_mode to config_profile" + )), + (OciAuthMode::ConfigProfile, true) => Err(format!( + "OCI provider '{slug}': profile '{profile_name}' is a session-token profile; \ + set oci.auth_mode to session_token" + )), + _ => Ok((profile.auth, profile.region)), + } + } + OciAuthMode::ResourcePrincipal => Ok((OciAuth::ResourcePrincipal, None)), + OciAuthMode::InstancePrincipal | OciAuthMode::OkeWorkloadIdentity => { + #[cfg(not(feature = "oci-principals"))] + { + Err(format!( + "OCI provider '{slug}': auth_mode={} is not supported in this build; \ + rebuild with the `oci-principals` cargo feature (needs OpenSSL), \ + or use api_key / config_profile / session_token / resource_principal", + mode.as_str() + )) + } + #[cfg(feature = "oci-principals")] + { + Ok(( + if mode == OciAuthMode::InstancePrincipal { + OciAuth::InstancePrincipal + } else { + OciAuth::OkeWorkloadIdentity + }, + None, + )) + } + } + } +} + +/// Maps an entry's OCI settings (and key, for `api_key` mode) to an +/// [`OciConfig`], reporting the first missing field by name. +pub(super) fn oci_config_from_entry( + slug: &str, + settings: &OciProviderSettings, + key: &str, + model: &str, +) -> Result { + let transport = match settings.transport { + OciTransportKind::Openai => OciTransport::OpenAiCompat { + base: OciOpenAiBase::OpenAi, + }, + OciTransportKind::Actions => OciTransport::OpenAiCompat { + base: OciOpenAiBase::Actions, + }, + OciTransportKind::NativeGeneric => OciTransport::Native { + api_format: OciApiFormat::Generic, + }, + OciTransportKind::NativeCohere => OciTransport::Native { + api_format: OciApiFormat::Cohere, + }, + }; + let compartment_id = non_empty(&settings.compartment_id); + // A GenAI API key carries its own compartment; IAM-signed calls must name + // one on every transport, `/openai/v1` included. + let needs_compartment = + settings.transport != OciTransportKind::Openai || settings.auth_mode != OciAuthMode::ApiKey; + if needs_compartment && compartment_id.is_none() { + return Err(format!( + "OCI provider '{slug}': transport '{}' with auth_mode={} requires oci.compartment_id (the compartment OCID)", + settings.transport.as_str(), + settings.auth_mode.as_str() + )); + } + + // OCI's OpenAI-compatible `/openai/v1` base serves requests in a + // Generative AI project, sent as `OpenAI-Project`. + let project_id = non_empty(&settings.project_id); + if settings.transport == OciTransportKind::Openai && project_id.is_none() { + return Err(format!( + "OCI provider '{slug}': transport 'openai' requires oci.project_id (the Generative AI project OCID)" + )); + } + + let (auth, profile_region) = resolve_auth(slug, settings, key)?; + let region = non_empty(&settings.region).or(profile_region); + if region.is_none() && matches!(settings.auth_mode, OciAuthMode::ApiKey) { + return Err(format!( + "OCI provider '{slug}' (auth_mode=api_key) requires oci.region (e.g. us-chicago-1)" + )); + } + + let serving = match non_empty(&settings.dedicated_endpoint_id) { + Some(endpoint_id) => OciServing::Dedicated { endpoint_id }, + None => OciServing::OnDemand, + }; + + let mut config = OciConfig::new(auth, model); + config.region = region; + config.transport = transport; + config.compartment_id = compartment_id; + config.project_id = project_id; + config.serving = serving; + Ok(config) +} + +/// Applies the entry's `endpoint` as the service host override: other OCI +/// realms, a private endpoint, or a local capture proxy (loopback http only). +/// A blank endpoint keeps the region-derived host, and so does the built-in +/// preset's URL: it is a display default (the `us-chicago-1` host), and +/// honouring it would send every region's requests to Chicago. +fn with_entry_endpoint(slug: &str, mut config: OciConfig, entry: &CloudProviderCreds) -> OciConfig { + let preset = builtin_cloud_provider("oci").map(|preset| preset.endpoint.trim_end_matches('/')); + config.endpoint = non_empty(&Some(entry.endpoint.clone())) + .filter(|endpoint| Some(endpoint.trim_end_matches('/')) != preset); + if config.endpoint.is_some() { + log::debug!("[providers][oci] slug={slug} using the entry endpoint override"); + } + config +} + +/// The complete [`OciConfig`] for an entry: its settings, the endpoint +/// override and the route's temperature override. +fn entry_oci_config( + slug: &str, + entry: &CloudProviderCreds, + settings: &OciProviderSettings, + key: &str, + model: &str, + temperature_override: Option, +) -> Result { + let mut config = with_entry_endpoint( + slug, + oci_config_from_entry(slug, settings, key, model)?, + entry, + ); + config.temperature_override = temperature_override; + Ok(config) +} + +/// Builds the OCI chat model for a resolved `oci` cloud slug, with the +/// service endpoint it calls (reported as the route's wire identity). +/// `temperature_override` is the route's `@` suffix, which wins +/// over the request's temperature as on every other cloud slug. +pub(super) fn build_oci_chat_model( + slug: &str, + entry: &CloudProviderCreds, + key: &str, + model: &str, + temperature_override: Option, +) -> anyhow::Result<(Arc>, String)> { + let settings = entry.oci.clone().unwrap_or_default(); + log::debug!( + "[providers][oci] building slug={slug} model={model} auth_mode={} transport={} dedicated={}", + settings.auth_mode.as_str(), + settings.transport.as_str(), + settings.dedicated_endpoint_id.is_some() + ); + let config = entry_oci_config(slug, entry, &settings, key, model, temperature_override) + .map_err(anyhow::Error::msg)?; + let endpoint = config + .service_endpoint() + .map_err(|e| anyhow::anyhow!("[chat-factory] OCI provider '{slug}': {e}"))?; + build_oci_model(config) + .map(|chat| (chat, endpoint)) + .map_err(|e| { + log::warn!( + "[providers][oci] build failed slug={slug} auth_mode={} transport={}", + settings.auth_mode.as_str(), + settings.transport.as_str() + ); + anyhow::anyhow!( + "[chat-factory] OCI provider '{slug}' (auth_mode={}, transport={}): {e}", + settings.auth_mode.as_str(), + settings.transport.as_str() + ) + }) +} + +#[cfg(test)] +#[path = "oci_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/inference/provider/factory/oci_tests.rs b/crates/openhuman-core/src/inference/provider/factory/oci_tests.rs new file mode 100644 index 00000000000..a5911037ef2 --- /dev/null +++ b/crates/openhuman-core/src/inference/provider/factory/oci_tests.rs @@ -0,0 +1,479 @@ +//! Tests for the OCI Generative AI cloud slug. +//! +//! No key material is committed: the OCI config's `key_file` holds a +//! placeholder. No test here touches the network: models are only +//! constructed. + +use super::*; +use crate::config::schema::cloud_providers::OciAuthMode; + +/// Contents of the profiles' `key_file`. Loading a profile only reads the +/// file; a key is parsed when a signed model is built, which these tests do +/// only through the session-token profile (its key is read per request). +const KEY_FILE_CONTENTS: &str = "placeholder key file, never parsed by these tests"; + +fn oci_entry(settings: OciProviderSettings) -> CloudProviderCreds { + CloudProviderCreds { + id: "p_oci".into(), + slug: "oci".into(), + label: "OCI Generative AI".into(), + endpoint: "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com".into(), + auth_style: AuthStyle::Oci, + oci: Some(settings), + ..Default::default() + } +} + +fn api_key_settings() -> OciProviderSettings { + OciProviderSettings { + auth_mode: OciAuthMode::ApiKey, + region: Some("us-chicago-1".into()), + project_id: Some("ocid1.generativeaiproject.test".into()), + ..Default::default() + } +} + +/// A temp `~/.oci`-shaped directory: a DEFAULT API-key profile, and a SESSION +/// profile that points at (not-yet-existing) token files. +fn oci_dir() -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let key = dir.path().join("key.pem"); + std::fs::write(&key, KEY_FILE_CONTENTS).expect("write key"); + let config = dir.path().join("config"); + std::fs::write( + &config, + format!( + "[DEFAULT]\nuser=ocid1.user.test\nfingerprint=aa:bb:cc\ntenancy=ocid1.tenancy.test\n\ + region=eu-frankfurt-1\nkey_file={key}\n\n\ + [SESSION]\nsecurity_token_file={token}\nkey_file={key}\nregion=us-ashburn-1\n", + key = key.display(), + token = dir.path().join("token").display(), + ), + ) + .expect("write config"); + (dir, config) +} + +fn profile_settings( + mode: OciAuthMode, + config: &std::path::Path, + profile: &str, +) -> OciProviderSettings { + OciProviderSettings { + auth_mode: mode, + config_file: Some(config.display().to_string()), + profile: Some(profile.into()), + compartment_id: Some("ocid1.compartment.test".into()), + project_id: Some("ocid1.generativeaiproject.test".into()), + ..Default::default() + } +} + +#[test] +fn api_key_mode_builds_over_each_transport() { + for (transport, needs_compartment) in [ + (OciTransportKind::Openai, false), + (OciTransportKind::Actions, true), + (OciTransportKind::NativeGeneric, true), + (OciTransportKind::NativeCohere, true), + ] { + let mut settings = api_key_settings(); + settings.transport = transport; + settings.compartment_id = needs_compartment.then(|| "ocid1.compartment.test".to_string()); + let entry = oci_entry(settings); + build_oci_chat_model("oci", &entry, "genai-key-not-real", "openai.gpt-5.5", None) + .unwrap_or_else(|e| panic!("{} must build: {e}", transport.as_str())); + } +} + +#[test] +fn api_key_mode_without_a_key_names_the_problem() { + let entry = oci_entry(api_key_settings()); + let error = build_oci_chat_model("oci", &entry, " ", "openai.gpt-5.5", None) + .err() + .expect("missing key must fail") + .to_string(); + assert!(error.contains("no API key stored"), "{error}"); + assert!(error.contains("'oci'"), "{error}"); +} + +#[test] +fn api_key_mode_requires_a_region() { + let mut settings = api_key_settings(); + settings.region = None; + let error = oci_config_from_entry("oci", &settings, "k", "m").unwrap_err(); + assert!(error.contains("oci.region"), "{error}"); +} + +#[test] +fn native_and_actions_transports_require_a_compartment() { + for transport in [ + OciTransportKind::Actions, + OciTransportKind::NativeGeneric, + OciTransportKind::NativeCohere, + ] { + let mut settings = api_key_settings(); + settings.transport = transport; + let error = oci_config_from_entry("oci", &settings, "k", "m").unwrap_err(); + assert!(error.contains("oci.compartment_id"), "{error}"); + assert!(error.contains(transport.as_str()), "{error}"); + } +} + +#[test] +fn signed_auth_on_the_openai_transport_requires_a_compartment() { + let (_dir, config_file) = oci_dir(); + let mut settings = profile_settings(OciAuthMode::ConfigProfile, &config_file, "DEFAULT"); + settings.transport = OciTransportKind::Openai; + settings.compartment_id = None; + let error = oci_config_from_entry("oci", &settings, "", "m").unwrap_err(); + assert!(error.contains("oci.compartment_id"), "{error}"); + assert!(error.contains("auth_mode=config_profile"), "{error}"); + + settings.compartment_id = Some("ocid1.compartment.test".into()); + let config = oci_config_from_entry("oci", &settings, "", "m").unwrap(); + assert_eq!( + config.compartment_id.as_deref(), + Some("ocid1.compartment.test") + ); +} + +#[test] +fn project_and_dedicated_endpoint_are_carried_into_the_config() { + let mut settings = api_key_settings(); + settings.project_id = Some(" ocid1.project.test ".into()); + settings.dedicated_endpoint_id = Some("ocid1.endpoint.test".into()); + let config = oci_config_from_entry("oci", &settings, "k", "cohere.command-a-03-2025").unwrap(); + assert_eq!(config.project_id.as_deref(), Some("ocid1.project.test")); + assert_eq!( + config.serving, + OciServing::Dedicated { + endpoint_id: "ocid1.endpoint.test".into() + } + ); + assert_eq!(config.model, "cohere.command-a-03-2025"); +} + +#[test] +fn entry_endpoint_overrides_the_region_host() { + let mut entry = oci_entry(api_key_settings()); + entry.endpoint = " https://genai.private.example.oraclecloud.com ".into(); + let config = oci_config_from_entry("oci", &api_key_settings(), "k", "m").unwrap(); + let config = with_entry_endpoint("oci", config, &entry); + assert_eq!( + config.endpoint.as_deref(), + Some("https://genai.private.example.oraclecloud.com") + ); +} + +#[test] +fn the_openai_transport_requires_a_project() { + for project in [None, Some(" ".to_string())] { + let mut settings = api_key_settings(); + settings.project_id = project; + let error = oci_config_from_entry("oci", &settings, "k", "m").unwrap_err(); + assert!(error.contains("oci.project_id"), "{error}"); + } + let mut settings = api_key_settings(); + settings.project_id = None; + settings.transport = OciTransportKind::NativeGeneric; + settings.compartment_id = Some("ocid1.compartment.test".into()); + oci_config_from_entry("oci", &settings, "k", "m").expect("only /openai/v1 needs a project"); +} + +#[test] +fn the_builtin_preset_endpoint_keeps_the_region_host() { + let mut settings = api_key_settings(); + settings.region = Some("eu-frankfurt-1".into()); + for endpoint in [ + "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", + "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/", + ] { + let mut entry = oci_entry(settings.clone()); + entry.endpoint = endpoint.into(); + let config = oci_config_from_entry("oci", &settings, "k", "m").unwrap(); + let config = with_entry_endpoint("oci", config, &entry); + assert_eq!(config.endpoint, None, "{endpoint}"); + assert_eq!(config.region.as_deref(), Some("eu-frankfurt-1")); + } +} + +#[test] +fn the_route_temperature_override_reaches_the_config() { + let settings = api_key_settings(); + let entry = oci_entry(settings.clone()); + let config = entry_oci_config("oci", &entry, &settings, "k", "m", Some(0.2)).unwrap(); + assert_eq!(config.temperature_override, Some(0.2)); + let config = entry_oci_config("oci", &entry, &settings, "k", "m", None).unwrap(); + assert_eq!(config.temperature_override, None); +} + +#[test] +fn blank_entry_endpoint_keeps_the_region_host() { + let mut entry = oci_entry(api_key_settings()); + entry.endpoint = " ".into(); + let config = oci_config_from_entry("oci", &api_key_settings(), "k", "m").unwrap(); + assert_eq!(with_entry_endpoint("oci", config, &entry).endpoint, None); +} + +#[test] +fn entry_endpoint_override_must_be_https_or_loopback() { + let mut entry = oci_entry(api_key_settings()); + entry.endpoint = "http://127.0.0.1:18766".into(); + build_oci_chat_model("oci", &entry, "genai-key-not-real", "openai.gpt-5.5", None) + .unwrap_or_else(|e| panic!("a loopback capture proxy must build: {e}")); + + entry.endpoint = "http://genai.example.com".into(); + let error = build_oci_chat_model("oci", &entry, "genai-key-not-real", "openai.gpt-5.5", None) + .err() + .expect("plain http to a remote host must fail") + .to_string(); + assert!(error.contains("https://"), "{error}"); + assert!(error.contains("'oci'"), "{error}"); +} + +#[test] +fn config_profile_reads_the_profile_and_inherits_its_region() { + let (_dir, config) = oci_dir(); + let settings = profile_settings(OciAuthMode::ConfigProfile, &config, "DEFAULT"); + let built = oci_config_from_entry("oci", &settings, "", "openai.gpt-5.5").unwrap(); + assert_eq!(built.region.as_deref(), Some("eu-frankfurt-1")); + assert!(matches!(built.auth, OciAuth::UserPrincipal { .. })); +} + +#[test] +fn explicit_region_overrides_the_profile_region() { + let (_dir, config) = oci_dir(); + let mut settings = profile_settings(OciAuthMode::ConfigProfile, &config, "DEFAULT"); + settings.region = Some("us-chicago-1".into()); + let built = oci_config_from_entry("oci", &settings, "", "m").unwrap(); + assert_eq!(built.region.as_deref(), Some("us-chicago-1")); +} + +#[test] +fn session_token_mode_uses_the_token_file_profile() { + let (_dir, config) = oci_dir(); + let settings = profile_settings(OciAuthMode::SessionToken, &config, "SESSION"); + let built = oci_config_from_entry("oci", &settings, "", "m").unwrap(); + assert!(matches!(built.auth, OciAuth::SessionTokenFile { .. })); + assert_eq!(built.region.as_deref(), Some("us-ashburn-1")); + build_oci_chat_model("oci", &oci_entry(settings), "", "openai.gpt-5.5", None).expect("builds"); +} + +#[test] +fn profile_kind_must_match_the_auth_mode() { + let (_dir, config) = oci_dir(); + let error = oci_config_from_entry( + "oci", + &profile_settings(OciAuthMode::SessionToken, &config, "DEFAULT"), + "", + "m", + ) + .unwrap_err(); + assert!(error.contains("not a session-token profile"), "{error}"); + let error = oci_config_from_entry( + "oci", + &profile_settings(OciAuthMode::ConfigProfile, &config, "SESSION"), + "", + "m", + ) + .unwrap_err(); + assert!( + error.contains("set oci.auth_mode to session_token"), + "{error}" + ); +} + +#[test] +fn missing_profile_and_missing_file_are_reported_with_the_provider_slug() { + let (dir, config) = oci_dir(); + let error = oci_config_from_entry( + "oci", + &profile_settings(OciAuthMode::ConfigProfile, &config, "NOPE"), + "", + "m", + ) + .unwrap_err(); + assert!(error.contains("'oci'") && error.contains("NOPE"), "{error}"); + let error = oci_config_from_entry( + "oci", + &profile_settings( + OciAuthMode::ConfigProfile, + &dir.path().join("absent"), + "DEFAULT", + ), + "", + "m", + ) + .unwrap_err(); + assert!(error.contains("could not read OCI config"), "{error}"); +} + +#[test] +fn errors_never_contain_key_material() { + let (_dir, config) = oci_dir(); + let error = oci_config_from_entry( + "oci", + &profile_settings(OciAuthMode::SessionToken, &config, "DEFAULT"), + "", + "m", + ) + .unwrap_err(); + assert!(!error.contains(KEY_FILE_CONTENTS), "{error}"); +} + +#[cfg(not(feature = "oci-principals"))] +#[test] +fn principal_modes_are_unsupported_without_the_feature() { + for mode in [ + OciAuthMode::InstancePrincipal, + OciAuthMode::OkeWorkloadIdentity, + ] { + let settings = OciProviderSettings { + auth_mode: mode, + region: Some("us-chicago-1".into()), + compartment_id: Some("ocid1.compartment.test".into()), + project_id: Some("ocid1.generativeaiproject.test".into()), + ..Default::default() + }; + let error = oci_config_from_entry("oci", &settings, "", "m").unwrap_err(); + assert!(error.contains("oci-principals"), "{error}"); + assert!(error.contains(mode.as_str()), "{error}"); + } +} + +#[test] +fn stored_key_is_required_only_for_api_key_mode() { + assert!(entry_requires_stored_key(&oci_entry(api_key_settings()))); + let mut no_block = oci_entry(api_key_settings()); + no_block.oci = None; + assert!(entry_requires_stored_key(&no_block)); + for mode in [ + OciAuthMode::ConfigProfile, + OciAuthMode::SessionToken, + OciAuthMode::ResourcePrincipal, + OciAuthMode::InstancePrincipal, + OciAuthMode::OkeWorkloadIdentity, + ] { + let mut settings = api_key_settings(); + settings.auth_mode = mode; + assert!(!entry_requires_stored_key(&oci_entry(settings)), "{mode:?}"); + } + let bearer = CloudProviderCreds { + auth_style: AuthStyle::Bearer, + ..Default::default() + }; + assert!(entry_requires_stored_key(&bearer)); +} + +#[tokio::test] +async fn oci_slug_routes_through_the_cloud_slug_factory() { + let _guard = crate::inference::inference_test_guard_async().await; + let (_dir, config_file) = oci_dir(); + let mut config = Config::default(); + config.cloud_providers.push(oci_entry(profile_settings( + OciAuthMode::SessionToken, + &config_file, + "SESSION", + ))); + let (_model, model_id) = + super::super::cloud_slug::try_create_cloud_slug_chat_model_from_string_with_native_tools( + "chat", + "oci:cohere.command-a-03-2025", + &config, + true, + &crate::security::egress::EgressLedger::none(), + ) + .await + .expect("oci slug is a configured cloud provider") + .expect("model builds from a session-token profile"); + assert_eq!(model_id, "cohere.command-a-03-2025"); +} + +#[tokio::test] +async fn oci_slug_with_a_missing_compartment_fails_through_the_factory() { + let _guard = crate::inference::inference_test_guard_async().await; + let mut settings = api_key_settings(); + settings.transport = OciTransportKind::NativeGeneric; + let mut config = Config::default(); + config.cloud_providers.push(oci_entry(settings)); + let error = + match super::super::cloud_slug::try_create_cloud_slug_chat_model_from_string_with_native_tools( + "chat", + "oci:openai.gpt-5.5", + &config, + true, + &crate::security::egress::EgressLedger::none(), + ) + .await + .expect("oci slug is a configured cloud provider") + { + Err(error) => error.to_string(), + Ok(_) => panic!("a native transport without a compartment must not build"), + }; + assert!(error.contains("oci.compartment_id"), "{error}"); +} + +#[tokio::test] +async fn inspection_records_the_oci_wire_identity() { + let _guard = crate::inference::inference_test_guard_async().await; + let (_dir, config_file) = oci_dir(); + let mut config = Config::default(); + config.cloud_providers.push(oci_entry(profile_settings( + OciAuthMode::SessionToken, + &config_file, + "SESSION", + ))); + let mut identity = None; + // What the doctor's inspection path pre-resolves for a keyless OCI + // profile: `lookup_key_for_slug_read_only` finds no stored key. + let credential = super::super::credentials::ReadOnlyCloudCredential { + key: String::new(), + is_oauth: false, + account_id: None, + }; + super::super::cloud_slug::try_create_cloud_slug_chat_model_from_string_with_native_tools_and_access( + "chat", + "oci:cohere.command-a-03-2025", + &config, + true, + &crate::security::egress::EgressLedger::none(), + None, + super::super::credentials::CredentialAccess::Inspection, + Some(&credential), + Some(&mut identity), + ) + .await + .expect("oci slug is a configured cloud provider") + .expect("model builds from a session-token profile"); + let (endpoint, credential, model, _) = identity.expect("the OCI route records its identity"); + // The preset URL on the entry is ignored; the host follows the region. + assert_eq!( + endpoint, + "https://inference.generativeai.us-ashburn-1.oci.oraclecloud.com" + ); + assert!( + credential.is_empty(), + "a session-token profile stores no key" + ); + assert_eq!(model, "cohere.command-a-03-2025"); +} + +#[test] +fn home_relative_config_paths_expand_to_the_home_directory() { + let Some(home) = std::env::var_os("HOME") + .filter(|home| !home.is_empty()) + .or_else(|| std::env::var_os("USERPROFILE")) + .map(PathBuf::from) + else { + return; + }; + assert_eq!(expand_home("~"), home); + assert_eq!(expand_home("~/.oci/config"), home.join(".oci/config")); + assert_eq!(expand_home("~\\.oci\\config"), home.join(".oci\\config")); + assert_eq!( + expand_home("/etc/oci/config"), + PathBuf::from("/etc/oci/config") + ); + assert_eq!(expand_home("~user/config"), PathBuf::from("~user/config")); +} diff --git a/crates/openhuman-core/src/inference/provider/factory/routing.rs b/crates/openhuman-core/src/inference/provider/factory/routing.rs index 4471823ac10..a64c7066101 100644 --- a/crates/openhuman-core/src/inference/provider/factory/routing.rs +++ b/crates/openhuman-core/src/inference/provider/factory/routing.rs @@ -203,6 +203,17 @@ pub(super) async fn route_has_usable_credentials(resolved: &str, config: &Config if let Some((slug, _)) = r.split_once(':') { let slug = slug.trim(); if !slug.is_empty() { + let keyless_oci = config.cloud_providers.iter().any(|entry| { + entry.slug == slug + && entry.auth_style == AuthStyle::Oci + && !super::oci::entry_requires_stored_key(entry) + }); + if keyless_oci { + log::debug!( + "[billing] route_has_usable_credentials slug={slug} usable=true (keyless oci)" + ); + return true; + } match lookup_key_for_slug(slug, config).await { Ok(key) => { let usable = !key.trim().is_empty(); diff --git a/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs b/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs index 2d0f60fc5df..aacb4be78b7 100644 --- a/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs @@ -280,3 +280,40 @@ fn default_model_with_bare_openai_keeps_managed_fallback() { "bare openai must resolve to the managed backend" ); } + +fn oci_entry(auth_mode: crate::config::schema::cloud_providers::OciAuthMode) -> CloudProviderCreds { + CloudProviderCreds { + id: "p_oci".to_string(), + slug: "oci".to_string(), + label: "OCI Generative AI".to_string(), + auth_style: AuthStyle::Oci, + oci: Some( + crate::config::schema::cloud_providers::OciProviderSettings { + auth_mode, + ..Default::default() + }, + ), + ..Default::default() + } +} + +/// OCI profile, session-token and principal modes keep no key in the +/// credential store, so the billing gate must not require one for them. +#[tokio::test] +async fn keyless_oci_routes_count_as_usable_credentials() { + use crate::config::schema::cloud_providers::OciAuthMode; + for mode in [ + OciAuthMode::ConfigProfile, + OciAuthMode::SessionToken, + OciAuthMode::ResourcePrincipal, + OciAuthMode::InstancePrincipal, + OciAuthMode::OkeWorkloadIdentity, + ] { + let mut config = Config::default(); + config.cloud_providers = vec![oci_entry(mode)]; + assert!( + route_has_usable_credentials("oci:openai.gpt-5.5", &config).await, + "{mode:?}" + ); + } +} diff --git a/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs b/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs index 6213884e7c2..acbf029dbec 100644 --- a/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs @@ -271,6 +271,7 @@ async fn hosted_cloud_slug_uses_explicit_auth_policy_and_model_entry() { endpoint: "https://hosted.example.test/v1".to_string(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("fixture/model-v1".to_string()), + oci: None, }); let observed = CoreContext::scope(context_b, async { diff --git a/crates/openhuman-core/src/inference/provider/factory_tests.rs b/crates/openhuman-core/src/inference/provider/factory_tests.rs index 03a8069daed..0307a89a2ac 100644 --- a/crates/openhuman-core/src/inference/provider/factory_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory_tests.rs @@ -112,6 +112,7 @@ fn fixture_managed_entry(id: &str) -> CloudProviderCreds { endpoint: "https://fixture.managed.test/v1".to_string(), auth_style: AuthStyle::OpenhumanJwt, default_model: Some("fixture/managed-default".into()), + oci: None, } } @@ -263,6 +264,7 @@ fn openai_entry(id: &str, slug: &str) -> CloudProviderCreds { endpoint: "https://api.openai.com/v1".to_string(), auth_style: AuthStyle::Bearer, default_model: Some("gpt-4o".to_string()), + oci: None, } } @@ -274,6 +276,7 @@ fn anthropic_entry(id: &str, slug: &str) -> CloudProviderCreds { endpoint: "https://api.anthropic.com/v1".to_string(), auth_style: AuthStyle::Anthropic, default_model: Some("claude-sonnet-4-6".to_string()), + oci: None, } } @@ -285,6 +288,7 @@ fn nvidia_nim_entry(id: &str, default_model: Option<&str>) -> CloudProviderCreds endpoint: "https://integrate.api.nvidia.com/v1".to_string(), auth_style: AuthStyle::Bearer, default_model: default_model.map(ToString::to_string), + oci: None, } } @@ -594,6 +598,7 @@ fn deepseek_entry(id: &str) -> CloudProviderCreds { endpoint: "https://api.deepseek.com/v1".to_string(), auth_style: AuthStyle::Bearer, default_model: Some("deepseek-chat".to_string()), + oci: None, } } diff --git a/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs b/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs index e091212f5a5..897aaab50be 100644 --- a/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs +++ b/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs @@ -122,6 +122,7 @@ pub(crate) async fn configure_openrouter_workspace( endpoint, auth_style: AuthStyle::Bearer, default_model: None, + oci: None, }); config.save().await.expect("save config"); @@ -188,6 +189,7 @@ pub(crate) async fn configure_generic_workspace(tmp: &TempDir, endpoint: String) endpoint, auth_style: AuthStyle::None, default_model: None, + oci: None, }); config.save().await.expect("save config"); config diff --git a/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs b/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs index a09b2591f15..ec00f928240 100644 --- a/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs +++ b/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs @@ -222,6 +222,21 @@ pub async fn list_configured_models_from_config( }; } + // OCI Generative AI signs (or bears an API key on) each request and its + // model catalog is a control-plane API, not an OpenAI `/models` route, so + // there is nothing to probe here. Return an empty list; the settings UI + // takes a typed OCI model id (e.g. `openai.gpt-5.5`). + if entry.auth_style == crate::config::schema::cloud_providers::AuthStyle::Oci { + log::debug!( + "[providers][list_models] oci slug={} model listing unavailable; returning empty list", + entry.slug + ); + return Ok(crate::core::Outcome::new( + serde_json::json!({ "models": Vec::::new() }), + vec!["OCI Generative AI model listing is not available; enter a model id".to_string()], + )); + } + // Sentry TAURI-RUST-114C/114D: the app stores Claude Code with the cosmetic // endpoint `cli://claude-code`. It runs as a local CLI and has no `/models` // listing, and reqwest cannot build a request for a non-http(s) URL, so the diff --git a/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs b/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs index 138f9c5e8d5..15f61eb7759 100644 --- a/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs +++ b/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs @@ -25,6 +25,7 @@ fn list_configured_models_accepts_slug() { endpoint: "https://api.openai.com/v1".to_string(), auth_style: AuthStyle::Bearer, default_model: None, + oci: None, }); // The find predicate must match on slug. diff --git a/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs b/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs index 05754fc6694..379e2b20127 100644 --- a/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs +++ b/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs @@ -181,6 +181,7 @@ fn cloud_providers_entry_takes_precedence_over_local_runtime_synthesis() { endpoint: "https://ollama.example.com/v1".to_string(), auth_style: AuthStyle::Bearer, default_model: None, + oci: None, }); let resolved = config @@ -242,3 +243,26 @@ fn missing_cloud_providers_entry_for_unknown_slug_still_errors() { "unknown slug with no cloud_providers entry must NOT synthesize", ); } + +#[tokio::test] +async fn oci_entries_answer_with_an_empty_catalog_without_a_network_request() { + // OCI Generative AI has no OpenAI-style `/models` route; the port would + // refuse a connection if the listing ever reached it. + let tmp = tempfile::tempdir().expect("tempdir"); + let mut config = configure_generic_workspace(&tmp, "http://127.0.0.1:0/v1".to_string()).await; + config.cloud_providers[0].auth_style = AuthStyle::Oci; + + let outcome = catalog_listing::list_configured_models_from_config("generic-test", &config) + .await + .expect("an OCI entry lists no models instead of failing"); + + assert_eq!(outcome.value["models"], serde_json::json!([])); + assert!( + outcome + .logs + .iter() + .any(|log| log.contains("enter a model id")), + "{:?}", + outcome.logs + ); +} diff --git a/crates/openhuman-core/src/inference/provider/models/local_runtime.rs b/crates/openhuman-core/src/inference/provider/models/local_runtime.rs index b4f64acfb8c..f4ed6aefdcc 100644 --- a/crates/openhuman-core/src/inference/provider/models/local_runtime.rs +++ b/crates/openhuman-core/src/inference/provider/models/local_runtime.rs @@ -51,5 +51,6 @@ pub fn synthesize_local_runtime_entry( // `AuthStyle::None` ignores it (see auth-style match below). auth_style: AuthStyle::None, default_model: None, + oci: None, }) } diff --git a/crates/openhuman-core/src/inference/provider/models/mod_tests.rs b/crates/openhuman-core/src/inference/provider/models/mod_tests.rs index dd8cb25424c..d5701c860a0 100644 --- a/crates/openhuman-core/src/inference/provider/models/mod_tests.rs +++ b/crates/openhuman-core/src/inference/provider/models/mod_tests.rs @@ -54,6 +54,7 @@ fn workspace_with_provider( endpoint: endpoint.to_string(), auth_style, default_model: None, + oci: None, }); config } diff --git a/crates/openhuman-core/src/inference/turn_models_native_tests.rs b/crates/openhuman-core/src/inference/turn_models_native_tests.rs index 97052a5d59d..12a5c481196 100644 --- a/crates/openhuman-core/src/inference/turn_models_native_tests.rs +++ b/crates/openhuman-core/src/inference/turn_models_native_tests.rs @@ -201,6 +201,7 @@ async fn native_turn_preserves_deepseek_route_metadata_after_cloud_resolution() endpoint: "https://api.deepseek.com/v1".into(), auth_style: AuthStyle::Bearer, default_model: Some("deepseek-chat".into()), + oci: None, }], ..crate::credentials::test_support::plaintext_fixture_config(tmp.path()) }; diff --git a/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs b/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs index 750a71b406f..b1593369bc5 100644 --- a/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs +++ b/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs @@ -58,6 +58,7 @@ async fn wire_models(summarizer_model: Option<&str>) -> WireModels { endpoint: format!("{}/api/v1", server.uri()), auth_style: AuthStyle::Bearer, default_model: Some(TURN_MODEL.into()), + oci: None, }); config.chat_provider = Some(format!("openrouter:{TURN_MODEL}")); config.context.summarizer_model = summarizer_model.map(str::to_owned); diff --git a/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs b/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs index 763e63f6ced..916afcd653f 100644 --- a/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs +++ b/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs @@ -71,7 +71,7 @@ Capability { name: "Configure AI", domain: "settings", category: CapabilityCategory::Settings, - description: "Configure managed, local, custom, and built-in BYOK LLM providers, including SumoPod and other OpenAI-compatible gateways. Custom providers can trust an uploaded PEM CA certificate for model listing and inference. Set per-workload routing preferences here too.", + description: "Configure managed, local, custom, and built-in BYOK LLM providers, including OCI Generative AI (API key, OCI config profile, session token, or principal auth), SumoPod and other OpenAI-compatible gateways. Custom providers can trust an uploaded PEM CA certificate for model listing and inference. Set per-workload routing preferences here too.", how_to: "Connections → API keys → LLM", status: CapabilityStatus::Stable, privacy: None, diff --git a/crates/openhuman-core/src/triage/routing_tests.rs b/crates/openhuman-core/src/triage/routing_tests.rs index 5a483158d3b..4e91d0d6d13 100644 --- a/crates/openhuman-core/src/triage/routing_tests.rs +++ b/crates/openhuman-core/src/triage/routing_tests.rs @@ -18,6 +18,7 @@ fn openai_entry(id: &str, slug: &str) -> CloudProviderCreds { endpoint: "https://api.openai.com/v1".to_string(), auth_style: AuthStyle::Bearer, default_model: Some("gpt-4o".to_string()), + oci: None, } } diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml index c4eb8aeb9b3..a86713ada8b 100644 --- a/crates/openhuman-embed/Cargo.toml +++ b/crates/openhuman-embed/Cargo.toml @@ -23,6 +23,7 @@ http-server = ["openhuman-core/http-server"] inference = ["openhuman-core/inference"] documents = ["openhuman-core/documents"] hosting = ["openhuman-core/hosting"] +oci-principals = ["openhuman-core/oci-principals"] inbound-queues = ["openhuman-core/inbound-queues"] modules = ["openhuman-core/modules", "tinybus/modules"] security-module = ["openhuman-core/security-module"] diff --git a/crates/openhuman-rpc/Cargo.toml b/crates/openhuman-rpc/Cargo.toml index 2e5d4331a4e..a88a2f9bd49 100644 --- a/crates/openhuman-rpc/Cargo.toml +++ b/crates/openhuman-rpc/Cargo.toml @@ -57,6 +57,7 @@ http-server = ["openhuman-tinyhumans/http-server"] inference = ["openhuman-tinyhumans/inference"] documents = ["openhuman-tinyhumans/documents"] hosting = ["openhuman-tinyhumans/hosting"] +oci-principals = ["openhuman-tinyhumans/oci-principals"] inbound-queues = ["openhuman-tinyhumans/inbound-queues"] modules = ["openhuman-tinyhumans/modules"] security-module = ["openhuman-tinyhumans/security-module"] diff --git a/crates/openhuman-tinyhumans/Cargo.toml b/crates/openhuman-tinyhumans/Cargo.toml index 62c59ee4c48..8a2678772d3 100644 --- a/crates/openhuman-tinyhumans/Cargo.toml +++ b/crates/openhuman-tinyhumans/Cargo.toml @@ -23,6 +23,7 @@ http-server = ["openhuman-embed/http-server"] inference = ["openhuman-embed/inference"] documents = ["openhuman-embed/documents"] hosting = ["openhuman-embed/hosting"] +oci-principals = ["openhuman-embed/oci-principals"] inbound-queues = ["openhuman-embed/inbound-queues"] modules = ["openhuman-embed/modules"] security-module = ["openhuman-embed/security-module"] diff --git a/crates/openhuman-tinyhumans/src/inference/tiers.rs b/crates/openhuman-tinyhumans/src/inference/tiers.rs index 781accba666..1ce75db4784 100644 --- a/crates/openhuman-tinyhumans/src/inference/tiers.rs +++ b/crates/openhuman-tinyhumans/src/inference/tiers.rs @@ -160,6 +160,7 @@ pub(crate) fn normalize_config(config: &mut Config) -> bool { .to_string(), auth_style: preset.auth_style, default_model: config.default_model.clone(), + oci: None, }, ); changed = true; diff --git a/crates/openhuman-tui/Cargo.toml b/crates/openhuman-tui/Cargo.toml index 34db098f933..57332497e2e 100644 --- a/crates/openhuman-tui/Cargo.toml +++ b/crates/openhuman-tui/Cargo.toml @@ -39,6 +39,7 @@ http-server = ["openhuman-rpc/http-server"] inference = ["openhuman-rpc/inference"] documents = ["openhuman-rpc/documents"] hosting = ["openhuman-rpc/hosting"] +oci-principals = ["openhuman-rpc/oci-principals"] inbound-queues = ["openhuman-rpc/inbound-queues"] modules = ["openhuman-rpc/modules"] security-module = ["openhuman-rpc/security-module"] diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md index 5ce5482d1a9..828e23ec9f5 100644 --- a/docs/TEST-COVERAGE-MATRIX.md +++ b/docs/TEST-COVERAGE-MATRIX.md @@ -593,6 +593,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent | 13.3.7 | Skill registry install sources + unique entry ids | RU+VU | `crates/openhuman-core/src/skills/catalog/ops_tests.rs`, `crates/openhuman-core/src/skills/catalog/ops_install_tests.rs`, `crates/openhuman-core/src/skills/ops_create_and_url_tests.rs`, `app/src/components/skills/__tests__/SkillsExplorerTab.test.tsx` | 🟡 | Entry ids and `SKILL.md` resolution come from the `tinyskills` registry: entries without a `SKILL.md` are `installable: false`, show "Not installable" with a source link, and installing one fails with `SKILL_REGISTRY_NO_DIRECT_DOWNLOAD` naming the page; a missing id suggests the closest ones; a throttled document host reports `SKILL_REGISTRY_RATE_LIMITED` with its retry delay. Live upstream hosts remain a manual check. | | 13.3.12 | Skill registry paging, detail, freshness and outages | RU+RI+VU+PW | `crates/openhuman-core/src/skills/catalog/ops_tests.rs`, `crates/openhuman-core/src/skills/catalog/transport_tests.rs`, `crates/openhuman-core/src/skills/catalog/registry_tests.rs`, `crates/openhuman-core/src/skills/catalog/tools_tests.rs`, `tests/in_process/skill_registry_e2e.rs`, `app/src/components/skills/__tests__/SkillsExplorerRegistryState.test.tsx`, `app/test/playwright/specs/skills-registry-catalog.spec.ts` | ✅ | Browse/search return one server page with `total`/`total_pages`; `detail` returns the overview and resolved download URL; the transport connects only to pinned addresses and returns redirects unfollowed; a 503 registry keeps serving the held catalog with `last_error`, which the app shows as an offline banner whose Retry forces a refresh; rate-limit and unreachable errors get their own copy. | | 13.3.13 | Skill install supply-chain scan gate | RU+RI+VU+PW | `crates/openhuman-core/src/skills/ops_install/scan_gate_tests.rs`, `crates/openhuman-core/src/skills/catalog/ops_install_tests.rs`, `crates/openhuman-core/src/skills/catalog/tools_tests.rs`, `crates/openhuman-core/src/skills/tools_tests.rs`, `tests/in_process/skill_registry_e2e.rs`, `app/src/components/skills/__tests__/ScanBlockedDialog.test.tsx`, `app/src/components/skills/__tests__/SkillsExplorerTab.test.tsx`, `app/src/components/skills/__tests__/InstallSkillDialog.test.tsx`, `app/test/playwright/specs/skills-registry-catalog.spec.ts` | ✅ | A blocking scan or failed fetch is fetched and scanned once more; a document that still blocks is not installed and returns `status: "scan_blocked"` with findings for catalog and pasted-URL installs; `acknowledged_digest` set to the refusal's `digest` installs that document only, and a changed document is refused afresh with its new digest (or installs if it now scans clean); the agent tools neither expose nor honour the flag; the app prompts with Block install focused and installs only on Install anyway; the registry cools down 45 s after a failed refresh and the retry does not refetch. | +| 13.3.14 | OCI Generative AI provider (BYOK) | RU+VU | `crates/openhuman-core/src/inference/provider/factory/oci_tests.rs`, `crates/openhuman-core/src/config/schema/oci_settings_tests.rs`, `crates/openhuman-core/src/config/schema/cloud_providers_tests.rs`, `crates/openhuman-core/src/inference/provider/factory/cloud_spec_tests.rs`, `app/src/components/settings/panels/ai/ociSettings.test.ts`, `app/src/components/settings/panels/ai/__tests__/OciSettingsDialog.test.tsx`, `app/src/components/settings/panels/ai/__tests__/useProviderConnect.test.ts`, `app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx` | 🟡 | RU covers mapping an `oci` entry onto the tinyinference provider: every auth mode and transport, required fields reported by name, the endpoint override and the `oci-principals` gate. VU covers the settings dialog, its compartment rule (the same as the core's), the connect flow with keyring key set/clear and rollback, and the connected-provider row. The signing and transports are tested in tinyinference, whose live check is a credential-gated example. No WD/PW E2E yet | | 13.3.8 | Managed default model (one OpenRouter model for every managed workload) | RU+RI | `crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rs` (`resolve_model_for_hint_maps_every_managed_hint_to_the_default_model`, `resolve_model_for_hint_uses_the_pinned_managed_default`, `resolve_model_for_hint_treats_retired_tier_slugs_as_role_aliases`), `crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs`, `crates/openhuman-core/src/triage/routing_tests.rs`, `crates/openhuman-core/src/agent/cost_tests.rs`, `crates/openhuman-core/src/platform/cost/route_tests.rs`, `crates/openhuman-core/src/config/migrations/retire_managed_tier_slugs_tests.rs`, `crates/openhuman-core/src/config/migrations/mod_tests.rs` (`run_pending_v12_to_v13_*`), `tests/json_rpc_e2e.rs` (routing cases, flows arc) | ✅ | The `chat-v1`/`agentic-v1`/… tier endpoints are retired: every managed workload role resolves to `config.default_model` when it names a catalog model, else `openrouter/deepseek/deepseek-v4-flash`; `hint:*` and retired slugs stay role aliases; migration 12→13 rewrites persisted slugs; cost classification and the flash price row | | 13.3.9 | Routing page: Default model row + per-workload tables always shown; providers header action | VU | `app/src/components/settings/panels/__tests__/AIPanel.test.tsx` (`shows the per-workload routing tables directly, with no mode selector`, `pins a managed default model from the routing page`), `app/src/services/api/__tests__/aiSettingsApi.test.ts` (`sends default_model only when the pinned default model changed`), `app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx` | ✅ | No Managed / Own / Advanced selector; the Default model row opens the managed catalog picker (list, alphabetical, search filters models) and persists `default_model`; "Add provider" lives in the page header | @@ -701,10 +702,10 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent | Status | Count | | ---------------- | ------------------------------------------------ | | ✅ Covered | 89 | -| 🟡 Partial | 27 | +| 🟡 Partial | 28 | | ❌ Missing | 26 | | 🚫 Manual smoke | 11 | -| **Total leaves** | **153 explicit + nested = 213 product features** | +| **Total leaves** | **154 explicit + nested = 214 product features** | PR-A delta: 13 leaves moved from ❌ → ✅ via 5 WDIO specs + 2 Vitest + 1 Rust integration test. Section 16.1 adds 11 leaves (10 ✅, 1 🟡) for the embedded library harness. Section 16.2 adds eight covered leaves for dynamic runtime configuration, lifecycle and generated documentation. diff --git a/docs/gitbooks/en/developing/engines.md b/docs/gitbooks/en/developing/engines.md index 23198001916..bc934909e66 100644 --- a/docs/gitbooks/en/developing/engines.md +++ b/docs/gitbooks/en/developing/engines.md @@ -24,6 +24,10 @@ Supported routes: `moonshot`, `gmi`, `huggingface`, `nvidia`, `zai`, `minimax`, `stepfun`, `kilocode`, `deepinfra`, `novita`, `venice`, `vercel-ai-gateway`, `sumopod`, `modelscope`. +- OCI Generative AI (`oci`): the host follows the entry's `region`, and the + sign-in method is an API key, an OCI config profile, a session token or a + principal, so most setups store no key. See + [Local models and bring your own key](../features/model-routing/local-and-byok-models.md#oci-generative-ai). Provider definitions live under `crates/openhuman-core/src/inference/provider/` (`factory.rs` turns a `:` string into a client, and `types.rs` holds the provider shapes). Setup and the local-model capability table are in [Local models and bring your own key](../features/model-routing/local-and-byok-models.md). Routing and fallback order are in [Automatic model routing](../features/model-routing/README.md). @@ -47,10 +51,10 @@ Memory is Recall, Fetch and Store over a pluggable engine. The contract is `tiny Two engines ship, both served by `tinymemory-integrations`: -| id | what | endpoint | key | -| --- | --- | --- | --- | -| `tinyhumans` | CortexDB hosted behind the TinyHumans backend (`/memory/*`) | the backend origin | the signed-in session or API key, resolved per request through the host credential seam | -| `cortexdb` | the user's own CortexDB (direct `/v1/*`) | `[memory.engines.cortexdb] endpoint` (default `https://api-v1.cortexdb.ai`) | stored in the OS keychain as `memory-cortexdb` | +| id | what | endpoint | key | +| ------------ | ----------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| `tinyhumans` | CortexDB hosted behind the TinyHumans backend (`/memory/*`) | the backend origin | the signed-in session or API key, resolved per request through the host credential seam | +| `cortexdb` | the user's own CortexDB (direct `/v1/*`) | `[memory.engines.cortexdb] endpoint` (default `https://api-v1.cortexdb.ai`) | stored in the OS keychain as `memory-cortexdb` | Select one with `[memory] engine` or from Connections > Memory > Engine (`openhuman.memory_engine_set`). `memory::engine::resolve` binds it. If you are signed out and have no CortexDB key, memory is off: the `memory` tool is not registered, ingestion does nothing and RPCs answer `MEMORY_OFF`. diff --git a/docs/gitbooks/en/features/model-routing/local-and-byok-models.md b/docs/gitbooks/en/features/model-routing/local-and-byok-models.md index 5bcecc92143..bdf657f3b58 100644 --- a/docs/gitbooks/en/features/model-routing/local-and-byok-models.md +++ b/docs/gitbooks/en/features/model-routing/local-and-byok-models.md @@ -52,17 +52,17 @@ ollama pull moondream:1.8b-v2-q4_K_S # vision, small A text-only model on Ollama still accepts an image request. It silently drops the image and answers from the prompt text alone, which reads as a confident but invented description. OpenHuman refuses to route a vision request to a chat-only model, but it helps to know which is which. -| Model | Size | Chat | Vision | Embeddings | -| -------------------------- | -------- | ------- | ------- | ---------------------------------- | -| `gemma3:270m-it-qat` | 0.2 GB | Yes | No | No | -| `gemma3:1b-it-qat` | 1.0 GB | Yes | No | No | -| `gemma3:4b-it-qat` | 4.0 GB | Yes | Yes | No | -| `gemma3n:e4b-it-q8_0` | 9.5 GB | Yes | No | No | -| `gemma4:e4b-it-q8_0` | 11.6 GB | Yes | Yes | No | -| `moondream:1.8b-v2-q4_K_S` | 1.7 GB | Minimal | Yes | No | -| `llava:7b` | 4.7 GB | Minimal | Yes | No | -| `bge-m3` | 1.2 GB | No | No | Yes, 1024 dimensions | -| `all-minilm:latest` | 0.05 GB | No | No | 384 dimensions | +| Model | Size | Chat | Vision | Embeddings | +| -------------------------- | ------- | ------- | ------ | -------------------- | +| `gemma3:270m-it-qat` | 0.2 GB | Yes | No | No | +| `gemma3:1b-it-qat` | 1.0 GB | Yes | No | No | +| `gemma3:4b-it-qat` | 4.0 GB | Yes | Yes | No | +| `gemma3n:e4b-it-q8_0` | 9.5 GB | Yes | No | No | +| `gemma4:e4b-it-q8_0` | 11.6 GB | Yes | Yes | No | +| `moondream:1.8b-v2-q4_K_S` | 1.7 GB | Minimal | Yes | No | +| `llava:7b` | 4.7 GB | Minimal | Yes | No | +| `bge-m3` | 1.2 GB | No | No | Yes, 1024 dimensions | +| `all-minilm:latest` | 0.05 GB | No | No | 384 dimensions | Two traps: @@ -128,6 +128,8 @@ Add your key in the desktop app under the LLM settings. It is stored in the OS k `openai`, `anthropic`, `google`, `openrouter`, `orcarouter`, `groq`, `mistral`, `deepseek`, `together`, `fireworks`, `cerebras`, `xai`, `moonshot`, `gmi`, `huggingface`, `nvidia`, `zai`, `minimax`, `stepfun`, `kilocode`, `deepinfra`, `novita`, `venice`, `vercel-ai-gateway`, `sumopod`, `modelscope` +`oci` is also built in, but it needs more than a key: its host follows the region you pick, and most of its sign-in methods store no key at all. See [OCI Generative AI](#oci-generative-ai). + Anything else that speaks the OpenAI-compatible API also works. Register it with your own slug and endpoint, and it routes the same way. For an HTTPS endpoint signed by a private or corporate CA, upload its PEM CA certificate in the custom provider editor. OpenHuman trusts that certificate for this provider's model listing and inference requests. You can also install the CA in the operating system's trust store; on macOS and Linux, `SSL_CERT_FILE` supplies a PEM bundle to the core process. @@ -151,6 +153,88 @@ To make one provider the default for everything that is not pinned, set `primary BYOK gets your provider's capabilities, not OpenHuman's. Before you pin `vision_provider`, confirm the model accepts image input. Before you pin `embeddings_provider`, confirm the provider serves an embeddings endpoint. Not every chat provider does. +### OCI Generative AI + +The `oci` slug talks to Oracle Cloud Infrastructure Generative AI through a native provider, not the OpenAI-compatible shim, so it can use OCI's own authentication. Pick **OCI Generative AI** in the LLM settings, or add an entry by hand. The model is the OCI model id: `oci:openai.gpt-5.5`, `oci:cohere.command-a-03-2025`, `oci:meta.llama-3.3-70b-instruct`. + +Everything except the optional API key is plain settings in `config.toml`. Key material for the profile modes is read from your OCI config directory when the model is built and is never copied into OpenHuman's config. + +| `auth_mode` | Credential | Notes | +| ----------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------- | +| `api_key` (default) | OCI Generative AI API key, kept in the OS keyring | Needs `region`. | +| `config_profile` | API-signing-key profile in `~/.oci/config` | Region defaults to the profile's. | +| `session_token` | Session-token profile from `oci session authenticate` | Token refreshes are picked up without a restart. | +| `resource_principal` | `OCI_RESOURCE_PRINCIPAL_*` environment (Functions, Container Instances) | Version 2.2 only. | +| `instance_principal` | Compute instance identity | Requires a build with the `oci-principals` cargo feature. | +| `oke_workload_identity` | OKE workload identity | Requires a build with the `oci-principals` cargo feature. | + +`transport` selects the wire protocol: + +| `transport` | Endpoint | Required settings | +| ------------------ | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `openai` (default) | `/openai/v1`, Chat Completions | `project_id`, the Generative AI project OCID (sent as `OpenAI-Project`). `compartment_id` too, unless `auth_mode = "api_key"`. | +| `actions` | `/20231130/actions/v1`, Chat Completions | `compartment_id` | +| `native_generic` | `/20231130/actions/chat`, `apiFormat: GENERIC` (Meta, xAI, Google, OpenAI-family) | `compartment_id` | +| `native_cohere` | `/20231130/actions/chat`, `apiFormat: COHERE` (Cohere Command) | `compartment_id` | + +Set `dedicated_endpoint_id` to address a dedicated AI cluster endpoint instead of an on-demand model. The service host comes from `region`. Leave the entry's `endpoint` blank unless you need a different host, such as another realm or a private endpoint; a non-blank `endpoint` replaces the region-derived host. + +```toml +# API key (stored in the keyring from the settings panel) +[[cloud_providers]] +slug = "oci" +label = "OCI Generative AI" +auth_style = "oci" +[cloud_providers.oci] +auth_mode = "api_key" +region = "us-chicago-1" +project_id = "ocid1.generativeaiproject.oc1.." +transport = "openai" + +# API-signing-key profile, native Cohere chat +[[cloud_providers]] +slug = "oci-cohere" +auth_style = "oci" +[cloud_providers.oci] +auth_mode = "config_profile" +config_file = "~/.oci/config" # optional; default $OCI_CLI_CONFIG_FILE or ~/.oci/config +profile = "DEFAULT" +compartment_id = "ocid1.compartment.oc1.." +transport = "native_cohere" + +# Session token (run `oci session authenticate --profile-name SESSION` first) +[[cloud_providers]] +slug = "oci-session" +auth_style = "oci" +[cloud_providers.oci] +auth_mode = "session_token" +profile = "SESSION" +region = "us-chicago-1" +compartment_id = "ocid1.compartment.oc1.." +transport = "native_generic" + +# Principals (no stored secret) +[[cloud_providers]] +slug = "oci-principal" +auth_style = "oci" +[cloud_providers.oci] +auth_mode = "instance_principal" # or "resource_principal" / "oke_workload_identity" +region = "us-ashburn-1" +compartment_id = "ocid1.compartment.oc1.." +project_id = "ocid1.generativeaiproject.oc1.." +transport = "openai" +``` + +Workload routes are top-level keys. Put them at the top of `config.toml`, above the first `[[cloud_providers]]` header: below it, TOML reads them as part of the last `[cloud_providers.oci]` table and they route nothing. + +```toml +# Top of config.toml, before any [[cloud_providers]] table +chat_provider = "oci:openai.gpt-5.5" +reasoning_provider = "oci-cohere:cohere.command-a-03-2025" +``` + +Errors name the missing field (`oci.region`, `oci.compartment_id`, `oci.project_id`) or the mismatch (a session-token profile used with `config_profile`). The model dropdown cannot list OCI models, so type the model id. + ## Mixing routes The workload fields are independent. A common privacy-minded setup keeps recurring background work on-device and saves a strong cloud model for the turns that need it: