import { getAgentExecutionConfig } from "../runtime/execution-config.ts"; import { isKnowledgeEnabled } from "#veryfront/agent/runtime/knowledge-tools.ts"; import type { DiscoveryResult } from "#veryfront/discovery/types.ts"; import { replaceDiscoveredProjectPrimitives } from "#veryfront/discovery/registry-replacement.ts"; import { createProjectDiscoveryConfig } from "#veryfront/discovery/project-discovery-config.ts"; import { clearTranspileCache } from "#veryfront/discovery/transpiler.ts"; import { getConfig, type VeryfrontConfig } from "#veryfront/config"; import { runWithRegistryTransaction } from "#veryfront/registry/project-scoped-registry-manager.ts"; import type { RuntimeAdapter } from "#veryfront/platform/adapters/base.ts"; import type { FileSystemAdapter } from "#veryfront/platform/adapters/base.ts"; import { getLocalAdapter } from "#veryfront/platform/adapters/registry.ts"; import { clearMCPRegistry } from "#veryfront/mcp"; import { workflowRegistry } from "#veryfront/workflow/registry.ts"; import { agentRegistry } from "../composition/index.ts"; import type { RuntimeAgentMarkdownDefinition, RuntimeAgentMcpServerConfig, } from "../runtime/agent-definition.ts"; import { getRuntimeAgentMarkdownDefinition, isRuntimeAgentMarkdownAgent, } from "../runtime/agent-markdown-adapter.ts"; import type { Agent, AgentConfig } from "../types.ts"; import type { Tool } from "#veryfront/tool/types.ts"; import type { AgentSystem } from "#veryfront/agent/types.ts"; import { flattenSystemInstructions } from "#veryfront/agent/runtime/tool-inventory.ts"; import { normalizeSourceIntegrationPolicy, type SourceIntegrationPolicyManifest, } from "#veryfront/integrations/source-policy.ts"; import { getActiveSourceIntegrationPolicy, runWithEffectiveSourceIntegrationPolicy, } from "#veryfront/integrations/source-policy-context.ts"; import { CONFIG_INVALID } from "#veryfront/errors"; import { compareStrings } from "#veryfront/utils/compare.ts"; import { defineOwnDataProperty } from "#veryfront/security/own-data-property.ts"; import { createPrivateMap } from "#veryfront/security/private-map.ts"; const objectSetPrototypeOf = Object.setPrototypeOf; const objectEntries = Object.entries; const arraySort = Array.prototype.sort; const apply = Reflect.apply; const mapGet = Map.prototype.get; const FRAMEWORK_KNOWLEDGE_TOOL_NAME = "veryfront__search_knowledge"; function shouldProjectPositiveToolName( name: string, knowledge: AgentConfig["knowledge"], ): boolean { return name !== FRAMEWORK_KNOWLEDGE_TOOL_NAME || !isKnowledgeEnabled(knowledge); } function selectedConfigToolNames( tools: Exclude, denied: boolean, knowledge?: AgentConfig["knowledge"], ): string[] { const entries = objectEntries(tools); const names: string[] = []; for (let index = 0; index < entries.length; index++) { const entry = entries[index]!; const name = entry[0]; if ( (entry[1] === false) === denied && (denied || shouldProjectPositiveToolName(name, knowledge)) ) { defineOwnDataProperty(names, names.length, name, { enumerable: true, configurable: true, writable: true, }); } } return apply(arraySort, names, [compareStrings]) as string[]; } function snapshotSerializableSkillSelector( skills: AgentConfig["skills"], ): RuntimeAgentMarkdownDefinition["skills"] { if (skills === undefined) return undefined; if (Array.isArray(skills)) { const values: string[] = []; for (let index = 0; index < skills.length; index += 1) { defineOwnDataProperty(values, values.length, skills[index], { enumerable: true, configurable: true, writable: true, }); } return values; } if (skills !== null && typeof skills === "object") { const values: Record = {}; for (const [key, value] of objectEntries(skills)) { defineOwnDataProperty(values, key, value, { enumerable: true, configurable: true, writable: true, }); } return values; } return skills; } /** Public API contract for project agent runtime agent source. */ export type ProjectAgentRuntimeAgentSource = "auto" | "code" | "markdown"; /** Public API contract for project agent runtime agent ID candidates. */ export type ProjectAgentRuntimeAgentIdCandidates = { codeAgentIds: string[]; markdownAgentIds: string[]; }; /** Input payload for discover project agent runtime. */ export type DiscoverProjectAgentRuntimeInput = { projectDir: string; adapter?: RuntimeAdapter; config?: VeryfrontConfig | null; fsAdapter?: FileSystemAdapter; cacheKey?: string; verbose?: boolean; /** Immutable outer restriction to preserve while loading and discovering this source. */ sourceIntegrationPolicy?: SourceIntegrationPolicyManifest; /** Explicit host-owned capability for a trusted local or dedicated runtime. */ allowHostProjectCodeExecution?: boolean; }; /** Project discovery plus the normalized policy owned by that exact source. */ export type ProjectAgentRuntimeDiscovery = DiscoveryResult & { sourceIntegrationPolicy: SourceIntegrationPolicyManifest; }; /** Execute a project-runtime lifetime without allowing an outer policy to widen. */ export function runWithProjectAgentRuntime( runtime: Pick, fn: () => T, ): T { return runWithEffectiveSourceIntegrationPolicy(runtime.sourceIntegrationPolicy, fn); } async function resolveAgentSystem(system: AgentConfig["system"]): Promise { return typeof system === "function" ? await system() : system; } function resolveAgentToolNames( tools: AgentConfig["tools"], knowledge: AgentConfig["knowledge"], ): boolean | string[] | undefined { if (tools === false) { return false; } if (tools === true) { return true; } if (!tools) { return undefined; } const names = selectedConfigToolNames(tools, false, knowledge); return names.length > 0 ? names : undefined; } /** * Explicit `false` entries carried separately so hosted preparation cannot * re-add a tool the agent author denied by name (for example the * runtime-essential skill loaders). */ function resolveAgentDeniedToolNames(tools: AgentConfig["tools"]): string[] | undefined { if (!tools || tools === true) { return undefined; } const names = selectedConfigToolNames(tools, true); return names.length > 0 ? names : undefined; } function resolveSerializableMcpServers( mcpServers: AgentConfig["mcpServers"], ): RuntimeAgentMcpServerConfig[] | undefined { if (mcpServers === undefined) { return undefined; } const serialized: RuntimeAgentMcpServerConfig[] = []; for (let index = 0; index < mcpServers.length; index++) { const server = { ...mcpServers[index]! }; objectSetPrototypeOf(server, null); if ("transport" in server) { throw CONFIG_INVALID.create({ detail: `HTTP MCP server "${server.id}" cannot be serialized into a hosted agent definition. ` + "Configure it on the hosted agent service, or use a first-party MCP preset.", }); } defineOwnDataProperty(serialized, serialized.length, { kind: server.kind, ...(server.kind === "veryfront-studio" && server.required !== undefined ? { required: server.required } : {}), ...(server.id === undefined ? {} : { id: server.id }), ...(server.toolPolicy === undefined ? {} : { toolPolicy: server.toolPolicy }), }, { enumerable: true, configurable: true, writable: true }); } return serialized; } /** Clear project agent runtime registries. */ export function clearProjectAgentRuntimeRegistries(): void { clearTranspileCache(); clearProjectAgentRuntimePrimitiveRegistries(); } function clearProjectAgentRuntimePrimitiveRegistries(): void { agentRegistry.clear(); clearMCPRegistry(); workflowRegistry.clear(); } /** Return inline tools for one selected project agent without sharing names across agents. */ export function getProjectAgentRuntimeInlineTools( result: Pick, agentId: string, ): Map { const tools = createPrivateMap(); const selected: Agent | undefined = apply(mapGet, result.agents, [agentId]); const selectedConfig = selected?.config; const configuredTools = selectedConfig?.tools; if (configuredTools === undefined || configuredTools === true) return tools; const knowledge = selectedConfig?.knowledge; const entries = objectEntries(configuredTools); for (let index = 0; index < entries.length; index++) { const entry = entries[index]!; const name = entry[0], value = entry[1]; if ( shouldProjectPositiveToolName(name, knowledge) && value !== false && value !== undefined && typeof value === "object" && typeof (value as Tool).execute === "function" ) { tools.set(name, value as Tool); } } return tools; } /** Discover project agent runtime helper. */ export async function discoverProjectAgentRuntime( input: DiscoverProjectAgentRuntimeInput, ): Promise { return await runWithEffectiveSourceIntegrationPolicy( input.sourceIntegrationPolicy, async () => { const config = input.config ?? await getConfig( input.projectDir, input.adapter ?? await getLocalAdapter(), input.cacheKey ? { cacheKey: input.cacheKey } : undefined, ); const discoveryOptions = createProjectDiscoveryConfig({ projectDir: input.projectDir, config, fsAdapter: input.fsAdapter, verbose: input.verbose, allowHostProjectCodeExecution: input.allowHostProjectCodeExecution, }); const currentSourcePolicy = normalizeSourceIntegrationPolicy(config.integrations); return await runWithEffectiveSourceIntegrationPolicy( currentSourcePolicy, async () => { const sourceIntegrationPolicy = getActiveSourceIntegrationPolicy() ?? currentSourcePolicy; const discovery = await runWithRegistryTransaction(async () => { // Reset the previous project generation inside the same transaction // that publishes its replacement. Concurrent readers therefore see // either complete generation, never an empty or partially updated one. clearProjectAgentRuntimePrimitiveRegistries(); const discovery = await replaceDiscoveredProjectPrimitives(discoveryOptions, { // Preserve the one-shot runtime contract: callers receive every // discovery error alongside the valid primitives and decide // whether those errors are fatal. Publication is still atomic. errorPolicy: "publish-valid", }); return discovery; }); return { ...discovery, sourceIntegrationPolicy }; }, ); }, ); } /** Does project agent runtime agent match source helper. */ export function doesProjectAgentRuntimeAgentMatchSource( runtimeAgent: Agent, source: ProjectAgentRuntimeAgentSource, ): boolean { if (source === "auto") { return true; } const markdownAgent = isRuntimeAgentMarkdownAgent(runtimeAgent); return source === "markdown" ? markdownAgent : !markdownAgent; } /** Create runtime agent definition from agent. */ export async function createRuntimeAgentDefinitionFromAgent( runtimeAgent: Agent, ): Promise { const markdownDefinition = getRuntimeAgentMarkdownDefinition(runtimeAgent); if (markdownDefinition) { return markdownDefinition; } const config = { ...getAgentExecutionConfig(runtimeAgent.config) }; objectSetPrototypeOf(config, null); const toolNames = resolveAgentToolNames(config.tools, config.knowledge); const deniedToolNames = resolveAgentDeniedToolNames(config.tools); const mcpServers = resolveSerializableMcpServers(config.mcpServers); const system = await resolveAgentSystem(config.system); const skills = snapshotSerializableSkillSelector(config.skills); return { id: runtimeAgent.id, name: config.name ?? runtimeAgent.id, description: config.description ?? "", ...(config.avatarUrl ?? config.avatar_url ? { avatarUrl: config.avatarUrl ?? config.avatar_url } : {}), instructions: typeof system === "string" ? system : flattenSystemInstructions(system), ...(typeof system === "string" ? {} : { system }), model: config.model, ...(config.temperature === undefined ? {} : { temperature: config.temperature }), ...(config.parallelToolCalls === undefined ? {} : { parallelToolCalls: config.parallelToolCalls }), ...(config.thinking === undefined ? {} : { thinking: config.thinking }), maxSteps: config.maxSteps, ...(config.providerTools ? { providerTools: config.providerTools } : {}), ...(skills === undefined ? {} : { skills }), ...(toolNames === undefined ? {} : { tools: toolNames }), ...(config.toolLoading === undefined ? {} : { toolLoading: config.toolLoading }), ...(config.bootstrapTools === undefined ? {} : { bootstrapTools: config.bootstrapTools }), ...(config.optionalBootstrapTools === undefined ? {} : { optionalBootstrapTools: config.optionalBootstrapTools }), ...(config.bootstrapSkill === undefined ? {} : { bootstrapSkill: config.bootstrapSkill }), ...(config.toolResultContext === undefined ? {} : { toolResultContext: config.toolResultContext }), ...(config.knowledge === undefined ? {} : { knowledge: config.knowledge }), ...(deniedToolNames === undefined ? {} : { deniedTools: deniedToolNames }), ...(config.delegates === undefined ? {} : { delegates: config.delegates }), ...(mcpServers === undefined ? {} : { mcpServers }), }; } /** Return project agent runtime agent ID candidates. */ export function getProjectAgentRuntimeAgentIdCandidates( discoveryResult: Pick | null | undefined, ): ProjectAgentRuntimeAgentIdCandidates { const codeAgentIds: string[] = []; const markdownAgentIds: string[] = []; for (const [agentId, runtimeAgent] of discoveryResult?.agents.entries() ?? []) { if (isRuntimeAgentMarkdownAgent(runtimeAgent)) { markdownAgentIds.push(agentId); } else { codeAgentIds.push(agentId); } } return { codeAgentIds: codeAgentIds.sort((left, right) => left.localeCompare(right)), markdownAgentIds: markdownAgentIds.sort((left, right) => left.localeCompare(right)), }; } /** Describe project agent runtime agent ID candidates helper. */ export function describeProjectAgentRuntimeAgentIdCandidates( input: ProjectAgentRuntimeAgentIdCandidates, ): string { const ids = [...new Set([...input.codeAgentIds, ...input.markdownAgentIds])] .sort((left, right) => left.localeCompare(right)); return ids.length > 0 ? ids.join(", ") : "none"; } /** Resolves single project agent runtime agent ID. */ export function resolveSingleProjectAgentRuntimeAgentId(input: { candidates: ProjectAgentRuntimeAgentIdCandidates; source: ProjectAgentRuntimeAgentSource; }): string | null { if (input.source === "code") { return input.candidates.codeAgentIds.length === 1 ? input.candidates.codeAgentIds[0] ?? null : null; } if (input.source === "markdown") { return input.candidates.markdownAgentIds.length === 1 ? input.candidates.markdownAgentIds[0] ?? null : null; } const candidateIds = [ ...new Set([...input.candidates.codeAgentIds, ...input.candidates.markdownAgentIds]), ]; return candidateIds.length === 1 ? candidateIds[0] ?? null : null; }