Add dynamic AI Workspace run profiles
This commit is contained in:
@@ -0,0 +1,347 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
|
||||
const SECRET_TOKEN = "secret-run-token-for-smoke";
|
||||
|
||||
const adapter = {
|
||||
id: "ops",
|
||||
appId: "ops",
|
||||
title: "NODE.DC Ops",
|
||||
};
|
||||
|
||||
const adapterPayload = {
|
||||
ok: true,
|
||||
appGrants: {
|
||||
ops: {
|
||||
appTitle: "NODE.DC Ops",
|
||||
surface: "ops",
|
||||
grantMode: "token-scoped-run-grants",
|
||||
context: {
|
||||
opsWorkspaceSlug: "nodedc",
|
||||
opsProjectId: "86629a11-eaff-4ad2-9f89-e5245a344fcc",
|
||||
},
|
||||
scopes: ["workspace:read", "project:read", "issue:read"],
|
||||
mcpServers: [
|
||||
{
|
||||
serverName: "nodedc ops agent",
|
||||
url: "https://ops-agents.nodedc.ru/mcp",
|
||||
required: true,
|
||||
startupTimeoutSec: 20,
|
||||
toolTimeoutSec: 60,
|
||||
httpHeaders: {
|
||||
Authorization: `Bearer ${SECRET_TOKEN}`,
|
||||
Accept: "application/json",
|
||||
"MCP-Protocol-Version": "2025-06-18",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const appGrants = normalizeEntitlementAdapterAppGrants(adapterPayload, adapter);
|
||||
const mcpServers = runProfileMcpServersFromAppGrants({}, appGrants);
|
||||
const appGrantSummary = summarizeRunAppGrants({ appGrants });
|
||||
const runProfile = {
|
||||
schemaVersion: "ai-workspace.run-profile.v1",
|
||||
runId: randomUUID(),
|
||||
createdAt: new Date("2026-06-13T00:00:00.000Z").toISOString(),
|
||||
owner: {
|
||||
ownerKey: "user:smoke-user",
|
||||
userId: "smoke-user",
|
||||
email: "smoke@example.test",
|
||||
role: "member",
|
||||
groups: ["engineering"],
|
||||
},
|
||||
sourceSurface: "engine",
|
||||
modeId: "ops",
|
||||
targetContexts: {
|
||||
ops: {
|
||||
opsWorkspaceSlug: "nodedc",
|
||||
opsProjectId: "86629a11-eaff-4ad2-9f89-e5245a344fcc",
|
||||
},
|
||||
},
|
||||
enabledToolPacks: ["engine", "ops", "ndc-agent-core"],
|
||||
appGrants: appGrantSummary,
|
||||
toolProfile: {
|
||||
schemaVersion: "ai-workspace.tool-profile.v1",
|
||||
enabledToolPacks: ["engine", "ops", "ndc-agent-core"],
|
||||
mcpServers,
|
||||
mcpServerNames: mcpServers.map((server) => server.serverName),
|
||||
requiredMcpServerNames: mcpServers.filter((server) => server.required).map((server) => server.serverName),
|
||||
},
|
||||
diagnostics: {
|
||||
schemaVersion: "ai-workspace.run-profile.diagnostics.v1",
|
||||
dynamicProfile: true,
|
||||
sourceSurface: "engine",
|
||||
modeId: "ops",
|
||||
entitlementAdapters: {
|
||||
source: "adapters+settings",
|
||||
adapters: [{ appId: "ops", status: "ok", required: true }],
|
||||
},
|
||||
mcpServerNames: mcpServers.map((server) => server.serverName),
|
||||
},
|
||||
};
|
||||
runProfile.diagnostics.profileHash = runProfileHash(runProfile);
|
||||
const publicProfile = redactRunProfile(runProfile);
|
||||
|
||||
assert.deepEqual(Object.keys(appGrants), ["ops"]);
|
||||
assert.equal(appGrants.ops.source, "entitlement-adapter");
|
||||
assert.equal(appGrants.ops.appId, "ops");
|
||||
assert.deepEqual(appGrantSummary.ops.scopes, ["workspace:read", "project:read", "issue:read"]);
|
||||
assert.equal(appGrantSummary.ops.hasMcpServers, true);
|
||||
assert.deepEqual(appGrantSummary.ops.mcpServerNames, ["nodedc_ops_agent"]);
|
||||
|
||||
assert.equal(mcpServers.length, 1);
|
||||
assert.equal(mcpServers[0].appId, "ops");
|
||||
assert.equal(mcpServers[0].serverName, "nodedc_ops_agent");
|
||||
assert.equal(mcpServers[0].required, true);
|
||||
assert.equal(mcpServers[0].httpHeaders.Authorization, `Bearer ${SECRET_TOKEN}`);
|
||||
assert.equal(mcpServers[0].httpHeaders.Accept, "application/json");
|
||||
|
||||
assert.equal(publicProfile.toolProfile.mcpServers.length, 1);
|
||||
assert.equal(publicProfile.toolProfile.mcpServers[0].serverName, "nodedc_ops_agent");
|
||||
assert.equal(publicProfile.toolProfile.mcpServers[0].httpHeaders.Authorization, "<redacted>");
|
||||
assert.equal(publicProfile.toolProfile.mcpServers[0].httpHeaders.Accept, "<redacted>");
|
||||
assert.equal(publicProfile.toolProfile.mcpServers[0].headers, undefined);
|
||||
assert.equal(JSON.stringify(publicProfile).includes(SECRET_TOKEN), false);
|
||||
assert.match(runProfile.diagnostics.profileHash, /^[a-f0-9]{16}$/);
|
||||
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
checks: [
|
||||
"adapter_grant_normalized",
|
||||
"token_scoped_ops_mcp_in_run_profile",
|
||||
"public_run_profile_redacts_mcp_headers",
|
||||
"stable_public_profile_hash",
|
||||
],
|
||||
mcpServerNames: runProfile.toolProfile.mcpServerNames,
|
||||
profileHash: runProfile.diagnostics.profileHash,
|
||||
}, null, 2));
|
||||
|
||||
function normalizeEntitlementAdapterAppGrants(payload, currentAdapter) {
|
||||
const source = isPlainObject(payload?.appGrants)
|
||||
? payload.appGrants
|
||||
: Array.isArray(payload?.appGrants)
|
||||
? payload.appGrants
|
||||
: payload?.grant || payload?.appGrant || payload?.entitlement || payload?.entitlements || payload?.grants || payload;
|
||||
const out = {};
|
||||
if (Array.isArray(source)) {
|
||||
for (const item of source) {
|
||||
const grant = normalizeEntitlementAdapterGrant(item, currentAdapter);
|
||||
if (grant?.appId) out[grant.appId] = grant;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (!isPlainObject(source)) return out;
|
||||
if (source.mcpServers || source.scopes || source.appId || source.app_id || source.surface) {
|
||||
const grant = normalizeEntitlementAdapterGrant(source, currentAdapter);
|
||||
if (grant?.appId) out[grant.appId] = grant;
|
||||
return out;
|
||||
}
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
const grant = normalizeEntitlementAdapterGrant(value, { ...currentAdapter, appId: normalizeKey(key) || currentAdapter.appId });
|
||||
if (grant?.appId) out[grant.appId] = grant;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeEntitlementAdapterGrant(value, currentAdapter) {
|
||||
if (!isPlainObject(value)) return null;
|
||||
const appId = normalizeKey(value.appId || value.app_id || currentAdapter.appId);
|
||||
if (!appId) return null;
|
||||
return {
|
||||
...value,
|
||||
appId,
|
||||
appTitle: optionalString(value.appTitle || value.app_title || value.title || currentAdapter.title),
|
||||
surface: optionalString(value.surface) || appId,
|
||||
source: "entitlement-adapter",
|
||||
adapterId: currentAdapter.id,
|
||||
};
|
||||
}
|
||||
|
||||
function runProfileMcpServersFromAppGrants(settings, appGrantsInput = {}) {
|
||||
const servers = [];
|
||||
const metadata = isPlainObject(settings?.metadata) ? settings.metadata : {};
|
||||
collectInstallerMcpServers(servers, metadata.mcpServers, {});
|
||||
const grants = isPlainObject(appGrantsInput) ? appGrantsInput : {};
|
||||
for (const [appId, grant] of Object.entries(grants)) {
|
||||
if (!isPlainObject(grant)) continue;
|
||||
collectInstallerMcpServers(servers, grant.mcpServers, {
|
||||
appId: optionalString(grant.appId) || normalizeKey(appId),
|
||||
appTitle: optionalString(grant.appTitle || grant.title),
|
||||
});
|
||||
}
|
||||
|
||||
const byServerName = new Map();
|
||||
for (const server of servers.map(sanitizeInstallerMcpServer).filter(Boolean)) {
|
||||
if (server.enabled === false) continue;
|
||||
byServerName.set(server.serverName, server);
|
||||
}
|
||||
return Array.from(byServerName.values());
|
||||
}
|
||||
|
||||
function summarizeRunAppGrants(metadata) {
|
||||
const grants = isPlainObject(metadata?.appGrants) ? metadata.appGrants : {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(grants)) {
|
||||
if (!isPlainObject(value)) continue;
|
||||
const appId = optionalString(value.appId) || normalizeKey(key);
|
||||
if (!appId) continue;
|
||||
const mcpServers = Array.isArray(value.mcpServers)
|
||||
? value.mcpServers
|
||||
: isPlainObject(value.mcpServers)
|
||||
? Object.values(value.mcpServers)
|
||||
: [];
|
||||
out[appId] = {
|
||||
appId,
|
||||
appTitle: optionalString(value.appTitle || value.title),
|
||||
surface: optionalString(value.surface) || appId,
|
||||
updatedAt: optionalString(value.updatedAt || value.updated_at),
|
||||
context: redactForPublicDiagnostics(isPlainObject(value.context) ? value.context : {}),
|
||||
scopes: uniqueStrings(Array.isArray(value.scopes) ? value.scopes : []),
|
||||
hasMcpServers: mcpServers.length > 0,
|
||||
mcpServerNames: mcpServers
|
||||
.map((server) => safeMcpServerName(server?.serverName || server?.server_name || server?.name))
|
||||
.filter(Boolean),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function collectInstallerMcpServers(target, value, defaults = {}) {
|
||||
const items = Array.isArray(value)
|
||||
? value
|
||||
: isPlainObject(value)
|
||||
? Object.values(value)
|
||||
: [];
|
||||
for (const item of items) {
|
||||
if (!isPlainObject(item)) continue;
|
||||
target.push({ ...defaults, ...item });
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeInstallerMcpServer(raw) {
|
||||
if (!isPlainObject(raw)) return null;
|
||||
const serverName = safeMcpServerName(raw.serverName || raw.server_name || raw.name);
|
||||
const url = optionalString(raw.url);
|
||||
if (!serverName || !url) return null;
|
||||
const httpHeaders = sanitizeInstallerMcpHeaders(raw.httpHeaders || raw.http_headers || raw.headers);
|
||||
return {
|
||||
appId: normalizeKey(raw.appId || raw.app_id) || "global",
|
||||
appTitle: optionalString(raw.appTitle || raw.app_title || raw.title),
|
||||
serverName,
|
||||
url,
|
||||
enabled: raw.enabled !== false,
|
||||
required: raw.required === true,
|
||||
startupTimeoutSec: sanitizeInteger(raw.startupTimeoutSec || raw.startup_timeout_sec, 20, 1, 600),
|
||||
toolTimeoutSec: sanitizeInteger(raw.toolTimeoutSec || raw.tool_timeout_sec, 60, 1, 3600),
|
||||
httpHeaders,
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeInstallerMcpHeaders(value) {
|
||||
if (!isPlainObject(value)) return {};
|
||||
const headers = {};
|
||||
for (const [key, rawValue] of Object.entries(value)) {
|
||||
const headerName = optionalString(key);
|
||||
const headerValue = optionalString(rawValue);
|
||||
if (!headerName || !headerValue || headerName.length > 120 || headerValue.length > 4000) continue;
|
||||
headers[headerName] = headerValue;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function runProfileHash(runProfile) {
|
||||
const publicProfile = redactRunProfile(runProfile);
|
||||
const stableProfile = {
|
||||
...publicProfile,
|
||||
runId: undefined,
|
||||
createdAt: undefined,
|
||||
diagnostics: {
|
||||
...(isPlainObject(publicProfile?.diagnostics) ? publicProfile.diagnostics : {}),
|
||||
profileHash: undefined,
|
||||
},
|
||||
};
|
||||
return createHash("sha256").update(JSON.stringify(stableProfile)).digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
function redactRunProfile(runProfile) {
|
||||
if (!isPlainObject(runProfile)) return null;
|
||||
return {
|
||||
...runProfile,
|
||||
targetContexts: redactForPublicDiagnostics(runProfile.targetContexts),
|
||||
appGrants: redactForPublicDiagnostics(runProfile.appGrants),
|
||||
toolProfile: {
|
||||
...(isPlainObject(runProfile.toolProfile) ? runProfile.toolProfile : {}),
|
||||
mcpServers: Array.isArray(runProfile.toolProfile?.mcpServers)
|
||||
? runProfile.toolProfile.mcpServers.map(redactMcpServer)
|
||||
: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function redactMcpServer(server) {
|
||||
if (!isPlainObject(server)) return {};
|
||||
const headers = isPlainObject(server.httpHeaders) ? server.httpHeaders : {};
|
||||
return {
|
||||
...server,
|
||||
httpHeaders: Object.fromEntries(Object.keys(headers).map((key) => [key, "<redacted>"])),
|
||||
headers: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function redactForPublicDiagnostics(value, depth = 0) {
|
||||
if (depth > 6) return "[max-depth]";
|
||||
if (Array.isArray(value)) return value.map((item) => redactForPublicDiagnostics(item, depth + 1));
|
||||
if (!isPlainObject(value)) return value;
|
||||
const out = {};
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
const normalizedKey = normalizeKey(key);
|
||||
if (
|
||||
normalizedKey.includes("token")
|
||||
|| normalizedKey.includes("secret")
|
||||
|| normalizedKey.includes("password")
|
||||
|| normalizedKey === "authorization"
|
||||
|| normalizedKey === "cookie"
|
||||
|| normalizedKey === "setcookie"
|
||||
) {
|
||||
out[key] = "<redacted>";
|
||||
} else {
|
||||
out[key] = redactForPublicDiagnostics(item, depth + 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function safeMcpServerName(value) {
|
||||
const text = optionalString(value);
|
||||
if (!text) return "";
|
||||
return text.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 80);
|
||||
}
|
||||
|
||||
function sanitizeInteger(value, fallback, min, max) {
|
||||
const number = Number(value || fallback);
|
||||
if (!Number.isFinite(number)) return fallback;
|
||||
return Math.min(Math.max(Math.trunc(number), min), max);
|
||||
}
|
||||
|
||||
function uniqueStrings(values) {
|
||||
return Array.from(new Set((Array.isArray(values) ? values : []).map(optionalString).filter(Boolean)));
|
||||
}
|
||||
|
||||
function normalizeKey(value) {
|
||||
return optionalString(value).toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
|
||||
}
|
||||
|
||||
function optionalString(value) {
|
||||
if (value === null || value === undefined) return "";
|
||||
const text = String(value).trim();
|
||||
return text.length ? text : "";
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -326,6 +326,8 @@ app.post("/api/ai-workspace/assistant/v1/threads/:threadId/dispatch", requireInt
|
||||
accessMode: "ops-write",
|
||||
};
|
||||
}
|
||||
const runProfile = await buildRunProfile({ owner, thread, executor, ownerSettings, bridgePayload });
|
||||
bridgePayload.runProfile = runProfile;
|
||||
let bridge = null;
|
||||
try {
|
||||
bridge = await dispatchExecutorMessage(executor, bridgePayload);
|
||||
@@ -379,6 +381,7 @@ app.post("/api/ai-workspace/assistant/v1/threads/:threadId/dispatch", requireInt
|
||||
executor,
|
||||
message,
|
||||
assistantMessage: null,
|
||||
runProfile: redactRunProfile(runProfile),
|
||||
bridge,
|
||||
});
|
||||
}));
|
||||
@@ -1018,6 +1021,7 @@ async function createBridgeRun({ owner, thread, executor, bridge, payload }) {
|
||||
const requestId = optionalString(bridge?.requestId);
|
||||
if (!requestId || bridge?.accepted !== true || bridge?.mode !== "hub") return null;
|
||||
const context = isPlainObject(payload?.context) ? payload.context : {};
|
||||
const runProfile = isPlainObject(payload?.runProfile) ? payload.runProfile : null;
|
||||
const metadata = {
|
||||
modeId: optionalString(context.modeId),
|
||||
modeTitle: optionalString(context.modeTitle),
|
||||
@@ -1025,6 +1029,7 @@ async function createBridgeRun({ owner, thread, executor, bridge, payload }) {
|
||||
threadTitle: optionalString(payload?.threadTitle) || thread.title,
|
||||
executorName: executor.name,
|
||||
executorType: executor.type,
|
||||
runProfile: runProfile ? redactRunProfile(runProfile) : null,
|
||||
};
|
||||
const result = await pool.query(
|
||||
`insert into ai_workspace_runs (
|
||||
@@ -1426,6 +1431,367 @@ function buildBridgeMessagePayload({ thread, message, history, executor, command
|
||||
};
|
||||
}
|
||||
|
||||
async function buildRunProfile({ owner, thread, executor, ownerSettings, bridgePayload }) {
|
||||
const context = isPlainObject(bridgePayload?.context) ? bridgePayload.context : {};
|
||||
const sourceSurface = optionalString(context.sourceSurface)
|
||||
|| optionalString(context.surface)
|
||||
|| thread.originSurface
|
||||
|| "global";
|
||||
const targetContexts = isPlainObject(context.contexts) ? context.contexts : {};
|
||||
const enabledToolPacks = mergeToolPacks(
|
||||
ownerSettings?.enabledToolPacks,
|
||||
thread.enabledToolPacks,
|
||||
bridgePayload?.enabledToolPacks
|
||||
);
|
||||
const grantResolution = await resolveRunAppGrants({ owner, context, ownerSettings });
|
||||
const appGrants = summarizeRunAppGrants({ appGrants: grantResolution.appGrants });
|
||||
const mcpServers = runProfileMcpServersFromAppGrants(ownerSettings, grantResolution.appGrants);
|
||||
const mcpServerNames = mcpServers.map((server) => server.serverName).filter(Boolean);
|
||||
const requiredMcpServerNames = mcpServers
|
||||
.filter((server) => server.required === true)
|
||||
.map((server) => server.serverName)
|
||||
.filter(Boolean);
|
||||
const diagnostics = {
|
||||
schemaVersion: "ai-workspace.run-profile.diagnostics.v1",
|
||||
dynamicProfile: true,
|
||||
contextReady: context.contextReady !== false,
|
||||
accessMode: optionalString(context.accessMode) || "chat",
|
||||
sourceSurface,
|
||||
modeId: optionalString(context.modeId) || "ops",
|
||||
targetSurfaces: Object.keys(targetContexts).map(normalizeKey).filter(Boolean).sort(),
|
||||
enabledToolPacks,
|
||||
appGrantIds: Object.keys(appGrants).sort(),
|
||||
entitlementAdapters: grantResolution.diagnostics,
|
||||
mcpServerNames,
|
||||
requiredMcpServerNames,
|
||||
missingContext: Array.isArray(context.missingContext)
|
||||
? context.missingContext.map(optionalString).filter(Boolean)
|
||||
: [],
|
||||
};
|
||||
const runProfile = {
|
||||
schemaVersion: "ai-workspace.run-profile.v1",
|
||||
runId: randomUUID(),
|
||||
createdAt: new Date().toISOString(),
|
||||
owner: publicOwner(owner),
|
||||
executor: {
|
||||
id: executor.id,
|
||||
type: executor.type,
|
||||
connectionMode: executor.connectionMode,
|
||||
},
|
||||
sourceSurface,
|
||||
modeId: optionalString(context.modeId) || "ops",
|
||||
modeTitle: optionalString(context.modeTitle) || "",
|
||||
targetContexts: redactForPublicDiagnostics(targetContexts),
|
||||
enabledToolPacks,
|
||||
appGrants,
|
||||
toolProfile: {
|
||||
schemaVersion: "ai-workspace.tool-profile.v1",
|
||||
enabledToolPacks,
|
||||
mcpServers,
|
||||
mcpServerNames,
|
||||
requiredMcpServerNames,
|
||||
},
|
||||
policyPrompt: buildRunProfilePolicyPrompt({ context, diagnostics }),
|
||||
diagnostics,
|
||||
};
|
||||
runProfile.diagnostics.profileHash = runProfileHash(runProfile);
|
||||
return runProfile;
|
||||
}
|
||||
|
||||
async function resolveRunAppGrants({ owner, context, ownerSettings }) {
|
||||
const metadata = isPlainObject(ownerSettings?.metadata) ? ownerSettings.metadata : {};
|
||||
const staticAppGrants = isPlainObject(metadata.appGrants) ? metadata.appGrants : {};
|
||||
const appGrants = { ...staticAppGrants };
|
||||
const adapterDiagnostics = [];
|
||||
const adapters = Array.isArray(config.entitlementAdapters) ? config.entitlementAdapters : [];
|
||||
if (!adapters.length) {
|
||||
return {
|
||||
appGrants,
|
||||
diagnostics: {
|
||||
source: "settings",
|
||||
adapters: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
for (const adapter of adapters) {
|
||||
const result = await fetchRunEntitlementAdapter({ adapter, owner, context, ownerSettings }).catch((error) => ({
|
||||
ok: false,
|
||||
error: errorMessage(error),
|
||||
}));
|
||||
if (!result.ok) {
|
||||
adapterDiagnostics.push({
|
||||
appId: adapter.appId,
|
||||
status: "error",
|
||||
required: adapter.required === true,
|
||||
error: sanitizeBridgeErrorText(result.error || "entitlement_adapter_failed"),
|
||||
});
|
||||
if (adapter.required === true) {
|
||||
const error = new Error(`entitlement_adapter_failed:${adapter.appId}`);
|
||||
error.status = 502;
|
||||
throw error;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const adapterAppGrants = normalizeEntitlementAdapterAppGrants(result.payload, adapter);
|
||||
for (const [appId, grant] of Object.entries(adapterAppGrants)) {
|
||||
if (!isPlainObject(grant)) continue;
|
||||
const existing = isPlainObject(appGrants[appId]) ? appGrants[appId] : {};
|
||||
appGrants[appId] = {
|
||||
...existing,
|
||||
...grant,
|
||||
appId,
|
||||
mcpServers: Object.hasOwn(grant, "mcpServers") ? grant.mcpServers : existing.mcpServers,
|
||||
};
|
||||
}
|
||||
adapterDiagnostics.push({
|
||||
appId: adapter.appId,
|
||||
status: "ok",
|
||||
required: adapter.required === true,
|
||||
grantIds: Object.keys(adapterAppGrants).sort(),
|
||||
mcpServerNames: Object.values(adapterAppGrants)
|
||||
.flatMap((grant) => {
|
||||
const servers = Array.isArray(grant?.mcpServers)
|
||||
? grant.mcpServers
|
||||
: isPlainObject(grant?.mcpServers)
|
||||
? Object.values(grant.mcpServers)
|
||||
: [];
|
||||
return servers.map((server) => safeMcpServerName(server?.serverName || server?.server_name || server?.name));
|
||||
})
|
||||
.filter(Boolean),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
appGrants,
|
||||
diagnostics: {
|
||||
source: adapterDiagnostics.some((item) => item.status === "ok") ? "adapters+settings" : "settings",
|
||||
adapters: adapterDiagnostics,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchRunEntitlementAdapter({ adapter, owner, context, ownerSettings }) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), adapter.timeoutMs);
|
||||
const body = JSON.stringify({
|
||||
schemaVersion: "ai-workspace.entitlement-request.v1",
|
||||
appId: adapter.appId,
|
||||
owner: publicOwner(owner),
|
||||
activeContext: redactForPublicDiagnostics(isPlainObject(ownerSettings?.activeContext) ? ownerSettings.activeContext : {}),
|
||||
runContext: redactForPublicDiagnostics(context),
|
||||
requestedAt: new Date().toISOString(),
|
||||
});
|
||||
try {
|
||||
const response = await fetch(adapter.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
...(adapter.authorization ? { Authorization: adapter.authorization } : {}),
|
||||
...adapter.headers,
|
||||
},
|
||||
body,
|
||||
signal: controller.signal,
|
||||
});
|
||||
const text = await response.text();
|
||||
let payload = {};
|
||||
try {
|
||||
payload = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
payload = { ok: false, error: "invalid_json_response" };
|
||||
}
|
||||
if (!response.ok || payload?.ok === false) {
|
||||
throw new Error(optionalString(payload?.error || payload?.message) || `http_${response.status}`);
|
||||
}
|
||||
return { ok: true, payload };
|
||||
} catch (error) {
|
||||
if (error?.name === "AbortError") throw new Error("entitlement_adapter_timeout");
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEntitlementAdapterAppGrants(payload, adapter) {
|
||||
const source = isPlainObject(payload?.appGrants)
|
||||
? payload.appGrants
|
||||
: Array.isArray(payload?.appGrants)
|
||||
? payload.appGrants
|
||||
: payload?.grant || payload?.appGrant || payload?.entitlement || payload?.entitlements || payload?.grants || payload;
|
||||
const out = {};
|
||||
if (Array.isArray(source)) {
|
||||
for (const item of source) {
|
||||
const grant = normalizeEntitlementAdapterGrant(item, adapter);
|
||||
if (grant?.appId) out[grant.appId] = grant;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (!isPlainObject(source)) return out;
|
||||
if (source.mcpServers || source.scopes || source.appId || source.app_id || source.surface) {
|
||||
const grant = normalizeEntitlementAdapterGrant(source, adapter);
|
||||
if (grant?.appId) out[grant.appId] = grant;
|
||||
return out;
|
||||
}
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
const grant = normalizeEntitlementAdapterGrant(value, { ...adapter, appId: normalizeKey(key) || adapter.appId });
|
||||
if (grant?.appId) out[grant.appId] = grant;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeEntitlementAdapterGrant(value, adapter) {
|
||||
if (!isPlainObject(value)) return null;
|
||||
const appId = normalizeKey(value.appId || value.app_id || adapter.appId);
|
||||
if (!appId) return null;
|
||||
return {
|
||||
...value,
|
||||
appId,
|
||||
appTitle: optionalString(value.appTitle || value.app_title || value.title || adapter.title),
|
||||
surface: optionalString(value.surface) || appId,
|
||||
source: "entitlement-adapter",
|
||||
adapterId: adapter.id,
|
||||
};
|
||||
}
|
||||
|
||||
function runProfileMcpServersFromSettings(settings) {
|
||||
const metadata = isPlainObject(settings?.metadata) ? settings.metadata : {};
|
||||
const appGrants = isPlainObject(metadata.appGrants) ? metadata.appGrants : {};
|
||||
return runProfileMcpServersFromAppGrants(settings, appGrants);
|
||||
}
|
||||
|
||||
function runProfileMcpServersFromAppGrants(settings, appGrantsInput = {}) {
|
||||
const servers = [];
|
||||
const metadata = isPlainObject(settings?.metadata) ? settings.metadata : {};
|
||||
collectInstallerMcpServers(servers, metadata.mcpServers, {});
|
||||
const appGrants = isPlainObject(appGrantsInput) ? appGrantsInput : {};
|
||||
for (const [appId, grant] of Object.entries(appGrants)) {
|
||||
if (!isPlainObject(grant)) continue;
|
||||
collectInstallerMcpServers(servers, grant.mcpServers, {
|
||||
appId: optionalString(grant.appId) || normalizeKey(appId),
|
||||
appTitle: optionalString(grant.appTitle || grant.title),
|
||||
});
|
||||
}
|
||||
|
||||
const byServerName = new Map();
|
||||
for (const server of servers.map(sanitizeInstallerMcpServer).filter(Boolean)) {
|
||||
if (server.enabled === false) continue;
|
||||
byServerName.set(server.serverName, server);
|
||||
}
|
||||
return Array.from(byServerName.values());
|
||||
}
|
||||
|
||||
function summarizeRunAppGrants(metadata) {
|
||||
const appGrants = isPlainObject(metadata?.appGrants) ? metadata.appGrants : {};
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(appGrants)) {
|
||||
if (!isPlainObject(value)) continue;
|
||||
const appId = optionalString(value.appId) || normalizeKey(key);
|
||||
if (!appId) continue;
|
||||
const mcpServers = Array.isArray(value.mcpServers)
|
||||
? value.mcpServers
|
||||
: isPlainObject(value.mcpServers)
|
||||
? Object.values(value.mcpServers)
|
||||
: [];
|
||||
out[appId] = {
|
||||
appId,
|
||||
appTitle: optionalString(value.appTitle || value.title),
|
||||
surface: optionalString(value.surface) || appId,
|
||||
updatedAt: optionalString(value.updatedAt || value.updated_at),
|
||||
context: redactForPublicDiagnostics(isPlainObject(value.context) ? value.context : {}),
|
||||
scopes: uniqueStrings(Array.isArray(value.scopes) ? value.scopes : []),
|
||||
hasMcpServers: mcpServers.length > 0,
|
||||
mcpServerNames: mcpServers
|
||||
.map((server) => safeMcpServerName(server?.serverName || server?.server_name || server?.name))
|
||||
.filter(Boolean),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function buildRunProfilePolicyPrompt({ context, diagnostics }) {
|
||||
const lines = [
|
||||
"AI Workspace dynamic run profile:",
|
||||
`- source surface: ${diagnostics.sourceSurface}`,
|
||||
`- mode: ${diagnostics.modeId}`,
|
||||
`- access mode: ${diagnostics.accessMode}`,
|
||||
`- context ready: ${diagnostics.contextReady ? "yes" : "no"}`,
|
||||
`- entitlement source: ${diagnostics.entitlementAdapters?.source || "settings"}`,
|
||||
`- enabled tool packs: ${diagnostics.enabledToolPacks.length ? diagnostics.enabledToolPacks.join(", ") : "none"}`,
|
||||
`- MCP servers available in this run: ${diagnostics.mcpServerNames.length ? diagnostics.mcpServerNames.join(", ") : "none"}`,
|
||||
"- MCP tokens and headers are runtime secrets and must never be printed in public answers.",
|
||||
];
|
||||
const opsContext = isPlainObject(context?.contexts?.ops) ? context.contexts.ops : {};
|
||||
if (opsContext.opsWorkspaceSlug || opsContext.opsProjectId) {
|
||||
lines.push(
|
||||
`- Ops target workspace: ${opsContext.opsWorkspaceSlug || opsContext.opsWorkspaceId || "unknown"}`,
|
||||
`- Ops target project: ${opsContext.opsProjectId || "unknown"}`
|
||||
);
|
||||
}
|
||||
const engineContext = isPlainObject(context?.contexts?.engine) ? context.contexts.engine : {};
|
||||
if (engineContext.workflowId || engineContext.agentNodeId) {
|
||||
lines.push(
|
||||
`- Engine target workflow: ${engineContext.workflowId || "unknown"}`,
|
||||
`- Engine target agent node: ${engineContext.agentNodeId || "unknown"}`
|
||||
);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function runProfileHash(runProfile) {
|
||||
const publicProfile = redactRunProfile(runProfile);
|
||||
const stableProfile = {
|
||||
...publicProfile,
|
||||
runId: undefined,
|
||||
createdAt: undefined,
|
||||
diagnostics: {
|
||||
...(isPlainObject(publicProfile?.diagnostics) ? publicProfile.diagnostics : {}),
|
||||
profileHash: undefined,
|
||||
},
|
||||
};
|
||||
return createHash("sha256").update(JSON.stringify(stableProfile)).digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
function redactRunProfile(runProfile) {
|
||||
if (!isPlainObject(runProfile)) return null;
|
||||
return {
|
||||
...runProfile,
|
||||
targetContexts: redactForPublicDiagnostics(runProfile.targetContexts),
|
||||
appGrants: redactForPublicDiagnostics(runProfile.appGrants),
|
||||
toolProfile: {
|
||||
...(isPlainObject(runProfile.toolProfile) ? runProfile.toolProfile : {}),
|
||||
mcpServers: Array.isArray(runProfile.toolProfile?.mcpServers)
|
||||
? runProfile.toolProfile.mcpServers.map(redactMcpServer)
|
||||
: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function redactMcpServer(server) {
|
||||
if (!isPlainObject(server)) return {};
|
||||
const headers = isPlainObject(server.httpHeaders) ? server.httpHeaders : {};
|
||||
return {
|
||||
...server,
|
||||
httpHeaders: Object.fromEntries(Object.keys(headers).map((key) => [key, "<redacted>"])),
|
||||
headers: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function redactForPublicDiagnostics(value, depth = 0) {
|
||||
if (depth > 6) return "[max-depth]";
|
||||
if (Array.isArray(value)) return value.map((item) => redactForPublicDiagnostics(item, depth + 1));
|
||||
if (!isPlainObject(value)) return value;
|
||||
const out = {};
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if (/token|secret|password|authorization|cookie|api[_-]?key/i.test(key)) {
|
||||
out[key] = "<redacted>";
|
||||
continue;
|
||||
}
|
||||
out[key] = redactForPublicDiagnostics(item, depth + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeSurfaceContexts(...contexts) {
|
||||
const out = {};
|
||||
for (const context of contexts) {
|
||||
@@ -2188,6 +2554,13 @@ function sanitizeDispatchCommand(payload) {
|
||||
function getRequestOwner(req) {
|
||||
const userId = optionalString(req.headers["x-nodedc-user-id"] || req.query.userId);
|
||||
const email = normalizeEmail(req.headers["x-nodedc-user-email"] || req.query.email);
|
||||
const role = normalizeKey(req.headers["x-nodedc-user-role"] || req.query.role);
|
||||
const groups = uniqueStrings(
|
||||
String(req.headers["x-nodedc-user-groups"] || req.query.groups || "")
|
||||
.split(/[\n,;]+/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
);
|
||||
if (!userId && !email) {
|
||||
throw badRequest("ai_workspace_owner_required");
|
||||
}
|
||||
@@ -2195,6 +2568,8 @@ function getRequestOwner(req) {
|
||||
key: email ? `email:${email}` : `user:${userId}`,
|
||||
userId,
|
||||
email,
|
||||
role: role || "",
|
||||
groups,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2203,6 +2578,8 @@ function publicOwner(owner) {
|
||||
ownerKey: owner.key,
|
||||
userId: owner.userId,
|
||||
email: owner.email,
|
||||
role: owner.role || "",
|
||||
groups: Array.isArray(owner.groups) ? owner.groups : [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2568,6 +2945,111 @@ function isDeployedPublicHubUrl(value) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseEntitlementAdapters() {
|
||||
const adapters = [];
|
||||
collectEntitlementAdapters(adapters, parseJsonEnv(
|
||||
process.env.AI_WORKSPACE_ENTITLEMENT_ADAPTERS_JSON ||
|
||||
process.env.NDC_AI_WORKSPACE_ENTITLEMENT_ADAPTERS_JSON ||
|
||||
""
|
||||
));
|
||||
collectEntitlementAdapter(adapters, "ops", {
|
||||
url: process.env.AI_WORKSPACE_OPS_ENTITLEMENT_URL || process.env.NDC_AI_WORKSPACE_OPS_ENTITLEMENT_URL,
|
||||
token: process.env.AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN || process.env.NDC_AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN,
|
||||
required: process.env.AI_WORKSPACE_OPS_ENTITLEMENT_REQUIRED || process.env.NDC_AI_WORKSPACE_OPS_ENTITLEMENT_REQUIRED,
|
||||
});
|
||||
collectEntitlementAdapter(adapters, "engine", {
|
||||
url: process.env.AI_WORKSPACE_ENGINE_ENTITLEMENT_URL || process.env.NDC_AI_WORKSPACE_ENGINE_ENTITLEMENT_URL,
|
||||
token: process.env.AI_WORKSPACE_ENGINE_ENTITLEMENT_TOKEN || process.env.NDC_AI_WORKSPACE_ENGINE_ENTITLEMENT_TOKEN,
|
||||
required: process.env.AI_WORKSPACE_ENGINE_ENTITLEMENT_REQUIRED || process.env.NDC_AI_WORKSPACE_ENGINE_ENTITLEMENT_REQUIRED,
|
||||
});
|
||||
|
||||
const byAppId = new Map();
|
||||
for (const adapter of adapters) {
|
||||
byAppId.set(adapter.appId, adapter);
|
||||
}
|
||||
return Array.from(byAppId.values());
|
||||
}
|
||||
|
||||
function parseJsonEnv(value) {
|
||||
const text = optionalString(value);
|
||||
if (!text) return null;
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function collectEntitlementAdapters(target, value) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collectEntitlementAdapter(target, "", item);
|
||||
return;
|
||||
}
|
||||
if (!isPlainObject(value)) return;
|
||||
for (const [appId, adapter] of Object.entries(value)) {
|
||||
collectEntitlementAdapter(target, appId, adapter);
|
||||
}
|
||||
}
|
||||
|
||||
function collectEntitlementAdapter(target, defaultAppId, value) {
|
||||
const adapter = sanitizeEntitlementAdapter(value, defaultAppId);
|
||||
if (adapter) target.push(adapter);
|
||||
}
|
||||
|
||||
function sanitizeEntitlementAdapter(value, defaultAppId = "") {
|
||||
if (!isPlainObject(value)) return null;
|
||||
const appId = normalizeKey(value.appId || value.app_id || defaultAppId);
|
||||
const url = cleanHttpEndpoint(value.url || value.endpoint);
|
||||
if (!appId || !url) return null;
|
||||
const tokenEnv = optionalString(value.tokenEnv || value.token_env);
|
||||
const rawToken = optionalString(value.token || value.bearerToken || value.bearer_token)
|
||||
|| (tokenEnv ? optionalString(process.env[tokenEnv]) : null)
|
||||
|| optionalString(process.env.NODEDC_INTERNAL_ACCESS_TOKEN)
|
||||
|| optionalString(process.env.NODEDC_PLATFORM_SERVICE_TOKEN)
|
||||
|| "";
|
||||
const authorization = optionalString(value.authorization || value.Authorization)
|
||||
|| (rawToken
|
||||
? rawToken.match(/^Bearer\s+/i) ? rawToken : `Bearer ${rawToken}`
|
||||
: "");
|
||||
return {
|
||||
id: optionalString(value.id) || appId,
|
||||
appId,
|
||||
title: optionalString(value.title || value.appTitle || value.app_title),
|
||||
url,
|
||||
authorization,
|
||||
headers: sanitizeAdapterHeaders(value.headers),
|
||||
required: value.required === true || isTruthy(value.required),
|
||||
timeoutMs: sanitizeInteger(value.timeoutMs || value.timeout_ms, 5000, 500, 30000),
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeAdapterHeaders(value) {
|
||||
if (!isPlainObject(value)) return {};
|
||||
const headers = {};
|
||||
for (const [key, rawValue] of Object.entries(value)) {
|
||||
const headerName = optionalString(key);
|
||||
const headerValue = optionalString(rawValue);
|
||||
if (!headerName || !headerValue || /[\r\n\0]/.test(headerName) || /[\r\n\0]/.test(headerValue)) continue;
|
||||
if (/^authorization$/i.test(headerName)) continue;
|
||||
headers[headerName] = headerValue;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function cleanHttpEndpoint(value) {
|
||||
const text = optionalString(value);
|
||||
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 readConfig() {
|
||||
const databaseUrl =
|
||||
process.env.DATABASE_URL ||
|
||||
@@ -2610,6 +3092,7 @@ function readConfig() {
|
||||
process.env.NODEDC_INTERNAL_ACCESS_TOKEN,
|
||||
process.env.NODEDC_PLATFORM_SERVICE_TOKEN,
|
||||
]),
|
||||
entitlementAdapters: parseEntitlementAdapters(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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