open-agentic-web 1.0.0 → 1.0.2

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,6 +1,6 @@
1
1
  # 🌐 Open Agentic Web SDK (`open-agentic-web`)
2
2
 
3
- [![npm version](https://img.shields.io/badge/npm-v1.0.0-blue.svg)](https://www.npmjs.com/package/open-agentic-web)
3
+ [![npm version](https://img.shields.io/badge/npm-v1.0.2-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
 
@@ -130,7 +130,7 @@ export class SiteActions {
130
130
  })
131
131
  );
132
132
 
133
- // 2. Irreversible action (triggers human confirmation dialog)
133
+ // 2. Irreversible action (enforces human confirmation before execution)
134
134
  registry.register(
135
135
  defineAction({
136
136
  name: "website_commit_booking",
@@ -168,6 +168,15 @@ Enable parent orchestrators to execute your site tools from an iframe using the
168
168
  <head>
169
169
  <meta charset="utf-8">
170
170
  <title>Action Bridge</title>
171
+ <!-- Browser Import Map for static hosting without bundlers -->
172
+ <script type="importmap">
173
+ {
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/"
177
+ }
178
+ }
179
+ </script>
171
180
  <script type="module">
172
181
  import { createActionRegistry, setupActionBridge } from "open-agentic-web";
173
182
  import { SiteActions } from "../site-actions.js";
@@ -176,7 +185,13 @@ Enable parent orchestrators to execute your site tools from an iframe using the
176
185
  SiteActions.registerActions(registry);
177
186
 
178
187
  // Listens for postMessage and MessageChannel handshakes from orchestrators
179
- setupActionBridge({ registry });
188
+ // Enforces human confirmation dialog for irreversible actions
189
+ setupActionBridge({
190
+ registry,
191
+ onConfirm: async ({ action, arguments: args, origin }) => {
192
+ return window.confirm(`Authorize action '${action}' requested by ${origin}?`);
193
+ }
194
+ });
180
195
  </script>
181
196
  </head>
182
197
  <body></body>
@@ -201,9 +216,9 @@ const quote = await client.execute("website_quote_transfer", {
201
216
 
202
217
  ---
203
218
 
204
- ## 🌐 4. Dynamic Federation & Swarm Engine (`open-agentic-web/federation`)
219
+ ## 🌐 4. Dynamic Federation & In-Browser LLM Runtime (`open-agentic-web/federation`)
205
220
 
206
- Mount and orchestrate third-party agentic web nodes on the fly in browser RAM with user consent:
221
+ Mount third-party agentic web nodes on the fly in browser RAM and execute autonomous agent turns with tool-calling:
207
222
 
208
223
  ```javascript
209
224
  import { AgentSwarm } from "open-agentic-web";
@@ -213,17 +228,34 @@ const swarm = new AgentSwarm({
213
228
  defaultModel: "alibaba/qwen3.8-flash"
214
229
  });
215
230
 
216
- // Mount an external specialist node with interactive user consent
231
+ // 1. Mount an external specialist node with interactive user consent
217
232
  await swarm.mountFromUrl("https://partner-dining.com", {
218
233
  onConsent: async ({ candidate, origin }) => {
219
234
  return window.confirm(`Allow agent '${candidate.name}' from ${origin} to join your journey?`);
220
235
  }
221
236
  });
222
237
 
223
- // Search active specialist nodes in the swarm
238
+ // 2. Search active specialist nodes in the swarm
239
+ const diningAgents = swarm.search({ category: "Dining" });
240
+
241
+ // 3. Execute an autonomous multi-step turn with BYOK LLM tool-calling
242
+ const turnResult = await swarm.runTurn({
243
+ prompt: "Find a waterfront dinner table for 2 guests around 7 PM",
244
+ apiKey: "otk_my_key", // Visitor's BYOK key
245
+ actionExecutor: async (toolName, args) => {
246
+ return client.execute(toolName, args);
247
+ },
248
+ onStep: ({ step, tool, arguments: args, result }) => {
249
+ console.log(`[Step ${step}] Executed ${tool}:`, result);
250
+ }
251
+ });
252
+
253
+ console.log("Agent response:", turnResult.text);
254
+
255
+ // 4. Search active specialist nodes in the swarm
224
256
  const diningAgents = swarm.search({ category: "Dining" });
225
257
 
226
- // Export current peer mappings to links.json format
258
+ // 5. Export current peer mappings to links.json format
227
259
  const linksConfig = swarm.exportLinks("my_hub_network");
228
260
  ```
229
261
 
package/bin/cli.mjs CHANGED
@@ -98,6 +98,17 @@ async function runFederation() {
98
98
  console.log(`Total checks run: ${fed.totalChecks}`);
99
99
  console.log(`Passed: ${colors.green}${fed.totalPassed}${colors.reset} | Failed: ${colors.red}${fed.totalFailed}${colors.reset}`);
100
100
 
101
+ if (fed.meshReport?.results && fed.meshReport.results.length > 0) {
102
+ console.log(`\n${colors.bold}Mesh Link & Policy Verification Details:${colors.reset}`);
103
+ fed.meshReport.results.forEach(res => {
104
+ if (res.status === "PASS") {
105
+ console.log(` ${colors.green}✅ PASS:${colors.reset} ${res.message}`);
106
+ } else {
107
+ console.log(` ${colors.red}❌ FAIL:${colors.reset} ${res.message}`);
108
+ }
109
+ });
110
+ }
111
+
101
112
  if (!fed.valid) {
102
113
  console.error(`\n${colors.red}${colors.bold}Federation validation failed.${colors.reset}\n`);
103
114
  process.exit(1);
@@ -223,21 +234,69 @@ export class SiteActions {
223
234
  <head>
224
235
  <meta charset="utf-8">
225
236
  <title>Action Bridge - ${nodeName}</title>
237
+ <!-- Browser Import Map: Resolves bare module specifiers on static hosts without a bundler -->
238
+ <script type="importmap">
239
+ {
240
+ "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/"
243
+ }
244
+ }
245
+ </script>
226
246
  <script type="module">
227
247
  import { createActionRegistry, setupActionBridge } from "open-agentic-web";
228
248
  import { SiteActions } from "../site-actions.js";
229
249
 
230
250
  const registry = createActionRegistry();
231
251
  SiteActions.registerActions(registry);
232
- setupActionBridge({ registry });
252
+
253
+ // Secure action bridge: allows cross-origin orchestrators while enforcing human confirmation for irreversible actions
254
+ setupActionBridge({
255
+ registry,
256
+ allowedOrigins: ["*"],
257
+ onConfirm: async ({ action, arguments: args, origin }) => {
258
+ return window.confirm("[Action Authorization] " + origin + " is requesting to execute '" + action + "'. Authorize this action?");
259
+ }
260
+ });
233
261
  </script>
234
262
  </head>
235
- <body></body>
263
+ <body>
264
+ <h3>Action Bridge for ${nodeName}</h3>
265
+ </body>
236
266
  </html>
237
267
  `;
238
268
  writeFileSync(join(bridgeDir, "action-bridge.html"), bridgeHtml);
239
269
 
240
- // 5. links.json
270
+ // 5. index.html presentation starter
271
+ const indexHtml = `<!doctype html>
272
+ <html lang="en">
273
+ <head>
274
+ <meta charset="utf-8">
275
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
276
+ <title>${nodeName} - Open Agentic Web Node</title>
277
+ <script type="importmap">
278
+ {
279
+ "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/"
282
+ }
283
+ }
284
+ </script>
285
+ </head>
286
+ <body style="font-family: system-ui, sans-serif; max-width: 720px; margin: 40px auto; padding: 0 16px; line-height: 1.5;">
287
+ <h1>🌐 ${nodeName}</h1>
288
+ <p>This is a conforming <strong>Open Agentic Web (MVP Profile 0.3)</strong> node.</p>
289
+ <ul>
290
+ <li>Machine Manifest: <code><a href="./agent-manifest.json">agent-manifest.json</a></code></li>
291
+ <li>Declarative Network: <code><a href="./${nodeName}.network.json">${nodeName}.network.json</a></code></li>
292
+ <li>Action Bridge: <code><a href="./bridge/action-bridge.html">bridge/action-bridge.html</a></code></li>
293
+ </ul>
294
+ </body>
295
+ </html>
296
+ `;
297
+ writeFileSync(join(fullPath, "index.html"), indexHtml);
298
+
299
+ // 6. links.json
241
300
  const links = {
242
301
  networks: {
243
302
  [`${nodeName}_network`]: {}
@@ -248,6 +307,7 @@ export class SiteActions {
248
307
  console.log(`\n${colors.green}${colors.bold}✨ Scaffolding complete!${colors.reset}`);
249
308
  console.log(`Created conforming Open Agentic Web node at: ${colors.cyan}${fullPath}${colors.reset}`);
250
309
  console.log(`Files generated:
310
+ ├── index.html
251
311
  ├── agent-manifest.json
252
312
  ├── ${nodeName}.network.json
253
313
  ├── site-actions.js
@@ -294,7 +354,7 @@ switch (command) {
294
354
  case "version":
295
355
  case "-v":
296
356
  case "--version":
297
- console.log("open-agentic-web v1.0.0");
357
+ console.log("open-agentic-web v1.0.2");
298
358
  break;
299
359
  case "help":
300
360
  case "--help":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-agentic-web",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
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",
package/src/actions.js CHANGED
@@ -12,6 +12,14 @@ export class ActionValidationError extends Error {
12
12
  }
13
13
  }
14
14
 
15
+ export class ActionSecurityError extends Error {
16
+ constructor(message, details = {}) {
17
+ super(message);
18
+ this.name = "ActionSecurityError";
19
+ this.details = details;
20
+ }
21
+ }
22
+
15
23
  /**
16
24
  * Validates a JavaScript value against a JSON Schema subset.
17
25
  * Supports: type, properties, required, additionalProperties, enum, items, min/max, minLength/maxLength.
@@ -169,6 +177,32 @@ export function defineAction(definition) {
169
177
  validation.errors
170
178
  );
171
179
  }
180
+
181
+ // Human confirmation security gate for irreversible actions
182
+ if (effect === "irreversible") {
183
+ const confirmHook = context.onConfirm || definition.onConfirm;
184
+ if (typeof confirmHook === "function") {
185
+ const approved = await confirmHook({
186
+ name,
187
+ action: name,
188
+ arguments: args,
189
+ effect,
190
+ context
191
+ });
192
+ if (!approved) {
193
+ throw new ActionSecurityError(
194
+ `Action '${name}' was rejected by user confirmation policy.`,
195
+ { action: name, effect, arguments: args }
196
+ );
197
+ }
198
+ } else if (context.requireConfirmation && !context.confirmed) {
199
+ throw new ActionSecurityError(
200
+ `Action '${name}' is irreversible and requires explicit confirmation.`,
201
+ { action: name, effect, arguments: args }
202
+ );
203
+ }
204
+ }
205
+
172
206
  return execute(args, context);
173
207
  }
174
208
  };
package/src/bridge.js CHANGED
@@ -3,15 +3,18 @@
3
3
  * Enables secure, sandboxed execution of site actions across origins via postMessage & MessageChannel.
4
4
  */
5
5
 
6
+ import { ActionSecurityError } from "./actions.js";
7
+
6
8
  export const ACTION_BRIDGE_PROTOCOL = "nsdeploy-actions-v1";
7
9
 
8
10
  /**
9
11
  * Sets up an action bridge listener in an iframe (bridge/action-bridge.html).
10
- * Responds to orchestrator handshake and routes tool execution calls to the registry.
12
+ * Enforces origin security, human confirmation for irreversible actions, and routes execution to the registry.
11
13
  */
12
14
  export function setupActionBridge({
13
15
  registry,
14
16
  allowedOrigins = ["*"],
17
+ onConfirm = null,
15
18
  protocol = ACTION_BRIDGE_PROTOCOL,
16
19
  windowObj = globalThis.window
17
20
  } = {}) {
@@ -19,11 +22,56 @@ export function setupActionBridge({
19
22
  throw new Error("Action bridge requires a browser window environment.");
20
23
  }
21
24
 
25
+ // Cross-origin federation allows orchestrators to connect; irreversible actions strictly enforce onConfirm
26
+ const effectiveAllowedOrigins = Array.isArray(allowedOrigins) && allowedOrigins.length > 0
27
+ ? allowedOrigins
28
+ : ["*"];
29
+
30
+ if (effectiveAllowedOrigins.includes("*")) {
31
+ console.warn(
32
+ "[ActionBridge Security Warning] allowedOrigins is set to wildcard ('*'). " +
33
+ "Any site can embed this bridge. Irreversible actions will strictly enforce onConfirm approval."
34
+ );
35
+ }
36
+
22
37
  let isConnected = false;
23
38
 
24
39
  const isOriginAllowed = (origin) => {
25
- if (allowedOrigins.includes("*")) return true;
26
- return allowedOrigins.includes(origin);
40
+ if (effectiveAllowedOrigins.includes("*")) return true;
41
+ return effectiveAllowedOrigins.includes(origin);
42
+ };
43
+
44
+ const executeWithSecurity = async (action, args, origin) => {
45
+ const actionDef = registry.get(action);
46
+ if (!actionDef) {
47
+ throw new Error(`Action '${action}' is not registered in this action registry.`);
48
+ }
49
+
50
+ // Irreversible action security check
51
+ if (actionDef.effect === "irreversible") {
52
+ if (typeof onConfirm !== "function") {
53
+ throw new ActionSecurityError(
54
+ `Action '${action}' is marked '${actionDef.effect}' and was rejected: no onConfirm handler is configured on this action bridge.`,
55
+ { action, effect: actionDef.effect, origin }
56
+ );
57
+ }
58
+
59
+ const approved = await onConfirm({
60
+ action,
61
+ arguments: args,
62
+ origin,
63
+ definition: actionDef
64
+ });
65
+
66
+ if (!approved) {
67
+ throw new ActionSecurityError(
68
+ `Action '${action}' was rejected by user confirmation.`,
69
+ { action, effect: actionDef.effect, origin }
70
+ );
71
+ }
72
+ }
73
+
74
+ return registry.execute(action, args, { origin, confirmed: true });
27
75
  };
28
76
 
29
77
  const handleMessage = async (event) => {
@@ -49,10 +97,17 @@ export function setupActionBridge({
49
97
 
50
98
  const { id, action, arguments: args } = portData;
51
99
  try {
52
- const result = await registry.execute(action, args, { origin });
100
+ const result = await executeWithSecurity(action, args, origin);
53
101
  port.postMessage({ id, ok: true, result, protocol });
54
102
  } catch (err) {
55
- port.postMessage({ id, ok: false, error: err.message, errors: err.errors || [], protocol });
103
+ port.postMessage({
104
+ id,
105
+ ok: false,
106
+ error: err.message,
107
+ errors: err.errors || [],
108
+ isSecurityError: err instanceof ActionSecurityError,
109
+ protocol
110
+ });
56
111
  }
57
112
  };
58
113
 
@@ -65,10 +120,17 @@ export function setupActionBridge({
65
120
  if (data.type === "call" && data.id && data.action) {
66
121
  const { id, action, arguments: args } = data;
67
122
  try {
68
- const result = await registry.execute(action, args, { origin });
123
+ const result = await executeWithSecurity(action, args, origin);
69
124
  source?.postMessage({ id, ok: true, result, protocol }, origin);
70
125
  } catch (err) {
71
- source?.postMessage({ id, ok: false, error: err.message, errors: err.errors || [], protocol }, origin);
126
+ source?.postMessage({
127
+ id,
128
+ ok: false,
129
+ error: err.message,
130
+ errors: err.errors || [],
131
+ isSecurityError: err instanceof ActionSecurityError,
132
+ protocol
133
+ }, origin);
72
134
  }
73
135
  }
74
136
  };
@@ -96,6 +158,7 @@ export function setupActionBridge({
96
158
 
97
159
  /**
98
160
  * Creates a client in the parent orchestrator to invoke actions on a peer bridge.
161
+ * Concurrency-safe: multiple parallel execute() calls await a single in-flight connection promise.
99
162
  */
100
163
  export function createActionBridgeClient({
101
164
  bridgeUrl,
@@ -109,23 +172,17 @@ export function createActionBridgeClient({
109
172
 
110
173
  let port = null;
111
174
  let iframe = null;
112
- let isConnecting = false;
175
+ let connectionPromise = null;
113
176
  const pendingRequests = new Map();
114
177
  let seq = 0;
115
178
 
116
179
  const targetOrigin = new URL(bridgeUrl, windowObj.location?.href || "http://localhost").origin;
117
180
 
118
- async function connect() {
119
- if (port) return port;
120
- if (isConnecting) {
121
- // Wait for existing handshake
122
- await new Promise(r => setTimeout(r, 200));
123
- return port;
124
- }
125
-
126
- isConnecting = true;
181
+ function connect() {
182
+ if (port) return Promise.resolve(port);
183
+ if (connectionPromise) return connectionPromise;
127
184
 
128
- return new Promise((resolve, reject) => {
185
+ connectionPromise = new Promise((resolve, reject) => {
129
186
  const timeout = setTimeout(() => {
130
187
  cleanup();
131
188
  reject(new Error(`Timed out connecting to action bridge at '${bridgeUrl}' (${brand})`));
@@ -145,7 +202,7 @@ export function createActionBridgeClient({
145
202
  port.onmessage = ({ data }) => {
146
203
  if (data?.type === "connected") {
147
204
  clearTimeout(timeout);
148
- isConnecting = false;
205
+ cleanup();
149
206
  resolve(port);
150
207
  return;
151
208
  }
@@ -167,13 +224,17 @@ export function createActionBridgeClient({
167
224
  }
168
225
 
169
226
  function cleanup() {
170
- isConnecting = false;
171
227
  windowObj.removeEventListener("message", onMessage);
172
228
  }
173
229
 
174
230
  windowObj.addEventListener("message", onMessage);
175
231
  windowObj.document.body.appendChild(iframe);
232
+ }).catch(err => {
233
+ connectionPromise = null;
234
+ throw err;
176
235
  });
236
+
237
+ return connectionPromise;
177
238
  }
178
239
 
179
240
  return {
@@ -211,6 +272,7 @@ export function createActionBridgeClient({
211
272
  iframe.parentNode.removeChild(iframe);
212
273
  iframe = null;
213
274
  }
275
+ connectionPromise = null;
214
276
  }
215
277
  };
216
278
  }
package/src/federation.js CHANGED
@@ -116,6 +116,40 @@ export class AgentSwarm {
116
116
  throw new Error(`Manifest at '${manifestEndpoint}' does not declare any networks.`);
117
117
  }
118
118
 
119
+ let hydratedTools = manifest.actions?.agentTools || [];
120
+ if (network && typeof network.hocon === "string") {
121
+ try {
122
+ const netPath = network.hocon.replace(/^\.\//, "");
123
+ const netUrl = `${cleanUrl}/${netPath}`;
124
+ const netRes = await fetchFn(netUrl);
125
+ if (netRes && netRes.ok) {
126
+ const netJson = await netRes.json();
127
+ const declaredTools = netJson.tools || [];
128
+ const toolDefs = new Map();
129
+ for (const t of declaredTools) {
130
+ if (t && t.name) {
131
+ const toolName = t.name;
132
+ const toolDesc = t.description || t.instructions || "";
133
+ const toolParams = t.function?.parameters || t.parameters || { type: "object", properties: {} };
134
+ toolDefs.set(toolName, { name: toolName, description: toolDesc, inputSchema: toolParams });
135
+ }
136
+ }
137
+
138
+ if (toolDefs.size > 0) {
139
+ const rawTools = manifest.actions?.agentTools || Array.from(toolDefs.keys());
140
+ hydratedTools = rawTools.map(t => {
141
+ const toolName = typeof t === "string" ? t : t.name;
142
+ const baseName = toolName.replace(/^website_/, "");
143
+ const matched = toolDefs.get(toolName) || toolDefs.get(baseName) || toolDefs.get(`website_${baseName}`);
144
+ return matched || (typeof t === "object" ? t : { name: toolName, description: "", inputSchema: { type: "object", properties: {} } });
145
+ });
146
+ }
147
+ }
148
+ } catch {
149
+ // Fallback to manifest action tools
150
+ }
151
+ }
152
+
119
153
  const candidateNode = {
120
154
  id: manifest.name || network.name || `node_${Date.now()}`,
121
155
  name: manifest.brand || manifest.description || manifest.name || network.name,
@@ -123,7 +157,7 @@ export class AgentSwarm {
123
157
  node_url: cleanUrl,
124
158
  category: manifest.category || (network.tags && network.tags[0]) || "Specialist",
125
159
  description: manifest.description || network.description || "",
126
- tools: manifest.actions?.agentTools || []
160
+ tools: hydratedTools
127
161
  };
128
162
 
129
163
  // User consent check
@@ -142,6 +176,187 @@ export class AgentSwarm {
142
176
  return this.registerNode(candidateNode);
143
177
  }
144
178
 
179
+ /**
180
+ * Export all registered tools across connected nodes as OpenAI-compatible function calling schemas.
181
+ */
182
+ getOpenAITools(toolSubset = null) {
183
+ const formatted = [];
184
+ const allowed = toolSubset ? new Set(toolSubset) : null;
185
+
186
+ for (const node of this.nodes.values()) {
187
+ for (const tool of (node.tools || [])) {
188
+ const name = typeof tool === "string" ? tool : tool.name;
189
+ if (allowed && !allowed.has(name)) continue;
190
+
191
+ const description = typeof tool === "object" && tool.description
192
+ ? tool.description
193
+ : `Action provided by specialist agent '${node.name}' (${node.category})`;
194
+
195
+ const parameters = typeof tool === "object" && tool.inputSchema
196
+ ? tool.inputSchema
197
+ : { type: "object", properties: {}, additionalProperties: true };
198
+
199
+ formatted.push({
200
+ type: "function",
201
+ function: {
202
+ name,
203
+ description,
204
+ parameters
205
+ }
206
+ });
207
+ }
208
+ }
209
+ return formatted;
210
+ }
211
+
212
+ /**
213
+ * Execute an in-browser agent turn with BYOK LLM inference and autonomous tool execution.
214
+ * Compatible with Mozilla Otari, OpenRouter, and standard OpenAI-compatible endpoints.
215
+ */
216
+ async runTurn({
217
+ prompt,
218
+ messages = null,
219
+ systemInstructions = "You are a helpful autonomous concierge on the Open Agentic Web.",
220
+ model = this.defaultModel,
221
+ routerUrl = this.defaultRouter,
222
+ apiKey = null,
223
+ actionExecutor = null,
224
+ maxSteps = 5,
225
+ onStep = null,
226
+ fetchFn = globalThis.fetch
227
+ }) {
228
+ if (!fetchFn) {
229
+ throw new Error("fetch is required to execute LLM turns.");
230
+ }
231
+
232
+ const conversation = messages
233
+ ? [...messages]
234
+ : [
235
+ { role: "system", content: systemInstructions },
236
+ { role: "user", content: prompt }
237
+ ];
238
+
239
+ const tools = this.getOpenAITools();
240
+ let step = 0;
241
+ let toolCallsCount = 0;
242
+
243
+ // Offline / Mock mode support for testing and airgapped environments
244
+ if (apiKey === "mock" || routerUrl === "mock") {
245
+ const mockToolCall = tools.length > 0 && prompt?.toLowerCase().includes("book")
246
+ ? { id: "call_mock_1", function: { name: tools[0].function.name, arguments: "{}" } }
247
+ : null;
248
+
249
+ if (mockToolCall && actionExecutor) {
250
+ const result = await actionExecutor(mockToolCall.function.name, {});
251
+ conversation.push({ role: "assistant", tool_calls: [mockToolCall], content: null });
252
+ 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 };
255
+ }
256
+
257
+ const reply = `Mock offline response for: ${prompt}`;
258
+ conversation.push({ role: "assistant", content: reply });
259
+ return { ok: true, text: reply, messages: conversation, stepsCount: 1, toolCallsCount: 0 };
260
+ }
261
+
262
+ const endpoint = routerUrl.endsWith("/chat/completions")
263
+ ? routerUrl
264
+ : `${routerUrl.replace(/\/$/, "")}/chat/completions`;
265
+
266
+ while (step < maxSteps) {
267
+ step++;
268
+
269
+ const payload = {
270
+ model,
271
+ messages: conversation,
272
+ tools: tools.length > 0 ? tools : undefined
273
+ };
274
+
275
+ const headers = {
276
+ "Content-Type": "application/json"
277
+ };
278
+ if (apiKey) {
279
+ headers["Authorization"] = `Bearer ${apiKey}`;
280
+ }
281
+
282
+ const res = await fetchFn(endpoint, {
283
+ method: "POST",
284
+ headers,
285
+ body: JSON.stringify(payload)
286
+ });
287
+
288
+ if (!res.ok) {
289
+ const errText = await res.text().catch(() => "");
290
+ throw new Error(`LLM inference failed at '${endpoint}' (HTTP ${res.status}): ${errText}`);
291
+ }
292
+
293
+ const data = await res.json();
294
+ const choice = data.choices?.[0];
295
+ const message = choice?.message;
296
+
297
+ if (!message) {
298
+ throw new Error("Invalid response format from LLM router: missing choices[0].message");
299
+ }
300
+
301
+ conversation.push(message);
302
+
303
+ // Check if model called tools
304
+ if (message.tool_calls && message.tool_calls.length > 0) {
305
+ for (const call of message.tool_calls) {
306
+ toolCallsCount++;
307
+ const toolName = call.function.name;
308
+ let args = {};
309
+ try {
310
+ args = JSON.parse(call.function.arguments || "{}");
311
+ } catch {
312
+ args = {};
313
+ }
314
+
315
+ let result;
316
+ if (typeof actionExecutor === "function") {
317
+ try {
318
+ result = await actionExecutor(toolName, args);
319
+ } catch (err) {
320
+ result = { ok: false, error: err.message };
321
+ }
322
+ } else {
323
+ result = { ok: true, message: `Tool '${toolName}' executed in swarm context.` };
324
+ }
325
+
326
+ if (typeof onStep === "function") {
327
+ try {
328
+ onStep({ step, tool: toolName, arguments: args, result });
329
+ } catch {}
330
+ }
331
+
332
+ conversation.push({
333
+ role: "tool",
334
+ tool_call_id: call.id,
335
+ name: toolName,
336
+ content: typeof result === "string" ? result : JSON.stringify(result)
337
+ });
338
+ }
339
+ } else {
340
+ // Model provided final answer
341
+ return {
342
+ ok: true,
343
+ text: message.content || "",
344
+ messages: conversation,
345
+ stepsCount: step,
346
+ toolCallsCount
347
+ };
348
+ }
349
+ }
350
+
351
+ return {
352
+ ok: true,
353
+ text: conversation[conversation.length - 1]?.content || "Turn reached max steps.",
354
+ messages: conversation,
355
+ stepsCount: step,
356
+ toolCallsCount
357
+ };
358
+ }
359
+
145
360
  /**
146
361
  * Subscribe to swarm changes.
147
362
  */
package/src/validator.js CHANGED
@@ -263,11 +263,67 @@ export async function validateNode(nodeDir) {
263
263
  );
264
264
 
265
265
  if (actionClass) {
266
- const actionTools = manifest.actions?.agentTools || [];
267
- report.assert(
268
- actionTools.length > 0,
269
- `site-actions provides registered action tools (${actionTools.length} declared in manifest)`
270
- );
266
+ const registeredActions = new Map();
267
+ const mockRegistry = {
268
+ register: (def) => {
269
+ if (Array.isArray(def)) {
270
+ def.forEach(d => mockRegistry.register(d));
271
+ return;
272
+ }
273
+ if (def && def.name) {
274
+ registeredActions.set(def.name, def);
275
+ }
276
+ }
277
+ };
278
+
279
+ let registrationOk = false;
280
+ try {
281
+ if (typeof actionClass.registerActions === "function") {
282
+ await actionClass.registerActions(mockRegistry);
283
+ registrationOk = true;
284
+ } else if (typeof actionClass === "function") {
285
+ const inst = new actionClass();
286
+ if (typeof inst.registerActions === "function") {
287
+ await inst.registerActions(mockRegistry);
288
+ registrationOk = true;
289
+ }
290
+ }
291
+ } catch (err) {
292
+ report.assert(false, `SiteActions.registerActions execution failed: ${err.message}`, { warning: false });
293
+ }
294
+
295
+ if (registrationOk) {
296
+ report.assert(
297
+ registeredActions.size > 0,
298
+ `SiteActions.registerActions registered ${registeredActions.size} action tool(s)`
299
+ );
300
+
301
+ const manifestTools = manifest.actions?.agentTools || [];
302
+ for (const declaredTool of manifestTools) {
303
+ const baseName = declaredTool.replace(/^website_/, "");
304
+ const hasTool = registeredActions.has(declaredTool) ||
305
+ registeredActions.has(baseName) ||
306
+ registeredActions.has(`website_${baseName}`);
307
+ report.assert(
308
+ hasTool,
309
+ `Declared tool '${declaredTool}' is implemented and registered by site-actions.js`
310
+ );
311
+
312
+ if (hasTool) {
313
+ const act = registeredActions.get(declaredTool) ||
314
+ registeredActions.get(baseName) ||
315
+ registeredActions.get(`website_${baseName}`);
316
+ report.assert(
317
+ typeof act.execute === "function",
318
+ `Tool '${declaredTool}' provides an executable handler`
319
+ );
320
+ report.assert(
321
+ ["read", "irreversible", "undoable"].includes(act.effect),
322
+ `Tool '${declaredTool}' declares valid effect ('${act.effect || 'missing'}')`
323
+ );
324
+ }
325
+ }
326
+ }
271
327
  }
272
328
  } catch (err) {
273
329
  report.assert(false, `site-actions.js can be inspected: ${err.message}`, { warning: true });
@@ -278,23 +334,109 @@ export async function validateNode(nodeDir) {
278
334
  }
279
335
 
280
336
  /**
281
- * Validates cross-site federation between a hub and peer nodes
337
+ * Validates cross-site federation between a hub and peer nodes.
338
+ * Verifies links.json mapping, peer_policy permissions, and network/tool alignment.
282
339
  */
283
340
  export async function validateFederation(hubDir, peerDirs = []) {
341
+ const env = await getNodeEnv();
342
+ const { fs, path } = env || {};
343
+
344
+ const report = new ConformanceReport("federation-mesh");
284
345
  const hubSummary = await validateNode(hubDir);
285
346
  const peerSummaries = [];
286
347
 
348
+ let hubManifest = null;
349
+ let hubLinks = null;
350
+
351
+ if (fs) {
352
+ try {
353
+ const hubManifestPath = path.join(path.resolve(hubDir), "agent-manifest.json");
354
+ if (fs.existsSync(hubManifestPath)) {
355
+ hubManifest = JSON.parse(fs.readFileSync(hubManifestPath, "utf-8"));
356
+ }
357
+ const hubLinksPath = path.join(path.resolve(hubDir), "links.json");
358
+ if (fs.existsSync(hubLinksPath)) {
359
+ hubLinks = JSON.parse(fs.readFileSync(hubLinksPath, "utf-8"));
360
+ }
361
+ } catch {}
362
+ }
363
+
364
+ report.assert(hubLinks !== null, "Hub provides a readable 'links.json' for peer federation");
365
+
366
+ // Collect all mapped peer keys/URLs from hub's links.json
367
+ const mappedPeers = new Map();
368
+ if (hubLinks && hubLinks.networks) {
369
+ for (const [netName, peerMap] of Object.entries(hubLinks.networks)) {
370
+ if (typeof peerMap === "object" && peerMap !== null) {
371
+ for (const [peerAlias, endpoint] of Object.entries(peerMap)) {
372
+ mappedPeers.set(peerAlias.toLowerCase(), { networkName: netName, endpoint });
373
+ }
374
+ }
375
+ }
376
+ }
377
+
287
378
  for (const peerDir of peerDirs) {
288
- peerSummaries.push(await validateNode(peerDir));
379
+ const peerSum = await validateNode(peerDir);
380
+ peerSummaries.push(peerSum);
381
+
382
+ if (fs) {
383
+ try {
384
+ const peerManifestPath = path.join(path.resolve(peerDir), "agent-manifest.json");
385
+ if (fs.existsSync(peerManifestPath)) {
386
+ const peerManifest = JSON.parse(fs.readFileSync(peerManifestPath, "utf-8"));
387
+ const peerNetName = peerManifest.networks?.[0]?.name || "";
388
+ const peerBrand = (peerManifest.brand || peerManifest.name || "").toLowerCase();
389
+ const peerDirBase = path.basename(peerDir).toLowerCase().replace(/-(node|site|app)$/, "");
390
+
391
+ // 1. Verify hub links.json maps this peer
392
+ const isMapped = mappedPeers.has(peerNetName.toLowerCase()) ||
393
+ mappedPeers.has(peerBrand) ||
394
+ mappedPeers.has(peerDirBase) ||
395
+ Array.from(mappedPeers.keys()).some(k => peerNetName.toLowerCase().includes(k) || peerDirBase.includes(k));
396
+
397
+ report.assert(
398
+ isMapped,
399
+ `Hub links.json maps peer network '${peerNetName || peerDirBase}' (${path.basename(peerDir)})`
400
+ );
401
+
402
+ // 2. Peer policy permissions check
403
+ if (peerManifest.peer_policy) {
404
+ if (peerManifest.peer_policy.mode === "closed") {
405
+ const allowedPeers = peerManifest.peer_policy.allowed_peers || peerManifest.allowed_peers || [];
406
+ report.assert(
407
+ allowedPeers.length > 0,
408
+ `Peer '${peerNetName || peerDirBase}' declares allowed_peers for closed federation`
409
+ );
410
+ } else {
411
+ report.assert(
412
+ peerManifest.peer_policy.mode === "open",
413
+ `Peer '${peerNetName || peerDirBase}' has open federation mode`
414
+ );
415
+ }
416
+ }
417
+
418
+ // 3. Network alignment: peer front_man exists
419
+ const peerFrontMan = peerManifest.networks?.[0]?.front_man;
420
+ report.assert(
421
+ typeof peerFrontMan === "string" && peerFrontMan.length > 0,
422
+ `Peer '${peerNetName || peerDirBase}' declares active front_man '${peerFrontMan}'`
423
+ );
424
+ }
425
+ } catch (err) {
426
+ report.assert(false, `Error reading peer manifest in '${peerDir}': ${err.message}`);
427
+ }
428
+ }
289
429
  }
290
430
 
291
- const allPassed = hubSummary.valid && peerSummaries.every(p => p.valid);
431
+ const allPassed = hubSummary.valid && peerSummaries.every(p => p.valid) && report.failed === 0;
432
+
292
433
  return {
293
434
  valid: allPassed,
294
435
  hub: hubSummary,
295
436
  peers: peerSummaries,
296
- totalChecks: hubSummary.total + peerSummaries.reduce((acc, p) => acc + p.total, 0),
297
- totalPassed: hubSummary.passed + peerSummaries.reduce((acc, p) => acc + p.passed, 0),
298
- totalFailed: hubSummary.failed + peerSummaries.reduce((acc, p) => acc + p.failed, 0)
437
+ meshReport: report.toSummary(),
438
+ totalChecks: hubSummary.total + peerSummaries.reduce((acc, p) => acc + p.total, 0) + report.passed + report.failed,
439
+ totalPassed: hubSummary.passed + peerSummaries.reduce((acc, p) => acc + p.passed, 0) + report.passed,
440
+ totalFailed: hubSummary.failed + peerSummaries.reduce((acc, p) => acc + p.failed, 0) + report.failed
299
441
  };
300
442
  }
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert";
2
2
  import { describe, it } from "node:test";
3
- import { ActionValidationError, createActionRegistry, defineAction, validateSchema } from "../src/actions.js";
3
+ import { ActionSecurityError, ActionValidationError, createActionRegistry, defineAction, validateSchema } from "../src/actions.js";
4
4
 
5
5
  describe("Open Agentic Web - Site Actions & Validation", () => {
6
6
  it("validates data correctly with validateSchema", () => {
@@ -92,4 +92,49 @@ describe("Open Agentic Web - Site Actions & Validation", () => {
92
92
  const execResult = await registry.execute("website_book_ticket", { count: 4 });
93
93
  assert.strictEqual(execResult.booked, 4);
94
94
  });
95
+
96
+ it("enforces human confirmation on irreversible actions", async () => {
97
+ let confirmCalled = false;
98
+ const action = defineAction({
99
+ name: "website_irreversible_transfer",
100
+ description: "Transfer money or commit booking",
101
+ effect: "irreversible",
102
+ inputSchema: {
103
+ type: "object",
104
+ properties: { amount: { type: "number" } },
105
+ required: ["amount"]
106
+ },
107
+ execute: async (args) => ({ transferred: args.amount })
108
+ });
109
+
110
+ // 1. Rejected if requireConfirmation is set and not confirmed
111
+ await assert.rejects(
112
+ async () => action.execute({ amount: 100 }, { requireConfirmation: true, confirmed: false }),
113
+ ActionSecurityError
114
+ );
115
+
116
+ // 2. onConfirm callback approves
117
+ const approvedResult = await action.execute(
118
+ { amount: 100 },
119
+ {
120
+ onConfirm: async ({ name, arguments: args }) => {
121
+ confirmCalled = true;
122
+ assert.strictEqual(name, "website_irreversible_transfer");
123
+ assert.strictEqual(args.amount, 100);
124
+ return true; // user confirms
125
+ }
126
+ }
127
+ );
128
+ assert.strictEqual(confirmCalled, true);
129
+ assert.strictEqual(approvedResult.transferred, 100);
130
+
131
+ // 3. onConfirm callback rejects
132
+ await assert.rejects(
133
+ async () => action.execute(
134
+ { amount: 100 },
135
+ { onConfirm: async () => false } // user declines
136
+ ),
137
+ ActionSecurityError
138
+ );
139
+ });
95
140
  });
@@ -78,4 +78,44 @@ describe("Open Agentic Web - Dynamic Swarm & Federation", () => {
78
78
  assert.strictEqual(mounted.id, "travel_shield");
79
79
  assert.strictEqual(swarm.getNodes().length, 1);
80
80
  });
81
+
82
+ it("formats tools and runs autonomous turn with tool execution", async () => {
83
+ const swarm = new AgentSwarm({
84
+ defaultRouter: "mock",
85
+ defaultModel: "alibaba/qwen3.8-flash"
86
+ });
87
+
88
+ swarm.registerNode({
89
+ id: "rides",
90
+ name: "CityGlide Rides",
91
+ category: "Mobility",
92
+ tools: [
93
+ {
94
+ name: "website_quote_ride",
95
+ description: "Get ride fare estimate",
96
+ inputSchema: { type: "object", properties: { destination: { type: "string" } } }
97
+ }
98
+ ]
99
+ });
100
+
101
+ const openaiTools = swarm.getOpenAITools();
102
+ assert.strictEqual(openaiTools.length, 1);
103
+ assert.strictEqual(openaiTools[0].function.name, "website_quote_ride");
104
+
105
+ let actionExecuted = false;
106
+ const turnResult = await swarm.runTurn({
107
+ prompt: "Please book a ride to the hotel",
108
+ apiKey: "mock",
109
+ actionExecutor: async (tool, args) => {
110
+ actionExecuted = true;
111
+ assert.strictEqual(tool, "website_quote_ride");
112
+ return { fare_usd: 45, status: "DISPATCHED" };
113
+ }
114
+ });
115
+
116
+ assert.strictEqual(turnResult.ok, true);
117
+ assert.strictEqual(actionExecuted, true);
118
+ assert.strictEqual(turnResult.toolCallsCount, 1);
119
+ assert.ok(turnResult.text.includes("website_quote_ride"));
120
+ });
81
121
  });
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "fixture_hub",
3
+ "networks": [
4
+ {
5
+ "name": "fixture_hub_net",
6
+ "front_man": "hub_concierge",
7
+ "hocon": "./hub.network.json"
8
+ }
9
+ ],
10
+ "llm_router": {
11
+ "base_url": "https://api.otari.ai/api/v1",
12
+ "default_model": "alibaba/qwen3.8-flash"
13
+ },
14
+ "actions": {
15
+ "agentTools": ["query_traveler_profile", "reserve_hub_package"]
16
+ },
17
+ "peer_policy": {
18
+ "mode": "open"
19
+ }
20
+ }
@@ -0,0 +1 @@
1
+ <!doctype html><html><head><meta charset="utf-8"><title>Bridge</title></head><body></body></html>
@@ -0,0 +1,15 @@
1
+ {
2
+ "tools": [
3
+ {
4
+ "name": "hub_concierge",
5
+ "instructions": "Autonomous fixture hub concierge agent coordinating travel bookings across peers.",
6
+ "function": {
7
+ "parameters": {
8
+ "type": "object",
9
+ "properties": { "destination": { "type": "string" } },
10
+ "required": ["destination"]
11
+ }
12
+ }
13
+ }
14
+ ]
15
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "networks": {
3
+ "fixture_hub_net": {
4
+ "fixture_peer_net": "http://localhost:8081"
5
+ }
6
+ }
7
+ }
@@ -0,0 +1,22 @@
1
+ export class SiteActions {
2
+ static registerActions(registry) {
3
+ registry.register({
4
+ name: "query_traveler_profile",
5
+ description: "Retrieve active traveler preferences",
6
+ effect: "read",
7
+ inputSchema: { type: "object", properties: {} },
8
+ execute: async () => ({ destination: "San Francisco", budget: 500 })
9
+ });
10
+ registry.register({
11
+ name: "reserve_hub_package",
12
+ description: "Confirm hotel booking package",
13
+ effect: "irreversible",
14
+ inputSchema: {
15
+ type: "object",
16
+ properties: { nights: { type: "integer" } },
17
+ required: ["nights"]
18
+ },
19
+ execute: async (args) => ({ confirmed: true, booking_id: "HUB-123" })
20
+ });
21
+ }
22
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "fixture_peer",
3
+ "networks": [
4
+ {
5
+ "name": "fixture_peer_net",
6
+ "front_man": "peer_dispatcher",
7
+ "hocon": "./peer.network.json"
8
+ }
9
+ ],
10
+ "llm_router": {
11
+ "base_url": "https://api.otari.ai/api/v1",
12
+ "default_model": "alibaba/qwen3.8-flash"
13
+ },
14
+ "actions": {
15
+ "agentTools": ["quote_ground_transit"]
16
+ },
17
+ "peer_policy": {
18
+ "mode": "open"
19
+ }
20
+ }
@@ -0,0 +1 @@
1
+ <!doctype html><html><head><meta charset="utf-8"><title>Bridge</title></head><body></body></html>
@@ -0,0 +1,5 @@
1
+ {
2
+ "networks": {
3
+ "fixture_peer_net": {}
4
+ }
5
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "tools": [
3
+ {
4
+ "name": "peer_dispatcher",
5
+ "instructions": "Autonomous fixture peer dispatcher agent quoting transit rates.",
6
+ "function": {
7
+ "parameters": {
8
+ "type": "object",
9
+ "properties": { "origin": { "type": "string" } },
10
+ "required": ["origin"]
11
+ }
12
+ }
13
+ }
14
+ ]
15
+ }
@@ -0,0 +1,11 @@
1
+ export class SiteActions {
2
+ static registerActions(registry) {
3
+ registry.register({
4
+ name: "quote_ground_transit",
5
+ description: "Quote ground transit transfer rates",
6
+ effect: "read",
7
+ inputSchema: { type: "object", properties: { origin: { type: "string" } } },
8
+ execute: async () => ({ fare: 50, vehicle: "Sedan" })
9
+ });
10
+ }
11
+ }
@@ -49,11 +49,33 @@ describe("Open Agentic Web - Conformance Validator", () => {
49
49
  assert.strictEqual(report.valid, true);
50
50
  });
51
51
 
52
+ it("validates standalone fixtures and federated mesh independently", async () => {
53
+ const fixtureHubDir = join(__dirname, "fixtures", "hub-node");
54
+ const fixturePeerDir = join(__dirname, "fixtures", "peer-node");
55
+
56
+ const hubSummary = await validateNode(fixtureHubDir);
57
+ assert.strictEqual(hubSummary.valid, true, `fixture hub failed: ${JSON.stringify(hubSummary.results.filter(r => r.status === 'FAIL'))}`);
58
+
59
+ const peerSummary = await validateNode(fixturePeerDir);
60
+ assert.strictEqual(peerSummary.valid, true, `fixture peer failed: ${JSON.stringify(peerSummary.results.filter(r => r.status === 'FAIL'))}`);
61
+
62
+ // Validate true cross-site federation (peer links, network alignment, allowed peers)
63
+ const fed = await validateFederation(fixtureHubDir, [fixturePeerDir]);
64
+ assert.strictEqual(fed.valid, true, `federation failed: ${JSON.stringify(fed.meshReport.results.filter(r => r.status === 'FAIL'))}`);
65
+ assert.ok(fed.totalChecks > 10);
66
+ });
67
+
52
68
  it("validates live repository nodes (tripsteward-hub, cityglide-node, metropass-node)", async () => {
53
69
  const hubDir = join(repoRoot, "sites", "tripsteward-hub");
54
70
  const ridesDir = join(repoRoot, "sites", "cityglide-node");
55
71
  const expDir = join(repoRoot, "sites", "metropass-node");
56
72
 
73
+ // Skip if running as standalone npm package where monorepo sites are absent
74
+ const { existsSync } = await import("node:fs");
75
+ if (!existsSync(hubDir)) {
76
+ return;
77
+ }
78
+
57
79
  const hubSummary = await validateNode(hubDir);
58
80
  assert.strictEqual(hubSummary.valid, true, `tripsteward-hub failed: ${JSON.stringify(hubSummary.results.filter(r => r.status === 'FAIL'))}`);
59
81