Add dynamic AI Workspace run profiles
This commit is contained in:
@@ -765,6 +765,7 @@ const FINAL_MESSAGE_PHASES = new Set(['final', 'final_answer', 'answer'])
|
||||
const BRIDGE_FILE = fileURLToPath(import.meta.url)
|
||||
const BRIDGE_DIR = path.dirname(BRIDGE_FILE)
|
||||
const NDC_AGENT_CODEX_HOME = path.resolve(process.env.AI_BRIDGE_NDC_AGENT_CODEX_HOME || path.join(BRIDGE_DIR, 'codex-home-ndc-agent-core'))
|
||||
const RUN_CODEX_HOME_ROOT = path.resolve(process.env.AI_BRIDGE_RUN_CODEX_HOME_ROOT || path.join(BRIDGE_DIR, 'codex-home-runs'))
|
||||
const DEFAULT_NDC_AGENT_MCP_API_BASE = 'http://127.0.0.1:3001/api/ndc-agent-mcp'
|
||||
const HUB_URL = String(process.env.AI_BRIDGE_HUB_URL || '').trim()
|
||||
const HUB_URLS = parseHubUrls(process.env.AI_BRIDGE_HUB_URLS || '', HUB_URL)
|
||||
@@ -1047,6 +1048,8 @@ async function readConversations() {
|
||||
|
||||
function buildPrompt(payload) {
|
||||
const context = payload?.context && typeof payload.context === 'object' ? payload.context : {}
|
||||
const runProfile = payload?.runProfile && typeof payload.runProfile === 'object' ? payload.runProfile : {}
|
||||
const runProfilePolicyPrompt = String(runProfile.policyPrompt || '').trim()
|
||||
const userMessage = String(payload?.message || '').trim()
|
||||
const history = payload?.resume ? [] : normalizeHistory(payload?.history || [])
|
||||
const isNdcAgentCore = String(context.modeId || '').trim() === 'ndc-agent-core'
|
||||
@@ -1142,6 +1145,10 @@ function buildPrompt(payload) {
|
||||
'System context guard:',
|
||||
guardInstruction,
|
||||
] : [],
|
||||
...runProfilePolicyPrompt ? [
|
||||
'',
|
||||
runProfilePolicyPrompt,
|
||||
] : [],
|
||||
'',
|
||||
...history.length ? [
|
||||
'Recent conversation from AI Workspace:',
|
||||
@@ -1455,8 +1462,12 @@ function buildResumeArgs(sessionId) {
|
||||
return [...base, 'resume', clean, '-']
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value))
|
||||
}
|
||||
|
||||
function isNdcAgentCorePayload(payload) {
|
||||
const context = payload?.context && typeof payload.context === 'object' ? payload.context : {}
|
||||
const context = isPlainObject(payload?.context) ? payload.context : {}
|
||||
return String(context.modeId || '').trim() === 'ndc-agent-core'
|
||||
}
|
||||
|
||||
@@ -1564,6 +1575,124 @@ function tomlString(value) {
|
||||
return JSON.stringify(String(value || ''))
|
||||
}
|
||||
|
||||
function tomlKey(value) {
|
||||
const key = String(value || '').trim()
|
||||
if (/^[A-Za-z0-9_-]+$/.test(key)) return key
|
||||
return JSON.stringify(key)
|
||||
}
|
||||
|
||||
function cleanMcpServerName(value) {
|
||||
const text = String(value || '').trim().replace(/[^A-Za-z0-9_-]+/g, '_').replace(/^_+|_+$/g, '')
|
||||
return text.slice(0, 80)
|
||||
}
|
||||
|
||||
function cleanRunDirectoryName(value) {
|
||||
const text = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^_+|_+$/g, '')
|
||||
return (text || `run-${Date.now()}`).slice(0, 120)
|
||||
}
|
||||
|
||||
function positiveInteger(value, fallback, min = 1, max = 600) {
|
||||
const parsed = Number(value)
|
||||
if (!Number.isFinite(parsed)) return fallback
|
||||
return Math.max(min, Math.min(max, Math.trunc(parsed)))
|
||||
}
|
||||
|
||||
function runProfileFromPayload(payload) {
|
||||
return isPlainObject(payload?.runProfile) ? payload.runProfile : {}
|
||||
}
|
||||
|
||||
function runProfileMcpServers(payload) {
|
||||
const runProfile = runProfileFromPayload(payload)
|
||||
const toolProfile = isPlainObject(runProfile.toolProfile) ? runProfile.toolProfile : {}
|
||||
const rawServers = Array.isArray(toolProfile.mcpServers) ? toolProfile.mcpServers : []
|
||||
const byName = new Map()
|
||||
for (const raw of rawServers) {
|
||||
const server = sanitizeRunMcpServer(raw)
|
||||
if (!server) continue
|
||||
byName.set(server.serverName, server)
|
||||
}
|
||||
return Array.from(byName.values())
|
||||
}
|
||||
|
||||
function sanitizeRunMcpServer(raw) {
|
||||
if (!isPlainObject(raw) || raw.enabled === false) return null
|
||||
const serverName = cleanMcpServerName(raw.serverName || raw.server_name || raw.name)
|
||||
const url = String(raw.url || '').trim()
|
||||
if (!serverName || !isHttpUrl(url)) return null
|
||||
return {
|
||||
serverName,
|
||||
url,
|
||||
required: raw.required === true,
|
||||
startupTimeoutSec: positiveInteger(raw.startupTimeoutSec || raw.startup_timeout_sec, 20, 1, 120),
|
||||
toolTimeoutSec: positiveInteger(raw.toolTimeoutSec || raw.tool_timeout_sec, 60, 1, 600),
|
||||
httpHeaders: sanitizeRunMcpHeaders(raw.httpHeaders || raw.http_headers || raw.headers),
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeRunMcpHeaders(value) {
|
||||
if (!isPlainObject(value)) return {}
|
||||
const out = {}
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
const headerName = String(key || '').trim()
|
||||
const headerValue = String(item ?? '').trim()
|
||||
if (!headerName || !headerValue) continue
|
||||
if (/[\r\n\0]/.test(headerName) || /[\r\n\0]/.test(headerValue)) continue
|
||||
out[headerName] = headerValue
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function runtimeCodexConfig() {
|
||||
return [
|
||||
'approval_policy = "never"',
|
||||
'sandbox_mode = "danger-full-access"',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function dynamicMcpServerConfig(server) {
|
||||
const lines = [
|
||||
`[mcp_servers.${tomlKey(server.serverName)}]`,
|
||||
`url = ${tomlString(server.url)}`,
|
||||
'enabled = true',
|
||||
`required = ${server.required ? 'true' : 'false'}`,
|
||||
`startup_timeout_sec = ${positiveInteger(server.startupTimeoutSec, 20, 1, 120)}`,
|
||||
`tool_timeout_sec = ${positiveInteger(server.toolTimeoutSec, 60, 1, 600)}`,
|
||||
]
|
||||
const headers = isPlainObject(server.httpHeaders) ? server.httpHeaders : {}
|
||||
const headerEntries = Object.entries(headers)
|
||||
if (headerEntries.length) {
|
||||
lines.push('', `[mcp_servers.${tomlKey(server.serverName)}.http_headers]`)
|
||||
for (const [key, value] of headerEntries) {
|
||||
lines.push(`${tomlKey(key)} = ${tomlString(value)}`)
|
||||
}
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function dynamicMcpConfig(servers) {
|
||||
return (Array.isArray(servers) ? servers : [])
|
||||
.map(dynamicMcpServerConfig)
|
||||
.filter(Boolean)
|
||||
.join('\n\n')
|
||||
}
|
||||
|
||||
function ndcAgentMcpServerConfig(mcpContext, cwd) {
|
||||
const ndcConfig = [
|
||||
'[mcp_servers.ndc_agent_core]',
|
||||
`command = ${tomlString('node')}`,
|
||||
`args = [${tomlString(NDC_AGENT_MCP_SERVER)}]`,
|
||||
'startup_timeout_sec = 20',
|
||||
'tool_timeout_sec = 120',
|
||||
].join('\n')
|
||||
return `${ndcConfig}\n${ndcAgentMcpEnvConfig(mcpContext, cwd)}`
|
||||
}
|
||||
|
||||
function dynamicCodexHomePath(payload, needsNdcAgentCore) {
|
||||
const runProfile = runProfileFromPayload(payload)
|
||||
const runId = cleanRunDirectoryName(runProfile.runId || payload?.requestId || payload?.threadId || '')
|
||||
return path.join(RUN_CODEX_HOME_ROOT, needsNdcAgentCore ? `ndc-${runId}` : runId)
|
||||
}
|
||||
|
||||
function stripTomlSection(raw, sectionName) {
|
||||
const section = String(sectionName || '').trim()
|
||||
if (!section) return String(raw || '')
|
||||
@@ -1717,43 +1846,43 @@ function ndcAgentMcpEnvConfig(mcpContext, cwd) {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
async function prepareNdcAgentCodexHome(mcpContext = {}, cwd = CODEX_CWD) {
|
||||
await fs.mkdir(NDC_AGENT_CODEX_HOME, { recursive: true })
|
||||
await copyIfExists(path.join(CODEX_HOME, 'auth.json'), path.join(NDC_AGENT_CODEX_HOME, 'auth.json'))
|
||||
const opsMcpConfig = await readOptionalOpsMcpConfig()
|
||||
const runtimeConfig = [
|
||||
'approval_policy = "never"',
|
||||
'sandbox_mode = "danger-full-access"',
|
||||
].join('\n')
|
||||
const ndcConfig = [
|
||||
'[mcp_servers.ndc_agent_core]',
|
||||
`command = ${tomlString('node')}`,
|
||||
`args = [${tomlString(NDC_AGENT_MCP_SERVER)}]`,
|
||||
'startup_timeout_sec = 20',
|
||||
'tool_timeout_sec = 120',
|
||||
].join('\n')
|
||||
async function prepareRunCodexHome({ payload = {}, cwd = CODEX_CWD, mcpContext = null, dynamicMcpServers = [] } = {}) {
|
||||
const needsNdcAgentCore = isPlainObject(mcpContext)
|
||||
const hasDynamicMcp = Array.isArray(dynamicMcpServers) && dynamicMcpServers.length > 0
|
||||
const codexHome = hasDynamicMcp
|
||||
? dynamicCodexHomePath(payload, needsNdcAgentCore)
|
||||
: NDC_AGENT_CODEX_HOME
|
||||
await fs.mkdir(codexHome, { recursive: true })
|
||||
await copyIfExists(path.join(CODEX_HOME, 'auth.json'), path.join(codexHome, 'auth.json'))
|
||||
const legacyOpsMcpConfig = needsNdcAgentCore && !hasDynamicMcp ? await readOptionalOpsMcpConfig() : ''
|
||||
const config = [
|
||||
runtimeConfig,
|
||||
`${ndcConfig}\n${ndcAgentMcpEnvConfig(mcpContext, cwd)}`,
|
||||
opsMcpConfig,
|
||||
runtimeCodexConfig(),
|
||||
needsNdcAgentCore ? ndcAgentMcpServerConfig(mcpContext, cwd) : '',
|
||||
hasDynamicMcp ? dynamicMcpConfig(dynamicMcpServers) : legacyOpsMcpConfig,
|
||||
].filter(Boolean).join('\n\n')
|
||||
await fs.writeFile(path.join(NDC_AGENT_CODEX_HOME, 'config.toml'), `${config}\n`, 'utf8')
|
||||
return NDC_AGENT_CODEX_HOME
|
||||
await fs.writeFile(path.join(codexHome, 'config.toml'), `${config}\n`, 'utf8')
|
||||
return codexHome
|
||||
}
|
||||
|
||||
async function codexInvocationForPayload(baseArgs, payload, cwd) {
|
||||
if (!isNdcAgentCorePayload(payload)) return { args: baseArgs, env: {} }
|
||||
const mcpContext = buildNdcAgentMcpContext(payload, cwd)
|
||||
const codexHome = await prepareNdcAgentCodexHome(mcpContext, cwd)
|
||||
const dynamicMcpServers = runProfileMcpServers(payload)
|
||||
const needsNdcAgentCore = isNdcAgentCorePayload(payload)
|
||||
if (!needsNdcAgentCore && !dynamicMcpServers.length) return { args: baseArgs, env: {}, dynamicMcpServerNames: [] }
|
||||
const mcpContext = needsNdcAgentCore ? buildNdcAgentMcpContext(payload, cwd) : null
|
||||
const codexHome = await prepareRunCodexHome({ payload, cwd, mcpContext, dynamicMcpServers })
|
||||
return {
|
||||
args: baseArgs,
|
||||
env: {
|
||||
CODEX_HOME: codexHome,
|
||||
NDC_AGENT_MCP_ROOT: CODEX_CWD,
|
||||
NDC_AGENT_MCP_CONTEXT: JSON.stringify(mcpContext),
|
||||
NDC_AGENT_MCP_API_BASE_URL: mcpContext.ndcAgentMcpApiBaseUrl,
|
||||
AI_BRIDGE_PAIRING_CODE: PAIRING_CODE,
|
||||
...(needsNdcAgentCore ? {
|
||||
NDC_AGENT_MCP_ROOT: CODEX_CWD,
|
||||
NDC_AGENT_MCP_CONTEXT: JSON.stringify(mcpContext),
|
||||
NDC_AGENT_MCP_API_BASE_URL: mcpContext.ndcAgentMcpApiBaseUrl,
|
||||
AI_BRIDGE_PAIRING_CODE: PAIRING_CODE,
|
||||
} : {}),
|
||||
},
|
||||
dynamicMcpServerNames: dynamicMcpServers.map((server) => server.serverName),
|
||||
codexHome,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2218,6 +2347,12 @@ async function runCodexForPayload(prompt, payload, onEvent = () => {}, cwd = COD
|
||||
})
|
||||
} catch {}
|
||||
}
|
||||
if (Array.isArray(invocation.dynamicMcpServerNames) && invocation.dynamicMcpServerNames.length) {
|
||||
onEvent({
|
||||
kind: 'run_profile',
|
||||
message: `Dynamic run profile MCP servers: ${invocation.dynamicMcpServerNames.join(', ')}`,
|
||||
})
|
||||
}
|
||||
const control = {
|
||||
requestId: meta?.requestId,
|
||||
threadId: payload?.threadId,
|
||||
@@ -2453,6 +2588,10 @@ async function handleBridgeCommand(command, payload = {}, onEvent = () => {}, me
|
||||
codexAuthPath: runtime.authPath,
|
||||
codexBin: CODEX_BIN,
|
||||
codexArgs: CODEX_ARGS,
|
||||
dynamicRunProfile: {
|
||||
enabled: true,
|
||||
codexHomeRoot: RUN_CODEX_HOME_ROOT,
|
||||
},
|
||||
cwd: CODEX_CWD,
|
||||
hubMode: hubState.mode,
|
||||
hubConnected: hubState.connected,
|
||||
|
||||
Reference in New Issue
Block a user