@openai/agents-core
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
82 lines • 2.74 kB
JavaScript
import { Handoff } from "../../handoff.mjs";
import { SANDBOX_AGENT_BRAND } from "../brand.mjs";
const sandboxConcurrencyGuards = new WeakMap();
const objectIds = new WeakMap();
let nextObjectId = 1;
export 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;
}
export 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
? 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;
}
}
}
export 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;
}
export function releaseSandboxAgents(agents) {
for (const agent of agents) {
const guard = sandboxConcurrencyGuards.get(agent);
if (guard) {
guard.activeRuns = Math.max(0, guard.activeRuns - 1);
}
}
}
export function isSandboxAgent(agent) {
return (Object.prototype.hasOwnProperty.call(agent, SANDBOX_AGENT_BRAND) &&
agent[SANDBOX_AGENT_BRAND] === true);
}
export function getObjectId(value) {
const existing = objectIds.get(value);
if (existing) {
return existing;
}
const assigned = nextObjectId++;
objectIds.set(value, assigned);
return assigned;
}
//# sourceMappingURL=agentKeys.mjs.map