Files
Kelx/utils/swarm/swarm.js
T
2026-11-30 16:32:37 +00:00

279 lines
11 KiB
JavaScript

// Swarm.js runner (corrected Node.js adaptation of OpenAI Swarm).
//
// Implements the `Swarm.run()` agentic loop described in the openai-swarm-node
// README, but with three production-grade corrections over the upstream sketch:
// 1. Native function calling for every provider (OpenAI/Anthropic/Google/
// Cohere) instead of brittle text/JSON scraping. The per-provider HTTP turn
// is INJECTED by the host so all transport, auth and message-threading stay
// in one audited place (index.js).
// 2. Real async tools. Each tool fn is awaited and may perform real side
// effects (file IO, console commands, downloads), and the loop feeds the
// verified result back to the model as a proper tool message.
// 3. Bounded, safe execution: hard caps on turns and total tool calls, a
// terminal `finish` tool, handoffs, and never-thrown tool execution so one
// failing tool cannot abort the run.
//
// The loop is provider-agnostic: it asks the injected `runTurn` adapter for the
// next assistant turn, executes any requested tools through the Agent's own
// functions, and appends the results via the adapter's message threading, until
// the model stops calling tools, calls `finish`, or a budget is hit.
const DEFAULT_MAX_TURNS = 24;
const DEFAULT_MAX_TOOL_CALLS = 80;
class Result {
// Tool functions may return a Result to hand off to another agent and/or
// update context variables, mirroring the upstream Swarm Result type.
constructor({ value = "", agent = null, contextVariables = {} } = {}) {
this.value = value;
this.agent = agent;
this.contextVariables = contextVariables || {};
}
}
function parseToolArguments(rawArguments) {
if (!rawArguments) return {};
if (typeof rawArguments === "object" && !Array.isArray(rawArguments)) return rawArguments;
try {
const parsed = JSON.parse(String(rawArguments));
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}
class Swarm {
/**
* @param {object} adapter Provider transport, injected by the host:
* - runTurn({ agent, threadState, contextVariables, options }) -> {
* content, thinking_content, toolCalls:[{id,name,arguments}], rawAssistant
* }
* - appendAssistant(threadState, { agent, rawAssistant, toolCalls })
* - appendToolResults(threadState, { toolCalls, results }) // results:[{id,name,result}]
* - createThreadState({ agent, messages, contextVariables }) -> threadState
* @param {object} [hooks]
* - onStep({ turn, toolCalls, results }) optional observability callback.
* - onEvent(event) async/sync callback for real-time streaming. Event shapes:
* { type: "thinking", turn, content }
* { type: "assistant_message", turn, content } // the model's narration
* { type: "tool_start", turn, id, name, args }
* { type: "tool_result", turn, id, name, ok, result, detail }
* { type: "tool_rejected", turn, id, name, reason }
* { type: "finish", summary }
* - approveToolCall({ name, args, turn }) -> boolean | { approved, reason }
* Called BEFORE executing a tool the host marks as sensitive. Return
* false / { approved:false } to reject; the model is told and continues.
* - isSensitiveTool(name) -> boolean. Which tools require approval.
*/
constructor(adapter, hooks = {}) {
if (!adapter || typeof adapter.runTurn !== "function") {
throw new Error("Swarm requires a transport adapter with a runTurn() function.");
}
this.adapter = adapter;
this.hooks = hooks || {};
}
async emit(event) {
if (typeof this.hooks.onEvent === "function") {
try { await this.hooks.onEvent(event); } catch { /* never let observability break the run */ }
}
}
async run({
agent,
messages = [],
contextVariables = {},
maxTurns = DEFAULT_MAX_TURNS,
maxToolCalls = DEFAULT_MAX_TOOL_CALLS,
options = {},
}) {
if (!agent) throw new Error("Swarm.run requires an initial agent.");
let currentAgent = agent;
let ctx = { ...(contextVariables || {}) };
const turnCap = Number.isFinite(maxTurns) && maxTurns > 0 ? maxTurns : DEFAULT_MAX_TURNS;
const toolCallCap = Number.isFinite(maxToolCalls) && maxToolCalls > 0 ? maxToolCalls : DEFAULT_MAX_TOOL_CALLS;
const threadState = this.adapter.createThreadState({
agent: currentAgent,
messages: Array.isArray(messages) ? messages.slice() : [],
contextVariables: ctx,
});
const transcript = []; // structured action log
const thinkingParts = [];
let finalContent = "";
let finishSummary = "";
let finished = false;
let totalToolCalls = 0;
let thinkingTimeMs = 0;
for (let turn = 0; turn < turnCap && !finished; turn += 1) {
const startedAt = Date.now();
let result;
try {
result = await this.adapter.runTurn({
agent: currentAgent,
threadState,
contextVariables: ctx,
options,
});
} catch (err) {
finalContent = `The AI provider failed on turn ${turn + 1}: ${String(err?.message || err).slice(0, 240)}.`;
break;
}
thinkingTimeMs += Date.now() - startedAt;
if (result?.thinking_content) {
thinkingParts.push(String(result.thinking_content));
await this.emit({ type: "thinking", turn, content: String(result.thinking_content) });
}
const toolCalls = Array.isArray(result?.toolCalls) ? result.toolCalls : [];
// Stream the model's narration ("Now I create index.html...") whenever it
// accompanies tool calls, so the user sees what the agent is doing live.
const narration = String(result?.content || "").trim();
if (narration && toolCalls.length) {
await this.emit({ type: "assistant_message", turn, content: narration });
}
// No tool calls => the model produced its final natural-language answer.
if (!toolCalls.length) {
finalContent = narration;
break;
}
// Record the assistant turn (with its tool calls) in the provider thread.
this.adapter.appendAssistant(threadState, {
agent: currentAgent,
rawAssistant: result.rawAssistant,
toolCalls,
content: result?.content || "",
});
const stepResults = [];
let handoffAgent = null;
for (const call of toolCalls) {
const name = String(call?.name || "").trim();
const args = parseToolArguments(call?.arguments);
// Terminal finish tool: ends the run with a summary.
if (name === "finish") {
finished = true;
finishSummary = String(args?.summary || "").trim();
stepResults.push({ id: call.id, name, result: { ok: true, finished: true, summary: finishSummary } });
transcript.push({ tool: name, args, ok: true, detail: finishSummary });
await this.emit({ type: "finish", summary: finishSummary });
continue;
}
if (totalToolCalls >= toolCallCap) {
finished = true;
finishSummary = finishSummary || "Reached the tool-call budget for this run and stopped.";
stepResults.push({ id: call.id, name, result: { ok: false, error: "Tool-call budget exhausted." } });
break;
}
totalToolCalls += 1;
await this.emit({ type: "tool_start", turn, id: call.id, name, args });
// Approval gate for sensitive tools (writes, deletes, commands, etc.).
// The host decides which tools are sensitive and whether each call is
// approved. A rejection is fed back to the model so it can adapt.
if (typeof this.hooks.isSensitiveTool === "function" && this.hooks.isSensitiveTool(name)
&& typeof this.hooks.approveToolCall === "function") {
let decision;
try {
decision = await this.hooks.approveToolCall({ name, args, turn, id: call.id });
} catch (err) {
decision = { approved: false, reason: String(err?.message || "Approval failed.") };
}
const approved = decision === true || decision?.approved === true;
if (!approved) {
const reason = (decision && decision.reason) ? String(decision.reason) : "The user rejected this action.";
const rejectResult = { ok: false, rejected: true, error: reason };
stepResults.push({ id: call.id, name, result: rejectResult });
transcript.push({ tool: name, args, ok: false, rejected: true, detail: reason });
await this.emit({ type: "tool_rejected", turn, id: call.id, name, reason });
continue;
}
}
const tool = currentAgent.getTool(name);
let toolResult;
if (!tool || typeof tool.fn !== "function") {
toolResult = { ok: false, error: `Unknown tool: ${name}.` };
} else {
try {
const raw = await tool.fn(args, ctx);
if (raw instanceof Result) {
if (raw.agent) handoffAgent = raw.agent;
if (raw.contextVariables) ctx = { ...ctx, ...raw.contextVariables };
toolResult = raw.value && typeof raw.value === "object"
? raw.value
: { ok: true, value: raw.value, handoff: raw.agent ? raw.agent.name : undefined };
} else if (raw && typeof raw === "object" && raw.__handoffAgent) {
// Convenience handoff: a tool returning { __handoffAgent: agent }.
handoffAgent = raw.__handoffAgent;
toolResult = { ok: true, handoff: handoffAgent.name };
} else {
toolResult = raw && typeof raw === "object" ? raw : { ok: true, value: raw };
}
} catch (err) {
// Tools must never abort the loop; surface the error to the model.
toolResult = { ok: false, error: String(err?.message || err || "Tool failed.").slice(0, 300) };
}
}
stepResults.push({ id: call.id, name, result: toolResult });
transcript.push({
tool: name,
args,
ok: toolResult?.ok !== false,
detail: toolResult?.ok === false ? toolResult.error : (toolResult?.message || ""),
});
await this.emit({
type: "tool_result",
turn,
id: call.id,
name,
ok: toolResult?.ok !== false,
result: toolResult,
detail: toolResult?.ok === false ? toolResult.error : (toolResult?.message || ""),
});
if (finished) break;
}
// Thread the tool results back so the model observes them next turn.
this.adapter.appendToolResults(threadState, { toolCalls, results: stepResults });
if (typeof this.hooks.onStep === "function") {
try { this.hooks.onStep({ turn, toolCalls, results: stepResults }); } catch { /* ignore */ }
}
// Apply a handoff (if any) AFTER threading results, like upstream Swarm.
if (handoffAgent) currentAgent = handoffAgent;
if (turn === turnCap - 1 && !finished && !finalContent) {
finalContent = "Reached the step limit before fully finishing the task.";
}
}
return {
agent: currentAgent,
finalContent: (finishSummary || finalContent || "").trim(),
finishSummary,
transcript,
contextVariables: ctx,
thinking_content: thinkingParts.join("\n\n").trim(),
thinking_time_ms: thinkingTimeMs,
totalToolCalls,
};
}
}
module.exports = { Swarm, Result, parseToolArguments };