feat(ai-provider): add Codex app-server integration (#267)
Co-authored-by: Sun8854 <Sun8854@users.noreply.github.com>
This commit is contained in:
@@ -69,6 +69,7 @@ import {
|
|||||||
type GenSparkAccountStatus,
|
type GenSparkAccountStatus,
|
||||||
type LegacyAiSettings,
|
type LegacyAiSettings,
|
||||||
} from '@genoffice/ai-provider'
|
} from '@genoffice/ai-provider'
|
||||||
|
import { listCodexModels, shutdownCodexAppServers } from '@genoffice/ai-provider/codex-app-server'
|
||||||
import {
|
import {
|
||||||
ensureGenofficeLogin,
|
ensureGenofficeLogin,
|
||||||
gskApiKey,
|
gskApiKey,
|
||||||
@@ -2624,6 +2625,7 @@ const activeAiStreams = new Map<string, AbortController>()
|
|||||||
* sheets' standalone AI handlers use the same channel names.
|
* sheets' standalone AI handlers use the same channel names.
|
||||||
*/
|
*/
|
||||||
export function registerAiIpc(): void {
|
export function registerAiIpc(): void {
|
||||||
|
app.once('before-quit', shutdownCodexAppServers)
|
||||||
ipcMain.handle('ai:get-settings', (): AiSettings => {
|
ipcMain.handle('ai:get-settings', (): AiSettings => {
|
||||||
const stored = readJson<Partial<AiSettings> & LegacyAiSettings>(SETTINGS_PATH(), {})
|
const stored = readJson<Partial<AiSettings> & LegacyAiSettings>(SETTINGS_PATH(), {})
|
||||||
// pre-lock legacy file: genspark selected with cloud tools opted out. The
|
// pre-lock legacy file: genspark selected with cloud tools opted out. The
|
||||||
@@ -2660,6 +2662,10 @@ export function registerAiIpc(): void {
|
|||||||
writeJson(SETTINGS_PATH(), settings)
|
writeJson(SETTINGS_PATH(), settings)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
ipcMain.handle('ai:codex-models', async (_event, cliPath: unknown) => {
|
||||||
|
return listCodexModels(typeof cliPath === 'string' ? cliPath : undefined)
|
||||||
|
})
|
||||||
|
|
||||||
ipcMain.handle('ai:stream', async (event, request: AiStreamRequest) => {
|
ipcMain.handle('ai:stream', async (event, request: AiStreamRequest) => {
|
||||||
const { requestId, settings, system, messages } = request
|
const { requestId, settings, system, messages } = request
|
||||||
const tools = request.tools ?? []
|
const tools = request.tools ?? []
|
||||||
@@ -2673,7 +2679,7 @@ export function registerAiIpc(): void {
|
|||||||
const send = (chunk: AiStreamChunk) => {
|
const send = (chunk: AiStreamChunk) => {
|
||||||
if (!event.sender.isDestroyed()) event.sender.send('ai:stream-chunk', chunk)
|
if (!event.sender.isDestroyed()) event.sender.send('ai:stream-chunk', chunk)
|
||||||
}
|
}
|
||||||
if (!config?.apiKey) {
|
if (!config || (provider !== 'codex' && !config.apiKey)) {
|
||||||
send({
|
send({
|
||||||
requestId,
|
requestId,
|
||||||
type: 'error',
|
type: 'error',
|
||||||
@@ -2681,7 +2687,7 @@ export function registerAiIpc(): void {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!config.model) {
|
if (provider !== 'codex' && !config.model) {
|
||||||
send({ requestId, type: 'error', error: tm('errNoModel') })
|
send({ requestId, type: 'error', error: tm('errNoModel') })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -2698,6 +2704,7 @@ export function registerAiIpc(): void {
|
|||||||
try {
|
try {
|
||||||
let stopReason: string | undefined
|
let stopReason: string | undefined
|
||||||
await streamForProvider(provider, config, system, messages, tools, maxTokens, {
|
await streamForProvider(provider, config, system, messages, tools, maxTokens, {
|
||||||
|
...(request.sessionId ? { sessionId: request.sessionId } : {}),
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
onDelta: (text) => send({ requestId, type: 'delta', text }),
|
onDelta: (text) => send({ requestId, type: 'delta', text }),
|
||||||
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
|
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
|
||||||
@@ -2820,13 +2827,13 @@ export function registerAiIpc(): void {
|
|||||||
if (provider === 'genspark' && config && !config.apiKey) {
|
if (provider === 'genspark' && config && !config.apiKey) {
|
||||||
config = { ...config, apiKey: gskApiKey() }
|
config = { ...config, apiKey: gskApiKey() }
|
||||||
}
|
}
|
||||||
if (!config?.apiKey) {
|
if (!config || (provider !== 'codex' && !config.apiKey)) {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: provider === 'genspark' ? tm('errGskNotLoggedIn') : tm('errNoApiKey', { provider }),
|
error: provider === 'genspark' ? tm('errGskNotLoggedIn') : tm('errNoApiKey', { provider }),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!config.model) return { ok: false, error: tm('errNoModel') }
|
if (provider !== 'codex' && !config.model) return { ok: false, error: tm('errNoModel') }
|
||||||
try {
|
try {
|
||||||
const result = await chatForProvider(provider, config, system, user)
|
const result = await chatForProvider(provider, config, system, user)
|
||||||
// the one-shot path reports HTTP failures as ok:false with the raw body —
|
// the one-shot path reports HTTP failures as ok:false with the raw body —
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ export type {
|
|||||||
AiStreamRequest,
|
AiStreamRequest,
|
||||||
GenSparkAccountStatus,
|
GenSparkAccountStatus,
|
||||||
} from '@genoffice/ai-provider'
|
} from '@genoffice/ai-provider'
|
||||||
export { AI_PROVIDERS } from '@genoffice/ai-provider'
|
export { AI_PROVIDERS } from '@genoffice/ai-provider/browser'
|
||||||
|
|
||||||
// ---- agent protocol: canonical types live in @genoffice/agent-core ----
|
// ---- agent protocol: canonical types live in @genoffice/agent-core ----
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ import {
|
|||||||
type GenSparkAccountStatus,
|
type GenSparkAccountStatus,
|
||||||
type LegacyAiSettings,
|
type LegacyAiSettings,
|
||||||
} from '@genoffice/ai-provider'
|
} from '@genoffice/ai-provider'
|
||||||
|
import { shutdownCodexAppServers } from '@genoffice/ai-provider/codex-app-server'
|
||||||
import { csvToXlsxBuffer, decodeCsvBuffer, sheetCsvToXlsxBuffer } from '../gateway/csv-import'
|
import { csvToXlsxBuffer, decodeCsvBuffer, sheetCsvToXlsxBuffer } from '../gateway/csv-import'
|
||||||
import {
|
import {
|
||||||
ensureGenofficeLogin,
|
ensureGenofficeLogin,
|
||||||
@@ -3026,6 +3027,7 @@ export function registerSheetsIpc(): void {
|
|||||||
let aiIpcRegistered = false
|
let aiIpcRegistered = false
|
||||||
|
|
||||||
export function registerSheetsAiIpc(): void {
|
export function registerSheetsAiIpc(): void {
|
||||||
|
app.once('before-quit', shutdownCodexAppServers)
|
||||||
if (aiIpcRegistered) return
|
if (aiIpcRegistered) return
|
||||||
aiIpcRegistered = true
|
aiIpcRegistered = true
|
||||||
|
|
||||||
@@ -3072,13 +3074,13 @@ export function registerSheetsAiIpc(): void {
|
|||||||
if (provider === 'genspark' && config && !config.apiKey) {
|
if (provider === 'genspark' && config && !config.apiKey) {
|
||||||
config = { ...config, apiKey: gskApiKey() }
|
config = { ...config, apiKey: gskApiKey() }
|
||||||
}
|
}
|
||||||
if (!config?.apiKey) {
|
if (!config || (provider !== 'codex' && !config.apiKey)) {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: provider === 'genspark' ? tm('errGskNotLoggedIn') : tm('errNoApiKey', { provider }),
|
error: provider === 'genspark' ? tm('errGskNotLoggedIn') : tm('errNoApiKey', { provider }),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!config.model) return { ok: false, error: tm('errNoModel') }
|
if (provider !== 'codex' && !config.model) return { ok: false, error: tm('errNoModel') }
|
||||||
try {
|
try {
|
||||||
const result = await chatForProvider(provider, config, request.system, request.user)
|
const result = await chatForProvider(provider, config, request.system, request.user)
|
||||||
// the one-shot path reports HTTP failures as ok:false with the raw body —
|
// the one-shot path reports HTTP failures as ok:false with the raw body —
|
||||||
@@ -3108,7 +3110,7 @@ export function registerSheetsAiIpc(): void {
|
|||||||
const send = (chunk: AiStreamChunk) => {
|
const send = (chunk: AiStreamChunk) => {
|
||||||
if (!event.sender.isDestroyed()) event.sender.send(IPC_CHANNELS.aiStreamChunk, chunk)
|
if (!event.sender.isDestroyed()) event.sender.send(IPC_CHANNELS.aiStreamChunk, chunk)
|
||||||
}
|
}
|
||||||
if (!config?.apiKey) {
|
if (!config || (provider !== 'codex' && !config.apiKey)) {
|
||||||
send({
|
send({
|
||||||
requestId,
|
requestId,
|
||||||
type: 'error',
|
type: 'error',
|
||||||
@@ -3116,7 +3118,7 @@ export function registerSheetsAiIpc(): void {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!config.model) {
|
if (provider !== 'codex' && !config.model) {
|
||||||
send({ requestId, type: 'error', error: tm('errNoModel') })
|
send({ requestId, type: 'error', error: tm('errNoModel') })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -3133,6 +3135,7 @@ export function registerSheetsAiIpc(): void {
|
|||||||
try {
|
try {
|
||||||
let stopReason: string | undefined
|
let stopReason: string | undefined
|
||||||
await streamForProvider(provider, config, system, messages, tools, maxTokens, {
|
await streamForProvider(provider, config, system, messages, tools, maxTokens, {
|
||||||
|
...(request.sessionId ? { sessionId: request.sessionId } : {}),
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
onDelta: (text) => send({ requestId, type: 'delta', text }),
|
onDelta: (text) => send({ requestId, type: 'delta', text }),
|
||||||
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
|
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
|
||||||
|
|||||||
@@ -2371,7 +2371,7 @@ export type WorkbookConditionalRule = z.infer<typeof conditionalRuleSchema>
|
|||||||
// ---- AI settings + chat/stream: canonical types live in @genoffice/ai-provider,
|
// ---- AI settings + chat/stream: canonical types live in @genoffice/ai-provider,
|
||||||
// shared with apps/docs. Validated here like every other renderer→main request in
|
// shared with apps/docs. Validated here like every other renderer→main request in
|
||||||
// this file; the validated shape is cast to AiSettings at the main-process call
|
// this file; the validated shape is cast to AiSettings at the main-process call
|
||||||
// site, which always has exactly the 5 known provider keys once merged through
|
// site, which has every known provider key once merged through
|
||||||
// resolveAiSettings/defaultAiSettings. ----
|
// resolveAiSettings/defaultAiSettings. ----
|
||||||
|
|
||||||
const aiProviderConfigSchema = z
|
const aiProviderConfigSchema = z
|
||||||
@@ -2379,6 +2379,7 @@ const aiProviderConfigSchema = z
|
|||||||
apiKey: z.string(),
|
apiKey: z.string(),
|
||||||
model: z.string(),
|
model: z.string(),
|
||||||
baseUrl: z.string().optional(),
|
baseUrl: z.string().optional(),
|
||||||
|
cliPath: z.string().optional(),
|
||||||
})
|
})
|
||||||
.strict()
|
.strict()
|
||||||
|
|
||||||
@@ -2461,6 +2462,7 @@ export const aiChatRequestSchema = z
|
|||||||
export const aiStreamRequestSchema = z
|
export const aiStreamRequestSchema = z
|
||||||
.object({
|
.object({
|
||||||
requestId: z.string().min(1),
|
requestId: z.string().min(1),
|
||||||
|
sessionId: z.string().uuid().optional(),
|
||||||
settings: aiSettingsInputSchema,
|
settings: aiSettingsInputSchema,
|
||||||
system: z.string(),
|
system: z.string(),
|
||||||
messages: z.array(agentMessageSchema).max(MAX_AI_MESSAGES),
|
messages: z.array(agentMessageSchema).max(MAX_AI_MESSAGES),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { contextBridge, ipcRenderer } from 'electron'
|
import { contextBridge, ipcRenderer } from 'electron'
|
||||||
import type { IpcRendererEvent } from 'electron'
|
import type { IpcRendererEvent } from 'electron'
|
||||||
import { AI_PROVIDERS, getProviderAdapter } from '@genoffice/ai-provider'
|
import { AI_PROVIDERS, getProviderAdapter } from '@genoffice/ai-provider/browser'
|
||||||
import type { AiSettings } from '@genoffice/ai-provider'
|
import type { AiSettings, CodexModelCatalog } from '@genoffice/ai-provider/browser'
|
||||||
import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open'
|
import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open'
|
||||||
import type {
|
import type {
|
||||||
AccountLoginEvent,
|
AccountLoginEvent,
|
||||||
@@ -252,7 +252,7 @@ const homeApi: HomeApi = {
|
|||||||
return AI_PROVIDERS.map((meta) => {
|
return AI_PROVIDERS.map((meta) => {
|
||||||
let defaultBaseUrl = ''
|
let defaultBaseUrl = ''
|
||||||
// genspark routes by model and custom has no default — both stay ''
|
// genspark routes by model and custom has no default — both stay ''
|
||||||
if (meta.id !== 'genspark' && !meta.needsBaseUrl) {
|
if (meta.id !== 'genspark' && !meta.needsBaseUrl && !meta.needsCliPath) {
|
||||||
defaultBaseUrl = getProviderAdapter(meta.id).resolveEndpoint({
|
defaultBaseUrl = getProviderAdapter(meta.id).resolveEndpoint({
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
model: meta.defaultModel,
|
model: meta.defaultModel,
|
||||||
@@ -261,6 +261,9 @@ const homeApi: HomeApi = {
|
|||||||
return { ...meta, defaultBaseUrl }
|
return { ...meta, defaultBaseUrl }
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
async getCodexModels(cliPath) {
|
||||||
|
return (await ipcRenderer.invoke('ai:codex-models', cliPath)) as CodexModelCatalog
|
||||||
|
},
|
||||||
async testAiSettings(settings) {
|
async testAiSettings(settings) {
|
||||||
const result: unknown = await ipcRenderer.invoke('ai:chat', {
|
const result: unknown = await ipcRenderer.invoke('ai:chat', {
|
||||||
settings,
|
settings,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { Dropdown } from '@genoffice/ui'
|
import { Dropdown } from '@genoffice/ui'
|
||||||
import {
|
import {
|
||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
MAX_MAX_OUTPUT_TOKENS,
|
MAX_MAX_OUTPUT_TOKENS,
|
||||||
MIN_MAX_OUTPUT_TOKENS,
|
MIN_MAX_OUTPUT_TOKENS,
|
||||||
clampMaxOutputTokens,
|
clampMaxOutputTokens,
|
||||||
} from '@genoffice/ai-provider'
|
} from '@genoffice/ai-provider/browser'
|
||||||
import type { AiSettings } from '@genoffice/ai-provider'
|
import type { AiSettings } from '@genoffice/ai-provider'
|
||||||
import { useI18n } from './locale'
|
import { useI18n } from './locale'
|
||||||
import type { StringKey, TFunc } from './locale'
|
import type { StringKey, TFunc } from './locale'
|
||||||
@@ -153,7 +153,9 @@ function Field({
|
|||||||
|
|
||||||
/** AI model pane: provider / model / key / base URL, saved to userData/ai-settings.json */
|
/** AI model pane: provider / model / key / base URL, saved to userData/ai-settings.json */
|
||||||
function AiModelPane({ t }: { t: TFunc }) {
|
function AiModelPane({ t }: { t: TFunc }) {
|
||||||
const [catalog] = useState<AiCatalogEntry[]>(() => window.aiOffice.getAiProviders?.() ?? [])
|
const [catalog, setCatalog] = useState<AiCatalogEntry[]>(
|
||||||
|
() => window.aiOffice.getAiProviders?.() ?? [],
|
||||||
|
)
|
||||||
const [settings, setSettings] = useState<AiSettings | null>(null)
|
const [settings, setSettings] = useState<AiSettings | null>(null)
|
||||||
const [dirty, setDirty] = useState(false)
|
const [dirty, setDirty] = useState(false)
|
||||||
const [saved, setSaved] = useState(false)
|
const [saved, setSaved] = useState(false)
|
||||||
@@ -162,6 +164,21 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
/** free-typed value of the output-cap field; committed (and clamped) on blur */
|
/** free-typed value of the output-cap field; committed (and clamped) on blur */
|
||||||
const [maxTokensDraft, setMaxTokensDraft] = useState<string | null>(null)
|
const [maxTokensDraft, setMaxTokensDraft] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const refreshCodexModels = useCallback(async (cliPath = '', selectedModel = '') => {
|
||||||
|
if (!window.aiOffice.getCodexModels) return
|
||||||
|
const live = await window.aiOffice.getCodexModels(cliPath)
|
||||||
|
setCatalog((current) =>
|
||||||
|
current.map((entry) => {
|
||||||
|
if (entry.id !== 'codex') return entry
|
||||||
|
const models =
|
||||||
|
selectedModel && !live.models.includes(selectedModel)
|
||||||
|
? [selectedModel, ...live.models]
|
||||||
|
: live.models
|
||||||
|
return { ...entry, models, defaultModel: live.defaultModel }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true
|
let alive = true
|
||||||
void window.aiOffice.getAiSettings?.().then((s) => {
|
void window.aiOffice.getAiSettings?.().then((s) => {
|
||||||
@@ -175,11 +192,15 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
s = { ...s, gskToolsEnabled: true }
|
s = { ...s, gskToolsEnabled: true }
|
||||||
}
|
}
|
||||||
setSettings(s)
|
setSettings(s)
|
||||||
|
const codex = s.providers.codex
|
||||||
|
if (codex) {
|
||||||
|
void refreshCodexModels(codex.cliPath ?? '', codex.model).catch(() => undefined)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
return () => {
|
return () => {
|
||||||
alive = false
|
alive = false
|
||||||
}
|
}
|
||||||
}, [])
|
}, [refreshCodexModels])
|
||||||
|
|
||||||
if (!settings) return null
|
if (!settings) return null
|
||||||
const provider = settings.provider
|
const provider = settings.provider
|
||||||
@@ -187,8 +208,11 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
const config = settings.providers[provider] ?? {
|
const config = settings.providers[provider] ?? {
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
model: meta?.defaultModel ?? '',
|
model: meta?.defaultModel ?? '',
|
||||||
|
baseUrl: undefined,
|
||||||
|
cliPath: undefined,
|
||||||
}
|
}
|
||||||
const isGenspark = provider === 'genspark'
|
const isGenspark = provider === 'genspark'
|
||||||
|
const isCodex = provider === 'codex'
|
||||||
|
|
||||||
const touch = () => {
|
const touch = () => {
|
||||||
setDirty(true)
|
setDirty(true)
|
||||||
@@ -236,7 +260,12 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
setTestResult(null)
|
setTestResult(null)
|
||||||
window.aiOffice
|
window.aiOffice
|
||||||
.testAiSettings?.(settings)
|
.testAiSettings?.(settings)
|
||||||
.then((r) => setTestResult(r ?? { ok: false }))
|
.then((r) => {
|
||||||
|
setTestResult(r ?? { ok: false })
|
||||||
|
if (r?.ok && isCodex) {
|
||||||
|
void refreshCodexModels(config.cliPath ?? '', config.model).catch(() => undefined)
|
||||||
|
}
|
||||||
|
})
|
||||||
.catch((error) =>
|
.catch((error) =>
|
||||||
setTestResult({ ok: false, error: error instanceof Error ? error.message : String(error) }),
|
setTestResult({ ok: false, error: error instanceof Error ? error.message : String(error) }),
|
||||||
)
|
)
|
||||||
@@ -268,7 +297,7 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="set-field-desc set-ai-note">
|
<div className="set-field-desc set-ai-note">
|
||||||
{isGenspark ? t('setAiGensparkHint') : t('setAiByokNote')}
|
{isGenspark ? t('setAiGensparkHint') : isCodex ? t('setAiCodexHint') : t('setAiByokNote')}
|
||||||
</div>
|
</div>
|
||||||
<div className="set-field">
|
<div className="set-field">
|
||||||
<div className="set-field-text">
|
<div className="set-field-text">
|
||||||
@@ -294,7 +323,32 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{!isGenspark && (
|
{isCodex ? (
|
||||||
|
<div className="set-field">
|
||||||
|
<div className="set-field-text">
|
||||||
|
<div className="set-field-stack">
|
||||||
|
<label className="set-field-label" htmlFor="set-ai-cli-path">
|
||||||
|
{t('setAiCodexPath')}
|
||||||
|
</label>
|
||||||
|
<div className="set-field-desc">{t('setAiCodexPathHint')}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
id="set-ai-cli-path"
|
||||||
|
className="set-input"
|
||||||
|
type="text"
|
||||||
|
value={config.cliPath ?? ''}
|
||||||
|
placeholder={t('setAiCodexAutoPlaceholder')}
|
||||||
|
spellCheck={false}
|
||||||
|
autoComplete="off"
|
||||||
|
onChange={(e) => updateConfig({ cliPath: e.target.value.trim() })}
|
||||||
|
onBlur={(e) => {
|
||||||
|
const cliPath = e.target.value.trim()
|
||||||
|
void refreshCodexModels(cliPath, config.model).catch(() => undefined)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : !isGenspark ? (
|
||||||
<>
|
<>
|
||||||
<div className="set-field">
|
<div className="set-field">
|
||||||
<div className="set-field-text">
|
<div className="set-field-text">
|
||||||
@@ -338,7 +392,7 @@ function AiModelPane({ t }: { t: TFunc }) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
) : null}
|
||||||
<div className="set-field">
|
<div className="set-field">
|
||||||
<div className="set-field-text">
|
<div className="set-field-text">
|
||||||
<div className="set-field-stack">
|
<div className="set-field-stack">
|
||||||
|
|||||||
@@ -118,6 +118,20 @@ const LOGOS: Record<AiProviderId, ReactNode> = {
|
|||||||
<path d="M12 0a12 12 0 100 24 12 12 0 000-24zM7.8 4.4Q8.6 8.5 12.7 9.3 8.6 10.1 7.8 14.2 7 10.1 2.9 9.3 7 8.5 7.8 4.4zM16.1 3.8Q16.6 6.4 19.2 6.9 16.6 7.4 16.1 10 15.6 7.4 13 6.9 15.6 6.4 16.1 3.8zm.5 6.8q.3 1.7 2 2-1.7.3-2 2-.3-1.7-2-2 1.7-.3 2-2zM6.1 16.8h11.8a1.1 1.1 0 010 2.2H6.1a1.1 1.1 0 010-2.2z" />
|
<path d="M12 0a12 12 0 100 24 12 12 0 000-24zM7.8 4.4Q8.6 8.5 12.7 9.3 8.6 10.1 7.8 14.2 7 10.1 2.9 9.3 7 8.5 7.8 4.4zM16.1 3.8Q16.6 6.4 19.2 6.9 16.6 7.4 16.1 10 15.6 7.4 13 6.9 15.6 6.4 16.1 3.8zm.5 6.8q.3 1.7 2 2-1.7.3-2 2-.3-1.7-2-2 1.7-.3 2-2zM6.1 16.8h11.8a1.1 1.1 0 010 2.2H6.1a1.1 1.1 0 010-2.2z" />
|
||||||
</svg>
|
</svg>
|
||||||
),
|
),
|
||||||
|
codex: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.8"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<rect x="2.5" y="4" width="19" height="16" rx="2.5" />
|
||||||
|
<path d="m7 9 3 3-3 3M12.5 15H17" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
anthropic: (
|
anthropic: (
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
<path
|
<path
|
||||||
|
|||||||
@@ -151,6 +151,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: '留空使用官方端点。',
|
setAiBaseUrlHint: '留空使用官方端点。',
|
||||||
setAiGensparkHint: '使用 Genspark 账号登录,无需 API key。',
|
setAiGensparkHint: '使用 Genspark 账号登录,无需 API key。',
|
||||||
|
setAiCodexPath: 'Codex 可执行文件',
|
||||||
|
setAiCodexPathHint: '仅自定义安装时填写;留空会自动检测。',
|
||||||
|
setAiCodexAutoPlaceholder: '留空自动检测(推荐)',
|
||||||
|
setAiCodexHint:
|
||||||
|
'自动查找并使用当前 Codex CLI,更新后无需重新选择;也可填写自定义路径。无需 API Key。',
|
||||||
setAiByokNote: '对话使用你自己的 key;网页搜索、生图等云工具仍需登录 Genspark。',
|
setAiByokNote: '对话使用你自己的 key;网页搜索、生图等云工具仍需登录 Genspark。',
|
||||||
setAiSave: '保存',
|
setAiSave: '保存',
|
||||||
setAiSaved: '已保存',
|
setAiSaved: '已保存',
|
||||||
@@ -349,6 +354,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Leave empty for the official endpoint.',
|
setAiBaseUrlHint: 'Leave empty for the official endpoint.',
|
||||||
setAiGensparkHint: 'Uses your Genspark sign-in; no API key needed.',
|
setAiGensparkHint: 'Uses your Genspark sign-in; no API key needed.',
|
||||||
|
setAiCodexPath: 'Codex executable',
|
||||||
|
setAiCodexPathHint: 'Only set this for a custom install; leave blank to auto-detect.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Auto-detect (recommended)',
|
||||||
|
setAiCodexHint:
|
||||||
|
'Automatically finds the current signed-in Codex CLI after updates; a custom path is optional. No API key is needed.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Chats use your own key; cloud tools (web search, image generation) still require the Genspark sign-in.',
|
'Chats use your own key; cloud tools (web search, image generation) still require the Genspark sign-in.',
|
||||||
setAiSave: 'Save',
|
setAiSave: 'Save',
|
||||||
@@ -563,6 +573,10 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: '空欄で公式エンドポイントを使用します。',
|
setAiBaseUrlHint: '空欄で公式エンドポイントを使用します。',
|
||||||
setAiGensparkHint: 'Genspark アカウントでサインインするため、API キーは不要です。',
|
setAiGensparkHint: 'Genspark アカウントでサインインするため、API キーは不要です。',
|
||||||
|
setAiCodexPath: 'Codex 実行ファイル',
|
||||||
|
setAiCodexPathHint: 'カスタムインストール時のみ指定します。空欄なら自動検出します。',
|
||||||
|
setAiCodexAutoPlaceholder: '自動検出(推奨)',
|
||||||
|
setAiCodexHint: 'ローカルでサインイン済みの Codex CLI を使用します。API キーは不要です。',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'チャットは自分のキーを使用します。ウェブ検索や画像生成などのクラウドツールには Genspark へのサインインが必要です。',
|
'チャットは自分のキーを使用します。ウェブ検索や画像生成などのクラウドツールには Genspark へのサインインが必要です。',
|
||||||
setAiSave: '保存',
|
setAiSave: '保存',
|
||||||
@@ -774,6 +788,10 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: '비워 두면 공식 엔드포인트를 사용합니다.',
|
setAiBaseUrlHint: '비워 두면 공식 엔드포인트를 사용합니다.',
|
||||||
setAiGensparkHint: 'Genspark 로그인으로 사용하며 API 키가 필요 없습니다.',
|
setAiGensparkHint: 'Genspark 로그인으로 사용하며 API 키가 필요 없습니다.',
|
||||||
|
setAiCodexPath: 'Codex 실행 파일',
|
||||||
|
setAiCodexPathHint: '사용자 지정 설치에만 입력하세요. 비워 두면 자동 감지합니다.',
|
||||||
|
setAiCodexAutoPlaceholder: '자동 감지(권장)',
|
||||||
|
setAiCodexHint: '로컬에서 로그인된 Codex CLI를 사용하므로 API 키가 필요 없습니다.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'대화는 자신의 키를 사용합니다. 웹 검색·이미지 생성 등 클라우드 도구는 여전히 Genspark 로그인이 필요합니다.',
|
'대화는 자신의 키를 사용합니다. 웹 검색·이미지 생성 등 클라우드 도구는 여전히 Genspark 로그인이 필요합니다.',
|
||||||
setAiSave: '저장',
|
setAiSave: '저장',
|
||||||
@@ -990,6 +1008,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Laisser vide pour le point de terminaison officiel.',
|
setAiBaseUrlHint: 'Laisser vide pour le point de terminaison officiel.',
|
||||||
setAiGensparkHint: 'Utilise votre connexion Genspark ; aucune clé API requise.',
|
setAiGensparkHint: 'Utilise votre connexion Genspark ; aucune clé API requise.',
|
||||||
|
setAiCodexPath: 'Exécutable Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'À renseigner uniquement pour une installation personnalisée ; sinon, détection automatique.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Détection auto (recommandé)',
|
||||||
|
setAiCodexHint: 'Utilise le CLI Codex connecté localement ; aucune clé API requise.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
"Les conversations utilisent votre propre clé ; les outils cloud (recherche web, génération d'images) nécessitent toujours la connexion Genspark.",
|
"Les conversations utilisent votre propre clé ; les outils cloud (recherche web, génération d'images) nécessitent toujours la connexion Genspark.",
|
||||||
setAiSave: 'Enregistrer',
|
setAiSave: 'Enregistrer',
|
||||||
@@ -1208,6 +1231,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Leer lassen für den offiziellen Endpunkt.',
|
setAiBaseUrlHint: 'Leer lassen für den offiziellen Endpunkt.',
|
||||||
setAiGensparkHint: 'Nutzt Ihre Genspark-Anmeldung; kein API-Schlüssel nötig.',
|
setAiGensparkHint: 'Nutzt Ihre Genspark-Anmeldung; kein API-Schlüssel nötig.',
|
||||||
|
setAiCodexPath: 'Codex-Programmdatei',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Nur bei einer benutzerdefinierten Installation angeben; leer lassen für automatische Erkennung.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Automatisch erkennen (empfohlen)',
|
||||||
|
setAiCodexHint: 'Verwendet die lokal angemeldete Codex CLI; kein API-Schlüssel nötig.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Chats verwenden Ihren eigenen Schlüssel; Cloud-Tools (Websuche, Bilderzeugung) erfordern weiterhin die Genspark-Anmeldung.',
|
'Chats verwenden Ihren eigenen Schlüssel; Cloud-Tools (Websuche, Bilderzeugung) erfordern weiterhin die Genspark-Anmeldung.',
|
||||||
setAiSave: 'Speichern',
|
setAiSave: 'Speichern',
|
||||||
@@ -1425,6 +1453,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Deja vacío para usar el endpoint oficial.',
|
setAiBaseUrlHint: 'Deja vacío para usar el endpoint oficial.',
|
||||||
setAiGensparkHint: 'Usa tu inicio de sesión de Genspark; no se necesita clave de API.',
|
setAiGensparkHint: 'Usa tu inicio de sesión de Genspark; no se necesita clave de API.',
|
||||||
|
setAiCodexPath: 'Ejecutable de Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Indícalo solo para una instalación personalizada; déjalo vacío para detectarlo automáticamente.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Detección automática (recomendado)',
|
||||||
|
setAiCodexHint: 'Usa la CLI de Codex con sesión local; no se necesita clave de API.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Los chats usan tu propia clave; las herramientas en la nube (búsqueda web, generación de imágenes) siguen requiriendo el inicio de sesión de Genspark.',
|
'Los chats usan tu propia clave; las herramientas en la nube (búsqueda web, generación de imágenes) siguen requiriendo el inicio de sesión de Genspark.',
|
||||||
setAiSave: 'Guardar',
|
setAiSave: 'Guardar',
|
||||||
@@ -1636,6 +1669,10 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'เว้นว่างเพื่อใช้ปลายทางอย่างเป็นทางการ',
|
setAiBaseUrlHint: 'เว้นว่างเพื่อใช้ปลายทางอย่างเป็นทางการ',
|
||||||
setAiGensparkHint: 'ใช้การลงชื่อเข้าใช้ Genspark ไม่ต้องใช้คีย์ API',
|
setAiGensparkHint: 'ใช้การลงชื่อเข้าใช้ Genspark ไม่ต้องใช้คีย์ API',
|
||||||
|
setAiCodexPath: 'ไฟล์ปฏิบัติการ Codex',
|
||||||
|
setAiCodexPathHint: 'กรอกเฉพาะเมื่อติดตั้งแบบกำหนดเอง เว้นว่างไว้เพื่อค้นหาอัตโนมัติ',
|
||||||
|
setAiCodexAutoPlaceholder: 'ค้นหาอัตโนมัติ (แนะนำ)',
|
||||||
|
setAiCodexHint: 'ใช้ Codex CLI ที่เข้าสู่ระบบไว้ในเครื่อง โดยไม่ต้องใช้คีย์ API',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'แชทใช้คีย์ของคุณเอง เครื่องมือคลาวด์ (ค้นเว็บ สร้างภาพ) ยังต้องลงชื่อเข้าใช้ Genspark',
|
'แชทใช้คีย์ของคุณเอง เครื่องมือคลาวด์ (ค้นเว็บ สร้างภาพ) ยังต้องลงชื่อเข้าใช้ Genspark',
|
||||||
setAiSave: 'บันทึก',
|
setAiSave: 'บันทึก',
|
||||||
@@ -1848,6 +1885,10 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Kosongkan untuk endpoint resmi.',
|
setAiBaseUrlHint: 'Kosongkan untuk endpoint resmi.',
|
||||||
setAiGensparkHint: 'Menggunakan login Genspark; tanpa kunci API.',
|
setAiGensparkHint: 'Menggunakan login Genspark; tanpa kunci API.',
|
||||||
|
setAiCodexPath: 'Berkas eksekusi Codex',
|
||||||
|
setAiCodexPathHint: 'Isi hanya untuk instalasi khusus; kosongkan agar terdeteksi otomatis.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Deteksi otomatis (disarankan)',
|
||||||
|
setAiCodexHint: 'Menggunakan Codex CLI yang sudah login secara lokal; tanpa kunci API.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Obrolan memakai kunci Anda sendiri; alat cloud (pencarian web, pembuatan gambar) tetap memerlukan login Genspark.',
|
'Obrolan memakai kunci Anda sendiri; alat cloud (pencarian web, pembuatan gambar) tetap memerlukan login Genspark.',
|
||||||
setAiSave: 'Simpan',
|
setAiSave: 'Simpan',
|
||||||
@@ -2061,6 +2102,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Оставьте пустым для официальной конечной точки.',
|
setAiBaseUrlHint: 'Оставьте пустым для официальной конечной точки.',
|
||||||
setAiGensparkHint: 'Использует вход в Genspark; ключ API не нужен.',
|
setAiGensparkHint: 'Использует вход в Genspark; ключ API не нужен.',
|
||||||
|
setAiCodexPath: 'Исполняемый файл Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Указывайте только для нестандартной установки; оставьте пустым для автоопределения.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Автоопределение (рекомендуется)',
|
||||||
|
setAiCodexHint: 'Использует локально авторизованный Codex CLI; ключ API не нужен.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Чаты используют ваш собственный ключ; облачные инструменты (веб-поиск, генерация изображений) по-прежнему требуют входа в Genspark.',
|
'Чаты используют ваш собственный ключ; облачные инструменты (веб-поиск, генерация изображений) по-прежнему требуют входа в Genspark.',
|
||||||
setAiSave: 'Сохранить',
|
setAiSave: 'Сохранить',
|
||||||
@@ -2272,6 +2318,10 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'اتركه فارغًا لاستخدام نقطة النهاية الرسمية.',
|
setAiBaseUrlHint: 'اتركه فارغًا لاستخدام نقطة النهاية الرسمية.',
|
||||||
setAiGensparkHint: 'يستخدم تسجيل الدخول إلى Genspark؛ لا حاجة لمفتاح API.',
|
setAiGensparkHint: 'يستخدم تسجيل الدخول إلى Genspark؛ لا حاجة لمفتاح API.',
|
||||||
|
setAiCodexPath: 'ملف Codex التنفيذي',
|
||||||
|
setAiCodexPathHint: 'حدده فقط للتثبيت المخصص؛ اتركه فارغًا للاكتشاف التلقائي.',
|
||||||
|
setAiCodexAutoPlaceholder: 'اكتشاف تلقائي (موصى به)',
|
||||||
|
setAiCodexHint: 'يستخدم Codex CLI المسجل محليًا؛ لا حاجة إلى مفتاح API.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'تستخدم المحادثات مفتاحك الخاص؛ أدوات السحابة (بحث الويب وتوليد الصور) ما زالت تتطلب تسجيل الدخول إلى Genspark.',
|
'تستخدم المحادثات مفتاحك الخاص؛ أدوات السحابة (بحث الويب وتوليد الصور) ما زالت تتطلب تسجيل الدخول إلى Genspark.',
|
||||||
setAiSave: 'حفظ',
|
setAiSave: 'حفظ',
|
||||||
@@ -2477,6 +2527,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Deixe vazio para o endpoint oficial.',
|
setAiBaseUrlHint: 'Deixe vazio para o endpoint oficial.',
|
||||||
setAiGensparkHint: 'Usa seu login Genspark; nenhuma chave de API necessária.',
|
setAiGensparkHint: 'Usa seu login Genspark; nenhuma chave de API necessária.',
|
||||||
|
setAiCodexPath: 'Executável do Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Preencha apenas para uma instalação personalizada; deixe em branco para detectar automaticamente.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Detectar automaticamente (recomendado)',
|
||||||
|
setAiCodexHint: 'Usa o Codex CLI conectado localmente; nenhuma chave de API é necessária.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Os chats usam sua própria chave; as ferramentas na nuvem (busca na web, geração de imagens) ainda exigem o login Genspark.',
|
'Os chats usam sua própria chave; as ferramentas na nuvem (busca na web, geração de imagens) ainda exigem o login Genspark.',
|
||||||
setAiSave: 'Salvar',
|
setAiSave: 'Salvar',
|
||||||
@@ -2681,6 +2736,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: "Lascia vuoto per l'endpoint ufficiale.",
|
setAiBaseUrlHint: "Lascia vuoto per l'endpoint ufficiale.",
|
||||||
setAiGensparkHint: 'Usa il tuo accesso Genspark; nessuna chiave API richiesta.',
|
setAiGensparkHint: 'Usa il tuo accesso Genspark; nessuna chiave API richiesta.',
|
||||||
|
setAiCodexPath: 'Eseguibile Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Compila solo per un’installazione personalizzata; lascia vuoto per il rilevamento automatico.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Rilevamento automatico (consigliato)',
|
||||||
|
setAiCodexHint: 'Usa Codex CLI con accesso locale; non è richiesta alcuna chiave API.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
"Le chat usano la tua chiave; gli strumenti cloud (ricerca web, generazione immagini) richiedono comunque l'accesso Genspark.",
|
"Le chat usano la tua chiave; gli strumenti cloud (ricerca web, generazione immagini) richiedono comunque l'accesso Genspark.",
|
||||||
setAiSave: 'Salva',
|
setAiSave: 'Salva',
|
||||||
@@ -2884,6 +2944,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Pozostaw puste, aby użyć oficjalnego punktu końcowego.',
|
setAiBaseUrlHint: 'Pozostaw puste, aby użyć oficjalnego punktu końcowego.',
|
||||||
setAiGensparkHint: 'Korzysta z logowania Genspark; klucz API nie jest potrzebny.',
|
setAiGensparkHint: 'Korzysta z logowania Genspark; klucz API nie jest potrzebny.',
|
||||||
|
setAiCodexPath: 'Plik wykonywalny Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Ustaw tylko dla instalacji niestandardowej; pozostaw puste, aby wykryć automatycznie.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Wykryj automatycznie (zalecane)',
|
||||||
|
setAiCodexHint: 'Używa lokalnie zalogowanego Codex CLI; klucz API nie jest potrzebny.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Czaty używają Twojego klucza; narzędzia w chmurze (wyszukiwanie, generowanie obrazów) nadal wymagają logowania Genspark.',
|
'Czaty używają Twojego klucza; narzędzia w chmurze (wyszukiwanie, generowanie obrazów) nadal wymagają logowania Genspark.',
|
||||||
setAiSave: 'Zapisz',
|
setAiSave: 'Zapisz',
|
||||||
@@ -3088,6 +3153,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Leeg laten voor het officiële eindpunt.',
|
setAiBaseUrlHint: 'Leeg laten voor het officiële eindpunt.',
|
||||||
setAiGensparkHint: 'Gebruikt je Genspark-login; geen API-sleutel nodig.',
|
setAiGensparkHint: 'Gebruikt je Genspark-login; geen API-sleutel nodig.',
|
||||||
|
setAiCodexPath: 'Codex-uitvoerbaar bestand',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Alleen invullen voor een aangepaste installatie; laat leeg voor automatische detectie.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Automatisch detecteren (aanbevolen)',
|
||||||
|
setAiCodexHint: 'Gebruikt de lokaal aangemelde Codex CLI; geen API-sleutel nodig.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Chats gebruiken je eigen sleutel; cloudtools (webzoeken, beeldgeneratie) vereisen nog steeds de Genspark-login.',
|
'Chats gebruiken je eigen sleutel; cloudtools (webzoeken, beeldgeneratie) vereisen nog steeds de Genspark-login.',
|
||||||
setAiSave: 'Opslaan',
|
setAiSave: 'Opslaan',
|
||||||
@@ -3291,6 +3361,12 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'Biarkan kosong untuk endpoint rasmi.',
|
setAiBaseUrlHint: 'Biarkan kosong untuk endpoint rasmi.',
|
||||||
setAiGensparkHint: 'Menggunakan log masuk Genspark; tiada kunci API diperlukan.',
|
setAiGensparkHint: 'Menggunakan log masuk Genspark; tiada kunci API diperlukan.',
|
||||||
|
setAiCodexPath: 'Fail boleh laku Codex',
|
||||||
|
setAiCodexPathHint:
|
||||||
|
'Isi hanya untuk pemasangan tersuai; biarkan kosong untuk pengesanan automatik.',
|
||||||
|
setAiCodexAutoPlaceholder: 'Kesan automatik (disyorkan)',
|
||||||
|
setAiCodexHint:
|
||||||
|
'Menggunakan Codex CLI yang telah log masuk secara setempat; tiada kunci API diperlukan.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'Sembang menggunakan kunci anda sendiri; alat awan (carian web, penjanaan imej) masih memerlukan log masuk Genspark.',
|
'Sembang menggunakan kunci anda sendiri; alat awan (carian web, penjanaan imej) masih memerlukan log masuk Genspark.',
|
||||||
setAiSave: 'Simpan',
|
setAiSave: 'Simpan',
|
||||||
@@ -3491,6 +3567,10 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'השאר ריק לנקודת הקצה הרשמית.',
|
setAiBaseUrlHint: 'השאר ריק לנקודת הקצה הרשמית.',
|
||||||
setAiGensparkHint: 'משתמש בכניסת Genspark שלך; אין צורך במפתח API.',
|
setAiGensparkHint: 'משתמש בכניסת Genspark שלך; אין צורך במפתח API.',
|
||||||
|
setAiCodexPath: 'קובץ ההפעלה של Codex',
|
||||||
|
setAiCodexPathHint: 'יש למלא רק בהתקנה מותאמת; השאר ריק לזיהוי אוטומטי.',
|
||||||
|
setAiCodexAutoPlaceholder: 'זיהוי אוטומטי (מומלץ)',
|
||||||
|
setAiCodexHint: 'משתמש ב-Codex CLI המחובר מקומית; אין צורך במפתח API.',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'שיחות משתמשות במפתח שלך; כלי ענן (חיפוש ברשת, יצירת תמונות) עדיין דורשים כניסת Genspark.',
|
'שיחות משתמשות במפתח שלך; כלי ענן (חיפוש ברשת, יצירת תמונות) עדיין דורשים כניסת Genspark.',
|
||||||
setAiSave: 'שמירה',
|
setAiSave: 'שמירה',
|
||||||
@@ -3693,6 +3773,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: 'आधिकारिक एंडपॉइंट के लिए खाली छोड़ें।',
|
setAiBaseUrlHint: 'आधिकारिक एंडपॉइंट के लिए खाली छोड़ें।',
|
||||||
setAiGensparkHint: 'आपके Genspark साइन-इन का उपयोग करता है; API कुंजी की आवश्यकता नहीं।',
|
setAiGensparkHint: 'आपके Genspark साइन-इन का उपयोग करता है; API कुंजी की आवश्यकता नहीं।',
|
||||||
|
setAiCodexPath: 'Codex निष्पादन फ़ाइल',
|
||||||
|
setAiCodexPathHint: 'केवल कस्टम इंस्टॉलेशन के लिए भरें; स्वतः पहचान के लिए खाली छोड़ें।',
|
||||||
|
setAiCodexAutoPlaceholder: 'स्वतः पहचान (अनुशंसित)',
|
||||||
|
setAiCodexHint:
|
||||||
|
'स्थानीय रूप से साइन-इन किए गए Codex CLI का उपयोग करता है; API कुंजी की आवश्यकता नहीं।',
|
||||||
setAiByokNote:
|
setAiByokNote:
|
||||||
'चैट आपकी अपनी कुंजी का उपयोग करती हैं; क्लाउड टूल (वेब खोज, छवि निर्माण) के लिए अभी भी Genspark साइन-इन आवश्यक है।',
|
'चैट आपकी अपनी कुंजी का उपयोग करती हैं; क्लाउड टूल (वेब खोज, छवि निर्माण) के लिए अभी भी Genspark साइन-इन आवश्यक है।',
|
||||||
setAiSave: 'सहेजें',
|
setAiSave: 'सहेजें',
|
||||||
@@ -3891,6 +3976,11 @@ export const strings = {
|
|||||||
setAiBaseUrl: 'Base URL',
|
setAiBaseUrl: 'Base URL',
|
||||||
setAiBaseUrlHint: '留空使用官方端點。',
|
setAiBaseUrlHint: '留空使用官方端點。',
|
||||||
setAiGensparkHint: '使用 Genspark 帳號登入,無需 API key。',
|
setAiGensparkHint: '使用 Genspark 帳號登入,無需 API key。',
|
||||||
|
setAiCodexPath: 'Codex 可執行檔',
|
||||||
|
setAiCodexPathHint: '僅自訂安裝時填寫;留空會自動偵測。',
|
||||||
|
setAiCodexAutoPlaceholder: '留空自動偵測(建議)',
|
||||||
|
setAiCodexHint:
|
||||||
|
'自動尋找目前的 Codex CLI,更新後無需重新選擇;也可填寫自訂路徑。無需 API Key。',
|
||||||
setAiByokNote: '對話使用你自己的 key;網頁搜尋、生圖等雲端工具仍需登入 Genspark。',
|
setAiByokNote: '對話使用你自己的 key;網頁搜尋、生圖等雲端工具仍需登入 Genspark。',
|
||||||
setAiSave: '儲存',
|
setAiSave: '儲存',
|
||||||
setAiSaved: '已儲存',
|
setAiSaved: '已儲存',
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import type { AiChatResponse, AiProviderMeta, AiSettings } from '@genoffice/ai-provider'
|
import type {
|
||||||
|
AiChatResponse,
|
||||||
|
AiProviderMeta,
|
||||||
|
AiSettings,
|
||||||
|
CodexModelCatalog,
|
||||||
|
} from '@genoffice/ai-provider'
|
||||||
import type { UpdateChannel } from './update-api'
|
import type { UpdateChannel } from './update-api'
|
||||||
|
|
||||||
/** UI language; kept self-contained here (mirrors Lang in @genoffice/i18n) */
|
/** UI language; kept self-contained here (mirrors Lang in @genoffice/i18n) */
|
||||||
@@ -159,6 +164,8 @@ export interface HomeApi {
|
|||||||
setAiSettings(settings: AiSettings): Promise<void>
|
setAiSettings(settings: AiSettings): Promise<void>
|
||||||
/** provider catalog with each fixed endpoint's default base URL (empty for genspark/custom) */
|
/** provider catalog with each fixed endpoint's default base URL (empty for genspark/custom) */
|
||||||
getAiProviders(): AiCatalogEntry[]
|
getAiProviders(): AiCatalogEntry[]
|
||||||
|
/** live Codex model catalog discovered through the current or overridden app-server */
|
||||||
|
getCodexModels(cliPath?: string): Promise<CodexModelCatalog>
|
||||||
/** one-shot round trip against the given (possibly unsaved) settings — the settings-UI connection test */
|
/** one-shot round trip against the given (possibly unsaved) settings — the settings-UI connection test */
|
||||||
testAiSettings(settings: AiSettings): Promise<AiChatResponse>
|
testAiSettings(settings: AiSettings): Promise<AiChatResponse>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import {
|
|||||||
type GenSparkAccountStatus,
|
type GenSparkAccountStatus,
|
||||||
type LegacyAiSettings,
|
type LegacyAiSettings,
|
||||||
} from '@genoffice/ai-provider'
|
} from '@genoffice/ai-provider'
|
||||||
|
import { shutdownCodexAppServers } from '@genoffice/ai-provider/codex-app-server'
|
||||||
import { fetchRemoteImage } from '@genoffice/electron-utils'
|
import { fetchRemoteImage } from '@genoffice/electron-utils'
|
||||||
import {
|
import {
|
||||||
webSearch,
|
webSearch,
|
||||||
@@ -107,6 +108,7 @@ function appendRunFailure(entry: AiRunFailure): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function registerAiIpc(): void {
|
export function registerAiIpc(): void {
|
||||||
|
app.once('before-quit', shutdownCodexAppServers)
|
||||||
// Node fetch (undici) direct connections get reset under VPN/tun setups; retry over Chromium's stack
|
// Node fetch (undici) direct connections get reset under VPN/tun setups; retry over Chromium's stack
|
||||||
setRescueFetch((url, init) => net.fetch(url, init))
|
setRescueFetch((url, init) => net.fetch(url, init))
|
||||||
setAiUserAgent(`GenOffice/${app.getVersion()}`)
|
setAiUserAgent(`GenOffice/${app.getVersion()}`)
|
||||||
@@ -155,7 +157,7 @@ export function registerAiIpc(): void {
|
|||||||
const send = (chunk: AiStreamChunk) => {
|
const send = (chunk: AiStreamChunk) => {
|
||||||
if (!event.sender.isDestroyed()) event.sender.send('ai:stream-chunk', chunk)
|
if (!event.sender.isDestroyed()) event.sender.send('ai:stream-chunk', chunk)
|
||||||
}
|
}
|
||||||
if (!config?.apiKey) {
|
if (!config || (provider !== 'codex' && !config.apiKey)) {
|
||||||
send({
|
send({
|
||||||
requestId,
|
requestId,
|
||||||
type: 'error',
|
type: 'error',
|
||||||
@@ -163,7 +165,7 @@ export function registerAiIpc(): void {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!config.model) {
|
if (provider !== 'codex' && !config.model) {
|
||||||
send({ requestId, type: 'error', error: tm('errNoModel') })
|
send({ requestId, type: 'error', error: tm('errNoModel') })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -180,6 +182,7 @@ export function registerAiIpc(): void {
|
|||||||
try {
|
try {
|
||||||
let stopReason: string | undefined
|
let stopReason: string | undefined
|
||||||
await streamForProvider(provider, config, system, messages, tools, maxTokens, {
|
await streamForProvider(provider, config, system, messages, tools, maxTokens, {
|
||||||
|
...(request.sessionId ? { sessionId: request.sessionId } : {}),
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
onDelta: (text) => send({ requestId, type: 'delta', text }),
|
onDelta: (text) => send({ requestId, type: 'delta', text }),
|
||||||
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
|
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
|
||||||
|
|||||||
@@ -10,7 +10,11 @@ import {
|
|||||||
type AgentSkill,
|
type AgentSkill,
|
||||||
type AgentTransport,
|
type AgentTransport,
|
||||||
} from '@genoffice/agent-core'
|
} from '@genoffice/agent-core'
|
||||||
import { getProviderAdapter, modelLacksVision, type AiSettings } from '@genoffice/ai-provider'
|
import {
|
||||||
|
getProviderAdapter,
|
||||||
|
modelLacksVision,
|
||||||
|
type AiSettings,
|
||||||
|
} from '@genoffice/ai-provider/browser'
|
||||||
import { auditSlideLayout } from './layout-audit'
|
import { auditSlideLayout } from './layout-audit'
|
||||||
import { createSlidesSkill, formatSlideDump, type DeckAccess } from './slides-skill'
|
import { createSlidesSkill, formatSlideDump, type DeckAccess } from './slides-skill'
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export type {
|
|||||||
AiStreamRequest,
|
AiStreamRequest,
|
||||||
GenSparkAccountStatus,
|
GenSparkAccountStatus,
|
||||||
} from '@genoffice/ai-provider'
|
} from '@genoffice/ai-provider'
|
||||||
export { AI_PROVIDERS } from '@genoffice/ai-provider'
|
export { AI_PROVIDERS } from '@genoffice/ai-provider/browser'
|
||||||
export type { AgentToolCall, AgentToolDef } from '@genoffice/agent-core'
|
export type { AgentToolCall, AgentToolDef } from '@genoffice/agent-core'
|
||||||
|
|
||||||
export type UiTheme = 'light' | 'dark' | 'system'
|
export type UiTheme = 'light' | 'dark' | 'system'
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ export interface IpcStreamChunk {
|
|||||||
/** The request forwarded to the main process to start one streaming turn. */
|
/** The request forwarded to the main process to start one streaming turn. */
|
||||||
export interface IpcStreamStart<S> {
|
export interface IpcStreamStart<S> {
|
||||||
requestId: string
|
requestId: string
|
||||||
|
/** Stable for the lifetime of one renderer-side transport. Providers with
|
||||||
|
* native conversations can reuse it across the tool loop and follow-ups. */
|
||||||
|
sessionId: string
|
||||||
settings: S
|
settings: S
|
||||||
system: string
|
system: string
|
||||||
messages: AgentMessage[]
|
messages: AgentMessage[]
|
||||||
@@ -69,6 +72,7 @@ export interface IpcTransportOptions<S> {
|
|||||||
*/
|
*/
|
||||||
export function createIpcTransport<S>(options: IpcTransportOptions<S>): AgentTransport {
|
export function createIpcTransport<S>(options: IpcTransportOptions<S>): AgentTransport {
|
||||||
const timeoutText = () => options.timeoutErrorText?.() ?? options.unknownErrorText()
|
const timeoutText = () => options.timeoutErrorText?.() ?? options.unknownErrorText()
|
||||||
|
const sessionId = crypto.randomUUID()
|
||||||
return {
|
return {
|
||||||
stream(request: AgentStreamRequest, cb) {
|
stream(request: AgentStreamRequest, cb) {
|
||||||
const requestId = crypto.randomUUID()
|
const requestId = crypto.randomUUID()
|
||||||
@@ -129,6 +133,7 @@ export function createIpcTransport<S>(options: IpcTransportOptions<S>): AgentTra
|
|||||||
Promise.resolve(
|
Promise.resolve(
|
||||||
options.start({
|
options.start({
|
||||||
requestId,
|
requestId,
|
||||||
|
sessionId,
|
||||||
settings: options.getSettings(),
|
settings: options.getSettings(),
|
||||||
system: request.system,
|
system: request.system,
|
||||||
messages: request.messages,
|
messages: request.messages,
|
||||||
|
|||||||
@@ -6,7 +6,9 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Multi-provider LLM streaming + one-shot chat client (Claude/Gemini/DeepSeek/OpenAI/custom), shared by AI Docs and future apps (Excel / PPT)",
|
"description": "Multi-provider LLM streaming + one-shot chat client (Claude/Gemini/DeepSeek/OpenAI/custom), shared by AI Docs and future apps (Excel / PPT)",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts"
|
".": "./src/index.ts",
|
||||||
|
"./browser": "./src/browser.ts",
|
||||||
|
"./codex-app-server": "./src/codex-app-server.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/** Browser-safe settings surface. Keep Node-backed transports out of renderer bundles. */
|
||||||
|
export type {
|
||||||
|
AiProviderConfig,
|
||||||
|
AiProviderId,
|
||||||
|
AiProviderMeta,
|
||||||
|
AiSettings,
|
||||||
|
CodexModelCatalog,
|
||||||
|
} from './types'
|
||||||
|
export {
|
||||||
|
AI_PROVIDERS,
|
||||||
|
DEFAULT_MAX_OUTPUT_TOKENS,
|
||||||
|
MAX_MAX_OUTPUT_TOKENS,
|
||||||
|
MIN_MAX_OUTPUT_TOKENS,
|
||||||
|
clampMaxOutputTokens,
|
||||||
|
} from './providers'
|
||||||
|
export { getProviderAdapter, modelLacksVision } from './registry'
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { chatAnthropic } from './protocols/anthropic'
|
import { chatAnthropic } from './protocols/anthropic'
|
||||||
import { chatGemini } from './protocols/gemini'
|
import { chatGemini } from './protocols/gemini'
|
||||||
import { chatOpenAiCompatible } from './protocols/openai-compatible'
|
import { chatOpenAiCompatible } from './protocols/openai-compatible'
|
||||||
|
import { chatCodexAppServer } from './codex-app-server'
|
||||||
import { getProviderAdapter, type ResolvedEndpoint } from './registry'
|
import { getProviderAdapter, type ResolvedEndpoint } from './registry'
|
||||||
import type { AiChatResponse, AiProviderConfig, AiProviderId } from './types'
|
import type { AiChatResponse, AiProviderConfig, AiProviderId } from './types'
|
||||||
import { AI_CHAT_RESPONSE_TIMEOUT_MS, createStreamWatchdog } from './watchdog'
|
import { AI_CHAT_RESPONSE_TIMEOUT_MS, createStreamWatchdog } from './watchdog'
|
||||||
@@ -28,6 +29,8 @@ export async function chatForProvider(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
switch (endpoint.protocol) {
|
switch (endpoint.protocol) {
|
||||||
|
case 'codex-app-server':
|
||||||
|
return chatCodexAppServer(config, system, user, wd.signal)
|
||||||
case 'anthropic':
|
case 'anthropic':
|
||||||
return chatAnthropic(wd, config, system, user, endpoint.baseUrl)
|
return chatAnthropic(wd, config, system, user, endpoint.baseUrl)
|
||||||
case 'gemini':
|
case 'gemini':
|
||||||
|
|||||||
@@ -0,0 +1,867 @@
|
|||||||
|
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
|
||||||
|
import { createHash, randomUUID } from 'node:crypto'
|
||||||
|
import { access, mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises'
|
||||||
|
import { createInterface } from 'node:readline'
|
||||||
|
import { delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import type { AgentImage, AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent-core'
|
||||||
|
import type { AiChatResponse, AiProviderConfig, CodexModelCatalog } from './types'
|
||||||
|
import { parseToolInput, type StreamCallbacks } from './protocols/shared'
|
||||||
|
import { createStreamWatchdog } from './watchdog'
|
||||||
|
|
||||||
|
interface CodexAppServerTurn {
|
||||||
|
text: string
|
||||||
|
toolCalls: Array<{
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
inputJson: string
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RpcMessage {
|
||||||
|
id?: unknown
|
||||||
|
method?: unknown
|
||||||
|
params?: unknown
|
||||||
|
result?: unknown
|
||||||
|
error?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RpcError {
|
||||||
|
code?: unknown
|
||||||
|
message?: unknown
|
||||||
|
data?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PendingRequest {
|
||||||
|
resolve: (value: unknown) => void
|
||||||
|
reject: (error: Error) => void
|
||||||
|
timer: ReturnType<typeof setTimeout>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NativeSession {
|
||||||
|
threadId: string
|
||||||
|
signature: string
|
||||||
|
messageFingerprints: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ModelEntry {
|
||||||
|
id?: unknown
|
||||||
|
model?: unknown
|
||||||
|
hidden?: unknown
|
||||||
|
isDefault?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
const DIAGNOSTIC_LIMIT = 16_000
|
||||||
|
const REQUEST_TIMEOUT_MS = 30_000
|
||||||
|
const IDLE_SHUTDOWN_MS = 120_000
|
||||||
|
const MAX_NATIVE_SESSIONS = 64
|
||||||
|
const MAX_MODEL_PAGES = 10
|
||||||
|
const CODEX_TEMP_PREFIX = 'genoffice-codex-app-server-'
|
||||||
|
const CODEX_BASE_INSTRUCTIONS =
|
||||||
|
'You are the language-model backend embedded in GenOffice. Never inspect or modify local files, run shell commands, browse, call MCP, use apps, or invoke any built-in Codex tool. The caller supplies the complete relevant conversation and a JSON Schema. Return exactly one assistant response matching that schema; GenOffice itself executes document tools.'
|
||||||
|
|
||||||
|
function cleanCliPath(value: string | undefined): string {
|
||||||
|
const trimmed = (value ?? '').trim()
|
||||||
|
if (
|
||||||
|
trimmed.length >= 2 &&
|
||||||
|
((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
|
||||||
|
(trimmed.startsWith("'") && trimmed.endsWith("'")))
|
||||||
|
) {
|
||||||
|
return trimmed.slice(1, -1)
|
||||||
|
}
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CodexCliResolutionOptions {
|
||||||
|
/** Override used by tests and portable distributions with the desktop bin tree elsewhere. */
|
||||||
|
managedInstallRoot?: string | undefined
|
||||||
|
env?: NodeJS.ProcessEnv | undefined
|
||||||
|
platform?: NodeJS.Platform | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fileExists(path: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
return (await stat(path)).isFile()
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function managedCodexRoot(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string | undefined {
|
||||||
|
if (platform !== 'win32') return undefined
|
||||||
|
const localAppData = env.LOCALAPPDATA ?? env.LocalAppData
|
||||||
|
return localAppData ? join(localAppData, 'OpenAI', 'Codex', 'bin') : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInside(path: string, root: string, platform: NodeJS.Platform): boolean {
|
||||||
|
const normalizedPath = resolve(path)
|
||||||
|
const normalizedRoot = resolve(root)
|
||||||
|
const pathValue = platform === 'win32' ? normalizedPath.toLowerCase() : normalizedPath
|
||||||
|
const rootValue = platform === 'win32' ? normalizedRoot.toLowerCase() : normalizedRoot
|
||||||
|
return pathValue === rootValue || pathValue.startsWith(`${rootValue}${sep}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function newestManagedCodex(root: string, platform: NodeJS.Platform): Promise<string | null> {
|
||||||
|
let entries
|
||||||
|
try {
|
||||||
|
entries = await readdir(root, { withFileTypes: true })
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const executable = platform === 'win32' ? 'codex.exe' : 'codex'
|
||||||
|
const candidates = await Promise.all(
|
||||||
|
entries
|
||||||
|
.filter((entry) => entry.isDirectory())
|
||||||
|
.map(async (entry) => {
|
||||||
|
const path = join(root, entry.name, executable)
|
||||||
|
try {
|
||||||
|
const [info, directoryInfo] = await Promise.all([
|
||||||
|
stat(path),
|
||||||
|
stat(join(root, entry.name)),
|
||||||
|
])
|
||||||
|
if (!info.isFile()) return null
|
||||||
|
const companion =
|
||||||
|
platform !== 'win32' ||
|
||||||
|
(await fileExists(join(root, entry.name, 'codex-code-mode-host.exe')))
|
||||||
|
return { path, modified: Math.max(info.mtimeMs, directoryInfo.mtimeMs), companion }
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const found = candidates.filter((candidate) => candidate !== null)
|
||||||
|
const complete = found.filter((candidate) => candidate.companion)
|
||||||
|
const pool = complete.length > 0 ? complete : found
|
||||||
|
pool.sort((a, b) => b.modified - a.modified || b.path.localeCompare(a.path))
|
||||||
|
return pool[0]?.path ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
async function codexOnPath(
|
||||||
|
platform: NodeJS.Platform,
|
||||||
|
env: NodeJS.ProcessEnv,
|
||||||
|
): Promise<string | null> {
|
||||||
|
const pathValue = env.PATH ?? env.Path ?? env.path ?? ''
|
||||||
|
if (!pathValue) return null
|
||||||
|
const names = platform === 'win32' ? ['codex.exe'] : ['codex']
|
||||||
|
for (const directory of pathValue.split(platform === 'win32' ? ';' : delimiter)) {
|
||||||
|
const cleanDirectory = cleanCliPath(directory)
|
||||||
|
if (!cleanDirectory) continue
|
||||||
|
for (const name of names) {
|
||||||
|
const candidate = join(cleanDirectory, name)
|
||||||
|
if (!(await fileExists(candidate))) continue
|
||||||
|
if (platform !== 'win32') {
|
||||||
|
try {
|
||||||
|
await access(candidate)
|
||||||
|
} catch {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the current Codex CLI on demand. Desktop-managed paths contain a
|
||||||
|
* release hash, so a saved path inside that tree is intentionally treated as
|
||||||
|
* automatic and upgraded to the newest complete installation.
|
||||||
|
*/
|
||||||
|
export async function resolveCodexCliPath(
|
||||||
|
configuredPath?: string,
|
||||||
|
options: CodexCliResolutionOptions = {},
|
||||||
|
): Promise<string> {
|
||||||
|
const platform = options.platform ?? process.platform
|
||||||
|
const env = options.env ?? process.env
|
||||||
|
const managedRoot = options.managedInstallRoot ?? managedCodexRoot(platform, env)
|
||||||
|
const configured = cleanCliPath(configuredPath)
|
||||||
|
|
||||||
|
if (configured) {
|
||||||
|
const configuredExecutable =
|
||||||
|
isAbsolute(configured) && (await stat(configured).catch(() => null))?.isDirectory()
|
||||||
|
? join(configured, platform === 'win32' ? 'codex.exe' : 'codex')
|
||||||
|
: configured
|
||||||
|
const managed =
|
||||||
|
managedRoot && isAbsolute(configuredExecutable)
|
||||||
|
? isInside(configuredExecutable, managedRoot, platform)
|
||||||
|
: false
|
||||||
|
if (!managed) {
|
||||||
|
if (!isAbsolute(configuredExecutable)) return configuredExecutable
|
||||||
|
if (await fileExists(configuredExecutable)) return configuredExecutable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (managedRoot) {
|
||||||
|
const managed = await newestManagedCodex(managedRoot, platform)
|
||||||
|
if (managed) return managed
|
||||||
|
}
|
||||||
|
const fromPath = await codexOnPath(platform, env)
|
||||||
|
if (fromPath) return fromPath
|
||||||
|
throw new Error(
|
||||||
|
'Codex CLI was not found automatically. Install or open the Codex app, or set a custom codex executable path.',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendDiagnostic(current: string, chunk: Buffer | string): string {
|
||||||
|
const next = current + chunk.toString()
|
||||||
|
return next.length <= DIAGNOSTIC_LIMIT ? next : next.slice(-DIAGNOSTIC_LIMIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
function rpcError(error: unknown): Error {
|
||||||
|
const value = error && typeof error === 'object' ? (error as RpcError) : undefined
|
||||||
|
const message = typeof value?.message === 'string' ? value.message : 'Unknown app-server error'
|
||||||
|
const code = typeof value?.code === 'number' ? ` (${value.code})` : ''
|
||||||
|
const data = value?.data === undefined ? '' : `: ${JSON.stringify(value.data)}`
|
||||||
|
return new Error(`Codex app-server error${code}: ${message}${data}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelledError(): Error {
|
||||||
|
const error = new Error('Codex app-server request was cancelled')
|
||||||
|
error.name = 'AbortError'
|
||||||
|
return error
|
||||||
|
}
|
||||||
|
|
||||||
|
function codexChildEnv(cliPath: string): NodeJS.ProcessEnv {
|
||||||
|
const env = { ...process.env }
|
||||||
|
// Electron on Windows can omit HOME even though USERPROFILE is present. The
|
||||||
|
// native Codex launcher uses HOME to find its normal login/config directory.
|
||||||
|
if (process.platform === 'win32' && !env.HOME && env.USERPROFILE) env.HOME = env.USERPROFILE
|
||||||
|
if (isAbsolute(cliPath)) {
|
||||||
|
const key = Object.keys(env).find((name) => name.toLowerCase() === 'path') ?? 'PATH'
|
||||||
|
env[key] = `${dirname(cliPath)};${env[key] ?? ''}`
|
||||||
|
}
|
||||||
|
return env
|
||||||
|
}
|
||||||
|
|
||||||
|
export function codexAppServerLaunchArgs(): string[] {
|
||||||
|
return ['app-server', '--listen', 'stdio://']
|
||||||
|
}
|
||||||
|
|
||||||
|
class CodexAppServerClient {
|
||||||
|
private readonly child: ChildProcessWithoutNullStreams
|
||||||
|
private readonly pending = new Map<number, PendingRequest>()
|
||||||
|
private readonly notificationListeners = new Set<(message: RpcMessage) => void>()
|
||||||
|
private readonly sessions = new Map<string, NativeSession>()
|
||||||
|
private readonly initialized: Promise<void>
|
||||||
|
private nextId = 1
|
||||||
|
private stderr = ''
|
||||||
|
private closed = false
|
||||||
|
private users = 0
|
||||||
|
private idleTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly cliPath: string,
|
||||||
|
private readonly onClose: () => void,
|
||||||
|
) {
|
||||||
|
this.child = spawn(cliPath, codexAppServerLaunchArgs(), {
|
||||||
|
env: codexChildEnv(cliPath),
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
windowsHide: true,
|
||||||
|
})
|
||||||
|
const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity })
|
||||||
|
lines.on('line', (line) => this.onLine(line))
|
||||||
|
this.child.stderr.on('data', (chunk: Buffer) => {
|
||||||
|
this.stderr = appendDiagnostic(this.stderr, chunk)
|
||||||
|
})
|
||||||
|
this.child.once('error', (error) => this.fail(error))
|
||||||
|
this.child.once('close', (code) => {
|
||||||
|
const detail = this.stderr.trim()
|
||||||
|
this.fail(
|
||||||
|
new Error(`Codex app-server exited (${code ?? 'unknown'})${detail ? `: ${detail}` : ''}`),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
this.initialized = this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
get isClosed(): boolean {
|
||||||
|
return this.closed
|
||||||
|
}
|
||||||
|
|
||||||
|
retain(): void {
|
||||||
|
this.users++
|
||||||
|
clearTimeout(this.idleTimer)
|
||||||
|
this.idleTimer = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
release(): void {
|
||||||
|
this.users = Math.max(0, this.users - 1)
|
||||||
|
if (this.users > 0 || this.closed) return
|
||||||
|
this.idleTimer = setTimeout(() => this.close(), IDLE_SHUTDOWN_MS)
|
||||||
|
this.idleTimer.unref?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
async ready(): Promise<void> {
|
||||||
|
await this.initialized
|
||||||
|
}
|
||||||
|
|
||||||
|
async request(method: string, params: unknown, timeoutMs = REQUEST_TIMEOUT_MS): Promise<unknown> {
|
||||||
|
await this.initialized
|
||||||
|
return this.requestWire(method, params, timeoutMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
notify(method: string, params?: unknown): void {
|
||||||
|
this.write(params === undefined ? { method } : { method, params })
|
||||||
|
}
|
||||||
|
|
||||||
|
onNotification(listener: (message: RpcMessage) => void): () => void {
|
||||||
|
this.notificationListeners.add(listener)
|
||||||
|
return () => this.notificationListeners.delete(listener)
|
||||||
|
}
|
||||||
|
|
||||||
|
getSession(id: string): NativeSession | undefined {
|
||||||
|
return this.sessions.get(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
setSession(id: string, session: NativeSession): void {
|
||||||
|
this.sessions.delete(id)
|
||||||
|
this.sessions.set(id, session)
|
||||||
|
while (this.sessions.size > MAX_NATIVE_SESSIONS) {
|
||||||
|
const oldest = this.sessions.keys().next().value as string | undefined
|
||||||
|
if (!oldest) break
|
||||||
|
this.sessions.delete(oldest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteSession(id: string): void {
|
||||||
|
this.sessions.delete(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
this.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private async initialize(): Promise<void> {
|
||||||
|
await this.requestWire('initialize', {
|
||||||
|
clientInfo: { name: 'genoffice', title: 'GenOffice', version: '0.1.0' },
|
||||||
|
capabilities: { experimentalApi: false, requestAttestation: false },
|
||||||
|
})
|
||||||
|
this.notify('initialized')
|
||||||
|
}
|
||||||
|
|
||||||
|
private requestWire(
|
||||||
|
method: string,
|
||||||
|
params: unknown,
|
||||||
|
timeoutMs = REQUEST_TIMEOUT_MS,
|
||||||
|
): Promise<unknown> {
|
||||||
|
if (this.closed) return Promise.reject(new Error('Codex app-server is not running'))
|
||||||
|
const id = this.nextId++
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
this.pending.delete(id)
|
||||||
|
reject(new Error(`Codex app-server request timed out: ${method}`))
|
||||||
|
}, timeoutMs)
|
||||||
|
timer.unref?.()
|
||||||
|
this.pending.set(id, { resolve, reject, timer })
|
||||||
|
try {
|
||||||
|
this.write({ method, id, params })
|
||||||
|
} catch (error) {
|
||||||
|
clearTimeout(timer)
|
||||||
|
this.pending.delete(id)
|
||||||
|
reject(error instanceof Error ? error : new Error(String(error)))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private write(message: unknown): void {
|
||||||
|
if (this.closed || !this.child.stdin.writable) {
|
||||||
|
throw new Error('Codex app-server input is closed')
|
||||||
|
}
|
||||||
|
this.child.stdin.write(`${JSON.stringify(message)}\n`)
|
||||||
|
}
|
||||||
|
|
||||||
|
private onLine(line: string): void {
|
||||||
|
let message: RpcMessage
|
||||||
|
try {
|
||||||
|
message = JSON.parse(line) as RpcMessage
|
||||||
|
} catch {
|
||||||
|
this.stderr = appendDiagnostic(this.stderr, `\nInvalid stdout JSON: ${line}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (typeof message.method === 'string' && message.id !== undefined) {
|
||||||
|
// GenOffice deliberately disables Codex-owned tools. Reply instead of
|
||||||
|
// leaving an unexpected server request pending forever.
|
||||||
|
this.write({
|
||||||
|
id: message.id,
|
||||||
|
error: { code: -32601, message: `Unsupported server request: ${message.method}` },
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (typeof message.id === 'number') {
|
||||||
|
const pending = this.pending.get(message.id)
|
||||||
|
if (!pending) return
|
||||||
|
clearTimeout(pending.timer)
|
||||||
|
this.pending.delete(message.id)
|
||||||
|
if (message.error !== undefined) pending.reject(rpcError(message.error))
|
||||||
|
else pending.resolve(message.result)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (typeof message.method === 'string') {
|
||||||
|
for (const listener of this.notificationListeners) listener(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fail(error: Error): void {
|
||||||
|
if (this.closed) return
|
||||||
|
this.closed = true
|
||||||
|
clearTimeout(this.idleTimer)
|
||||||
|
for (const pending of this.pending.values()) {
|
||||||
|
clearTimeout(pending.timer)
|
||||||
|
pending.reject(error)
|
||||||
|
}
|
||||||
|
this.pending.clear()
|
||||||
|
this.sessions.clear()
|
||||||
|
this.notificationListeners.clear()
|
||||||
|
this.onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
private close(): void {
|
||||||
|
if (this.closed) return
|
||||||
|
try {
|
||||||
|
this.child.kill()
|
||||||
|
} finally {
|
||||||
|
this.fail(new Error('Codex app-server stopped after being idle'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const clients = new Map<string, CodexAppServerClient>()
|
||||||
|
|
||||||
|
/** Stop every child process during Electron shutdown or integration-test cleanup. */
|
||||||
|
export function shutdownCodexAppServers(): void {
|
||||||
|
for (const client of [...clients.values()]) client.stop()
|
||||||
|
clients.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clientFor(cliPathValue: string | undefined): Promise<CodexAppServerClient> {
|
||||||
|
const cliPath = await resolveCodexCliPath(cliPathValue)
|
||||||
|
const key = process.platform === 'win32' ? cliPath.toLowerCase() : cliPath
|
||||||
|
const existing = clients.get(key)
|
||||||
|
if (existing && !existing.isClosed) return existing
|
||||||
|
const client = new CodexAppServerClient(cliPath, () => {
|
||||||
|
if (clients.get(key) === client) clients.delete(key)
|
||||||
|
})
|
||||||
|
clients.set(key, client)
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
async function withClient<T>(
|
||||||
|
cliPath: string | undefined,
|
||||||
|
action: (client: CodexAppServerClient) => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
const client = await clientFor(cliPath)
|
||||||
|
client.retain()
|
||||||
|
try {
|
||||||
|
await client.ready()
|
||||||
|
return await action(client)
|
||||||
|
} finally {
|
||||||
|
client.release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function imageExtension(image: AgentImage): string {
|
||||||
|
const subtype = image.mime.split('/')[1]?.toLowerCase() ?? ''
|
||||||
|
if (subtype === 'jpeg' || subtype === 'jpg') return '.jpg'
|
||||||
|
if (subtype === 'png') return '.png'
|
||||||
|
if (subtype === 'webp') return '.webp'
|
||||||
|
if (subtype === 'gif') return '.gif'
|
||||||
|
return '.img'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function materializeImages(messages: AgentMessage[], tempDir: string): Promise<string[]> {
|
||||||
|
const paths: string[] = []
|
||||||
|
for (const message of messages) {
|
||||||
|
if (message.role !== 'user') continue
|
||||||
|
for (const image of message.images ?? []) {
|
||||||
|
const path = join(tempDir, `image-${paths.length + 1}${imageExtension(image)}`)
|
||||||
|
await writeFile(path, Buffer.from(image.base64, 'base64'))
|
||||||
|
paths.push(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
function conversationForPrompt(messages: AgentMessage[]): unknown[] {
|
||||||
|
let imageIndex = 0
|
||||||
|
return messages.map((message) => {
|
||||||
|
if (message.role === 'user') {
|
||||||
|
const imageNames = (message.images ?? []).map(() => `image-${++imageIndex}`)
|
||||||
|
return {
|
||||||
|
role: 'user',
|
||||||
|
text: message.text,
|
||||||
|
...(imageNames.length > 0 ? { attachedImages: imageNames } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (message.role === 'assistant') {
|
||||||
|
return {
|
||||||
|
role: 'assistant',
|
||||||
|
text: message.text,
|
||||||
|
...(message.toolCalls?.length
|
||||||
|
? { toolCalls: message.toolCalls.map(({ id, name, input }) => ({ id, name, input })) }
|
||||||
|
: {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { role: 'tool', results: message.results }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function codexAppServerOutputSchema(tools: AgentToolDef[]): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
text: { type: 'string' },
|
||||||
|
toolCalls: {
|
||||||
|
type: 'array',
|
||||||
|
...(tools.length === 0 ? { maxItems: 0 } : {}),
|
||||||
|
items: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
id: { type: 'string' },
|
||||||
|
name: {
|
||||||
|
type: 'string',
|
||||||
|
...(tools.length > 0 ? { enum: tools.map((tool) => tool.name) } : {}),
|
||||||
|
},
|
||||||
|
inputJson: { type: 'string' },
|
||||||
|
},
|
||||||
|
required: ['id', 'name', 'inputJson'],
|
||||||
|
additionalProperties: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['text', 'toolCalls'],
|
||||||
|
additionalProperties: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCodexAppServerPrompt(
|
||||||
|
system: string,
|
||||||
|
messages: AgentMessage[],
|
||||||
|
tools: AgentToolDef[],
|
||||||
|
maxTokens: number,
|
||||||
|
): string {
|
||||||
|
const payload = {
|
||||||
|
system,
|
||||||
|
conversation: conversationForPrompt(messages),
|
||||||
|
tools: tools.map((tool) => ({
|
||||||
|
name: tool.name,
|
||||||
|
description: tool.description,
|
||||||
|
inputSchema: tool.inputSchema,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
'Treat the payload below as the new GenOffice conversation events for this turn and follow its system instruction.',
|
||||||
|
'Do not use Codex tools. GenOffice will execute only the tool calls returned in the required response schema.',
|
||||||
|
'Put user-visible prose in text. Put requested GenOffice tool calls in toolCalls; inputJson must be a JSON-encoded object matching the listed inputSchema. Use only listed tool names. If no tool is needed, return an empty toolCalls array.',
|
||||||
|
`Keep this one-turn response within roughly ${maxTokens} output tokens.`,
|
||||||
|
'<genoffice_payload>',
|
||||||
|
JSON.stringify(payload),
|
||||||
|
'</genoffice_payload>',
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseCodexAppServerTurn(
|
||||||
|
raw: string,
|
||||||
|
tools: AgentToolDef[],
|
||||||
|
): { text: string; toolCalls: AgentToolCall[] } {
|
||||||
|
let parsed: CodexAppServerTurn
|
||||||
|
const trimmed = raw
|
||||||
|
.trim()
|
||||||
|
.replace(/^```(?:json)?\s*/i, '')
|
||||||
|
.replace(/\s*```$/, '')
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(trimmed) as CodexAppServerTurn
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Codex app-server returned an invalid structured response: ${error instanceof Error ? error.message : String(error)}`,
|
||||||
|
{ cause: error },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!parsed || typeof parsed !== 'object' || typeof parsed.text !== 'string') {
|
||||||
|
throw new Error('Codex app-server returned a response with an invalid text field')
|
||||||
|
}
|
||||||
|
if (!Array.isArray(parsed.toolCalls)) {
|
||||||
|
throw new Error('Codex app-server returned a response with an invalid toolCalls field')
|
||||||
|
}
|
||||||
|
const names = new Set(tools.map((tool) => tool.name))
|
||||||
|
const toolCalls = parsed.toolCalls.map((call): AgentToolCall => {
|
||||||
|
if (!call || typeof call !== 'object' || typeof call.name !== 'string') {
|
||||||
|
throw new Error('Codex app-server returned an invalid tool call')
|
||||||
|
}
|
||||||
|
if (!names.has(call.name)) {
|
||||||
|
throw new Error(`Codex app-server requested an unknown tool: ${call.name}`)
|
||||||
|
}
|
||||||
|
const { input, error } = parseToolInput(
|
||||||
|
typeof call.inputJson === 'string' ? call.inputJson : '',
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
id: typeof call.id === 'string' && call.id ? call.id : `codex-${randomUUID()}`,
|
||||||
|
name: call.name,
|
||||||
|
input,
|
||||||
|
...(error ? { inputError: error } : {}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (!parsed.text && toolCalls.length === 0) {
|
||||||
|
throw new Error('Codex app-server returned no content')
|
||||||
|
}
|
||||||
|
return { text: parsed.text, toolCalls }
|
||||||
|
}
|
||||||
|
|
||||||
|
function fingerprint(message: AgentMessage): string {
|
||||||
|
return createHash('sha256').update(JSON.stringify(message)).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionSignature(system: string, tools: AgentToolDef[], model: string): string {
|
||||||
|
return createHash('sha256').update(JSON.stringify({ system, tools, model })).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function incrementalMessages(
|
||||||
|
existing: NativeSession | undefined,
|
||||||
|
signature: string,
|
||||||
|
messages: AgentMessage[],
|
||||||
|
): AgentMessage[] | null {
|
||||||
|
if (!existing || existing.signature !== signature) return null
|
||||||
|
if (messages.length < existing.messageFingerprints.length) return null
|
||||||
|
for (let index = 0; index < existing.messageFingerprints.length; index++) {
|
||||||
|
if (fingerprint(messages[index]!) !== existing.messageFingerprints[index]) return null
|
||||||
|
}
|
||||||
|
// The assistant response is already native app-server history. GenOffice's
|
||||||
|
// following tool results or user message are the only new events to inject.
|
||||||
|
return messages.slice(existing.messageFingerprints.length).filter((m) => m.role !== 'assistant')
|
||||||
|
}
|
||||||
|
|
||||||
|
function objectValue(value: unknown): Record<string, unknown> | undefined {
|
||||||
|
return value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function threadIdFrom(result: unknown): string {
|
||||||
|
const thread = objectValue(objectValue(result)?.thread)
|
||||||
|
if (typeof thread?.id !== 'string' || !thread.id) {
|
||||||
|
throw new Error('Codex app-server did not return a thread id')
|
||||||
|
}
|
||||||
|
return thread.id
|
||||||
|
}
|
||||||
|
|
||||||
|
function finalMessageFromTurn(params: unknown): string {
|
||||||
|
const turn = objectValue(objectValue(params)?.turn)
|
||||||
|
const items = Array.isArray(turn?.items) ? turn.items : []
|
||||||
|
for (let index = items.length - 1; index >= 0; index--) {
|
||||||
|
const item = objectValue(items[index])
|
||||||
|
if (item?.type === 'agentMessage' && typeof item.text === 'string') return item.text
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startNativeThread(
|
||||||
|
client: CodexAppServerClient,
|
||||||
|
config: AiProviderConfig,
|
||||||
|
tempDir: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const result = await client.request('thread/start', {
|
||||||
|
...(config.model.trim() ? { model: config.model.trim() } : {}),
|
||||||
|
cwd: tempDir,
|
||||||
|
approvalPolicy: 'never',
|
||||||
|
sandbox: 'read-only',
|
||||||
|
serviceName: 'genoffice',
|
||||||
|
baseInstructions: CODEX_BASE_INSTRUCTIONS,
|
||||||
|
ephemeral: true,
|
||||||
|
})
|
||||||
|
return threadIdFrom(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForTurn(
|
||||||
|
client: CodexAppServerClient,
|
||||||
|
threadId: string,
|
||||||
|
start: () => Promise<unknown>,
|
||||||
|
signal: AbortSignal,
|
||||||
|
cb: StreamCallbacks,
|
||||||
|
): Promise<string> {
|
||||||
|
if (signal.aborted) throw cancelledError()
|
||||||
|
let turnId = ''
|
||||||
|
let finalText = ''
|
||||||
|
let settled = false
|
||||||
|
return new Promise<string>((resolve, reject) => {
|
||||||
|
const finish = (error?: Error) => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
unsubscribe()
|
||||||
|
signal.removeEventListener('abort', onAbort)
|
||||||
|
if (error) reject(error)
|
||||||
|
else resolve(finalText)
|
||||||
|
}
|
||||||
|
const onAbort = () => {
|
||||||
|
if (turnId) {
|
||||||
|
void client.request('turn/interrupt', { threadId, turnId }).catch(() => undefined)
|
||||||
|
}
|
||||||
|
finish(cancelledError())
|
||||||
|
}
|
||||||
|
const unsubscribe = client.onNotification((message) => {
|
||||||
|
const params = objectValue(message.params)
|
||||||
|
if (params?.threadId !== threadId) return
|
||||||
|
cb.onActivity?.()
|
||||||
|
const eventTurnId = typeof params.turnId === 'string' ? params.turnId : ''
|
||||||
|
if (turnId && eventTurnId && eventTurnId !== turnId) return
|
||||||
|
if (message.method === 'turn/started') {
|
||||||
|
const turn = objectValue(params.turn)
|
||||||
|
if (typeof turn?.id === 'string') turnId = turn.id
|
||||||
|
} else if (message.method === 'item/completed') {
|
||||||
|
const item = objectValue(params.item)
|
||||||
|
if (item?.type === 'agentMessage' && typeof item.text === 'string') finalText = item.text
|
||||||
|
} else if (message.method === 'item/reasoning/summaryTextDelta') {
|
||||||
|
if (typeof params.delta === 'string') cb.onReasoningDelta?.(params.delta)
|
||||||
|
} else if (message.method === 'turn/completed') {
|
||||||
|
const turn = objectValue(params.turn)
|
||||||
|
if (typeof turn?.id === 'string') turnId = turn.id
|
||||||
|
if (!finalText) finalText = finalMessageFromTurn(params)
|
||||||
|
if (turn?.status === 'failed') {
|
||||||
|
const error = objectValue(turn.error)
|
||||||
|
finish(
|
||||||
|
new Error(typeof error?.message === 'string' ? error.message : 'Codex turn failed'),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
} else if (message.method === 'error') {
|
||||||
|
const error = objectValue(params.error) ?? params
|
||||||
|
finish(new Error(typeof error?.message === 'string' ? error.message : 'Codex turn failed'))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
signal.addEventListener('abort', onAbort, { once: true })
|
||||||
|
void start()
|
||||||
|
.then((result) => {
|
||||||
|
const turn = objectValue(objectValue(result)?.turn)
|
||||||
|
if (typeof turn?.id === 'string') turnId = turn.id
|
||||||
|
})
|
||||||
|
.catch((error) => finish(error instanceof Error ? error : new Error(String(error))))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runCodexAppServer(
|
||||||
|
config: AiProviderConfig,
|
||||||
|
system: string,
|
||||||
|
messages: AgentMessage[],
|
||||||
|
tools: AgentToolDef[],
|
||||||
|
maxTokens: number,
|
||||||
|
cb: StreamCallbacks,
|
||||||
|
): Promise<void> {
|
||||||
|
const tempDir = await mkdtemp(join(tmpdir(), CODEX_TEMP_PREFIX))
|
||||||
|
const nativeSessionId = cb.sessionId ?? `one-shot-${randomUUID()}`
|
||||||
|
try {
|
||||||
|
await withClient(config.cliPath, async (client) => {
|
||||||
|
const signature = sessionSignature(system, tools, config.model.trim())
|
||||||
|
let session = client.getSession(nativeSessionId)
|
||||||
|
let nextMessages = incrementalMessages(session, signature, messages)
|
||||||
|
if (!session || nextMessages === null) {
|
||||||
|
session = {
|
||||||
|
threadId: await startNativeThread(client, config, tempDir),
|
||||||
|
signature,
|
||||||
|
messageFingerprints: [],
|
||||||
|
}
|
||||||
|
client.setSession(nativeSessionId, session)
|
||||||
|
nextMessages = messages
|
||||||
|
}
|
||||||
|
const imagePaths = await materializeImages(nextMessages, tempDir)
|
||||||
|
const prompt = buildCodexAppServerPrompt(system, nextMessages, tools, maxTokens)
|
||||||
|
try {
|
||||||
|
const raw = await waitForTurn(
|
||||||
|
client,
|
||||||
|
session.threadId,
|
||||||
|
() =>
|
||||||
|
client.request('turn/start', {
|
||||||
|
threadId: session.threadId,
|
||||||
|
input: [
|
||||||
|
{ type: 'text', text: prompt, text_elements: [] },
|
||||||
|
...imagePaths.map((path) => ({ type: 'localImage', path })),
|
||||||
|
],
|
||||||
|
outputSchema: codexAppServerOutputSchema(tools),
|
||||||
|
}),
|
||||||
|
cb.signal,
|
||||||
|
cb,
|
||||||
|
)
|
||||||
|
const turn = parseCodexAppServerTurn(raw, tools)
|
||||||
|
session.messageFingerprints = messages.map(fingerprint)
|
||||||
|
if (turn.text) cb.onDelta(turn.text)
|
||||||
|
for (const call of turn.toolCalls) cb.onToolCall(call)
|
||||||
|
} catch (error) {
|
||||||
|
client.deleteSession(nativeSessionId)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
await rm(tempDir, { recursive: true, force: true }).catch(() => undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function streamCodexAppServer(
|
||||||
|
config: AiProviderConfig,
|
||||||
|
system: string,
|
||||||
|
messages: AgentMessage[],
|
||||||
|
tools: AgentToolDef[],
|
||||||
|
maxTokens: number,
|
||||||
|
cb: StreamCallbacks,
|
||||||
|
): Promise<void> {
|
||||||
|
const wd = createStreamWatchdog(cb.signal)
|
||||||
|
return wd.guard(() =>
|
||||||
|
runCodexAppServer(config, system, messages, tools, maxTokens, {
|
||||||
|
...cb,
|
||||||
|
signal: wd.signal,
|
||||||
|
onActivity: () => {
|
||||||
|
wd.touch()
|
||||||
|
cb.onActivity?.()
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function chatCodexAppServer(
|
||||||
|
config: AiProviderConfig,
|
||||||
|
system: string,
|
||||||
|
user: string,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<AiChatResponse> {
|
||||||
|
let content = ''
|
||||||
|
await runCodexAppServer(config, system, [{ role: 'user', text: user }], [], 1024, {
|
||||||
|
signal,
|
||||||
|
sessionId: `chat-${randomUUID()}`,
|
||||||
|
onDelta: (text) => {
|
||||||
|
content += text
|
||||||
|
},
|
||||||
|
onToolCall: () => undefined,
|
||||||
|
})
|
||||||
|
return content
|
||||||
|
? { ok: true, content }
|
||||||
|
: { ok: false, error: 'Codex app-server returned no content' }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listCodexModels(cliPath?: string): Promise<CodexModelCatalog> {
|
||||||
|
return withClient(cliPath, async (client) => {
|
||||||
|
const account = objectValue(await client.request('account/read', { refreshToken: false }))
|
||||||
|
if (account?.requiresOpenaiAuth === true && account.account == null) {
|
||||||
|
throw new Error('Codex CLI is not signed in. Run codex login, then try again.')
|
||||||
|
}
|
||||||
|
const models: string[] = []
|
||||||
|
let defaultModel = ''
|
||||||
|
let cursor: string | null = null
|
||||||
|
for (let page = 0; page < MAX_MODEL_PAGES; page++) {
|
||||||
|
const result = objectValue(
|
||||||
|
await client.request('model/list', { cursor, limit: 100, includeHidden: false }),
|
||||||
|
)
|
||||||
|
const data = Array.isArray(result?.data) ? result.data : []
|
||||||
|
for (const value of data) {
|
||||||
|
const entry = objectValue(value) as ModelEntry | undefined
|
||||||
|
if (!entry || entry.hidden === true) continue
|
||||||
|
const id =
|
||||||
|
typeof entry.id === 'string'
|
||||||
|
? entry.id
|
||||||
|
: typeof entry.model === 'string'
|
||||||
|
? entry.model
|
||||||
|
: ''
|
||||||
|
if (!id || models.includes(id)) continue
|
||||||
|
models.push(id)
|
||||||
|
if (entry.isDefault === true) defaultModel = id
|
||||||
|
}
|
||||||
|
cursor = typeof result?.nextCursor === 'string' ? result.nextCursor : null
|
||||||
|
if (!cursor) break
|
||||||
|
}
|
||||||
|
if (!defaultModel) defaultModel = models[0] ?? ''
|
||||||
|
return { models, defaultModel }
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
export type {
|
export type {
|
||||||
AiChatRequest,
|
AiChatRequest,
|
||||||
AiChatResponse,
|
AiChatResponse,
|
||||||
|
CodexModelCatalog,
|
||||||
AiProviderConfig,
|
AiProviderConfig,
|
||||||
AiProviderId,
|
AiProviderId,
|
||||||
AiProviderMeta,
|
AiProviderMeta,
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ export interface StreamCallbacks {
|
|||||||
onStopReason?: (reason: string) => void
|
onStopReason?: (reason: string) => void
|
||||||
/** bytes arrived on the wire (fires per network chunk, including SSE pings; used for keepalive) */
|
/** bytes arrived on the wire (fires per network chunk, including SSE pings; used for keepalive) */
|
||||||
onActivity?: () => void
|
onActivity?: () => void
|
||||||
|
/** Stable renderer transport id for providers with native sessions. */
|
||||||
|
sessionId?: string
|
||||||
signal: AbortSignal
|
signal: AbortSignal
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ export const AI_PROVIDERS: AiProviderMeta[] = [
|
|||||||
defaultModel: 'claude-opus-4-7',
|
defaultModel: 'claude-opus-4-7',
|
||||||
keyPlaceholder: 'Not required - sign in to Genspark',
|
keyPlaceholder: 'Not required - sign in to Genspark',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'codex',
|
||||||
|
label: 'Codex CLI',
|
||||||
|
// Populated at runtime from codex app-server model/list. Empty also lets
|
||||||
|
// the CLI select the account's current default without a stale hardcode.
|
||||||
|
models: [],
|
||||||
|
defaultModel: '',
|
||||||
|
keyPlaceholder: '',
|
||||||
|
needsCliPath: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: 'anthropic',
|
id: 'anthropic',
|
||||||
label: 'Claude',
|
label: 'Claude',
|
||||||
@@ -234,6 +244,7 @@ export function defaultAiSettings(
|
|||||||
apiKey: defaultApiKeys?.[meta.id] ?? '',
|
apiKey: defaultApiKeys?.[meta.id] ?? '',
|
||||||
model: meta.defaultModel,
|
model: meta.defaultModel,
|
||||||
baseUrl: meta.needsBaseUrl ? '' : undefined,
|
baseUrl: meta.needsBaseUrl ? '' : undefined,
|
||||||
|
cliPath: meta.needsCliPath ? '' : undefined,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { provider: 'genspark', providers, gskToolsEnabled: true }
|
return { provider: 'genspark', providers, gskToolsEnabled: true }
|
||||||
@@ -246,8 +257,8 @@ export function cloudToolsEnabled(settings: Pick<AiSettings, 'gskToolsEnabled'>)
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The stored provider selection is honored only when its config is usable
|
* The stored provider selection is honored only when its config is usable
|
||||||
* (api-key providers need a key and a model id; providers flagged
|
* (api-key providers need a key and a model id; custom also needs a base URL).
|
||||||
* needsBaseUrl also need a base URL). Anything else — including unknown
|
* Codex can auto-discover its executable. Anything else — including unknown
|
||||||
* ids from a hand-edited
|
* ids from a hand-edited
|
||||||
* settings file — falls back to genspark, so a half-filled setup degrades
|
* settings file — falls back to genspark, so a half-filled setup degrades
|
||||||
* to the signed-in default instead of silently disabling AI.
|
* to the signed-in default instead of silently disabling AI.
|
||||||
@@ -257,7 +268,9 @@ export function activeProvider(settings: AiSettings): AiProviderId {
|
|||||||
if (provider === 'genspark') return 'genspark'
|
if (provider === 'genspark') return 'genspark'
|
||||||
const meta = AI_PROVIDERS.find((m) => m.id === provider)
|
const meta = AI_PROVIDERS.find((m) => m.id === provider)
|
||||||
const config = settings.providers?.[provider]
|
const config = settings.providers?.[provider]
|
||||||
if (!meta || !config?.model) return 'genspark'
|
if (!meta || !config) return 'genspark'
|
||||||
|
if (meta.needsCliPath) return provider
|
||||||
|
if (!config.model) return 'genspark'
|
||||||
if (meta.needsBaseUrl) {
|
if (meta.needsBaseUrl) {
|
||||||
// Custom OpenAI-compatible endpoints (Ollama, LM Studio, vLLM) accept
|
// Custom OpenAI-compatible endpoints (Ollama, LM Studio, vLLM) accept
|
||||||
// anonymous requests: base URL + model suffice, the key stays optional.
|
// anonymous requests: base URL + model suffice, the key stays optional.
|
||||||
@@ -328,6 +341,7 @@ function trimConfigs(providers: AiSettings['providers']): AiSettings['providers'
|
|||||||
apiKey: config.apiKey?.trim() ?? '',
|
apiKey: config.apiKey?.trim() ?? '',
|
||||||
model: config.model?.trim() ?? '',
|
model: config.model?.trim() ?? '',
|
||||||
...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl.trim() } : {}),
|
...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl.trim() } : {}),
|
||||||
|
...(config.cliPath !== undefined ? { cliPath: config.cliPath.trim() } : {}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return trimmed
|
return trimmed
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ import { GEMINI_BASE_URL } from './protocols/gemini'
|
|||||||
import { AI_PROVIDERS, GENSPARK_LLM_BASE_URLS } from './providers'
|
import { AI_PROVIDERS, GENSPARK_LLM_BASE_URLS } from './providers'
|
||||||
import type { AiProviderConfig, AiProviderId, AiProviderMeta } from './types'
|
import type { AiProviderConfig, AiProviderId, AiProviderMeta } from './types'
|
||||||
|
|
||||||
/** The three wire protocols every provider maps onto. */
|
/** Wire protocols every provider maps onto, including the official Codex app-server bridge. */
|
||||||
export type AiProtocol = 'anthropic' | 'gemini' | 'openai-compatible'
|
export type AiProtocol = 'anthropic' | 'gemini' | 'openai-compatible' | 'codex-app-server'
|
||||||
|
|
||||||
export interface ProviderCapabilities {
|
export interface ProviderCapabilities {
|
||||||
/** 'gsk-login': the Genspark session key is injected by the main process; 'api-key': the user supplies their own key */
|
/** How the provider authenticates: app login, user key, or the Codex CLI's existing login. */
|
||||||
auth: 'gsk-login' | 'api-key'
|
auth: 'gsk-login' | 'api-key' | 'codex-chatgpt'
|
||||||
/** chat models accept image input (declarative; for custom endpoints it is assumed, not known) */
|
/** chat models accept image input (declarative; for custom endpoints it is assumed, not known) */
|
||||||
vision: boolean
|
vision: boolean
|
||||||
}
|
}
|
||||||
@@ -150,6 +150,13 @@ export const AI_PROVIDER_ADAPTERS: Record<AiProviderId, ProviderAdapter> = {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
codex: {
|
||||||
|
meta: metaOf('codex'),
|
||||||
|
capabilities: { auth: 'codex-chatgpt', vision: true },
|
||||||
|
resolveEndpoint() {
|
||||||
|
return { protocol: 'codex-app-server', baseUrl: '' }
|
||||||
|
},
|
||||||
|
},
|
||||||
anthropic: {
|
anthropic: {
|
||||||
meta: metaOf('anthropic'),
|
meta: metaOf('anthropic'),
|
||||||
capabilities: { auth: 'api-key', vision: true },
|
capabilities: { auth: 'api-key', vision: true },
|
||||||
|
|||||||
@@ -3,8 +3,9 @@ import { withOutputCapFallback } from './output-cap'
|
|||||||
import { streamAnthropic } from './protocols/anthropic'
|
import { streamAnthropic } from './protocols/anthropic'
|
||||||
import { streamGemini } from './protocols/gemini'
|
import { streamGemini } from './protocols/gemini'
|
||||||
import { streamOpenAiCompatible } from './protocols/openai-compatible'
|
import { streamOpenAiCompatible } from './protocols/openai-compatible'
|
||||||
|
import { streamCodexAppServer } from './codex-app-server'
|
||||||
import type { StreamCallbacks } from './protocols/shared'
|
import type { StreamCallbacks } from './protocols/shared'
|
||||||
import { getProviderAdapter } from './registry'
|
import { getProviderAdapter, type AiProtocol } from './registry'
|
||||||
import type { AiProviderConfig, AiProviderId } from './types'
|
import type { AiProviderConfig, AiProviderId } from './types'
|
||||||
|
|
||||||
export { streamAnthropic } from './protocols/anthropic'
|
export { streamAnthropic } from './protocols/anthropic'
|
||||||
@@ -25,8 +26,12 @@ export async function streamForProvider(
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const endpoint = getProviderAdapter(provider).resolveEndpoint(config)
|
const endpoint = getProviderAdapter(provider).resolveEndpoint(config)
|
||||||
const { baseUrl } = endpoint
|
const { baseUrl } = endpoint
|
||||||
|
if (endpoint.protocol === 'codex-app-server') {
|
||||||
|
return streamCodexAppServer(config, system, messages, tools, maxTokens, cb)
|
||||||
|
}
|
||||||
|
const protocol: Exclude<AiProtocol, 'codex-app-server'> = endpoint.protocol
|
||||||
return withOutputCapFallback(baseUrl, config.model, maxTokens, (cap) => {
|
return withOutputCapFallback(baseUrl, config.model, maxTokens, (cap) => {
|
||||||
switch (endpoint.protocol) {
|
switch (protocol) {
|
||||||
case 'anthropic':
|
case 'anthropic':
|
||||||
return streamAnthropic(config, system, messages, tools, cap, cb, baseUrl)
|
return streamAnthropic(config, system, messages, tools, cap, cb, baseUrl)
|
||||||
case 'gemini':
|
case 'gemini':
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent
|
|||||||
|
|
||||||
export type AiProviderId =
|
export type AiProviderId =
|
||||||
| 'genspark'
|
| 'genspark'
|
||||||
|
| 'codex'
|
||||||
| 'anthropic'
|
| 'anthropic'
|
||||||
| 'gemini'
|
| 'gemini'
|
||||||
| 'deepseek'
|
| 'deepseek'
|
||||||
@@ -29,6 +30,14 @@ export interface AiProviderConfig {
|
|||||||
model: string
|
model: string
|
||||||
/** required for custom; for other direct providers it overrides the default endpoint (regional mirrors) */
|
/** required for custom; for other direct providers it overrides the default endpoint (regional mirrors) */
|
||||||
baseUrl?: string | undefined
|
baseUrl?: string | undefined
|
||||||
|
/** optional Codex CLI override; empty means auto-detect the current authenticated install */
|
||||||
|
cliPath?: string | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Live picker data returned by Codex app-server's model/list method. */
|
||||||
|
export interface CodexModelCatalog {
|
||||||
|
models: string[]
|
||||||
|
defaultModel: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AiProviderMeta {
|
export interface AiProviderMeta {
|
||||||
@@ -38,6 +47,7 @@ export interface AiProviderMeta {
|
|||||||
defaultModel: string
|
defaultModel: string
|
||||||
keyPlaceholder: string
|
keyPlaceholder: string
|
||||||
needsBaseUrl?: boolean
|
needsBaseUrl?: boolean
|
||||||
|
needsCliPath?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AiSettings {
|
export interface AiSettings {
|
||||||
@@ -82,6 +92,8 @@ export interface AiChatResponse {
|
|||||||
|
|
||||||
export interface AiStreamRequest {
|
export interface AiStreamRequest {
|
||||||
requestId: string
|
requestId: string
|
||||||
|
/** Stable renderer transport id used to retain native provider sessions. */
|
||||||
|
sessionId?: string
|
||||||
settings: AiSettings
|
settings: AiSettings
|
||||||
system: string
|
system: string
|
||||||
messages: AgentMessage[]
|
messages: AgentMessage[]
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { mkdtemp, mkdir, rm, utimes, writeFile } from 'node:fs/promises'
|
||||||
|
import { join } from 'node:path'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import type { AgentToolDef } from '@genoffice/agent-core'
|
||||||
|
import {
|
||||||
|
buildCodexAppServerPrompt,
|
||||||
|
codexAppServerLaunchArgs,
|
||||||
|
codexAppServerOutputSchema,
|
||||||
|
parseCodexAppServerTurn,
|
||||||
|
resolveCodexCliPath,
|
||||||
|
} from '../src/codex-app-server'
|
||||||
|
|
||||||
|
const tools: AgentToolDef[] = [
|
||||||
|
{
|
||||||
|
name: 'replace_text',
|
||||||
|
description: 'Replace document text',
|
||||||
|
inputSchema: {
|
||||||
|
type: 'object',
|
||||||
|
properties: { before: { type: 'string' }, after: { type: 'string' } },
|
||||||
|
required: ['before', 'after'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
describe('Codex app-server bridge', () => {
|
||||||
|
it('automatically selects the newest complete desktop-managed Codex install', async () => {
|
||||||
|
const root = await mkdtemp(join(tmpdir(), 'genoffice-codex-discovery-'))
|
||||||
|
try {
|
||||||
|
const older = join(root, 'old-release')
|
||||||
|
const newer = join(root, 'new-release')
|
||||||
|
await mkdir(older)
|
||||||
|
await mkdir(newer)
|
||||||
|
for (const directory of [older, newer]) {
|
||||||
|
await writeFile(join(directory, 'codex.exe'), '')
|
||||||
|
await writeFile(join(directory, 'codex-code-mode-host.exe'), '')
|
||||||
|
}
|
||||||
|
await utimes(join(older, 'codex.exe'), new Date(1_000), new Date(1_000))
|
||||||
|
await utimes(join(newer, 'codex.exe'), new Date(2_000), new Date(2_000))
|
||||||
|
await utimes(older, new Date(1_000), new Date(1_000))
|
||||||
|
await utimes(newer, new Date(2_000), new Date(2_000))
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
resolveCodexCliPath('', { platform: 'win32', managedInstallRoot: root, env: {} }),
|
||||||
|
).resolves.toBe(join(newer, 'codex.exe'))
|
||||||
|
} finally {
|
||||||
|
await rm(root, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('migrates a stale saved hash path to the current managed install', async () => {
|
||||||
|
const root = await mkdtemp(join(tmpdir(), 'genoffice-codex-migration-'))
|
||||||
|
try {
|
||||||
|
const current = join(root, 'current-release')
|
||||||
|
await mkdir(current)
|
||||||
|
await writeFile(join(current, 'codex.exe'), '')
|
||||||
|
await writeFile(join(current, 'codex-code-mode-host.exe'), '')
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
resolveCodexCliPath(join(root, 'removed-release', 'codex.exe'), {
|
||||||
|
platform: 'win32',
|
||||||
|
managedInstallRoot: root,
|
||||||
|
env: {},
|
||||||
|
}),
|
||||||
|
).resolves.toBe(join(current, 'codex.exe'))
|
||||||
|
} finally {
|
||||||
|
await rm(root, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('starts the official stdio app-server instead of assuming an HTTP endpoint', () => {
|
||||||
|
expect(codexAppServerLaunchArgs()).toEqual(['app-server', '--listen', 'stdio://'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('builds a strict one-turn output schema with only known tool names', () => {
|
||||||
|
const schema = codexAppServerOutputSchema(tools) as {
|
||||||
|
properties: { toolCalls: { items: { properties: { name: { enum: string[] } } } } }
|
||||||
|
}
|
||||||
|
expect(schema.properties.toolCalls.items.properties.name.enum).toEqual(['replace_text'])
|
||||||
|
expect(codexAppServerOutputSchema([])).toMatchObject({
|
||||||
|
properties: { toolCalls: { maxItems: 0 } },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('serializes new conversation events, tool results and schemas', () => {
|
||||||
|
const prompt = buildCodexAppServerPrompt(
|
||||||
|
'Edit only when requested.',
|
||||||
|
[
|
||||||
|
{ role: 'user', text: 'Change A to B.' },
|
||||||
|
{
|
||||||
|
role: 'assistant',
|
||||||
|
text: '',
|
||||||
|
toolCalls: [{ id: 'call-1', name: 'replace_text', input: { before: 'A', after: 'B' } }],
|
||||||
|
},
|
||||||
|
{ role: 'tool', results: [{ id: 'call-1', name: 'replace_text', output: 'done' }] },
|
||||||
|
],
|
||||||
|
tools,
|
||||||
|
8192,
|
||||||
|
)
|
||||||
|
expect(prompt).toContain('Edit only when requested.')
|
||||||
|
expect(prompt).toContain('replace_text')
|
||||||
|
expect(prompt).toContain('"output":"done"')
|
||||||
|
expect(prompt).toContain('8192 output tokens')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('parses text and JSON-encoded GenOffice tool arguments', () => {
|
||||||
|
expect(
|
||||||
|
parseCodexAppServerTurn(
|
||||||
|
JSON.stringify({
|
||||||
|
text: 'I will make that change.',
|
||||||
|
toolCalls: [
|
||||||
|
{
|
||||||
|
id: 'call-1',
|
||||||
|
name: 'replace_text',
|
||||||
|
inputJson: JSON.stringify({ before: 'A', after: 'B' }),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
tools,
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
text: 'I will make that change.',
|
||||||
|
toolCalls: [{ id: 'call-1', name: 'replace_text', input: { before: 'A', after: 'B' } }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects unknown tools and empty final turns', () => {
|
||||||
|
expect(() =>
|
||||||
|
parseCodexAppServerTurn(
|
||||||
|
JSON.stringify({ text: '', toolCalls: [{ id: 'x', name: 'shell', inputJson: '{}' }] }),
|
||||||
|
tools,
|
||||||
|
),
|
||||||
|
).toThrow('unknown tool')
|
||||||
|
expect(() =>
|
||||||
|
parseCodexAppServerTurn(JSON.stringify({ text: '', toolCalls: [] }), tools),
|
||||||
|
).toThrow('no content')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -22,6 +22,8 @@ describe('defaultAiSettings', () => {
|
|||||||
expect(settings.providers[meta.id].model).toBe(meta.defaultModel)
|
expect(settings.providers[meta.id].model).toBe(meta.defaultModel)
|
||||||
}
|
}
|
||||||
expect(settings.providers.custom.baseUrl).toBe('')
|
expect(settings.providers.custom.baseUrl).toBe('')
|
||||||
|
expect(settings.providers.codex.cliPath).toBe('')
|
||||||
|
expect(settings.providers.codex.model).toBe('')
|
||||||
expect(settings.providers.anthropic.baseUrl).toBeUndefined()
|
expect(settings.providers.anthropic.baseUrl).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -265,6 +267,21 @@ describe('activeProvider', () => {
|
|||||||
expect(activeProvider(settings)).toBe('custom')
|
expect(activeProvider(settings)).toBe('custom')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('auto-discovers Codex without an API key and preserves an optional override', () => {
|
||||||
|
const settings = defaultAiSettings()
|
||||||
|
settings.provider = 'codex'
|
||||||
|
expect(activeProvider(settings)).toBe('codex')
|
||||||
|
settings.providers.codex.cliPath = ' C:\\Tools\\codex.exe '
|
||||||
|
expect(activeProvider(settings)).toBe('codex')
|
||||||
|
|
||||||
|
const resolved = resolveAiSettings(
|
||||||
|
{ providers: { codex: settings.providers.codex } as never },
|
||||||
|
defaultAiSettings(),
|
||||||
|
)
|
||||||
|
expect(resolved.providers.codex.cliPath).toBe('C:\\Tools\\codex.exe')
|
||||||
|
expect(resolved.providers.codex.apiKey).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
it('falls back to genspark for unknown ids from a hand-edited settings file', () => {
|
it('falls back to genspark for unknown ids from a hand-edited settings file', () => {
|
||||||
const settings = defaultAiSettings()
|
const settings = defaultAiSettings()
|
||||||
settings.provider = 'nonsense' as AiProviderId
|
settings.provider = 'nonsense' as AiProviderId
|
||||||
|
|||||||
@@ -212,10 +212,26 @@ describe('provider registry', () => {
|
|||||||
|
|
||||||
it('only genspark authenticates through the gsk login', () => {
|
it('only genspark authenticates through the gsk login', () => {
|
||||||
for (const [id, adapter] of Object.entries(AI_PROVIDER_ADAPTERS)) {
|
for (const [id, adapter] of Object.entries(AI_PROVIDER_ADAPTERS)) {
|
||||||
expect(adapter.capabilities.auth).toBe(id === 'genspark' ? 'gsk-login' : 'api-key')
|
expect(adapter.capabilities.auth).toBe(
|
||||||
|
id === 'genspark' ? 'gsk-login' : id === 'codex' ? 'codex-chatgpt' : 'api-key',
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('routes Codex to the auto-discovered local process bridge', () => {
|
||||||
|
expect(
|
||||||
|
AI_PROVIDER_ADAPTERS.codex.resolveEndpoint({
|
||||||
|
apiKey: '',
|
||||||
|
model: 'gpt-5.6-terra',
|
||||||
|
cliPath: 'C:\\Tools\\codex.exe',
|
||||||
|
}),
|
||||||
|
).toEqual({ protocol: 'codex-app-server', baseUrl: '' })
|
||||||
|
expect(AI_PROVIDER_ADAPTERS.codex.resolveEndpoint(config('gpt-5.6-terra'))).toEqual({
|
||||||
|
protocol: 'codex-app-server',
|
||||||
|
baseUrl: '',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('throws a typed error for ids outside the registry', () => {
|
it('throws a typed error for ids outside the registry', () => {
|
||||||
expect(() => getProviderAdapter('nonsense' as AiProviderId)).toThrow(
|
expect(() => getProviderAdapter('nonsense' as AiProviderId)).toThrow(
|
||||||
'Unknown provider: nonsense',
|
'Unknown provider: nonsense',
|
||||||
|
|||||||
Reference in New Issue
Block a user