open-agentic-web 0.0.0-stage → 1.0.1
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/LICENSE +17 -0
- package/README.md +286 -2
- package/bin/cli.mjs +351 -0
- package/package.json +48 -4
- package/src/actions.js +271 -0
- package/src/bridge.js +278 -0
- package/src/federation.js +340 -0
- package/src/index.js +10 -0
- package/src/validator.js +442 -0
- package/test/actions.test.mjs +140 -0
- package/test/federation.test.mjs +121 -0
- package/test/fixtures/hub-node/agent-manifest.json +20 -0
- package/test/fixtures/hub-node/bridge/action-bridge.html +1 -0
- package/test/fixtures/hub-node/hub.network.json +15 -0
- package/test/fixtures/hub-node/links.json +7 -0
- package/test/fixtures/hub-node/site-actions.js +22 -0
- package/test/fixtures/peer-node/agent-manifest.json +20 -0
- package/test/fixtures/peer-node/bridge/action-bridge.html +1 -0
- package/test/fixtures/peer-node/links.json +5 -0
- package/test/fixtures/peer-node/peer.network.json +15 -0
- package/test/fixtures/peer-node/site-actions.js +11 -0
- package/test/validator.test.mjs +93 -0
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "open-agentic-web",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Standard developer toolkit, conformance linter & in-browser runtime for the Open Agentic Web (Cognizant / Mozilla / MIT NANDA MVP Profile 0.3)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"open-agentic-web": "./bin/cli.mjs",
|
|
9
|
+
"oaw": "./bin/cli.mjs"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/index.js",
|
|
13
|
+
"./actions": "./src/actions.js",
|
|
14
|
+
"./validator": "./src/validator.js",
|
|
15
|
+
"./bridge": "./src/bridge.js",
|
|
16
|
+
"./federation": "./src/federation.js"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node test/validator.test.mjs && node test/actions.test.mjs && node test/federation.test.mjs"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"open-agentic-web",
|
|
23
|
+
"agentic-web",
|
|
24
|
+
"ai-agents",
|
|
25
|
+
"neuro-san",
|
|
26
|
+
"nsdeploy",
|
|
27
|
+
"multi-agent",
|
|
28
|
+
"byok",
|
|
29
|
+
"federation",
|
|
30
|
+
"web-agents",
|
|
31
|
+
"cognizant"
|
|
32
|
+
],
|
|
33
|
+
"author": "TripSteward & Open Agentic Web Community",
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/Elroi-thecreator/tripsteward-agentic-travel.git",
|
|
38
|
+
"directory": "packages/open-agentic-web"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/Elroi-thecreator/tripsteward-agentic-travel#readme",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/Elroi-thecreator/tripsteward-agentic-travel/issues"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=18.0.0"
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/actions.js
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
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
|
+
export class ActionSecurityError extends Error {
|
|
16
|
+
constructor(message, details = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "ActionSecurityError";
|
|
19
|
+
this.details = details;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Validates a JavaScript value against a JSON Schema subset.
|
|
25
|
+
* Supports: type, properties, required, additionalProperties, enum, items, min/max, minLength/maxLength.
|
|
26
|
+
*/
|
|
27
|
+
export function validateSchema(schema, data, path = "") {
|
|
28
|
+
const errors = [];
|
|
29
|
+
if (!schema || typeof schema !== "object") return { valid: true, errors: [] };
|
|
30
|
+
|
|
31
|
+
const fieldDesc = path ? `at '${path}'` : "input";
|
|
32
|
+
|
|
33
|
+
// Type check
|
|
34
|
+
if (schema.type) {
|
|
35
|
+
const expectedType = schema.type;
|
|
36
|
+
const actualType = Array.isArray(data)
|
|
37
|
+
? "array"
|
|
38
|
+
: data === null
|
|
39
|
+
? "null"
|
|
40
|
+
: typeof data;
|
|
41
|
+
|
|
42
|
+
if (expectedType === "integer") {
|
|
43
|
+
if (typeof data !== "number" || !Number.isInteger(data)) {
|
|
44
|
+
errors.push(`Expected integer ${fieldDesc}, got ${actualType}`);
|
|
45
|
+
}
|
|
46
|
+
} else if (expectedType === "number") {
|
|
47
|
+
if (typeof data !== "number" || Number.isNaN(data)) {
|
|
48
|
+
errors.push(`Expected number ${fieldDesc}, got ${actualType}`);
|
|
49
|
+
}
|
|
50
|
+
} else if (actualType !== expectedType) {
|
|
51
|
+
errors.push(`Expected ${expectedType} ${fieldDesc}, got ${actualType}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Enum check
|
|
56
|
+
if (Array.isArray(schema.enum) && data !== undefined) {
|
|
57
|
+
if (!schema.enum.includes(data)) {
|
|
58
|
+
errors.push(`Value ${JSON.stringify(data)} ${fieldDesc} is not one of: ${schema.enum.map(v => JSON.stringify(v)).join(", ")}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Object checks
|
|
63
|
+
if (data !== null && typeof data === "object" && !Array.isArray(data)) {
|
|
64
|
+
// Required properties
|
|
65
|
+
if (Array.isArray(schema.required)) {
|
|
66
|
+
for (const reqKey of schema.required) {
|
|
67
|
+
if (data[reqKey] === undefined) {
|
|
68
|
+
errors.push(`Missing required property '${reqKey}' ${fieldDesc}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Property-level validation
|
|
74
|
+
if (schema.properties && typeof schema.properties === "object") {
|
|
75
|
+
for (const [propKey, propSchema] of Object.entries(schema.properties)) {
|
|
76
|
+
if (data[propKey] !== undefined) {
|
|
77
|
+
const subPath = path ? `${path}.${propKey}` : propKey;
|
|
78
|
+
const subResult = validateSchema(propSchema, data[propKey], subPath);
|
|
79
|
+
errors.push(...subResult.errors);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// additionalProperties
|
|
85
|
+
if (schema.additionalProperties === false && schema.properties) {
|
|
86
|
+
const allowedKeys = new Set(Object.keys(schema.properties));
|
|
87
|
+
for (const key of Object.keys(data)) {
|
|
88
|
+
if (!allowedKeys.has(key)) {
|
|
89
|
+
errors.push(`Unexpected property '${key}' ${fieldDesc} (additionalProperties: false)`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Array items check
|
|
96
|
+
if (Array.isArray(data) && schema.items) {
|
|
97
|
+
data.forEach((item, index) => {
|
|
98
|
+
const subPath = `${path}[${index}]`;
|
|
99
|
+
const itemResult = validateSchema(schema.items, item, subPath);
|
|
100
|
+
errors.push(...itemResult.errors);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// String bounds
|
|
105
|
+
if (typeof data === "string") {
|
|
106
|
+
if (schema.minLength !== undefined && data.length < schema.minLength) {
|
|
107
|
+
errors.push(`String ${fieldDesc} length (${data.length}) is less than minLength ${schema.minLength}`);
|
|
108
|
+
}
|
|
109
|
+
if (schema.maxLength !== undefined && data.length > schema.maxLength) {
|
|
110
|
+
errors.push(`String ${fieldDesc} length (${data.length}) exceeds maxLength ${schema.maxLength}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Numeric bounds
|
|
115
|
+
if (typeof data === "number") {
|
|
116
|
+
if (schema.minimum !== undefined && data < schema.minimum) {
|
|
117
|
+
errors.push(`Number ${fieldDesc} (${data}) is less than minimum ${schema.minimum}`);
|
|
118
|
+
}
|
|
119
|
+
if (schema.maximum !== undefined && data > schema.maximum) {
|
|
120
|
+
errors.push(`Number ${fieldDesc} (${data}) exceeds maximum ${schema.maximum}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
valid: errors.length === 0,
|
|
126
|
+
errors
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Define a conforming Open Agentic Web site action with runtime schema validation.
|
|
132
|
+
*/
|
|
133
|
+
export function defineAction(definition) {
|
|
134
|
+
if (!definition || typeof definition !== "object") {
|
|
135
|
+
throw new Error("Action definition must be a valid configuration object.");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const { name, description, effect = "read", inputSchema = {}, execute, confirmsInWindow = false } = definition;
|
|
139
|
+
|
|
140
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
141
|
+
throw new Error("Action must declare a non-empty string 'name'.");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (typeof description !== "string" || !description.trim()) {
|
|
145
|
+
throw new Error(`Action '${name}' must declare a descriptive 'description'.`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const validEffects = ["read", "irreversible", "undoable"];
|
|
149
|
+
if (!validEffects.includes(effect)) {
|
|
150
|
+
throw new Error(`Action '${name}' declares invalid effect '${effect}'. Must be one of: ${validEffects.join(", ")}.`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (typeof execute !== "function") {
|
|
154
|
+
throw new Error(`Action '${name}' must provide an executable async function 'execute(args, context)'.`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const normalizedInputSchema = {
|
|
158
|
+
type: "object",
|
|
159
|
+
properties: inputSchema.properties || {},
|
|
160
|
+
required: inputSchema.required || [],
|
|
161
|
+
additionalProperties: inputSchema.additionalProperties ?? false,
|
|
162
|
+
...inputSchema
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
name,
|
|
167
|
+
description,
|
|
168
|
+
effect,
|
|
169
|
+
inputSchema: normalizedInputSchema,
|
|
170
|
+
confirmsInWindow,
|
|
171
|
+
rawExecute: execute,
|
|
172
|
+
execute: async (args = {}, context = {}) => {
|
|
173
|
+
const validation = validateSchema(normalizedInputSchema, args);
|
|
174
|
+
if (!validation.valid) {
|
|
175
|
+
throw new ActionValidationError(
|
|
176
|
+
`Validation failed for action '${name}':\n- ${validation.errors.join("\n- ")}`,
|
|
177
|
+
validation.errors
|
|
178
|
+
);
|
|
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
|
+
|
|
206
|
+
return execute(args, context);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Create a registry of site actions.
|
|
213
|
+
*/
|
|
214
|
+
export function createActionRegistry() {
|
|
215
|
+
const actionsMap = new Map();
|
|
216
|
+
|
|
217
|
+
return {
|
|
218
|
+
/**
|
|
219
|
+
* Register one or multiple actions.
|
|
220
|
+
*/
|
|
221
|
+
register(actionDef) {
|
|
222
|
+
if (Array.isArray(actionDef)) {
|
|
223
|
+
actionDef.forEach(act => this.register(act));
|
|
224
|
+
return this;
|
|
225
|
+
}
|
|
226
|
+
const action = actionDef.rawExecute ? actionDef : defineAction(actionDef);
|
|
227
|
+
actionsMap.set(action.name, action);
|
|
228
|
+
return this;
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
get(name) {
|
|
232
|
+
return actionsMap.get(name);
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
has(name) {
|
|
236
|
+
return actionsMap.has(name);
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
list() {
|
|
240
|
+
return Array.from(actionsMap.values());
|
|
241
|
+
},
|
|
242
|
+
|
|
243
|
+
names() {
|
|
244
|
+
return Array.from(actionsMap.keys());
|
|
245
|
+
},
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Output catalog of registered tools suitable for agent-manifest.json or discovery
|
|
249
|
+
*/
|
|
250
|
+
catalog() {
|
|
251
|
+
return this.list().map(a => ({
|
|
252
|
+
name: a.name,
|
|
253
|
+
description: a.description,
|
|
254
|
+
effect: a.effect,
|
|
255
|
+
inputSchema: a.inputSchema,
|
|
256
|
+
confirmsInWindow: a.confirmsInWindow
|
|
257
|
+
}));
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Execute an action by name with input arguments
|
|
262
|
+
*/
|
|
263
|
+
async execute(name, args = {}, context = {}) {
|
|
264
|
+
const action = actionsMap.get(name);
|
|
265
|
+
if (!action) {
|
|
266
|
+
throw new Error(`Action '${name}' is not registered in this action registry.`);
|
|
267
|
+
}
|
|
268
|
+
return action.execute(args, context);
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
}
|
package/src/bridge.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
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
|
+
import { ActionSecurityError } from "./actions.js";
|
|
7
|
+
|
|
8
|
+
export const ACTION_BRIDGE_PROTOCOL = "nsdeploy-actions-v1";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Sets up an action bridge listener in an iframe (bridge/action-bridge.html).
|
|
12
|
+
* Enforces origin security, human confirmation for irreversible actions, and routes execution to the registry.
|
|
13
|
+
*/
|
|
14
|
+
export function setupActionBridge({
|
|
15
|
+
registry,
|
|
16
|
+
allowedOrigins = null,
|
|
17
|
+
onConfirm = null,
|
|
18
|
+
protocol = ACTION_BRIDGE_PROTOCOL,
|
|
19
|
+
windowObj = globalThis.window
|
|
20
|
+
} = {}) {
|
|
21
|
+
if (!windowObj) {
|
|
22
|
+
throw new Error("Action bridge requires a browser window environment.");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Strict origin security: default to own origin if not specified
|
|
26
|
+
const effectiveAllowedOrigins = allowedOrigins !== null
|
|
27
|
+
? allowedOrigins
|
|
28
|
+
: [windowObj.location?.origin].filter(Boolean);
|
|
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
|
+
|
|
37
|
+
let isConnected = false;
|
|
38
|
+
|
|
39
|
+
const isOriginAllowed = (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 });
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const handleMessage = async (event) => {
|
|
78
|
+
const { data, origin, source, ports } = event;
|
|
79
|
+
|
|
80
|
+
if (!data || typeof data !== "object" || data.protocol !== protocol) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (!isOriginAllowed(origin)) {
|
|
85
|
+
console.warn(`[ActionBridge] Rejected postMessage from untrusted origin: ${origin}`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Handle handshake request
|
|
90
|
+
if (data.type === "connect" || data.type === "ready") {
|
|
91
|
+
if (ports && ports[0]) {
|
|
92
|
+
const port = ports[0];
|
|
93
|
+
isConnected = true;
|
|
94
|
+
|
|
95
|
+
port.onmessage = async ({ data: portData }) => {
|
|
96
|
+
if (!portData || portData.type !== "call") return;
|
|
97
|
+
|
|
98
|
+
const { id, action, arguments: args } = portData;
|
|
99
|
+
try {
|
|
100
|
+
const result = await executeWithSecurity(action, args, origin);
|
|
101
|
+
port.postMessage({ id, ok: true, result, protocol });
|
|
102
|
+
} catch (err) {
|
|
103
|
+
port.postMessage({
|
|
104
|
+
id,
|
|
105
|
+
ok: false,
|
|
106
|
+
error: err.message,
|
|
107
|
+
errors: err.errors || [],
|
|
108
|
+
isSecurityError: err instanceof ActionSecurityError,
|
|
109
|
+
protocol
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
port.postMessage({ type: "connected", protocol, ok: true });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Direct fallback communication if no MessageChannel
|
|
120
|
+
if (data.type === "call" && data.id && data.action) {
|
|
121
|
+
const { id, action, arguments: args } = data;
|
|
122
|
+
try {
|
|
123
|
+
const result = await executeWithSecurity(action, args, origin);
|
|
124
|
+
source?.postMessage({ id, ok: true, result, protocol }, origin);
|
|
125
|
+
} catch (err) {
|
|
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);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
windowObj.addEventListener("message", handleMessage);
|
|
139
|
+
|
|
140
|
+
// Announce readiness to parent window
|
|
141
|
+
if (windowObj.parent && windowObj.parent !== windowObj) {
|
|
142
|
+
try {
|
|
143
|
+
windowObj.parent.postMessage({ type: "ready", protocol }, "*");
|
|
144
|
+
} catch {
|
|
145
|
+
// Ignored if parent is cross-origin
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
dispose() {
|
|
151
|
+
windowObj.removeEventListener("message", handleMessage);
|
|
152
|
+
},
|
|
153
|
+
isConnected() {
|
|
154
|
+
return isConnected;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
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.
|
|
162
|
+
*/
|
|
163
|
+
export function createActionBridgeClient({
|
|
164
|
+
bridgeUrl,
|
|
165
|
+
brand = "Peer Node",
|
|
166
|
+
timeoutMs = 15000,
|
|
167
|
+
windowObj = globalThis.window
|
|
168
|
+
} = {}) {
|
|
169
|
+
if (!windowObj) {
|
|
170
|
+
throw new Error("Action bridge client requires a browser window environment.");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let port = null;
|
|
174
|
+
let iframe = null;
|
|
175
|
+
let connectionPromise = null;
|
|
176
|
+
const pendingRequests = new Map();
|
|
177
|
+
let seq = 0;
|
|
178
|
+
|
|
179
|
+
const targetOrigin = new URL(bridgeUrl, windowObj.location?.href || "http://localhost").origin;
|
|
180
|
+
|
|
181
|
+
function connect() {
|
|
182
|
+
if (port) return Promise.resolve(port);
|
|
183
|
+
if (connectionPromise) return connectionPromise;
|
|
184
|
+
|
|
185
|
+
connectionPromise = new Promise((resolve, reject) => {
|
|
186
|
+
const timeout = setTimeout(() => {
|
|
187
|
+
cleanup();
|
|
188
|
+
reject(new Error(`Timed out connecting to action bridge at '${bridgeUrl}' (${brand})`));
|
|
189
|
+
}, timeoutMs);
|
|
190
|
+
|
|
191
|
+
iframe = windowObj.document.createElement("iframe");
|
|
192
|
+
iframe.style.display = "none";
|
|
193
|
+
iframe.src = bridgeUrl;
|
|
194
|
+
|
|
195
|
+
function onMessage(event) {
|
|
196
|
+
if (event.origin !== targetOrigin || event.data?.protocol !== ACTION_BRIDGE_PROTOCOL) return;
|
|
197
|
+
|
|
198
|
+
if (event.data?.type === "ready") {
|
|
199
|
+
const channel = new MessageChannel();
|
|
200
|
+
port = channel.port1;
|
|
201
|
+
|
|
202
|
+
port.onmessage = ({ data }) => {
|
|
203
|
+
if (data?.type === "connected") {
|
|
204
|
+
clearTimeout(timeout);
|
|
205
|
+
cleanup();
|
|
206
|
+
resolve(port);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (data?.id && pendingRequests.has(data.id)) {
|
|
211
|
+
const { res, rej } = pendingRequests.get(data.id);
|
|
212
|
+
pendingRequests.delete(data.id);
|
|
213
|
+
if (data.ok) res(data.result);
|
|
214
|
+
else rej(new Error(data.error || "Action execution failed."));
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
iframe.contentWindow?.postMessage(
|
|
219
|
+
{ type: "connect", protocol: ACTION_BRIDGE_PROTOCOL },
|
|
220
|
+
targetOrigin,
|
|
221
|
+
[channel.port2]
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function cleanup() {
|
|
227
|
+
windowObj.removeEventListener("message", onMessage);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
windowObj.addEventListener("message", onMessage);
|
|
231
|
+
windowObj.document.body.appendChild(iframe);
|
|
232
|
+
}).catch(err => {
|
|
233
|
+
connectionPromise = null;
|
|
234
|
+
throw err;
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
return connectionPromise;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
async execute(actionName, args = {}) {
|
|
242
|
+
await connect();
|
|
243
|
+
const id = `req_${++seq}_${Date.now()}`;
|
|
244
|
+
|
|
245
|
+
return new Promise((res, rej) => {
|
|
246
|
+
const timer = setTimeout(() => {
|
|
247
|
+
pendingRequests.delete(id);
|
|
248
|
+
rej(new Error(`Timeout calling action '${actionName}' on '${brand}' (${timeoutMs}ms)`));
|
|
249
|
+
}, timeoutMs);
|
|
250
|
+
|
|
251
|
+
pendingRequests.set(id, {
|
|
252
|
+
res: (result) => { clearTimeout(timer); res(result); },
|
|
253
|
+
rej: (err) => { clearTimeout(timer); rej(err); }
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
port.postMessage({
|
|
257
|
+
type: "call",
|
|
258
|
+
id,
|
|
259
|
+
action: actionName,
|
|
260
|
+
arguments: args,
|
|
261
|
+
protocol: ACTION_BRIDGE_PROTOCOL
|
|
262
|
+
});
|
|
263
|
+
});
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
dispose() {
|
|
267
|
+
if (port) {
|
|
268
|
+
try { port.close(); } catch {}
|
|
269
|
+
port = null;
|
|
270
|
+
}
|
|
271
|
+
if (iframe && iframe.parentNode) {
|
|
272
|
+
iframe.parentNode.removeChild(iframe);
|
|
273
|
+
iframe = null;
|
|
274
|
+
}
|
|
275
|
+
connectionPromise = null;
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
}
|