feat(ai-workspace): add local relay profiles
This commit is contained in:
@@ -879,6 +879,26 @@ function cleanRunKey(value, limit = 160) {
|
||||
return String(value || '').trim().slice(0, limit)
|
||||
}
|
||||
|
||||
function terminateProcessTree(child, signal = 'SIGTERM') {
|
||||
if (!child) return
|
||||
if (process.platform === 'win32' && child.pid) {
|
||||
try {
|
||||
const args = ['/PID', String(child.pid), '/T']
|
||||
if (signal === 'SIGKILL') args.push('/F')
|
||||
const killer = spawn('taskkill', args, {
|
||||
windowsHide: true,
|
||||
stdio: 'ignore',
|
||||
shell: false,
|
||||
})
|
||||
killer.unref?.()
|
||||
return
|
||||
} catch {}
|
||||
}
|
||||
try {
|
||||
child.kill(signal)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function registerActiveCodexRun(control = {}, child, onEvent = () => {}) {
|
||||
const requestId = cleanRunKey(control.requestId, 120)
|
||||
const threadId = cleanRunKey(control.threadId, 160)
|
||||
@@ -898,14 +918,10 @@ function registerActiveCodexRun(control = {}, child, onEvent = () => {}) {
|
||||
try {
|
||||
run.onEvent({ kind: 'stopped', message: 'Codex stop requested.' })
|
||||
} catch {}
|
||||
try {
|
||||
run.child.kill('SIGTERM')
|
||||
} catch {}
|
||||
terminateProcessTree(run.child, 'SIGTERM')
|
||||
run.stopTimer = setTimeout(() => {
|
||||
if (run.closed) return
|
||||
try {
|
||||
run.child.kill('SIGKILL')
|
||||
} catch {}
|
||||
terminateProcessTree(run.child, 'SIGKILL')
|
||||
}, CODEX_STOP_GRACE_MS)
|
||||
return true
|
||||
},
|
||||
@@ -1049,6 +1065,13 @@ 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 toolProfile = runProfile.toolProfile && typeof runProfile.toolProfile === 'object' ? runProfile.toolProfile : {}
|
||||
const assistantActions = toolProfile.assistantActions && typeof toolProfile.assistantActions === 'object'
|
||||
? toolProfile.assistantActions
|
||||
: {}
|
||||
const assistantActionIds = Array.isArray(assistantActions.actionIds)
|
||||
? assistantActions.actionIds.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: []
|
||||
const runProfilePolicyPrompt = String(runProfile.policyPrompt || '').trim()
|
||||
const userMessage = String(payload?.message || '').trim()
|
||||
const history = payload?.resume ? [] : normalizeHistory(payload?.history || [])
|
||||
@@ -1116,7 +1139,7 @@ function buildPrompt(payload) {
|
||||
`- Selected agentNodeId: ${context.agentNodeId || 'unknown'}`,
|
||||
'- Read the second-level graph with GET /subworkflow?workflowId=<workflowId>&nodeId=<agentNodeId>.',
|
||||
'- Apply graph edits with POST /subworkflow/patch using JSON: { workflowId, nodeId, intent, operations }.',
|
||||
'- Prefer the MCP tools exposed by the ndc_agent_core server: ndc_get_context, ndc_get_subworkflow, ndc_search_nodes, ndc_get_node_definition, ndc_apply_subworkflow_patch, ndc_validate_subworkflow.',
|
||||
'- Prefer the MCP tools exposed by the ndc_agent_core server: ndc_get_context, ndc_get_subworkflow, ndc_search_nodes, ndc_get_node_definition, ndc_apply_subworkflow_patch, ndc_validate_subworkflow, assistant_action_call.',
|
||||
'- Do not use direct NDC core runtime MCP servers, local workflow files, or shell probes for graph edits in this mode.',
|
||||
'- Use only ndc_agent_core MCP tools for the selected second-level workflow and stop after a cancellation, fetch, or policy error with the exact tool name and error.',
|
||||
'- In public answers, use only NDC labels: NDC workflow, NDC node, NDC node type, NDC nodebase, and NDC Agent Core.',
|
||||
@@ -1125,6 +1148,15 @@ function buildPrompt(payload) {
|
||||
'- Prefer small patches and preserve existing node ids, node names, positions, parameters, and connections unless the user asks to change them.',
|
||||
'- After saving through the Engine API, the open Engine canvas refreshes from dc.subworkflow.json; never edit local files or use shell fallbacks for graph changes in this mode.',
|
||||
],
|
||||
'',
|
||||
'Assistant action routing contract:',
|
||||
`- Assistant action ids available in this run: ${assistantActionIds.length ? assistantActionIds.join(', ') : 'none'}.`,
|
||||
'- For Launcher/HUB/admin/access/users/invites/roles/service grants requests, use only the ndc_agent_core MCP tool assistant_action_call.',
|
||||
'- Do not use codex_apps readonly connectors, read_handoff, local files, shell search, logs, or workspace scans for Launcher/HUB live administrative data.',
|
||||
'- Use phase="execute" for read-only action calls after selecting the structured action id.',
|
||||
'- Use phase="preview" before any privileged/write action, ask for explicit confirmation, then use phase="execute" only after confirmation.',
|
||||
'- Useful read action ids when advertised: hub.access_request.list_pending, hub.invite.list_pending, hub.user.read_admin_summary.',
|
||||
'- If assistant_action_call is unavailable or the gateway returns an error, report that exact tool/error and stop; do not guess from local files.',
|
||||
] : [],
|
||||
...(isOpsMode || opsContext.opsWorkspaceSlug || opsContext.opsProjectId ? [
|
||||
'',
|
||||
@@ -1134,8 +1166,12 @@ function buildPrompt(payload) {
|
||||
`- Selected Ops project id: ${opsContext.opsProjectId || 'unknown'}`,
|
||||
`- Selected Ops project identifier: ${opsContext.opsProjectIdentifier || 'unknown'}`,
|
||||
'- Prefer the MCP tools exposed for NODE.DC Ops when creating, updating, moving, or reading tasks.',
|
||||
'- If assistant action ids include ops.card.list_recent, ops.card.create, or ops.card.add_comment, these are the canonical Ops card actions for this run.',
|
||||
'- Use assistant_action_call phase="execute" for Ops card reads after selecting ops.card.list_recent.',
|
||||
'- Use assistant_action_call phase="preview" before Ops card create/comment writes, ask for explicit confirmation, then call phase="execute" with the returned confirmation token.',
|
||||
'- Before writing Ops tasks, use the Ops MCP project/context tools when available and include a unique idempotency key for write tools.',
|
||||
'- If Ops MCP tools are unavailable in the Codex session, say that the Ops context is selected but the Ops MCP tools are unavailable.',
|
||||
'- If direct Ops MCP tools are unavailable but the Ops assistant action ids are advertised, do not refuse; route through assistant_action_call.',
|
||||
'- If neither direct Ops MCP tools nor Ops assistant action ids are available, say that the Ops context is selected but live Ops tools are unavailable.',
|
||||
'- Do not claim that an Engine workflow or Engine agent node is required for Ops task writes.',
|
||||
'- If the current request is about Ops tasks and Ops workspace/project are selected, treat that as the writable Ops target.',
|
||||
'- In public answers, use NODE.DC/Ops labels and never expose internal vendor names.',
|
||||
@@ -1480,6 +1516,11 @@ function insertBeforePromptStdin(args, extras) {
|
||||
|
||||
function buildNdcAgentMcpContext(payload, cwd) {
|
||||
const context = payload?.context && typeof payload.context === 'object' ? payload.context : {}
|
||||
const runProfile = payload?.runProfile && typeof payload.runProfile === 'object' ? payload.runProfile : {}
|
||||
const toolProfile = runProfile.toolProfile && typeof runProfile.toolProfile === 'object' ? runProfile.toolProfile : {}
|
||||
const assistantActions = toolProfile.assistantActions && typeof toolProfile.assistantActions === 'object'
|
||||
? toolProfile.assistantActions
|
||||
: {}
|
||||
const apiBaseUrl = deriveNdcAgentMcpApiBaseUrl(context)
|
||||
return {
|
||||
workflowId: String(context.workflowId || '').trim(),
|
||||
@@ -1492,6 +1533,14 @@ function buildNdcAgentMcpContext(payload, cwd) {
|
||||
schemaVersion: 'v2.3.2',
|
||||
n8nMcpRefPath: NDC_AGENT_MCP_REF_PATH,
|
||||
workspacePath: cwd,
|
||||
assistantActions: {
|
||||
actionIds: Array.isArray(assistantActions.actionIds)
|
||||
? assistantActions.actionIds.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
},
|
||||
assistantActionOwner: runProfile.owner && typeof runProfile.owner === 'object' ? runProfile.owner : {},
|
||||
assistantActionGatewayUrl: String(assistantActions.gatewayUrl || '').trim(),
|
||||
assistantActionGatewayToken: String(assistantActions.gatewayToken || '').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1502,6 +1551,7 @@ function deriveNdcAgentMcpApiBaseUrl(context) {
|
||||
if (!isHttpUrl(explicit)) return hubDerived || DEFAULT_NDC_AGENT_MCP_API_BASE
|
||||
if (hubDerived && isProtectedNodedcEngineUrl(explicit)) return hubDerived
|
||||
if (isLoopbackUrl(explicit) && hubDerived) return hubDerived
|
||||
if (isPrivateNetworkUrl(explicit) && hubDerived) return hubDerived
|
||||
if (!explicit.endsWith('/api/ndc-agent-mcp')) return `${explicit.replace(/\/+$/, '')}/api/ndc-agent-mcp`
|
||||
return explicit
|
||||
}
|
||||
@@ -1521,6 +1571,21 @@ function isLoopbackUrl(value) {
|
||||
}
|
||||
}
|
||||
|
||||
function isPrivateNetworkUrl(value) {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
const host = url.hostname.toLowerCase()
|
||||
if (host === 'localhost' || host === '0.0.0.0' || host === '::1' || host.startsWith('127.')) return true
|
||||
if (host.startsWith('192.168.')) return true
|
||||
if (host.startsWith('10.')) return true
|
||||
if (host.startsWith('169.254.')) return true
|
||||
const match = host.match(/^172\.(\d+)\./)
|
||||
return Boolean(match && Number(match[1]) >= 16 && Number(match[1]) <= 31)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isHttpUrl(value) {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
@@ -1854,7 +1919,7 @@ async function prepareRunCodexHome({ payload = {}, cwd = CODEX_CWD, mcpContext =
|
||||
: 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 legacyOpsMcpConfig = ''
|
||||
const config = [
|
||||
runtimeCodexConfig(),
|
||||
needsNdcAgentCore ? ndcAgentMcpServerConfig(mcpContext, cwd) : '',
|
||||
@@ -1878,6 +1943,8 @@ async function codexInvocationForPayload(baseArgs, payload, cwd) {
|
||||
NDC_AGENT_MCP_ROOT: CODEX_CWD,
|
||||
NDC_AGENT_MCP_CONTEXT: JSON.stringify(mcpContext),
|
||||
NDC_AGENT_MCP_API_BASE_URL: mcpContext.ndcAgentMcpApiBaseUrl,
|
||||
NDC_AGENT_MCP_FETCH_TIMEOUT_MS: process.env.NDC_AGENT_MCP_FETCH_TIMEOUT_MS || '30000',
|
||||
AI_WORKSPACE_ASSISTANT_ACTION_FETCH_TIMEOUT_MS: process.env.AI_WORKSPACE_ASSISTANT_ACTION_FETCH_TIMEOUT_MS || '45000',
|
||||
AI_BRIDGE_PAIRING_CODE: PAIRING_CODE,
|
||||
} : {}),
|
||||
},
|
||||
@@ -2399,7 +2466,7 @@ function runCodex(prompt, args = CODEX_ARGS, onEvent = () => {}, timeoutMs = MES
|
||||
const timeout = setTimeout(() => {
|
||||
killed = true
|
||||
onEvent({ kind: 'timeout', message: 'Codex process timed out.' })
|
||||
child.kill('SIGTERM')
|
||||
terminateProcessTree(child, 'SIGTERM')
|
||||
}, timeoutMs)
|
||||
|
||||
child.stdout.on('data', (chunk) => {
|
||||
@@ -2431,7 +2498,7 @@ function runCodex(prompt, args = CODEX_ARGS, onEvent = () => {}, timeoutMs = MES
|
||||
plainStdout += text
|
||||
onEvent({ kind: 'stdout', stream: 'stdout', text })
|
||||
}
|
||||
if (Buffer.byteLength(stdout) > MAX_STDIO_BYTES) child.kill('SIGTERM')
|
||||
if (Buffer.byteLength(stdout) > MAX_STDIO_BYTES) terminateProcessTree(child, 'SIGTERM')
|
||||
})
|
||||
child.stderr.on('data', (chunk) => {
|
||||
const text = String(chunk)
|
||||
@@ -2441,7 +2508,7 @@ function runCodex(prompt, args = CODEX_ARGS, onEvent = () => {}, timeoutMs = MES
|
||||
}
|
||||
stderr += text
|
||||
onEvent({ kind: 'stderr', stream: 'stderr', text: sanitizeCodexErrorText(text) })
|
||||
if (Buffer.byteLength(stderr) > MAX_STDIO_BYTES) child.kill('SIGTERM')
|
||||
if (Buffer.byteLength(stderr) > MAX_STDIO_BYTES) terminateProcessTree(child, 'SIGTERM')
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
clearTimeout(timeout)
|
||||
@@ -2927,6 +2994,8 @@ const ROOT = process.env.NDC_AGENT_MCP_ROOT || process.cwd()
|
||||
const DEFAULT_API_BASE = 'http://127.0.0.1:3001/api/ndc-agent-mcp'
|
||||
const DEFAULT_SCHEMA_VERSION = 'v2.3.2'
|
||||
const ENGINE_FETCH_TIMEOUT_MS = Number(process.env.NDC_AGENT_MCP_FETCH_TIMEOUT_MS || 8000)
|
||||
const DEFAULT_ASSISTANT_ACTION_GATEWAY_PATH = '/api/ai-workspace/assistant/v1/actions'
|
||||
const ASSISTANT_ACTION_FETCH_TIMEOUT_MS = Number(process.env.AI_WORKSPACE_ASSISTANT_ACTION_FETCH_TIMEOUT_MS || ENGINE_FETCH_TIMEOUT_MS)
|
||||
const context = parseContext()
|
||||
const nodeCatalogCache = new Map()
|
||||
let transportMode = null
|
||||
@@ -3025,8 +3094,13 @@ function parseContext() {
|
||||
if (raw) {
|
||||
try { parsed = JSON.parse(raw) || {} } catch {}
|
||||
}
|
||||
const assistantActions = parseObject(
|
||||
parsed.assistantActions ||
|
||||
process.env.AI_WORKSPACE_ASSISTANT_ACTIONS ||
|
||||
{},
|
||||
)
|
||||
return {
|
||||
modeId: 'ndc-agent-core',
|
||||
modeId: cleanString(parsed.modeId || 'ndc-agent-core'),
|
||||
workflowId: cleanString(parsed.workflowId || process.env.NDC_AGENT_MCP_WORKFLOW_ID || ''),
|
||||
workflowTitle: cleanString(parsed.workflowTitle || process.env.NDC_AGENT_MCP_WORKFLOW_TITLE || ''),
|
||||
agentNodeId: cleanString(parsed.agentNodeId || process.env.NDC_AGENT_MCP_NODE_ID || ''),
|
||||
@@ -3036,6 +3110,20 @@ function parseContext() {
|
||||
apiBaseUrl: cleanApiBase(parsed.ndcAgentMcpApiBaseUrl || process.env.NDC_AGENT_MCP_API_BASE_URL || DEFAULT_API_BASE),
|
||||
schemaVersion: cleanString(parsed.schemaVersion || process.env.NDC_AGENT_MCP_SCHEMA_VERSION || DEFAULT_SCHEMA_VERSION),
|
||||
n8nMcpRefPath: cleanString(parsed.n8nMcpRefPath || process.env.NDC_AGENT_MCP_REF_PATH || path.resolve(ROOT, '..', 'tools', 'NDCMCP')),
|
||||
assistantActions,
|
||||
assistantActionOwner: parseObject(parsed.assistantActionOwner || {}),
|
||||
assistantActionGatewayUrl: cleanHttpUrl(
|
||||
parsed.assistantActionGatewayUrl ||
|
||||
process.env.AI_WORKSPACE_ASSISTANT_ACTION_GATEWAY_URL ||
|
||||
deriveAssistantActionGatewayUrlFromHub() ||
|
||||
'',
|
||||
),
|
||||
assistantActionGatewayToken: cleanString(
|
||||
parsed.assistantActionGatewayToken ||
|
||||
process.env.AI_WORKSPACE_ASSISTANT_ACTION_GATEWAY_TOKEN ||
|
||||
'',
|
||||
4000,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3043,6 +3131,32 @@ function cleanString(value, max = 1000) {
|
||||
return String(value || '').trim().slice(0, max)
|
||||
}
|
||||
|
||||
function parseObject(value, fallback = {}) {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) return value
|
||||
const text = String(value || '').trim()
|
||||
if (!text) return fallback
|
||||
try {
|
||||
const parsed = JSON.parse(text)
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function cleanHttpUrl(value) {
|
||||
const text = cleanString(value, 2000).replace(/\/+$/, '')
|
||||
if (!text) return ''
|
||||
try {
|
||||
const url = new URL(text)
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return ''
|
||||
url.username = ''
|
||||
url.password = ''
|
||||
return url.toString().replace(/\/+$/, '')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function cleanApiBase(value) {
|
||||
const raw = cleanString(value || DEFAULT_API_BASE)
|
||||
return raw.replace(/\/+$/, '') || DEFAULT_API_BASE
|
||||
@@ -3069,6 +3183,20 @@ function isLoopbackUrl(value) {
|
||||
}
|
||||
}
|
||||
|
||||
function isPrivateNetworkUrl(value) {
|
||||
try {
|
||||
const host = new URL(value).hostname.toLowerCase()
|
||||
if (host === 'localhost' || host === '0.0.0.0' || host === '::1' || host.startsWith('127.')) return true
|
||||
if (host.startsWith('192.168.')) return true
|
||||
if (host.startsWith('10.')) return true
|
||||
if (host.startsWith('169.254.')) return true
|
||||
const match = host.match(/^172\.(\d+)\./)
|
||||
return Boolean(match && Number(match[1]) >= 16 && Number(match[1]) <= 31)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function hubOriginToApiBase(value) {
|
||||
try {
|
||||
const url = new URL(cleanString(value, 1000))
|
||||
@@ -3091,6 +3219,32 @@ function hubOriginToApiBase(value) {
|
||||
}
|
||||
}
|
||||
|
||||
function hubOriginToAssistantActionGateway(value) {
|
||||
try {
|
||||
const url = new URL(cleanString(value, 1000))
|
||||
const host = url.hostname.toLowerCase()
|
||||
if (!host) return ''
|
||||
if (url.protocol === 'wss:') url.protocol = 'https:'
|
||||
else if (url.protocol === 'ws:') url.protocol = 'http:'
|
||||
else if (url.protocol !== 'http:' && url.protocol !== 'https:') return ''
|
||||
url.pathname = ''
|
||||
url.search = ''
|
||||
url.hash = ''
|
||||
const origin = url.toString().replace(/\/+$/, '')
|
||||
return `${origin}${DEFAULT_ASSISTANT_ACTION_GATEWAY_PATH}`
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function deriveAssistantActionGatewayUrlFromHub() {
|
||||
const candidates = [
|
||||
hubOriginToAssistantActionGateway(process.env.AI_BRIDGE_HUB_URL),
|
||||
...splitList(process.env.AI_BRIDGE_HUB_URLS).map(hubOriginToAssistantActionGateway),
|
||||
].filter(Boolean)
|
||||
return uniqueStrings(candidates)[0] || ''
|
||||
}
|
||||
|
||||
function cleanPairingCode(value) {
|
||||
return cleanString(value, 100).toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 32)
|
||||
}
|
||||
@@ -3106,10 +3260,10 @@ function engineApiBaseCandidates() {
|
||||
...splitList(process.env.AI_BRIDGE_HUB_URLS).map(hubOriginToApiBase),
|
||||
]
|
||||
const envBase = cleanString(process.env.NDC_AGENT_MCP_API_BASE_URL, 1000).replace(/\/+$/, '')
|
||||
if (explicit && !isLoopbackUrl(explicit)) {
|
||||
if (explicit && !isPrivateNetworkUrl(explicit)) {
|
||||
return uniqueStrings([explicit, envBase])
|
||||
}
|
||||
if (envBase && !isLoopbackUrl(envBase)) {
|
||||
if (envBase && !isPrivateNetworkUrl(envBase)) {
|
||||
return uniqueStrings([envBase, explicit])
|
||||
}
|
||||
if (hubBases.some(Boolean)) {
|
||||
@@ -3191,6 +3345,88 @@ async function loadN8nMcpVersion() {
|
||||
return pkg?.version ? String(pkg.version) : '2.33.2'
|
||||
}
|
||||
|
||||
function assistantActionGatewayEndpoint() {
|
||||
const base = cleanHttpUrl(context.assistantActionGatewayUrl)
|
||||
if (!base) return ''
|
||||
if (base.endsWith(DEFAULT_ASSISTANT_ACTION_GATEWAY_PATH) || base.endsWith('/actions')) return base
|
||||
return `${base}${DEFAULT_ASSISTANT_ACTION_GATEWAY_PATH}`
|
||||
}
|
||||
|
||||
function assistantActionIds() {
|
||||
return Array.isArray(context.assistantActions?.actionIds)
|
||||
? context.assistantActions.actionIds.map((item) => cleanString(item, 200)).filter(Boolean)
|
||||
: []
|
||||
}
|
||||
|
||||
function assistantActionOwnerHeaders() {
|
||||
const owner = parseObject(context.assistantActionOwner, {})
|
||||
const headers = {}
|
||||
const put = (name, value) => {
|
||||
const text = cleanString(value, 1000)
|
||||
if (text) headers[name] = text
|
||||
}
|
||||
put('x-nodedc-user-id', owner.userId || owner.user_id)
|
||||
put('x-nodedc-user-email', owner.email)
|
||||
put('x-nodedc-user-role', owner.role)
|
||||
const groups = Array.isArray(owner.groups)
|
||||
? owner.groups.map((item) => cleanString(item, 120)).filter(Boolean).join(',')
|
||||
: owner.groups
|
||||
put('x-nodedc-user-groups', groups)
|
||||
return headers
|
||||
}
|
||||
|
||||
async function assistantActionFetch(payload = {}) {
|
||||
const endpoint = assistantActionGatewayEndpoint()
|
||||
const token = context.assistantActionGatewayToken
|
||||
if (!endpoint || !token) {
|
||||
return {
|
||||
ok: false,
|
||||
decision: 'assistant_action_gateway_unavailable',
|
||||
reason: 'Assistant action gateway URL/token is not configured for this run.',
|
||||
actionIds: assistantActionIds(),
|
||||
}
|
||||
}
|
||||
|
||||
let res = null
|
||||
let text = ''
|
||||
let json = null
|
||||
try {
|
||||
res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
...assistantActionOwnerHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(ASSISTANT_ACTION_FETCH_TIMEOUT_MS),
|
||||
})
|
||||
text = await res.text().catch(() => '')
|
||||
try { json = text ? JSON.parse(text) : null } catch {}
|
||||
} catch (error) {
|
||||
const out = new Error(`assistant_action_gateway_fetch_failed:${fetchFailureText(error)}`)
|
||||
out.payload = { decision: 'assistant_action_gateway_fetch_failed' }
|
||||
throw out
|
||||
}
|
||||
|
||||
if (!res.ok || json?.ok === false) {
|
||||
const out = new Error(json?.message || json?.error || `assistant_action_http_${res.status}`)
|
||||
out.status = res.status
|
||||
out.payload = json && typeof json === 'object'
|
||||
? json
|
||||
: { status: res.status, preview: cleanString(text, 400) }
|
||||
throw out
|
||||
}
|
||||
if (!json || typeof json !== 'object') {
|
||||
const out = new Error(`assistant_action_non_json_response:${res.status}`)
|
||||
out.status = 502
|
||||
out.payload = { status: res.status, preview: cleanString(text, 400) }
|
||||
throw out
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
function engineApiUrl(pathname) {
|
||||
return engineApiUrls(pathname)[0] || ''
|
||||
}
|
||||
@@ -3365,6 +3601,7 @@ async function handleGetContext() {
|
||||
...context,
|
||||
apiBaseCandidates: engineApiBaseCandidates(),
|
||||
n8nMcpVersion,
|
||||
assistantActionGatewayConfigured: Boolean(context.assistantActionGatewayUrl && context.assistantActionGatewayToken),
|
||||
contract: {
|
||||
sourceOfTruth: 'Engine second-level dc.subworkflow.json',
|
||||
writeApi: `${context.apiBaseUrl}/subworkflow/patch`,
|
||||
@@ -3375,6 +3612,40 @@ async function handleGetContext() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAssistantActionCall(args = {}) {
|
||||
const phase = cleanString(args.phase || args.mode || 'preview', 40)
|
||||
if (!['preview', 'dry-run', 'execute'].includes(phase)) throw new Error('assistant_action_phase_invalid')
|
||||
|
||||
const input = parseObject(args.input || {}, {})
|
||||
const actionId = cleanString(args.actionId || input.actionId || '', 240)
|
||||
const intent = cleanString(args.intent || input.intent || '', 2000)
|
||||
if (actionId) input.actionId = actionId
|
||||
if (intent) input.intent = intent
|
||||
|
||||
const availableIds = assistantActionIds()
|
||||
if (actionId && availableIds.length && !availableIds.includes(actionId)) {
|
||||
throw new Error(`assistant_action_not_advertised:${actionId}`)
|
||||
}
|
||||
if (!actionId && !intent) {
|
||||
throw new Error('assistant_action_input_required')
|
||||
}
|
||||
|
||||
const confirmationToken = cleanString(
|
||||
args.confirmationToken ||
|
||||
args.confirmation?.token ||
|
||||
input.confirmationToken ||
|
||||
'',
|
||||
2000,
|
||||
)
|
||||
if (confirmationToken) input.confirmationToken = confirmationToken
|
||||
|
||||
return assistantActionFetch({
|
||||
phase,
|
||||
input,
|
||||
...(confirmationToken ? { confirmationToken } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
async function handleGetSubworkflow(args) {
|
||||
const target = targetFromArgs(args)
|
||||
const q = new URLSearchParams(target)
|
||||
@@ -3571,6 +3842,22 @@ const tools = [
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'assistant_action_call',
|
||||
description: 'Call the NODE.DC assistant action layer after interpreting user intent. Use execute for read actions after structured action selection; use preview before any privileged/write action and execute only after explicit confirmation.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
phase: { type: 'string', enum: ['preview', 'dry-run', 'execute'] },
|
||||
actionId: { type: 'string' },
|
||||
intent: { type: 'string' },
|
||||
input: { type: 'object', additionalProperties: true },
|
||||
confirmationToken: { type: 'string' },
|
||||
confirmation: { type: 'object', additionalProperties: true },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
async function callTool(name, args) {
|
||||
@@ -3580,6 +3867,7 @@ async function callTool(name, args) {
|
||||
if (name === 'ndc_search_nodes') return handleSearchNodes(args)
|
||||
if (name === 'ndc_get_node_definition') return handleGetNodeDefinition(args)
|
||||
if (name === 'ndc_validate_subworkflow') return handleValidateSubworkflow(args)
|
||||
if (name === 'assistant_action_call') return handleAssistantActionCall(args)
|
||||
throw new Error(`unknown_tool:${name}`)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user