caelum0x 2104300b21 feat(toolgate): Open Agentic Web Challenge entry — /agentic-web manifest + runtime
Adds a spec-conforming site on Cognizant/MIT Media Lab Project NANDA/Mozilla
Otari/AWS's Minimum Viable Specification for a Worldwide Agentic Web (MVP
Profile 0.3, github.com/cognizant-ai-labs/agentic-web):

- GET /agentic-web/agent-manifest.json: public site manifest (networks,
  front_man, hocon location, agent_mcp, peer_policy, deployment), CORS-
  enabled, built live from the real catalog (tool/capability/free counts),
  never a static fixture.
- GET /agentic-web/toolgate.network.json: resolved network definition (one
  front agent, toolgate_gateway) whose only external capability is
  Toolgate's own already-live /mcp (search_tools/describe_tool/call_tool) --
  every tool call this network makes reaches the real, metered catalog.
- GET /agentic-web/runtime.js: browser runtime (plain JS) -- parses and
  validates a network, runs the BYOK agent loop (bounded steps/time) against
  the live MCP endpoint, and can load + run a second agent site's published
  network after explicit per-origin consent (spec s3.2).
- GET /agentic-web: the page, Apple-style icon-only controls, no emoji, a
  key/settings panel that reuses Toolgate's existing bearer-key auth.
- /mcp gains CORS (OPTIONS preflight + Access-Control-Allow-Origin) so a
  peer agentic site's browser runtime can call it directly, per the spec's
  CORS-enabled-public-artifacts requirement and the challenge's "callable by
  other agentic websites" ask.

Verified locally (SWITCHYARD_STORE=memory): manifest/network/runtime.js all
serve with real catalog counts and CORS headers; /mcp OPTIONS preflights
correctly; full search_tools -> describe_tool -> call_tool chain returns
real live results (npm react 19.3.1, axios 1.21.1); page loads clean in a
headless browser with no console errors; settings panel saves/clears keys;
fail-closed path confirmed (no LLM router configured -> explicit error, no
silent mock). cargo check + clippy clean, 0 warnings.

Scoped to apps/toolgate only; no other paths touched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:32:55 +03:00

402 lines
15 KiB
JavaScript

