UNPKG

@openai/agents-core

Version:

The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.

90 lines • 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.allocateAgentKeys = allocateAgentKeys; exports.indexAgentsByKey = indexAgentsByKey; exports.acquireSandboxAgent = acquireSandboxAgent; exports.releaseSandboxAgents = releaseSandboxAgents; exports.isSandboxAgent = isSandboxAgent; exports.getObjectId = getObjectId; const handoff_1 = require("../../handoff.js"); const brand_1 = require("../brand.js"); const sandboxConcurrencyGuards = new WeakMap(); const objectIds = new WeakMap(); let nextObjectId = 1; function allocateAgentKeys(startingAgent) { const keys = new Map(); const counts = new Map(); const usedKeys = new Set(); for (const agent of collectReachableAgents(startingAgent)) { keys.set(getObjectId(agent), allocateUniqueAgentKey(agent.name, counts, usedKeys)); } return keys; } function indexAgentsByKey(startingAgent, keys) { return new Map(collectReachableAgents(startingAgent).flatMap((agent) => { const key = keys.get(getObjectId(agent)); return key ? [[key, agent]] : []; })); } function collectReachableAgents(startingAgent) { const agents = []; const queue = [startingAgent]; const visited = new Set(); while (queue.length > 0) { const agent = queue.shift(); if (visited.has(agent)) { continue; } visited.add(agent); agents.push(agent); for (const handoff of agent.handoffs) { queue.push(handoff instanceof handoff_1.Handoff ? handoff.agent : handoff); } } return agents; } function allocateUniqueAgentKey(agentName, counts, usedKeys) { while (true) { const count = counts.get(agentName) ?? 0; counts.set(agentName, count + 1); const candidate = count === 0 ? agentName : `${agentName}_${count + 1}`; if (!usedKeys.has(candidate)) { usedKeys.add(candidate); return candidate; } } } function acquireSandboxAgent(agent) { const agentId = getObjectId(agent); const guard = sandboxConcurrencyGuards.get(agent) ?? { activeRuns: 0 }; sandboxConcurrencyGuards.set(agent, guard); if (guard.activeRuns > 0) { throw new Error(`SandboxAgent '${agent.name}' cannot be reused concurrently across runs`); } guard.activeRuns += 1; return agentId; } function releaseSandboxAgents(agents) { for (const agent of agents) { const guard = sandboxConcurrencyGuards.get(agent); if (guard) { guard.activeRuns = Math.max(0, guard.activeRuns - 1); } } } function isSandboxAgent(agent) { return (Object.prototype.hasOwnProperty.call(agent, brand_1.SANDBOX_AGENT_BRAND) && agent[brand_1.SANDBOX_AGENT_BRAND] === true); } function getObjectId(value) { const existing = objectIds.get(value); if (existing) { return existing; } const assigned = nextObjectId++; objectIds.set(value, assigned); return assigned; } //# sourceMappingURL=agentKeys.js.map