open-agentic-web 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # 🌐 Open Agentic Web SDK (`open-agentic-web`)
2
2
 
3
- [![npm version](https://img.shields.io/badge/npm-v1.0.2-blue.svg)](https://www.npmjs.com/package/open-agentic-web)
3
+ [![npm version](https://img.shields.io/badge/npm-v1.0.3-blue.svg)](https://www.npmjs.com/package/open-agentic-web)
4
4
  [![License](https://img.shields.io/badge/License-Apache_2.0-green.svg)](https://opensource.org/licenses/Apache-2.0)
5
5
  [![Specification](https://img.shields.io/badge/Spec-Open%20Agentic%20Web%20MVP%200.3-orange.svg)](https://cognizant-ai-labs.github.io/agentic-web/specs/mvp-v0.3.json)
6
6
 
7
- The **Open Agentic Web SDK** (`open-agentic-web`) is the official developer toolkit, conformance linter, and in-browser runtime for building, validating, and federating autonomous web agents.
7
+ The **Open Agentic Web SDK** (`open-agentic-web`) is the zero-dependency SDK, conformance CLI & browser runtime for building, validating, and federating autonomous web agents.
8
8
 
9
9
  Compliant with the **Cognizant AI Lab / Mozilla Otari / MIT NANDA Open Agentic Web (MVP Profile 0.3)** specification.
10
10
 
@@ -172,8 +172,8 @@ Enable parent orchestrators to execute your site tools from an iframe using the
172
172
  <script type="importmap">
173
173
  {
174
174
  "imports": {
175
- "open-agentic-web": "https://esm.sh/open-agentic-web@1.0.2",
176
- "open-agentic-web/": "https://esm.sh/open-agentic-web@1.0.2/"
175
+ "open-agentic-web": "https://esm.sh/open-agentic-web@1.0.3",
176
+ "open-agentic-web/": "https://esm.sh/open-agentic-web@1.0.3/"
177
177
  }
178
178
  }
179
179
  </script>
@@ -252,10 +252,7 @@ const turnResult = await swarm.runTurn({
252
252
 
253
253
  console.log("Agent response:", turnResult.text);
254
254
 
255
- // 4. Search active specialist nodes in the swarm
256
- const diningAgents = swarm.search({ category: "Dining" });
257
-
258
- // 5. Export current peer mappings to links.json format
255
+ // 4. Export current peer mappings to links.json format
259
256
  const linksConfig = swarm.exportLinks("my_hub_network");
260
257
  ```
261
258
 
package/bin/cli.mjs CHANGED
@@ -6,8 +6,18 @@
6
6
  */
7
7
 
8
8
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
- import { basename, join, resolve } from "node:path";
10
- import { validateFederation, validateNode } from "../src/validator.js";
9
+ import { basename, dirname, join, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { validateFederation, validateManifest, validateNetwork, validateNode } from "../src/validator.js";
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = dirname(__filename);
15
+
16
+ let VERSION = "1.0.3";
17
+ try {
18
+ const pkg = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
19
+ if (pkg.version) VERSION = pkg.version;
20
+ } catch {}
11
21
 
12
22
  const args = process.argv.slice(2);
13
23
  const command = args[0] || "help";
@@ -47,6 +57,89 @@ ${colors.bold}EXAMPLES:${colors.reset}
47
57
  `);
48
58
  }
49
59
 
60
+ async function validateRemoteUrl(urlStr) {
61
+ const cleanUrl = urlStr.replace(/\/$/, "");
62
+ const results = [];
63
+ let failed = 0;
64
+
65
+ try {
66
+ const manifestUrl = `${cleanUrl}/agent-manifest.json`;
67
+ const manifestRes = await fetch(manifestUrl);
68
+
69
+ // Check CORS
70
+ const corsHeader = manifestRes.headers.get("access-control-allow-origin");
71
+ if (corsHeader === "*" || corsHeader) {
72
+ results.push({ status: "PASS", message: `CORS header present on manifest: 'Access-Control-Allow-Origin: ${corsHeader}'` });
73
+ } else {
74
+ results.push({ status: "WARN", message: `Missing 'Access-Control-Allow-Origin' header on ${manifestUrl}. Remote browser swarms may be blocked by CORS.` });
75
+ }
76
+
77
+ if (!manifestRes.ok) {
78
+ results.push({ status: "FAIL", message: `Failed to fetch agent-manifest.json from '${manifestUrl}' (HTTP ${manifestRes.status})` });
79
+ failed++;
80
+ return { target: cleanUrl, valid: false, failed, results };
81
+ }
82
+
83
+ results.push({ status: "PASS", message: `Successfully fetched 'agent-manifest.json'` });
84
+ const manifest = await manifestRes.json();
85
+ const manifestCheck = validateManifest(manifest);
86
+ results.push(...manifestCheck.results);
87
+ if (!manifestCheck.valid) failed += manifestCheck.failed;
88
+
89
+ // Check bridge
90
+ const bridgeUrl = `${cleanUrl}/bridge/action-bridge.html`;
91
+ try {
92
+ const bridgeRes = await fetch(bridgeUrl);
93
+ if (bridgeRes.ok) {
94
+ results.push({ status: "PASS", message: `Live action bridge available at '${bridgeUrl}'` });
95
+ const xfo = bridgeRes.headers.get("x-frame-options");
96
+ if (xfo && (xfo.toUpperCase() === "DENY" || xfo.toUpperCase() === "SAMEORIGIN")) {
97
+ results.push({ status: "FAIL", message: `Action bridge has 'X-Frame-Options: ${xfo}' which prevents cross-origin embedding by orchestrators!` });
98
+ failed++;
99
+ } else {
100
+ results.push({ status: "PASS", message: `X-Frame-Options allows cross-origin embedding` });
101
+ }
102
+ } else {
103
+ results.push({ status: "WARN", message: `Action bridge at '${bridgeUrl}' returned HTTP ${bridgeRes.status}` });
104
+ }
105
+ } catch (e) {
106
+ results.push({ status: "WARN", message: `Could not verify action bridge at '${bridgeUrl}': ${e.message}` });
107
+ }
108
+
109
+ // Check declarative network if declared
110
+ const netPath = manifest.networks?.[0]?.hocon;
111
+ if (netPath && typeof netPath === "string") {
112
+ const networkUrl = `${cleanUrl}/${netPath.replace(/^\.\//, "")}`;
113
+ try {
114
+ const netRes = await fetch(networkUrl);
115
+ if (netRes.ok) {
116
+ results.push({ status: "PASS", message: `Fetched declarative network from '${networkUrl}'` });
117
+ const netJson = await netRes.json();
118
+ const netCheck = validateNetwork(netJson);
119
+ results.push(...netCheck.results);
120
+ if (!netCheck.valid) failed += netCheck.failed;
121
+ } else {
122
+ results.push({ status: "FAIL", message: `Referenced network file at '${networkUrl}' returned HTTP ${netRes.status}` });
123
+ failed++;
124
+ }
125
+ } catch (e) {
126
+ results.push({ status: "FAIL", message: `Failed to fetch network graph from '${networkUrl}': ${e.message}` });
127
+ failed++;
128
+ }
129
+ }
130
+ } catch (err) {
131
+ results.push({ status: "FAIL", message: `Network error connecting to '${cleanUrl}': ${err.message}` });
132
+ failed++;
133
+ }
134
+
135
+ return {
136
+ target: cleanUrl,
137
+ valid: failed === 0,
138
+ failed,
139
+ results
140
+ };
141
+ }
142
+
50
143
  async function runValidate() {
51
144
  const targetDirs = args.slice(1).length > 0 ? args.slice(1) : ["."];
52
145
  let overallFailed = 0;
@@ -54,8 +147,9 @@ async function runValidate() {
54
147
  console.log(`\n${colors.bold}✈️ Running Open Agentic Web Conformance Linter${colors.reset}\n`);
55
148
 
56
149
  for (const dir of targetDirs) {
57
- const summary = await validateNode(dir);
58
- console.log(`${colors.bold}Testing Node:${colors.reset} ${colors.cyan}${summary.target}${colors.reset}`);
150
+ const isRemote = dir.startsWith("http://") || dir.startsWith("https://");
151
+ const summary = isRemote ? await validateRemoteUrl(dir) : await validateNode(dir);
152
+ console.log(`${colors.bold}Testing ${isRemote ? "Live Node" : "Node"}:${colors.reset} ${colors.cyan}${summary.target}${colors.reset}`);
59
153
 
60
154
  summary.results.forEach(res => {
61
155
  if (res.status === "PASS") {
@@ -238,8 +332,8 @@ export class SiteActions {
238
332
  <script type="importmap">
239
333
  {
240
334
  "imports": {
241
- "open-agentic-web": "https://esm.sh/open-agentic-web@1.0.2",
242
- "open-agentic-web/": "https://esm.sh/open-agentic-web@1.0.2/"
335
+ "open-agentic-web": "https://esm.sh/open-agentic-web@${VERSION}",
336
+ "open-agentic-web/": "https://esm.sh/open-agentic-web@${VERSION}/"
243
337
  }
244
338
  }
245
339
  </script>
@@ -277,8 +371,8 @@ export class SiteActions {
277
371
  <script type="importmap">
278
372
  {
279
373
  "imports": {
280
- "open-agentic-web": "https://esm.sh/open-agentic-web@1.0.2",
281
- "open-agentic-web/": "https://esm.sh/open-agentic-web@1.0.2/"
374
+ "open-agentic-web": "https://esm.sh/open-agentic-web@${VERSION}",
375
+ "open-agentic-web/": "https://esm.sh/open-agentic-web@${VERSION}/"
282
376
  }
283
377
  }
284
378
  </script>
@@ -354,7 +448,7 @@ switch (command) {
354
448
  case "version":
355
449
  case "-v":
356
450
  case "--version":
357
- console.log("open-agentic-web v1.0.2");
451
+ console.log(`open-agentic-web v${VERSION}`);
358
452
  break;
359
453
  case "help":
360
454
  case "--help":
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "open-agentic-web",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Standard developer toolkit, conformance linter & in-browser runtime for the Open Agentic Web (Cognizant / Mozilla / MIT NANDA MVP Profile 0.3)",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
7
8
  "bin": {
8
9
  "open-agentic-web": "./bin/cli.mjs",
9
10
  "oaw": "./bin/cli.mjs"
package/src/actions.js CHANGED
@@ -257,6 +257,49 @@ export function createActionRegistry() {
257
257
  }));
258
258
  },
259
259
 
260
+ /**
261
+ * Export tools in OpenAI / Vercel AI SDK function calling format
262
+ */
263
+ toOpenAITools() {
264
+ return this.list().map(a => ({
265
+ type: "function",
266
+ function: {
267
+ name: a.name,
268
+ description: a.description,
269
+ parameters: a.inputSchema
270
+ }
271
+ }));
272
+ },
273
+
274
+ /**
275
+ * Export tools in Model Context Protocol (MCP) format
276
+ */
277
+ toMCPTools() {
278
+ return this.list().map(a => ({
279
+ name: a.name,
280
+ description: a.description,
281
+ inputSchema: a.inputSchema
282
+ }));
283
+ },
284
+
285
+ /**
286
+ * Register tools into browser native WebMCP (navigator.modelContext) if available
287
+ */
288
+ async registerWebMCP() {
289
+ if (typeof navigator !== "undefined" && navigator.modelContext && typeof navigator.modelContext.registerTool === "function") {
290
+ for (const act of this.list()) {
291
+ await navigator.modelContext.registerTool({
292
+ name: act.name,
293
+ description: act.description,
294
+ parameters: act.inputSchema,
295
+ execute: async (args) => this.execute(act.name, args)
296
+ });
297
+ }
298
+ return true;
299
+ }
300
+ return false;
301
+ },
302
+
260
303
  /**
261
304
  * Execute an action by name with input arguments
262
305
  */
package/src/bridge.js CHANGED
@@ -14,6 +14,7 @@ export const ACTION_BRIDGE_PROTOCOL = "nsdeploy-actions-v1";
14
14
  export function setupActionBridge({
15
15
  registry,
16
16
  allowedOrigins = ["*"],
17
+ manifestUrl = null,
17
18
  onConfirm = null,
18
19
  protocol = ACTION_BRIDGE_PROTOCOL,
19
20
  windowObj = globalThis.window
@@ -23,10 +24,26 @@ export function setupActionBridge({
23
24
  }
24
25
 
25
26
  // Cross-origin federation allows orchestrators to connect; irreversible actions strictly enforce onConfirm
26
- const effectiveAllowedOrigins = Array.isArray(allowedOrigins) && allowedOrigins.length > 0
27
- ? allowedOrigins
27
+ let effectiveAllowedOrigins = Array.isArray(allowedOrigins) && allowedOrigins.length > 0
28
+ ? [...allowedOrigins]
28
29
  : ["*"];
29
30
 
31
+ // Runtime enforcement of agent-manifest.json peer_policy if provided
32
+ if (manifestUrl && typeof windowObj.fetch === "function") {
33
+ windowObj.fetch(manifestUrl)
34
+ .then(res => res.json())
35
+ .then(manifest => {
36
+ const policy = manifest.peer_policy;
37
+ if (policy && policy.mode === "closed" && Array.isArray(policy.allowed_peers)) {
38
+ effectiveAllowedOrigins = [...policy.allowed_peers];
39
+ console.info(`[ActionBridge] Restricting allowedOrigins to peer_policy.allowed_peers:`, effectiveAllowedOrigins);
40
+ }
41
+ })
42
+ .catch(err => {
43
+ console.warn(`[ActionBridge] Unable to load manifest policy from '${manifestUrl}':`, err);
44
+ });
45
+ }
46
+
30
47
  if (effectiveAllowedOrigins.includes("*")) {
31
48
  console.warn(
32
49
  "[ActionBridge Security Warning] allowedOrigins is set to wildcard ('*'). " +
@@ -93,7 +110,17 @@ export function setupActionBridge({
93
110
  isConnected = true;
94
111
 
95
112
  port.onmessage = async ({ data: portData }) => {
96
- if (!portData || portData.type !== "call") return;
113
+ if (!portData) return;
114
+
115
+ // Catalog discovery RPC
116
+ if (portData.type === "catalog") {
117
+ const { id } = portData;
118
+ const tools = registry.catalog();
119
+ port.postMessage({ id, ok: true, tools, protocol });
120
+ return;
121
+ }
122
+
123
+ if (portData.type !== "call") return;
97
124
 
98
125
  const { id, action, arguments: args } = portData;
99
126
  try {
@@ -116,6 +143,13 @@ export function setupActionBridge({
116
143
  }
117
144
  }
118
145
 
146
+ // Direct fallback catalog discovery if no MessageChannel
147
+ if (data.type === "catalog" && data.id) {
148
+ const tools = registry.catalog();
149
+ source?.postMessage({ id: data.id, ok: true, tools, protocol }, origin);
150
+ return;
151
+ }
152
+
119
153
  // Direct fallback communication if no MessageChannel
120
154
  if (data.type === "call" && data.id && data.action) {
121
155
  const { id, action, arguments: args } = data;
@@ -210,7 +244,7 @@ export function createActionBridgeClient({
210
244
  if (data?.id && pendingRequests.has(data.id)) {
211
245
  const { res, rej } = pendingRequests.get(data.id);
212
246
  pendingRequests.delete(data.id);
213
- if (data.ok) res(data.result);
247
+ if (data.ok) res(data.tools !== undefined ? data.tools : data.result);
214
248
  else rej(new Error(data.error || "Action execution failed."));
215
249
  }
216
250
  };
@@ -263,6 +297,32 @@ export function createActionBridgeClient({
263
297
  });
264
298
  },
265
299
 
300
+ /**
301
+ * Fetch runtime action catalog with full inputSchema parameter definitions from remote bridge.
302
+ */
303
+ async getCatalog() {
304
+ await connect();
305
+ const id = `cat_${++seq}_${Date.now()}`;
306
+
307
+ return new Promise((res, rej) => {
308
+ const timer = setTimeout(() => {
309
+ pendingRequests.delete(id);
310
+ rej(new Error(`Timeout fetching catalog from '${brand}' (${timeoutMs}ms)`));
311
+ }, timeoutMs);
312
+
313
+ pendingRequests.set(id, {
314
+ res: (tools) => { clearTimeout(timer); res(tools); },
315
+ rej: (err) => { clearTimeout(timer); rej(err); }
316
+ });
317
+
318
+ port.postMessage({
319
+ type: "catalog",
320
+ id,
321
+ protocol: ACTION_BRIDGE_PROTOCOL
322
+ });
323
+ });
324
+ },
325
+
266
326
  dispose() {
267
327
  if (port) {
268
328
  try { port.close(); } catch {}
package/src/federation.js CHANGED
@@ -4,12 +4,15 @@
4
4
  * of peer agentic web nodes on the fly with 100% client-side privacy.
5
5
  */
6
6
 
7
+ import { createActionBridgeClient } from "./bridge.js";
8
+
7
9
  export class AgentSwarm {
8
10
  constructor({ defaultRouter = "https://api.otari.ai/api/v1", defaultModel = "alibaba/qwen3.8-flash" } = {}) {
9
11
  this.defaultRouter = defaultRouter;
10
12
  this.defaultModel = defaultModel;
11
13
  this.nodes = new Map();
12
14
  this.listeners = new Set();
15
+ this._toolMap = new Map();
13
16
  }
14
17
 
15
18
  /**
@@ -61,7 +64,11 @@ export class AgentSwarm {
61
64
  node.name.toLowerCase().includes(q) ||
62
65
  node.description.toLowerCase().includes(q) ||
63
66
  node.category.toLowerCase().includes(q) ||
64
- node.tools.some(t => t.toLowerCase().includes(q));
67
+ node.tools.some(t =>
68
+ (typeof t === "string" ? t : `${t?.name || ""} ${t?.description || ""}`)
69
+ .toLowerCase()
70
+ .includes(q)
71
+ );
65
72
 
66
73
  return matchCat && matchQuery;
67
74
  });
@@ -94,8 +101,9 @@ export class AgentSwarm {
94
101
  /**
95
102
  * Mount a remote conforming agentic web node from its public URL.
96
103
  * If onConsent hook is provided, requests user approval before registering.
104
+ * In browser contexts, optionally auto-wires an ActionBridgeClient and hydrates live catalog.
97
105
  */
98
- async mountFromUrl(nodeUrl, { onConsent = null, fetchFn = globalThis.fetch } = {}) {
106
+ async mountFromUrl(nodeUrl, { onConsent = null, autoWireBridge = true, fetchFn = globalThis.fetch } = {}) {
99
107
  if (!fetchFn) {
100
108
  throw new Error("fetch is required to mount remote agentic web nodes.");
101
109
  }
@@ -150,6 +158,23 @@ export class AgentSwarm {
150
158
  }
151
159
  }
152
160
 
161
+ // Optional Auto-Wired Action Bridge Client in browser DOM contexts
162
+ let bridgeClient = null;
163
+ if (autoWireBridge && typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined") {
164
+ try {
165
+ bridgeClient = createActionBridgeClient({
166
+ bridgeUrl: `${cleanUrl}/bridge/action-bridge.html`,
167
+ brand: manifest.brand || manifest.name || "Peer Bridge"
168
+ });
169
+ const liveCatalog = await bridgeClient.getCatalog().catch(() => null);
170
+ if (Array.isArray(liveCatalog) && liveCatalog.length > 0) {
171
+ hydratedTools = liveCatalog;
172
+ }
173
+ } catch {
174
+ // Fallback to static declarations
175
+ }
176
+ }
177
+
153
178
  const candidateNode = {
154
179
  id: manifest.name || network.name || `node_${Date.now()}`,
155
180
  name: manifest.brand || manifest.description || manifest.name || network.name,
@@ -157,7 +182,8 @@ export class AgentSwarm {
157
182
  node_url: cleanUrl,
158
183
  category: manifest.category || (network.tags && network.tags[0]) || "Specialist",
159
184
  description: manifest.description || network.description || "",
160
- tools: hydratedTools
185
+ tools: hydratedTools,
186
+ _bridgeClient: bridgeClient
161
187
  };
162
188
 
163
189
  // User consent check
@@ -169,6 +195,9 @@ export class AgentSwarm {
169
195
  });
170
196
 
171
197
  if (!approved) {
198
+ if (bridgeClient && typeof bridgeClient.dispose === "function") {
199
+ bridgeClient.dispose();
200
+ }
172
201
  throw new Error(`Mounting of node '${candidateNode.name}' was declined by user consent.`);
173
202
  }
174
203
  }
@@ -176,17 +205,58 @@ export class AgentSwarm {
176
205
  return this.registerNode(candidateNode);
177
206
  }
178
207
 
208
+ /**
209
+ * Resolve an exposed tool name back to its owning node and raw tool name.
210
+ */
211
+ resolveTool(toolName) {
212
+ if (this._toolMap.has(toolName)) {
213
+ return this._toolMap.get(toolName);
214
+ }
215
+ if (toolName.includes("__")) {
216
+ const idx = toolName.indexOf("__");
217
+ const nodeId = toolName.slice(0, idx);
218
+ const rawName = toolName.slice(idx + 2);
219
+ const node = this.nodes.get(nodeId);
220
+ return { node, rawName, nodeId };
221
+ }
222
+ for (const node of this.nodes.values()) {
223
+ const hasTool = (node.tools || []).some(t => (typeof t === "string" ? t : t.name) === toolName);
224
+ if (hasTool) return { node, rawName: toolName, nodeId: node.id };
225
+ }
226
+ return { node: null, rawName: toolName, nodeId: null };
227
+ }
228
+
179
229
  /**
180
230
  * Export all registered tools across connected nodes as OpenAI-compatible function calling schemas.
231
+ * Automatically namespaces function names (${nodeId}__${toolName}) when collisions exist across nodes.
181
232
  */
182
- getOpenAITools(toolSubset = null) {
233
+ getOpenAITools(toolSubset = null, { namespace = "auto" } = {}) {
183
234
  const formatted = [];
184
235
  const allowed = toolSubset ? new Set(toolSubset) : null;
236
+ this._toolMap.clear();
185
237
 
238
+ // Count tool names across all nodes to detect cross-peer collisions
239
+ const toolCounts = new Map();
186
240
  for (const node of this.nodes.values()) {
187
241
  for (const tool of (node.tools || [])) {
188
- const name = typeof tool === "string" ? tool : tool.name;
189
- if (allowed && !allowed.has(name)) continue;
242
+ const rawName = typeof tool === "string" ? tool : tool.name;
243
+ if (allowed && !allowed.has(rawName)) continue;
244
+ toolCounts.set(rawName, (toolCounts.get(rawName) || 0) + 1);
245
+ }
246
+ }
247
+
248
+ for (const node of this.nodes.values()) {
249
+ for (const tool of (node.tools || [])) {
250
+ const rawName = typeof tool === "string" ? tool : tool.name;
251
+ if (allowed && !allowed.has(rawName)) continue;
252
+
253
+ const isCollision = (toolCounts.get(rawName) || 0) > 1;
254
+ const shouldNamespace = namespace === true || (namespace === "auto" && isCollision);
255
+ const safeNodeId = (node.id || "peer").replace(/[^a-zA-Z0-9_]/g, "_");
256
+ const exposedName = shouldNamespace ? `${safeNodeId}__${rawName}` : rawName;
257
+
258
+ this._toolMap.set(exposedName, { node, rawName, nodeId: node.id });
259
+ this._toolMap.set(rawName, { node, rawName, nodeId: node.id });
190
260
 
191
261
  const description = typeof tool === "object" && tool.description
192
262
  ? tool.description
@@ -199,7 +269,7 @@ export class AgentSwarm {
199
269
  formatted.push({
200
270
  type: "function",
201
271
  function: {
202
- name,
272
+ name: exposedName,
203
273
  description,
204
274
  parameters
205
275
  }
@@ -212,6 +282,7 @@ export class AgentSwarm {
212
282
  /**
213
283
  * Execute an in-browser agent turn with BYOK LLM inference and autonomous tool execution.
214
284
  * Compatible with Mozilla Otari, OpenRouter, and standard OpenAI-compatible endpoints.
285
+ * Auto-routes to peer action bridges when actionExecutor is omitted, and supports SSE token streaming.
215
286
  */
216
287
  async runTurn({
217
288
  prompt,
@@ -223,6 +294,8 @@ export class AgentSwarm {
223
294
  actionExecutor = null,
224
295
  maxSteps = 5,
225
296
  onStep = null,
297
+ stream = false,
298
+ onToken = null,
226
299
  fetchFn = globalThis.fetch
227
300
  }) {
228
301
  if (!fetchFn) {
@@ -246,12 +319,21 @@ export class AgentSwarm {
246
319
  ? { id: "call_mock_1", function: { name: tools[0].function.name, arguments: "{}" } }
247
320
  : null;
248
321
 
249
- if (mockToolCall && actionExecutor) {
250
- const result = await actionExecutor(mockToolCall.function.name, {});
322
+ if (mockToolCall) {
323
+ let result;
324
+ const { node, rawName } = this.resolveTool(mockToolCall.function.name);
325
+ if (typeof actionExecutor === "function") {
326
+ result = await actionExecutor(rawName, {}, { nodeId: node?.id, namespacedName: mockToolCall.function.name, node });
327
+ } else if (node && node._bridgeClient && typeof node._bridgeClient.execute === "function") {
328
+ result = await node._bridgeClient.execute(rawName, {});
329
+ } else {
330
+ result = { ok: true, simulated: true, tool: rawName };
331
+ }
332
+
251
333
  conversation.push({ role: "assistant", tool_calls: [mockToolCall], content: null });
252
334
  conversation.push({ role: "tool", tool_call_id: mockToolCall.id, name: mockToolCall.function.name, content: JSON.stringify(result) });
253
- conversation.push({ role: "assistant", content: `Mock synthesis completed for ${mockToolCall.function.name}.` });
254
- return { ok: true, text: `Mock synthesis completed for ${mockToolCall.function.name}.`, messages: conversation, stepsCount: 2, toolCallsCount: 1 };
335
+ conversation.push({ role: "assistant", content: `Mock synthesis completed for ${rawName}.` });
336
+ return { ok: true, text: `Mock synthesis completed for ${rawName}.`, messages: conversation, stepsCount: 2, toolCallsCount: 1 };
255
337
  }
256
338
 
257
339
  const reply = `Mock offline response for: ${prompt}`;
@@ -269,7 +351,8 @@ export class AgentSwarm {
269
351
  const payload = {
270
352
  model,
271
353
  messages: conversation,
272
- tools: tools.length > 0 ? tools : undefined
354
+ tools: tools.length > 0 ? tools : undefined,
355
+ stream: Boolean(stream && typeof onToken === "function")
273
356
  };
274
357
 
275
358
  const headers = {
@@ -290,12 +373,62 @@ export class AgentSwarm {
290
373
  throw new Error(`LLM inference failed at '${endpoint}' (HTTP ${res.status}): ${errText}`);
291
374
  }
292
375
 
293
- const data = await res.json();
294
- const choice = data.choices?.[0];
295
- const message = choice?.message;
376
+ let message;
377
+ if (payload.stream && res.body && typeof res.body.getReader === "function") {
378
+ const reader = res.body.getReader();
379
+ const decoder = new TextDecoder("utf-8");
380
+ let buffer = "";
381
+ let fullContent = "";
382
+ const toolCallsMap = new Map();
383
+
384
+ while (true) {
385
+ const { done, value } = await reader.read();
386
+ if (done) break;
387
+ buffer += decoder.decode(value, { stream: true });
388
+ const lines = buffer.split("\n");
389
+ buffer = lines.pop() || "";
390
+
391
+ for (const line of lines) {
392
+ const trimmed = line.trim();
393
+ if (!trimmed || trimmed.startsWith(":") || trimmed === "data: [DONE]") continue;
394
+ if (trimmed.startsWith("data: ")) {
395
+ try {
396
+ const chunk = JSON.parse(trimmed.slice(6));
397
+ const delta = chunk.choices?.[0]?.delta;
398
+ if (delta?.content) {
399
+ fullContent += delta.content;
400
+ onToken(delta.content);
401
+ }
402
+ if (delta?.tool_calls) {
403
+ for (const tc of delta.tool_calls) {
404
+ const idx = tc.index ?? 0;
405
+ if (!toolCallsMap.has(idx)) {
406
+ toolCallsMap.set(idx, { id: tc.id || `call_${idx}`, function: { name: tc.function?.name || "", arguments: "" } });
407
+ }
408
+ const existing = toolCallsMap.get(idx);
409
+ if (tc.id) existing.id = tc.id;
410
+ if (tc.function?.name) existing.function.name += tc.function.name;
411
+ if (tc.function?.arguments) existing.function.arguments += tc.function.arguments;
412
+ }
413
+ }
414
+ } catch {}
415
+ }
416
+ }
417
+ }
418
+
419
+ const tool_calls = Array.from(toolCallsMap.values()).filter(t => t.function.name);
420
+ message = {
421
+ role: "assistant",
422
+ content: fullContent || null,
423
+ tool_calls: tool_calls.length > 0 ? tool_calls : undefined
424
+ };
425
+ } else {
426
+ const data = await res.json();
427
+ message = data.choices?.[0]?.message;
428
+ }
296
429
 
297
430
  if (!message) {
298
- throw new Error("Invalid response format from LLM router: missing choices[0].message");
431
+ throw new Error("Invalid response format from LLM router: missing message in choices");
299
432
  }
300
433
 
301
434
  conversation.push(message);
@@ -313,19 +446,31 @@ export class AgentSwarm {
313
446
  }
314
447
 
315
448
  let result;
449
+ const { node, rawName } = this.resolveTool(toolName);
450
+
316
451
  if (typeof actionExecutor === "function") {
317
452
  try {
318
- result = await actionExecutor(toolName, args);
453
+ result = await actionExecutor(rawName, args, {
454
+ nodeId: node?.id,
455
+ namespacedName: toolName,
456
+ node
457
+ });
458
+ } catch (err) {
459
+ result = { ok: false, error: err.message };
460
+ }
461
+ } else if (node && node._bridgeClient && typeof node._bridgeClient.execute === "function") {
462
+ try {
463
+ result = await node._bridgeClient.execute(rawName, args);
319
464
  } catch (err) {
320
465
  result = { ok: false, error: err.message };
321
466
  }
322
467
  } else {
323
- result = { ok: true, message: `Tool '${toolName}' executed in swarm context.` };
468
+ result = { ok: true, message: `Tool '${rawName}' executed in swarm context.` };
324
469
  }
325
470
 
326
471
  if (typeof onStep === "function") {
327
472
  try {
328
- onStep({ step, tool: toolName, arguments: args, result });
473
+ onStep({ step, tool: rawName, namespacedTool: toolName, arguments: args, result });
329
474
  } catch {}
330
475
  }
331
476
 
@@ -357,6 +502,18 @@ export class AgentSwarm {
357
502
  };
358
503
  }
359
504
 
505
+ /**
506
+ * Dispose all active bridge client iframes associated with mounted nodes.
507
+ */
508
+ dispose() {
509
+ for (const node of this.nodes.values()) {
510
+ if (node._bridgeClient && typeof node._bridgeClient.dispose === "function") {
511
+ try { node._bridgeClient.dispose(); } catch {}
512
+ node._bridgeClient = null;
513
+ }
514
+ }
515
+ }
516
+
360
517
  /**
361
518
  * Subscribe to swarm changes.
362
519
  */
package/src/index.d.ts ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Open Agentic Web SDK (open-agentic-web) — TypeScript Declarations
3
+ * Spec: Cognizant AI Lab / Mozilla Otari / MIT NANDA MVP Profile 0.3
4
+ */
5
+
6
+ export type ActionEffect = "read" | "irreversible" | "undoable";
7
+
8
+ export interface JSONSchema {
9
+ type?: string;
10
+ properties?: Record<string, JSONSchema>;
11
+ required?: string[];
12
+ items?: JSONSchema;
13
+ minLength?: number;
14
+ maxLength?: number;
15
+ minimum?: number;
16
+ maximum?: number;
17
+ description?: string;
18
+ enum?: any[];
19
+ [key: string]: any;
20
+ }
21
+
22
+ export interface ActionDefinition {
23
+ name: string;
24
+ description: string;
25
+ effect?: ActionEffect;
26
+ inputSchema?: JSONSchema;
27
+ confirmsInWindow?: boolean;
28
+ execute: (args: Record<string, any>, context?: any) => Promise<any>;
29
+ rawExecute?: (args: Record<string, any>, context?: any) => Promise<any>;
30
+ }
31
+
32
+ export interface ActionCatalogEntry {
33
+ name: string;
34
+ description: string;
35
+ effect: ActionEffect;
36
+ inputSchema: JSONSchema;
37
+ confirmsInWindow?: boolean;
38
+ }
39
+
40
+ export interface OpenAITool {
41
+ type: "function";
42
+ function: {
43
+ name: string;
44
+ description: string;
45
+ parameters: JSONSchema;
46
+ };
47
+ }
48
+
49
+ export interface MCPTool {
50
+ name: string;
51
+ description: string;
52
+ inputSchema: JSONSchema;
53
+ }
54
+
55
+ export interface ActionRegistry {
56
+ register(actionDef: ActionDefinition | ActionDefinition[]): ActionRegistry;
57
+ get(name: string): ActionDefinition | undefined;
58
+ has(name: string): boolean;
59
+ list(): ActionDefinition[];
60
+ names(): string[];
61
+ catalog(): ActionCatalogEntry[];
62
+ toOpenAITools(): OpenAITool[];
63
+ toMCPTools(): MCPTool[];
64
+ registerWebMCP(): Promise<boolean>;
65
+ execute(name: string, args?: Record<string, any>, context?: any): Promise<any>;
66
+ }
67
+
68
+ export class ActionSecurityError extends Error {
69
+ action?: string;
70
+ effect?: ActionEffect;
71
+ origin?: string;
72
+ errors?: string[];
73
+ constructor(message: string, details?: Record<string, any>);
74
+ }
75
+
76
+ export function defineAction(definition: ActionDefinition): ActionDefinition;
77
+ export function createActionRegistry(): ActionRegistry;
78
+ export function validateSchema(schema: JSONSchema, data: any, path?: string): { valid: boolean; errors: string[] };
79
+
80
+ export const ACTION_BRIDGE_PROTOCOL: string;
81
+
82
+ export interface SetupActionBridgeOptions {
83
+ registry: ActionRegistry;
84
+ allowedOrigins?: string[];
85
+ manifestUrl?: string | null;
86
+ onConfirm?: (details: {
87
+ action: string;
88
+ arguments: Record<string, any>;
89
+ origin: string;
90
+ definition?: ActionDefinition;
91
+ }) => boolean | Promise<boolean>;
92
+ protocol?: string;
93
+ windowObj?: any;
94
+ }
95
+
96
+ export interface ActionBridgeHandle {
97
+ dispose(): void;
98
+ isConnected(): boolean;
99
+ }
100
+
101
+ export function setupActionBridge(options: SetupActionBridgeOptions): ActionBridgeHandle;
102
+
103
+ export interface ActionBridgeClientOptions {
104
+ bridgeUrl: string;
105
+ brand?: string;
106
+ timeoutMs?: number;
107
+ windowObj?: any;
108
+ }
109
+
110
+ export interface ActionBridgeClient {
111
+ execute(actionName: string, args?: Record<string, any>): Promise<any>;
112
+ getCatalog(): Promise<ActionCatalogEntry[]>;
113
+ dispose(): void;
114
+ }
115
+
116
+ export function createActionBridgeClient(options: ActionBridgeClientOptions): ActionBridgeClient;
117
+
118
+ export interface AgentNode {
119
+ id: string;
120
+ name: string;
121
+ category?: string;
122
+ front_man?: string;
123
+ node_url?: string;
124
+ description?: string;
125
+ tools?: Array<string | { name: string; description?: string; inputSchema?: JSONSchema }>;
126
+ icon?: string;
127
+ _bridgeClient?: ActionBridgeClient | null;
128
+ }
129
+
130
+ export interface AgentSwarmOptions {
131
+ defaultRouter?: string;
132
+ defaultModel?: string;
133
+ }
134
+
135
+ export interface RunTurnOptions {
136
+ prompt?: string;
137
+ messages?: Array<{ role: string; content: string | null; tool_calls?: any[] }>;
138
+ systemInstructions?: string;
139
+ model?: string;
140
+ routerUrl?: string;
141
+ apiKey?: string | null;
142
+ actionExecutor?: ((
143
+ toolName: string,
144
+ args: Record<string, any>,
145
+ meta?: { nodeId?: string | null; namespacedName?: string; node?: AgentNode | null }
146
+ ) => Promise<any>) | null;
147
+ maxSteps?: number;
148
+ onStep?: (stepInfo: {
149
+ step: number;
150
+ tool: string;
151
+ namespacedTool?: string;
152
+ arguments: Record<string, any>;
153
+ result: any;
154
+ }) => void;
155
+ stream?: boolean;
156
+ onToken?: (delta: string) => void;
157
+ fetchFn?: typeof fetch;
158
+ }
159
+
160
+ export interface TurnResult {
161
+ ok: boolean;
162
+ text: string;
163
+ messages: any[];
164
+ stepsCount: number;
165
+ toolCallsCount: number;
166
+ }
167
+
168
+ export class AgentSwarm {
169
+ defaultRouter: string;
170
+ defaultModel: string;
171
+ nodes: Map<string, AgentNode>;
172
+ constructor(options?: AgentSwarmOptions);
173
+ registerNode(node: AgentNode): AgentNode;
174
+ unregisterNode(id: string): boolean;
175
+ getNode(id: string): AgentNode | undefined;
176
+ getNodes(): AgentNode[];
177
+ search(filter?: { query?: string; category?: string }): AgentNode[];
178
+ exportLinks(hubNetworkName?: string): { networks: Record<string, Record<string, string>> };
179
+ mountFromUrl(nodeUrl: string, options?: {
180
+ onConsent?: (details: { candidate: AgentNode; manifest: any; origin: string }) => boolean | Promise<boolean>;
181
+ autoWireBridge?: boolean;
182
+ fetchFn?: typeof fetch;
183
+ }): Promise<AgentNode>;
184
+ resolveTool(toolName: string): { node: AgentNode | null; rawName: string; nodeId: string | null };
185
+ getOpenAITools(toolSubset?: string[] | null, options?: { namespace?: boolean | "auto" }): OpenAITool[];
186
+ runTurn(options: RunTurnOptions): Promise<TurnResult>;
187
+ dispose(): void;
188
+ subscribe(callback: (nodes: AgentNode[]) => void): () => boolean;
189
+ }
190
+
191
+ export interface ValidationItem {
192
+ status: "PASS" | "WARN" | "FAIL";
193
+ message: string;
194
+ }
195
+
196
+ export interface ValidationResult {
197
+ target?: string;
198
+ valid: boolean;
199
+ failed: number;
200
+ passed: number;
201
+ warnings: number;
202
+ results: ValidationItem[];
203
+ }
204
+
205
+ export interface FederationReport {
206
+ valid: boolean;
207
+ totalChecks: number;
208
+ totalPassed: number;
209
+ totalFailed: number;
210
+ meshReport?: {
211
+ valid: boolean;
212
+ results: ValidationItem[];
213
+ };
214
+ }
215
+
216
+ export function validateNode(nodeDir: string): Promise<ValidationResult>;
217
+ export function validateManifest(manifest: any): ValidationResult;
218
+ export function validateNetwork(network: any): ValidationResult;
219
+ export function validateFederation(hubDir: string, peerDirs: string[]): Promise<FederationReport>;
@@ -137,4 +137,39 @@ describe("Open Agentic Web - Site Actions & Validation", () => {
137
137
  ActionSecurityError
138
138
  );
139
139
  });
140
+
141
+ it("exports actions to OpenAI tools, MCP tools, and WebMCP adapter format", async () => {
142
+ const registry = createActionRegistry();
143
+ registry.register(
144
+ defineAction({
145
+ name: "website_check_rates",
146
+ description: "Check live daily room rates",
147
+ effect: "read",
148
+ inputSchema: {
149
+ type: "object",
150
+ properties: { room_type: { type: "string" } },
151
+ required: ["room_type"]
152
+ },
153
+ execute: async (args) => ({ rate: 199 })
154
+ })
155
+ );
156
+
157
+ // OpenAI format
158
+ const openaiTools = registry.toOpenAITools();
159
+ assert.strictEqual(openaiTools.length, 1);
160
+ assert.strictEqual(openaiTools[0].type, "function");
161
+ assert.strictEqual(openaiTools[0].function.name, "website_check_rates");
162
+ assert.deepStrictEqual(openaiTools[0].function.parameters.required, ["room_type"]);
163
+
164
+ // MCP format
165
+ const mcpTools = registry.toMCPTools();
166
+ assert.strictEqual(mcpTools.length, 1);
167
+ assert.strictEqual(mcpTools[0].name, "website_check_rates");
168
+ assert.strictEqual(mcpTools[0].description, "Check live daily room rates");
169
+ assert.deepStrictEqual(mcpTools[0].inputSchema.required, ["room_type"]);
170
+
171
+ // WebMCP gracefully returns false if navigator.modelContext is not present in Node
172
+ const webMcpRegistered = await registry.registerWebMCP();
173
+ assert.strictEqual(webMcpRegistered, false);
174
+ });
140
175
  });
@@ -118,4 +118,77 @@ describe("Open Agentic Web - Dynamic Swarm & Federation", () => {
118
118
  assert.strictEqual(turnResult.toolCallsCount, 1);
119
119
  assert.ok(turnResult.text.includes("website_quote_ride"));
120
120
  });
121
+
122
+ it("searches hydrated tool objects without crashing and finds tools by description", () => {
123
+ const swarm = new AgentSwarm();
124
+ swarm.registerNode({
125
+ id: "node_hydrated",
126
+ name: "Hydrated Node",
127
+ category: "Services",
128
+ tools: [
129
+ {
130
+ name: "website_check_availability",
131
+ description: "Inspect live catamaran sunset cruises"
132
+ }
133
+ ]
134
+ });
135
+
136
+ // Search by tool description query keyword
137
+ const results = swarm.search({ query: "catamaran" });
138
+ assert.strictEqual(results.length, 1);
139
+ assert.strictEqual(results[0].id, "node_hydrated");
140
+
141
+ // Search by tool name
142
+ const resultsByName = swarm.search({ query: "availability" });
143
+ assert.strictEqual(resultsByName.length, 1);
144
+ });
145
+
146
+ it("auto-namespaces tools on cross-peer collision and strips prefix before execution", async () => {
147
+ const swarm = new AgentSwarm({
148
+ defaultRouter: "mock",
149
+ defaultModel: "alibaba/qwen3.8-flash"
150
+ });
151
+
152
+ swarm.registerNode({
153
+ id: "node_a",
154
+ name: "Provider A",
155
+ category: "Inventory",
156
+ tools: [{ name: "website_query_inventory", description: "Query Provider A stock" }]
157
+ });
158
+
159
+ swarm.registerNode({
160
+ id: "node_b",
161
+ name: "Provider B",
162
+ category: "Inventory",
163
+ tools: [{ name: "website_query_inventory", description: "Query Provider B stock" }]
164
+ });
165
+
166
+ const tools = swarm.getOpenAITools();
167
+ assert.strictEqual(tools.length, 2);
168
+ // Both function names should be namespaced to prevent 400 Duplicate function name error
169
+ const names = tools.map(t => t.function.name);
170
+ assert.ok(names.includes("node_a__website_query_inventory"));
171
+ assert.ok(names.includes("node_b__website_query_inventory"));
172
+
173
+ // Tool resolution strips the prefix
174
+ const resolved = swarm.resolveTool("node_a__website_query_inventory");
175
+ assert.strictEqual(resolved.rawName, "website_query_inventory");
176
+ assert.strictEqual(resolved.nodeId, "node_a");
177
+
178
+ // In runTurn mock mode, actionExecutor receives the stripped raw tool name
179
+ let receivedToolName = null;
180
+ let receivedMeta = null;
181
+ await swarm.runTurn({
182
+ prompt: "book inventory now",
183
+ apiKey: "mock",
184
+ actionExecutor: async (tool, args, meta) => {
185
+ receivedToolName = tool;
186
+ receivedMeta = meta;
187
+ return { ok: true };
188
+ }
189
+ });
190
+
191
+ assert.strictEqual(receivedToolName, "website_query_inventory");
192
+ assert.ok(receivedMeta?.nodeId === "node_a" || receivedMeta?.nodeId === "node_b");
193
+ });
121
194
  });