// Scribase Toolgate — open-agentic-web browser runtime.
//
// A plain-JS implementation of the minimum runtime behavior in the
// "Minimum Viable Specification for a Worldwide Agentic Web" (MVP Profile
// 0.3, Cognizant AI Lab / MIT Media Lab Project NANDA / Mozilla Otari /
// AWS): https://github.com/cognizant-ai-labs/agentic-web
//
// What this does, matched to the spec's section numbers:
// - s3.1 Parse and validate: rejects a malformed network before any model
// call (missing front agent, duplicate agent names, bad external refs).
// - s3.1 Run the agent loop: OpenAI-compatible function calling against a
// visitor-supplied BYOK router, bounded steps/time (s3.1 "Bound
// execution").
// - s3.1 Use grounded capabilities: every tool call is a real MCP
// `tools/call` against Toolgate's live `/mcp` (or a peer's, for a loaded
// peer network) — never a mock result.
// - s3.2 Loading a peer agent site: explicit per-origin consent, then
// fetch + validate the peer's own agent-manifest.json/network, and run
// it in THIS browser with the caller's own router/key (s4 "Router-only
// disclosure" — a peer's manifest can never replace the active router
// or receive the visitor's key).
// - s4 Pluggable inference / BYOK: router base URL, model and key are
// read from origin-scoped localStorage only, attached only to requests
// sent to that router, never put in URLs/manifests/prompts/peer
// requests (s4 "Credential handling").
// - s5 Fail closed / observable execution: every contacted origin, tool
// call and consent decision is appended to the Activity log; a failure
// stops that invocation rather than being reported as success.
//
// What this intentionally does NOT implement (all explicitly optional in
// the MVP): sly_data (private context) forwarding, coded-tool bundles,
// cross-site browser actions, model-compatibility negotiation. None of
// those are required for MVP conformance (s3.2 "MVP boundary").
const STORE_KEY_TOOLGATE = "toolgate.agentic-web.tg-key.v1";
const STORE_KEY_ROUTER = "toolgate.agentic-web.router.v1";
const MAX_STEPS = 6;
const MAX_EXECUTION_MS = 30000;
const $ = (id) => document.getElementById(id);
// ---------------------------------------------------------------- storage
function loadProfile() {
let router = {};
try {
router = JSON.parse(localStorage.getItem(STORE_KEY_ROUTER) || "{}");
} catch {
router = {};
}
return {
toolgateKey: localStorage.getItem(STORE_KEY_TOOLGATE) || "",
routerBase: router.base || "",
routerModel: router.model || "",
routerKey: router.key || "",
};
}
function saveProfile(p) {
localStorage.setItem(STORE_KEY_TOOLGATE, p.toolgateKey || "");
localStorage.setItem(
STORE_KEY_ROUTER,
JSON.stringify({ base: p.routerBase || "", model: p.routerModel || "", key: p.routerKey || "" })
);
}
function clearProfile() {
localStorage.removeItem(STORE_KEY_TOOLGATE);
localStorage.removeItem(STORE_KEY_ROUTER);
}
// --------------------------------------------------------------- activity
function activityLine(text) {
const el = $("activity");
if (!el) return;
const line = document.createElement("div");
line.textContent = `${new Date().toLocaleTimeString()} — ${text}`;
el.prepend(line);
while (el.children.length > 40) el.removeChild(el.lastChild);
}
function logMessage(role, text) {
const el = $("log");
if (!el) return;
const div = document.createElement("div");
div.className = `msg ${role}`;
div.textContent = text;
el.appendChild(div);
el.scrollTop = el.scrollHeight;
}
// ------------------------------------------------------------------ fetch
async function fetchJson(url, opts = {}, timeoutMs = 10000) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const resp = await fetch(url, { ...opts, signal: ctrl.signal });
activityLine(`fetched ${new URL(url, location.href).origin} — ${resp.status}`);
const body = await resp.json().catch(() => null);
if (!resp.ok) {
const err = new Error(`${resp.status} ${resp.statusText}`);
err.body = body;
throw err;
}
return body;
} finally {
clearTimeout(timer);
}
}
let rpcId = 0;
async function mcpCall(mcpUrl, method, params, bearerKey) {
const headers = { "content-type": "application/json" };
if (bearerKey) headers.authorization = `Bearer ${bearerKey}`;
const payload = { jsonrpc: "2.0", id: ++rpcId, method, params };
const data = await fetchJson(mcpUrl, { method: "POST", headers, body: JSON.stringify(payload) });
if (data && data.error) {
const err = new Error(data.error.message || "MCP error");
err.rpcError = data.error;
throw err;
}
return data ? data.result : null;
}
// ------------------------------------------------------- validate & load
/** s3.1 "Parse and validate": reject malformed networks before any model call. */
function validateNetwork(def) {
if (!def || !Array.isArray(def.tools) || def.tools.length === 0) {
throw new Error("invalid network: no agent definitions");
}
const names = new Set();
for (const agent of def.tools) {
if (!agent || typeof agent.name !== "string" || !agent.name) {
throw new Error("invalid network: an agent is missing its name");
}
if (names.has(agent.name)) {
throw new Error(`invalid network: duplicate agent name "${agent.name}"`);
}
names.add(agent.name);
const fn = agent.function || {};
if (!agent.description && !fn.description) {
throw new Error(`invalid network: agent "${agent.name}" has no function description`);
}
for (const t of agent.tools || []) {
if (typeof t === "string") {
if (!names.has(t) && !def.tools.some((a) => a.name === t)) {
throw new Error(`invalid network: agent "${agent.name}" references unknown agent "${t}"`);
}
} else if (t && typeof t === "object") {
if (!t.url) throw new Error(`invalid network: agent "${agent.name}" has a tool entry with no url`);
} else {
throw new Error(`invalid network: agent "${agent.name}" has a malformed tool entry`);
}
}
}
return { names };
}
function findAgent(def, name) {
return (def.tools || []).find((a) => a.name === name);
}
/** Resolve a peer-network reference per spec s3.2 step 1: the final path
* segment is the network name; everything before it is the site base whose
* agent-manifest.json is fetched. */
function resolvePeerRef(url) {
const u = new URL(url);
const parts = u.pathname.split("/").filter(Boolean);
const name = parts.pop() || "";
u.pathname = parts.length ? `/${parts.join("/")}/` : "/";
return { base: u.toString(), name };
}
async function loadPeerNetwork(refUrl) {
const { base, name } = resolvePeerRef(refUrl);
const origin = new URL(base).origin;
const ok = await requestConsent(origin, `load and run the "${name}" agent network`);
if (!ok) {
activityLine(`consent denied: ${origin}`);
throw new Error("consent denied");
}
activityLine(`consent granted: ${origin}`);
const manifestUrl = new URL("agent-manifest.json", base).toString();
const manifest = await fetchJson(manifestUrl);
const entry = (manifest.networks || []).find((n) => n.name === name);
if (!entry) throw new Error(`peer manifest has no network named "${name}"`);
const defUrl = new URL(entry.hocon, base).toString();
const def = await fetchJson(defUrl);
validateNetwork(def);
return { name: entry.name, frontMan: entry.front_man, description: entry.description, def, origin };
}
// -------------------------------------------------------------- consent
function requestConsent(origin, purpose) {
return new Promise((resolve) => {
const panel = $("consent-panel");
if (!panel) {
resolve(window.confirm(`Allow contacting ${origin} to ${purpose}?`));
return;
}
$("consent-text").textContent = `${origin} — ${purpose}`;
panel.classList.remove("hidden");
const done = (ok) => {
panel.classList.add("hidden");
$("consent-allow").onclick = null;
$("consent-deny").onclick = null;
resolve(ok);
};
$("consent-allow").onclick = () => done(true);
$("consent-deny").onclick = () => done(false);
});
}
// --------------------------------------------------------------- the LLM
function mcpToolsToOpenAiFunctions(mcpTools, allow) {
return mcpTools
.filter((t) => !allow || allow.includes(t.name))
.map((t) => ({
type: "function",
function: { name: t.name, description: t.description, parameters: t.inputSchema || { type: "object", properties: {} } },
}));
}
async function chatCompletion(profile, messages, tools) {
if (!profile.routerBase || !profile.routerKey) {
throw new Error("no LLM router configured — open settings and add a BYOK router + key");
}
const url = `${profile.routerBase.replace(/\/$/, "")}/chat/completions`;
const headers = { "content-type": "application/json", authorization: `Bearer ${profile.routerKey}` };
const body = JSON.stringify({ model: profile.routerModel || "gpt-4o-mini", messages, tools, tool_choice: "auto" });
const data = await fetchJson(url, { method: "POST", headers, body }, 25000);
return data.choices[0].message;
}
// ----------------------------------------------------------- agent loop
/** s3.1 "Run the agent loop" + "Bound execution": tool calls + delegation,
* capped steps and elapsed time, every call going through the network's
* own declared MCP server (so a peer network's calls reach the PEER's MCP,
* never Toolgate's — s3.2's "peer uses the caller's router" rule only
* covers inference, not the peer's own tool capabilities). */
async function runAgentLoop(network, userText, profile) {
const front = findAgent(network.def, network.frontMan);
if (!front) throw new Error(`front agent "${network.frontMan}" not found in network`);
const mcpRef = (front.tools || []).find((t) => typeof t === "object" && t.url);
let mcpTools = [];
if (mcpRef) {
activityLine(`listing tools at ${mcpRef.url}`);
const listed = await mcpCall(mcpRef.url, "tools/list", {}, profile.toolgateKey);
mcpTools = (listed && listed.tools) || [];
}
const functions = mcpToolsToOpenAiFunctions(mcpTools, mcpRef && mcpRef.tools);
const messages = [
{ role: "system", content: front.instructions || front.function?.description || "" },
{ role: "user", content: userText },
];
const deadline = Date.now() + MAX_EXECUTION_MS;
for (let step = 0; step < MAX_STEPS; step++) {
if (Date.now() > deadline) throw new Error("execution budget exceeded");
const msg = await chatCompletion(profile, messages, functions.length ? functions : undefined);
messages.push(msg);
if (!msg.tool_calls || msg.tool_calls.length === 0) {
return msg.content || "";
}
for (const call of msg.tool_calls) {
if (Date.now() > deadline) throw new Error("execution budget exceeded");
let args = {};
try {
args = JSON.parse(call.function.arguments || "{}");
} catch {
args = {};
}
activityLine(`call_tool ${call.function.name}(${JSON.stringify(args)})`);
let resultText;
try {
const result = await mcpCall(mcpRef.url, "tools/call", { name: call.function.name, arguments: args }, profile.toolgateKey);
resultText = JSON.stringify((result && result.structuredContent) ?? result);
} catch (e) {
// s5 "Fail closed": a failed tool call is reported to the model as
// a failure, never silently treated as success.
resultText = JSON.stringify({ ok: false, error: String(e.message || e) });
}
messages.push({ role: "tool", tool_call_id: call.id, content: resultText });
}
}
throw new Error("too many steps without a final answer (composition/step budget)");
}
// -------------------------------------------------------------------- UI
let currentNetwork = null;
async function initDefaultNetwork() {
const manifest = await fetchJson("/agentic-web/agent-manifest.json");
const entry = manifest.networks[0];
const def = await fetchJson(new URL(entry.hocon, location.origin).toString());
validateNetwork(def);
currentNetwork = { name: entry.name, frontMan: entry.front_man, description: entry.description, def, origin: location.origin };
$("network-name").textContent = entry.name;
$("network-desc").textContent = entry.description;
const chips = $("sample-chips");
chips.innerHTML = "";
for (const q of entry.sample_queries || []) {
const b = document.createElement("button");
b.className = "chip";
b.textContent = q;
b.onclick = () => {
$("chat-input").value = q;
send();
};
chips.appendChild(b);
}
activityLine(`loaded network "${entry.name}" from ${location.origin}`);
}
async function send() {
const input = $("chat-input");
const text = input.value.trim();
if (!text || !currentNetwork) return;
input.value = "";
logMessage("user", text);
const profile = loadProfile();
if (!profile.toolgateKey) {
logMessage("sys", "Add a Toolgate API key in settings first.");
return;
}
try {
const answer = await runAgentLoop(currentNetwork, text, profile);
logMessage("agent", answer || "(no answer)");
} catch (e) {
logMessage("sys", `failed: ${e.message || e}`);
}
}
function wireSettings() {
const profile = loadProfile();
$("tg-key").value = profile.toolgateKey;
$("llm-base").value = profile.routerBase;
$("llm-model").value = profile.routerModel;
$("llm-key").value = profile.routerKey;
$("settings-toggle").onclick = () => $("settings").classList.toggle("hidden");
$("settings-save").onclick = () => {
saveProfile({
toolgateKey: $("tg-key").value.trim(),
routerBase: $("llm-base").value.trim(),
routerModel: $("llm-model").value.trim(),
routerKey: $("llm-key").value.trim(),
});
activityLine("settings saved (origin-scoped localStorage only)");
};
$("settings-clear").onclick = () => {
clearProfile();
$("tg-key").value = "";
$("llm-base").value = "";
$("llm-model").value = "";
$("llm-key").value = "";
activityLine("settings cleared");
};
}
function wireChat() {
$("chat-send").onclick = send;
$("chat-input").addEventListener("keydown", (e) => {
if (e.key === "Enter") send();
});
}
function wirePeer() {
$("peer-load").onclick = async () => {
const url = $("peer-url").value.trim();
if (!url) return;
try {
const peer = await loadPeerNetwork(url);
currentNetwork = peer;
$("network-name").textContent = peer.name;
$("network-desc").textContent = peer.description || `loaded from ${peer.origin}`;
$("sample-chips").innerHTML = "";
activityLine(`switched to peer network "${peer.name}" from ${peer.origin}`);
} catch (e) {
activityLine(`peer load failed: ${e.message || e}`);
}
};
}
window.addEventListener("DOMContentLoaded", () => {
wireSettings();
wireChat();
wirePeer();
initDefaultNetwork().catch((e) => {
$("network-desc").textContent = `failed to load the published network: ${e.message || e}`;
});
});