open-agentic-web 0.0.0-stage → 1.0.0

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/src/actions.js ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Open Agentic Web — Site Actions & Runtime Framework
3
+ * Implements type-safe action definitions, JSON schema validation,
4
+ * effect categories ('read', 'irreversible', 'undoable'), and action registry.
5
+ */
6
+
7
+ export class ActionValidationError extends Error {
8
+ constructor(message, errors = []) {
9
+ super(message);
10
+ this.name = "ActionValidationError";
11
+ this.errors = errors;
12
+ }
13
+ }
14
+
15
+ /**
16
+ * Validates a JavaScript value against a JSON Schema subset.
17
+ * Supports: type, properties, required, additionalProperties, enum, items, min/max, minLength/maxLength.
18
+ */
19
+ export function validateSchema(schema, data, path = "") {
20
+ const errors = [];
21
+ if (!schema || typeof schema !== "object") return { valid: true, errors: [] };
22
+
23
+ const fieldDesc = path ? `at '${path}'` : "input";
24
+
25
+ // Type check
26
+ if (schema.type) {
27
+ const expectedType = schema.type;
28
+ const actualType = Array.isArray(data)
29
+ ? "array"
30
+ : data === null
31
+ ? "null"
32
+ : typeof data;
33
+
34
+ if (expectedType === "integer") {
35
+ if (typeof data !== "number" || !Number.isInteger(data)) {
36
+ errors.push(`Expected integer ${fieldDesc}, got ${actualType}`);
37
+ }
38
+ } else if (expectedType === "number") {
39
+ if (typeof data !== "number" || Number.isNaN(data)) {
40
+ errors.push(`Expected number ${fieldDesc}, got ${actualType}`);
41
+ }
42
+ } else if (actualType !== expectedType) {
43
+ errors.push(`Expected ${expectedType} ${fieldDesc}, got ${actualType}`);
44
+ }
45
+ }
46
+
47
+ // Enum check
48
+ if (Array.isArray(schema.enum) && data !== undefined) {
49
+ if (!schema.enum.includes(data)) {
50
+ errors.push(`Value ${JSON.stringify(data)} ${fieldDesc} is not one of: ${schema.enum.map(v => JSON.stringify(v)).join(", ")}`);
51
+ }
52
+ }
53
+
54
+ // Object checks
55
+ if (data !== null && typeof data === "object" && !Array.isArray(data)) {
56
+ // Required properties
57
+ if (Array.isArray(schema.required)) {
58
+ for (const reqKey of schema.required) {
59
+ if (data[reqKey] === undefined) {
60
+ errors.push(`Missing required property '${reqKey}' ${fieldDesc}`);
61
+ }
62
+ }
63
+ }
64
+
65
+ // Property-level validation
66
+ if (schema.properties && typeof schema.properties === "object") {
67
+ for (const [propKey, propSchema] of Object.entries(schema.properties)) {
68
+ if (data[propKey] !== undefined) {
69
+ const subPath = path ? `${path}.${propKey}` : propKey;
70
+ const subResult = validateSchema(propSchema, data[propKey], subPath);
71
+ errors.push(...subResult.errors);
72
+ }
73
+ }
74
+ }
75
+
76
+ // additionalProperties
77
+ if (schema.additionalProperties === false && schema.properties) {
78
+ const allowedKeys = new Set(Object.keys(schema.properties));
79
+ for (const key of Object.keys(data)) {
80
+ if (!allowedKeys.has(key)) {
81
+ errors.push(`Unexpected property '${key}' ${fieldDesc} (additionalProperties: false)`);
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ // Array items check
88
+ if (Array.isArray(data) && schema.items) {
89
+ data.forEach((item, index) => {
90
+ const subPath = `${path}[${index}]`;
91
+ const itemResult = validateSchema(schema.items, item, subPath);
92
+ errors.push(...itemResult.errors);
93
+ });
94
+ }
95
+
96
+ // String bounds
97
+ if (typeof data === "string") {
98
+ if (schema.minLength !== undefined && data.length < schema.minLength) {
99
+ errors.push(`String ${fieldDesc} length (${data.length}) is less than minLength ${schema.minLength}`);
100
+ }
101
+ if (schema.maxLength !== undefined && data.length > schema.maxLength) {
102
+ errors.push(`String ${fieldDesc} length (${data.length}) exceeds maxLength ${schema.maxLength}`);
103
+ }
104
+ }
105
+
106
+ // Numeric bounds
107
+ if (typeof data === "number") {
108
+ if (schema.minimum !== undefined && data < schema.minimum) {
109
+ errors.push(`Number ${fieldDesc} (${data}) is less than minimum ${schema.minimum}`);
110
+ }
111
+ if (schema.maximum !== undefined && data > schema.maximum) {
112
+ errors.push(`Number ${fieldDesc} (${data}) exceeds maximum ${schema.maximum}`);
113
+ }
114
+ }
115
+
116
+ return {
117
+ valid: errors.length === 0,
118
+ errors
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Define a conforming Open Agentic Web site action with runtime schema validation.
124
+ */
125
+ export function defineAction(definition) {
126
+ if (!definition || typeof definition !== "object") {
127
+ throw new Error("Action definition must be a valid configuration object.");
128
+ }
129
+
130
+ const { name, description, effect = "read", inputSchema = {}, execute, confirmsInWindow = false } = definition;
131
+
132
+ if (typeof name !== "string" || !name.trim()) {
133
+ throw new Error("Action must declare a non-empty string 'name'.");
134
+ }
135
+
136
+ if (typeof description !== "string" || !description.trim()) {
137
+ throw new Error(`Action '${name}' must declare a descriptive 'description'.`);
138
+ }
139
+
140
+ const validEffects = ["read", "irreversible", "undoable"];
141
+ if (!validEffects.includes(effect)) {
142
+ throw new Error(`Action '${name}' declares invalid effect '${effect}'. Must be one of: ${validEffects.join(", ")}.`);
143
+ }
144
+
145
+ if (typeof execute !== "function") {
146
+ throw new Error(`Action '${name}' must provide an executable async function 'execute(args, context)'.`);
147
+ }
148
+
149
+ const normalizedInputSchema = {
150
+ type: "object",
151
+ properties: inputSchema.properties || {},
152
+ required: inputSchema.required || [],
153
+ additionalProperties: inputSchema.additionalProperties ?? false,
154
+ ...inputSchema
155
+ };
156
+
157
+ return {
158
+ name,
159
+ description,
160
+ effect,
161
+ inputSchema: normalizedInputSchema,
162
+ confirmsInWindow,
163
+ rawExecute: execute,
164
+ execute: async (args = {}, context = {}) => {
165
+ const validation = validateSchema(normalizedInputSchema, args);
166
+ if (!validation.valid) {
167
+ throw new ActionValidationError(
168
+ `Validation failed for action '${name}':\n- ${validation.errors.join("\n- ")}`,
169
+ validation.errors
170
+ );
171
+ }
172
+ return execute(args, context);
173
+ }
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Create a registry of site actions.
179
+ */
180
+ export function createActionRegistry() {
181
+ const actionsMap = new Map();
182
+
183
+ return {
184
+ /**
185
+ * Register one or multiple actions.
186
+ */
187
+ register(actionDef) {
188
+ if (Array.isArray(actionDef)) {
189
+ actionDef.forEach(act => this.register(act));
190
+ return this;
191
+ }
192
+ const action = actionDef.rawExecute ? actionDef : defineAction(actionDef);
193
+ actionsMap.set(action.name, action);
194
+ return this;
195
+ },
196
+
197
+ get(name) {
198
+ return actionsMap.get(name);
199
+ },
200
+
201
+ has(name) {
202
+ return actionsMap.has(name);
203
+ },
204
+
205
+ list() {
206
+ return Array.from(actionsMap.values());
207
+ },
208
+
209
+ names() {
210
+ return Array.from(actionsMap.keys());
211
+ },
212
+
213
+ /**
214
+ * Output catalog of registered tools suitable for agent-manifest.json or discovery
215
+ */
216
+ catalog() {
217
+ return this.list().map(a => ({
218
+ name: a.name,
219
+ description: a.description,
220
+ effect: a.effect,
221
+ inputSchema: a.inputSchema,
222
+ confirmsInWindow: a.confirmsInWindow
223
+ }));
224
+ },
225
+
226
+ /**
227
+ * Execute an action by name with input arguments
228
+ */
229
+ async execute(name, args = {}, context = {}) {
230
+ const action = actionsMap.get(name);
231
+ if (!action) {
232
+ throw new Error(`Action '${name}' is not registered in this action registry.`);
233
+ }
234
+ return action.execute(args, context);
235
+ }
236
+ };
237
+ }
package/src/bridge.js ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Open Agentic Web — Cross-Origin Action Bridge (nsdeploy-actions-v1 protocol)
3
+ * Enables secure, sandboxed execution of site actions across origins via postMessage & MessageChannel.
4
+ */
5
+
6
+ export const ACTION_BRIDGE_PROTOCOL = "nsdeploy-actions-v1";
7
+
8
+ /**
9
+ * 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.
11
+ */
12
+ export function setupActionBridge({
13
+ registry,
14
+ allowedOrigins = ["*"],
15
+ protocol = ACTION_BRIDGE_PROTOCOL,
16
+ windowObj = globalThis.window
17
+ } = {}) {
18
+ if (!windowObj) {
19
+ throw new Error("Action bridge requires a browser window environment.");
20
+ }
21
+
22
+ let isConnected = false;
23
+
24
+ const isOriginAllowed = (origin) => {
25
+ if (allowedOrigins.includes("*")) return true;
26
+ return allowedOrigins.includes(origin);
27
+ };
28
+
29
+ const handleMessage = async (event) => {
30
+ const { data, origin, source, ports } = event;
31
+
32
+ if (!data || typeof data !== "object" || data.protocol !== protocol) {
33
+ return;
34
+ }
35
+
36
+ if (!isOriginAllowed(origin)) {
37
+ console.warn(`[ActionBridge] Rejected postMessage from untrusted origin: ${origin}`);
38
+ return;
39
+ }
40
+
41
+ // Handle handshake request
42
+ if (data.type === "connect" || data.type === "ready") {
43
+ if (ports && ports[0]) {
44
+ const port = ports[0];
45
+ isConnected = true;
46
+
47
+ port.onmessage = async ({ data: portData }) => {
48
+ if (!portData || portData.type !== "call") return;
49
+
50
+ const { id, action, arguments: args } = portData;
51
+ try {
52
+ const result = await registry.execute(action, args, { origin });
53
+ port.postMessage({ id, ok: true, result, protocol });
54
+ } catch (err) {
55
+ port.postMessage({ id, ok: false, error: err.message, errors: err.errors || [], protocol });
56
+ }
57
+ };
58
+
59
+ port.postMessage({ type: "connected", protocol, ok: true });
60
+ return;
61
+ }
62
+ }
63
+
64
+ // Direct fallback communication if no MessageChannel
65
+ if (data.type === "call" && data.id && data.action) {
66
+ const { id, action, arguments: args } = data;
67
+ try {
68
+ const result = await registry.execute(action, args, { origin });
69
+ source?.postMessage({ id, ok: true, result, protocol }, origin);
70
+ } catch (err) {
71
+ source?.postMessage({ id, ok: false, error: err.message, errors: err.errors || [], protocol }, origin);
72
+ }
73
+ }
74
+ };
75
+
76
+ windowObj.addEventListener("message", handleMessage);
77
+
78
+ // Announce readiness to parent window
79
+ if (windowObj.parent && windowObj.parent !== windowObj) {
80
+ try {
81
+ windowObj.parent.postMessage({ type: "ready", protocol }, "*");
82
+ } catch {
83
+ // Ignored if parent is cross-origin
84
+ }
85
+ }
86
+
87
+ return {
88
+ dispose() {
89
+ windowObj.removeEventListener("message", handleMessage);
90
+ },
91
+ isConnected() {
92
+ return isConnected;
93
+ }
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Creates a client in the parent orchestrator to invoke actions on a peer bridge.
99
+ */
100
+ export function createActionBridgeClient({
101
+ bridgeUrl,
102
+ brand = "Peer Node",
103
+ timeoutMs = 15000,
104
+ windowObj = globalThis.window
105
+ } = {}) {
106
+ if (!windowObj) {
107
+ throw new Error("Action bridge client requires a browser window environment.");
108
+ }
109
+
110
+ let port = null;
111
+ let iframe = null;
112
+ let isConnecting = false;
113
+ const pendingRequests = new Map();
114
+ let seq = 0;
115
+
116
+ const targetOrigin = new URL(bridgeUrl, windowObj.location?.href || "http://localhost").origin;
117
+
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;
127
+
128
+ return new Promise((resolve, reject) => {
129
+ const timeout = setTimeout(() => {
130
+ cleanup();
131
+ reject(new Error(`Timed out connecting to action bridge at '${bridgeUrl}' (${brand})`));
132
+ }, timeoutMs);
133
+
134
+ iframe = windowObj.document.createElement("iframe");
135
+ iframe.style.display = "none";
136
+ iframe.src = bridgeUrl;
137
+
138
+ function onMessage(event) {
139
+ if (event.origin !== targetOrigin || event.data?.protocol !== ACTION_BRIDGE_PROTOCOL) return;
140
+
141
+ if (event.data?.type === "ready") {
142
+ const channel = new MessageChannel();
143
+ port = channel.port1;
144
+
145
+ port.onmessage = ({ data }) => {
146
+ if (data?.type === "connected") {
147
+ clearTimeout(timeout);
148
+ isConnecting = false;
149
+ resolve(port);
150
+ return;
151
+ }
152
+
153
+ if (data?.id && pendingRequests.has(data.id)) {
154
+ const { res, rej } = pendingRequests.get(data.id);
155
+ pendingRequests.delete(data.id);
156
+ if (data.ok) res(data.result);
157
+ else rej(new Error(data.error || "Action execution failed."));
158
+ }
159
+ };
160
+
161
+ iframe.contentWindow?.postMessage(
162
+ { type: "connect", protocol: ACTION_BRIDGE_PROTOCOL },
163
+ targetOrigin,
164
+ [channel.port2]
165
+ );
166
+ }
167
+ }
168
+
169
+ function cleanup() {
170
+ isConnecting = false;
171
+ windowObj.removeEventListener("message", onMessage);
172
+ }
173
+
174
+ windowObj.addEventListener("message", onMessage);
175
+ windowObj.document.body.appendChild(iframe);
176
+ });
177
+ }
178
+
179
+ return {
180
+ async execute(actionName, args = {}) {
181
+ await connect();
182
+ const id = `req_${++seq}_${Date.now()}`;
183
+
184
+ return new Promise((res, rej) => {
185
+ const timer = setTimeout(() => {
186
+ pendingRequests.delete(id);
187
+ rej(new Error(`Timeout calling action '${actionName}' on '${brand}' (${timeoutMs}ms)`));
188
+ }, timeoutMs);
189
+
190
+ pendingRequests.set(id, {
191
+ res: (result) => { clearTimeout(timer); res(result); },
192
+ rej: (err) => { clearTimeout(timer); rej(err); }
193
+ });
194
+
195
+ port.postMessage({
196
+ type: "call",
197
+ id,
198
+ action: actionName,
199
+ arguments: args,
200
+ protocol: ACTION_BRIDGE_PROTOCOL
201
+ });
202
+ });
203
+ },
204
+
205
+ dispose() {
206
+ if (port) {
207
+ try { port.close(); } catch {}
208
+ port = null;
209
+ }
210
+ if (iframe && iframe.parentNode) {
211
+ iframe.parentNode.removeChild(iframe);
212
+ iframe = null;
213
+ }
214
+ }
215
+ };
216
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Open Agentic Web — Dynamic Swarm & Federation Engine
3
+ * Handles in-browser discovery, permission-checked mounting, and unmounting
4
+ * of peer agentic web nodes on the fly with 100% client-side privacy.
5
+ */
6
+
7
+ export class AgentSwarm {
8
+ constructor({ defaultRouter = "https://api.otari.ai/api/v1", defaultModel = "alibaba/qwen3.8-flash" } = {}) {
9
+ this.defaultRouter = defaultRouter;
10
+ this.defaultModel = defaultModel;
11
+ this.nodes = new Map();
12
+ this.listeners = new Set();
13
+ }
14
+
15
+ /**
16
+ * Register a new agentic node into the active swarm.
17
+ */
18
+ registerNode(node) {
19
+ if (!node || !node.id) {
20
+ throw new Error("Node configuration must declare a unique 'id'.");
21
+ }
22
+
23
+ const normalizedNode = {
24
+ id: node.id,
25
+ name: node.name || node.id,
26
+ category: node.category || "General",
27
+ front_man: node.front_man || "agent",
28
+ node_url: node.node_url || "",
29
+ tools: Array.isArray(node.tools) ? node.tools : [],
30
+ icon: node.icon || "🌐",
31
+ description: node.description || "",
32
+ connectedAt: Date.now(),
33
+ status: "connected",
34
+ ...node
35
+ };
36
+
37
+ this.nodes.set(normalizedNode.id, normalizedNode);
38
+ this._notify();
39
+ return normalizedNode;
40
+ }
41
+
42
+ /**
43
+ * Unregister / unlink an agent node from the swarm.
44
+ */
45
+ unregisterNode(id) {
46
+ const existed = this.nodes.delete(id);
47
+ if (existed) this._notify();
48
+ return existed;
49
+ }
50
+
51
+ /**
52
+ * Search connected or catalog nodes by keyword or category.
53
+ */
54
+ search({ query = "", category = "all" } = {}) {
55
+ const q = query.trim().toLowerCase();
56
+ const cat = category.trim().toLowerCase();
57
+
58
+ return Array.from(this.nodes.values()).filter(node => {
59
+ const matchCat = !cat || cat === "all" || node.category.toLowerCase() === cat;
60
+ const matchQuery = !q ||
61
+ node.name.toLowerCase().includes(q) ||
62
+ node.description.toLowerCase().includes(q) ||
63
+ node.category.toLowerCase().includes(q) ||
64
+ node.tools.some(t => t.toLowerCase().includes(q));
65
+
66
+ return matchCat && matchQuery;
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Get all registered nodes.
72
+ */
73
+ getNodes() {
74
+ return Array.from(this.nodes.values());
75
+ }
76
+
77
+ /**
78
+ * Export dynamic links.json structure.
79
+ */
80
+ exportLinks(hubNetworkName = "hub_orchestrator") {
81
+ const links = {
82
+ networks: {
83
+ [hubNetworkName]: {}
84
+ }
85
+ };
86
+
87
+ for (const [id, node] of this.nodes.entries()) {
88
+ links.networks[hubNetworkName][id] = node.node_url;
89
+ }
90
+
91
+ return links;
92
+ }
93
+
94
+ /**
95
+ * Mount a remote conforming agentic web node from its public URL.
96
+ * If onConsent hook is provided, requests user approval before registering.
97
+ */
98
+ async mountFromUrl(nodeUrl, { onConsent = null, fetchFn = globalThis.fetch } = {}) {
99
+ if (!fetchFn) {
100
+ throw new Error("fetch is required to mount remote agentic web nodes.");
101
+ }
102
+
103
+ const cleanUrl = nodeUrl.replace(/\/$/, "");
104
+ const manifestEndpoint = cleanUrl.endsWith(".json")
105
+ ? cleanUrl
106
+ : `${cleanUrl}/agent-manifest.json`;
107
+
108
+ const response = await fetchFn(manifestEndpoint);
109
+ if (!response.ok) {
110
+ throw new Error(`Failed to fetch manifest from '${manifestEndpoint}' (HTTP ${response.status})`);
111
+ }
112
+
113
+ const manifest = await response.json();
114
+ const network = manifest.networks?.[0];
115
+ if (!network) {
116
+ throw new Error(`Manifest at '${manifestEndpoint}' does not declare any networks.`);
117
+ }
118
+
119
+ const candidateNode = {
120
+ id: manifest.name || network.name || `node_${Date.now()}`,
121
+ name: manifest.brand || manifest.description || manifest.name || network.name,
122
+ front_man: network.front_man,
123
+ node_url: cleanUrl,
124
+ category: manifest.category || (network.tags && network.tags[0]) || "Specialist",
125
+ description: manifest.description || network.description || "",
126
+ tools: manifest.actions?.agentTools || []
127
+ };
128
+
129
+ // User consent check
130
+ if (typeof onConsent === "function") {
131
+ const approved = await onConsent({
132
+ candidate: candidateNode,
133
+ manifest,
134
+ origin: new URL(cleanUrl).origin
135
+ });
136
+
137
+ if (!approved) {
138
+ throw new Error(`Mounting of node '${candidateNode.name}' was declined by user consent.`);
139
+ }
140
+ }
141
+
142
+ return this.registerNode(candidateNode);
143
+ }
144
+
145
+ /**
146
+ * Subscribe to swarm changes.
147
+ */
148
+ subscribe(callback) {
149
+ this.listeners.add(callback);
150
+ return () => this.listeners.delete(callback);
151
+ }
152
+
153
+ _notify() {
154
+ const nodes = this.getNodes();
155
+ for (const cb of this.listeners) {
156
+ try { cb(nodes); } catch (e) { console.error("Swarm listener error:", e); }
157
+ }
158
+ }
159
+ }
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Open Agentic Web SDK & Conformance Toolkit
3
+ * Official developer library for building, validating, and federating
4
+ * autonomous web agents adhering to Cognizant / Mozilla / MIT NANDA MVP Profile 0.3.
5
+ */
6
+
7
+ export * from "./actions.js";
8
+ export * from "./bridge.js";
9
+ export * from "./validator.js";
10
+ export * from "./federation.js";