@nac3/runtime 2.8.0 → 2.9.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.
@@ -0,0 +1,641 @@
1
+ // Generated by build.mjs -- do not edit. Source: yujin.app/nac-spec/js/nac-mcp-interop.js
2
+ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
3
+ /**
4
+ * NAC MCP Interop -- host-side runtime for cross-app navigation.
5
+ *
6
+ * Adds FOUR public functions to window.NAC:
7
+ *
8
+ * NAC.export_tree(opts?) -> NACExportV1
9
+ * NAC.import_remote_tree(payload, conn) -> RemoteHandle
10
+ * NAC.list_remote_apps() -> RemoteHandle[]
11
+ * NAC.disconnect_remote(namespace) -> void
12
+ *
13
+ * And patches NAC.click / fill / tab / tab_by_label / etc to
14
+ * detect 'remote:<namespace>:<peer_id>' prefixes and proxy the
15
+ * call via the registered transport (http or stdio).
16
+ *
17
+ * Spec: docs/NAC_INTEROP_MCP.md.
18
+ *
19
+ * STATUS: published since 2.9.0 as the fourth entry of the package
20
+ * (owner decision D-31 of 2026-11-27, closing PND-137). Until that day
21
+ * this header said "v2.3 PREVIEW, lives in branch feat/nac-interop-mcp"
22
+ * while the file sat in main and reached no adopter: the build emitted
23
+ * three bundles and npm install brought none of this.
24
+ *
25
+ * import '@nac3/runtime'; // first: the runtime
26
+ * import '@nac3/runtime/mcp-interop'; // then: this
27
+ *
28
+ * Load order is the same contract js/nac-v2-extensions.js has: with no
29
+ * window.NAC this file warns and installs nothing.
30
+ *
31
+ * WHAT IT IS NOT. Cross-app navigation is OPTIONAL and no conformance
32
+ * level mentions it. An agent reaches a NAC3 application by calling
33
+ * NAC.click / NAC.call on the document, or through the intermediary of
34
+ * SPEC 11.1; what this file adds is a different capability -- driving a
35
+ * SECOND application by name from inside the first.
36
+ *
37
+ * IT NEEDS A DOCUMENT. The proxy reports through DOM events, so three
38
+ * of the four functions refuse by name under the headless profile
39
+ * (SPEC 19) instead of throwing ReferenceError at a property of
40
+ * undefined -- the same rule D-26 wrote for the primitives of the core
41
+ * runtime. list_remote_apps() reads state only and works anywhere.
42
+ */
43
+
44
+ (function (global) {
45
+ 'use strict';
46
+
47
+ if (!global.NAC) {
48
+ console.warn('[nac-interop] NAC runtime not loaded yet; skipping interop install');
49
+ return;
50
+ }
51
+ if (global.NAC.__interop_installed) return;
52
+ global.NAC.__interop_installed = true;
53
+
54
+ var REMOTE_PREFIX = 'remote:';
55
+ var _remotes = Object.create(null); /* namespace -> RemoteHandle */
56
+ var _origClick, _origFill, _origSelect, _origTab, _origTabByLabel,
57
+ _origGoToSection, _origDragDrop, _origEditField,
58
+ _origDtAddRow, _origDtRemoveRow, _origDtEditCell, _origDtCommit,
59
+ _origDtDiscard, _origDtReadAggregate;
60
+
61
+ /* ---------- Helpers ---------- */
62
+
63
+ function _now() { return new Date().toISOString(); }
64
+
65
+ function _err(code, message) {
66
+ var e = new Error(message);
67
+ e.code = code;
68
+ return e;
69
+ }
70
+
71
+ /* D-26 made this the rule for the core runtime: a primitive that
72
+ needs a document NAMES that it has none instead of dying on a
73
+ property of undefined. This module became publishable the day it
74
+ entered the package (D-31), and a published entry that throws
75
+ ReferenceError on a server is the same defect wearing a new file
76
+ name. Three of the four public functions report through DOM
77
+ events; list_remote_apps does not, and is not guarded. */
78
+ function _requireDocument(fnName) {
79
+ if (typeof document === 'undefined') {
80
+ throw _err('no_document',
81
+ fnName + ': cross-app navigation reports through DOM events and there is no '
82
+ + 'document in this process (SPEC 19 headless profile). list_remote_apps() is '
83
+ + 'the only function here that works without one.');
84
+ }
85
+ }
86
+
87
+ /* 2.9.1 (PND-161) -- WHERE THE HOST'S CREDENTIAL IS ALLOWED TO GO.
88
+
89
+ import_remote_tree takes two arguments with very different
90
+ standing: `conn`, which the HOST wrote, and `payload`, which is
91
+ DATA THE PEER SENT. The ack subscription was built from
92
+ payload.ack_endpoint and carried conn.bearer on the query string,
93
+ so the other side of the channel chose the destination of the
94
+ host's credential: a peer that is malicious, or merely
95
+ compromised, pointed it at its own collector and the browser
96
+ delivered it.
97
+
98
+ The rule now is the one the host can actually reason about: the
99
+ credential travels only to the origin the HOST already trusted
100
+ with it -- the origin of conn.endpoint -- or to an endpoint the
101
+ host named itself in conn.ack_endpoint. A same-origin
102
+ payload.ack_endpoint still works, which is the shape every real
103
+ bridge has (the SSE route lives beside the RPC route), so no
104
+ legitimate deployment changes.
105
+
106
+ What this does NOT fix, and is accepted and documented: the bearer
107
+ still rides the query string, because EventSource cannot carry
108
+ headers. That is why pinning the origin matters -- a query string
109
+ ends up in proxy logs and Referer headers, and now at least it is
110
+ the logs of the host's own bridge. */
111
+ function _originOf(url, base) {
112
+ try {
113
+ if (typeof URL !== 'function') return null;
114
+ var b = base || (typeof location !== 'undefined' ? location.href : undefined);
115
+ return new URL(String(url), b).origin;
116
+ } catch (e) {
117
+ return null;
118
+ }
119
+ }
120
+ function _ackEndpointAllowed(ackEndpoint, connEndpoint) {
121
+ var want = _originOf(connEndpoint);
122
+ var got = _originOf(ackEndpoint, connEndpoint);
123
+ /* Fail closed: an origin that cannot be resolved is not an origin
124
+ that was checked. */
125
+ if (!want || !got) return false;
126
+ return want === got;
127
+ }
128
+
129
+ function _parseRemote(nac_id) {
130
+ if (typeof nac_id !== 'string') return null;
131
+ if (nac_id.indexOf(REMOTE_PREFIX) !== 0) return null;
132
+ var rest = nac_id.slice(REMOTE_PREFIX.length);
133
+ var colon = rest.indexOf(':');
134
+ if (colon < 0) return null;
135
+ return {
136
+ namespace: rest.slice(0, colon),
137
+ peer_id: rest.slice(colon + 1)
138
+ };
139
+ }
140
+
141
+ function _emitLocalAck(plugin, action_id, ok, detail) {
142
+ var name = ok ? 'nac:action:succeeded' : 'nac:action:failed';
143
+ document.dispatchEvent(new CustomEvent(name, {
144
+ detail: Object.assign({
145
+ plugin: plugin,
146
+ action_id: action_id,
147
+ is_trusted: false, /* remote actions are NEVER user-trusted */
148
+ via_interop: true
149
+ }, detail || {})
150
+ }));
151
+ }
152
+
153
+ /* ---------- export_tree ---------- */
154
+
155
+ function export_tree(opts) {
156
+ _requireDocument('export_tree');
157
+ opts = opts || {};
158
+ var scope = opts.scope || 'full';
159
+ var includeDom = !!opts.include_dom_state;
160
+ var includeLocales = opts.include_locales || null;
161
+
162
+ /* Collect manifests. We prefer NAC.list_registered_plugins
163
+ (v2.3 introspection helper) because it returns EVERY
164
+ registered manifest regardless of DOM mount state -- which
165
+ is the correct behavior for export (a peer can want to
166
+ export a manifest even if the plugin's DOM is currently
167
+ hidden). Fall back to NAC.describe()'s plugin list if the
168
+ helper isn't there (older runtimes). */
169
+ var manifests = {};
170
+ var snap = (typeof global.NAC.describe === 'function') ? global.NAC.describe() : { plugins: [], active: null };
171
+ var pluginSlugs;
172
+ if (typeof global.NAC.list_registered_plugins === 'function') {
173
+ pluginSlugs = global.NAC.list_registered_plugins();
174
+ } else {
175
+ pluginSlugs = (snap.plugins || []).map(function (p) { return p && p.plugin; }).filter(Boolean);
176
+ }
177
+ pluginSlugs.forEach(function (slug) {
178
+ var m = (typeof global.NAC.manifest === 'function') ? global.NAC.manifest(slug) : null;
179
+ if (!m) return;
180
+ if (includeLocales && Array.isArray(includeLocales)) {
181
+ m = _filterLocales(m, includeLocales);
182
+ }
183
+ if (scope === 'active_plugin' && snap.active !== slug) return;
184
+ if (scope.indexOf('plugin_slug:') === 0 && scope.slice(12) !== slug) return;
185
+ manifests[slug] = m;
186
+ });
187
+
188
+ /* Collect v2.0 scope tree if available. */
189
+ var scopeTree = [];
190
+ var dataTables = [];
191
+ if (typeof global.NAC.describe_v2 === 'function') {
192
+ try {
193
+ var v2 = global.NAC.describe_v2();
194
+ scopeTree = v2.v2_scope_entries || [];
195
+ dataTables = v2.data_tables || [];
196
+ } catch (e) { /* tolerated */ }
197
+ }
198
+
199
+ /* State block. */
200
+ var state = {
201
+ user_lang: (global.NacChat && global.NacChat._lang) || document.documentElement.lang || 'en'
202
+ };
203
+ if (includeDom) {
204
+ state.url = location.href;
205
+ state.title = document.title;
206
+ }
207
+
208
+ return {
209
+ app_id: global.__YUJIN_APP_ID__ || 'nac-app-' + Math.random().toString(36).slice(2, 10),
210
+ app_version: global.__YUJIN_APP_VERSION__ || '1.0.0',
211
+ nac_version: '2.3',
212
+ exported_at: _now(),
213
+ active_plugin: snap.active || null,
214
+ manifests: manifests,
215
+ scope_tree: scopeTree,
216
+ data_tables: dataTables,
217
+ state: state,
218
+ ack_endpoint: global.__YUJIN_ACK_ENDPOINT__ || null /* host-configurable */
219
+ };
220
+ }
221
+
222
+ function _filterLocales(manifest, locales) {
223
+ /* Deep-clone the manifest with label_i18n restricted to the
224
+ requested locales. Idempotent + side-effect-free. */
225
+ function reduce(obj) {
226
+ if (obj == null || typeof obj !== 'object') return obj;
227
+ if (Array.isArray(obj)) return obj.map(reduce);
228
+ var out = {};
229
+ for (var k in obj) {
230
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) continue;
231
+ if (k === 'label_i18n' && obj[k] && typeof obj[k] === 'object') {
232
+ var filtered = {};
233
+ locales.forEach(function (loc) {
234
+ if (obj[k][loc]) filtered[loc] = obj[k][loc];
235
+ });
236
+ out[k] = filtered;
237
+ } else {
238
+ out[k] = reduce(obj[k]);
239
+ }
240
+ }
241
+ return out;
242
+ }
243
+ return reduce(manifest);
244
+ }
245
+
246
+ /* ---------- import_remote_tree ---------- */
247
+
248
+ function import_remote_tree(payload, conn) {
249
+ _requireDocument('import_remote_tree');
250
+ if (!payload || typeof payload !== 'object') {
251
+ throw _err('invalid', 'import_remote_tree: payload required');
252
+ }
253
+ if (!conn || !conn.endpoint || !conn.bearer) {
254
+ throw _err('invalid', 'import_remote_tree: conn.endpoint + conn.bearer required');
255
+ }
256
+ var transport = conn.transport || 'http';
257
+ var namespace = conn.namespace || payload.app_id;
258
+ if (!namespace) throw _err('invalid', 'import_remote_tree: namespace required (no app_id in payload)');
259
+ /* 2.9.1 (PND-166) -- the namespace is the first segment of
260
+ "remote:<ns>:<peer_id>" and _parseRemote splits at the FIRST
261
+ colon, so a namespace containing one makes every id under it
262
+ ambiguous. It defaults to payload.app_id, which the PEER chose:
263
+ measured, a peer declaring app_id "bank:widget" routed
264
+ NAC.click('remote:bank:widget:pay') to the endpoint and bearer of
265
+ an unrelated peer named "bank". Refused by name instead of
266
+ imported into an ambiguity. */
267
+ if (String(namespace).indexOf(':') >= 0) {
268
+ throw _err('invalid',
269
+ 'import_remote_tree: namespace "' + namespace + '" contains ":", which is the '
270
+ + 'separator of remote:<namespace>:<peer_id> -- every id under it would be '
271
+ + 'ambiguous. Pass conn.namespace with no colon.');
272
+ }
273
+ if (_remotes[namespace]) {
274
+ throw _err('conflict', 'import_remote_tree: namespace "' + namespace + '" already imported; disconnect first');
275
+ }
276
+
277
+ /* Register each remote plugin under namespaced slug. */
278
+ var importedPlugins = [];
279
+ for (var slug in payload.manifests) {
280
+ if (!Object.prototype.hasOwnProperty.call(payload.manifests, slug)) continue;
281
+ var m = payload.manifests[slug];
282
+ var nsSlug = REMOTE_PREFIX + namespace + ':' + slug;
283
+ /* Build a namespaced copy of the manifest. */
284
+ var nsManifest = JSON.parse(JSON.stringify(m));
285
+ nsManifest.plugin_slug = nsSlug;
286
+ nsManifest.__interop_origin = { namespace: namespace, peer_plugin: slug };
287
+ /* Prefix every id in elements / tabs / fields / actions. */
288
+ ['elements', 'tabs', 'fields', 'actions'].forEach(function (key) {
289
+ if (Array.isArray(nsManifest[key])) {
290
+ nsManifest[key].forEach(function (el) {
291
+ if (el && el.id) el.__peer_id = el.id;
292
+ if (el && el.id) el.id = REMOTE_PREFIX + namespace + ':' + el.id;
293
+ if (el && el.nac_id) el.__peer_nac_id = el.nac_id;
294
+ if (el && el.nac_id) el.nac_id = REMOTE_PREFIX + namespace + ':' + el.nac_id;
295
+ });
296
+ }
297
+ });
298
+ try {
299
+ global.NAC.register(nsManifest);
300
+ importedPlugins.push(nsSlug);
301
+ } catch (e) {
302
+ console.error('[nac-interop] failed to register namespaced plugin', nsSlug, e);
303
+ }
304
+ }
305
+
306
+ /* Build the handle. */
307
+ var handle = {
308
+ namespace: namespace,
309
+ app_id: payload.app_id,
310
+ app_version: payload.app_version,
311
+ nac_version: payload.nac_version,
312
+ imported_at: _now(),
313
+ transport: transport,
314
+ endpoint: conn.endpoint,
315
+ bearer: conn.bearer,
316
+ hmac_secret: conn.hmac_secret || null,
317
+ imported_plugins: importedPlugins,
318
+ sse: null,
319
+ _stats: { invocations: 0, successes: 0, failures: 0 }
320
+ };
321
+ _remotes[namespace] = handle;
322
+
323
+ /* Auto-subscribe to ack events -- see _ackEndpointAllowed for why
324
+ the host's endpoint wins over the peer's. */
325
+ if (conn.auto_subscribe !== false && transport === 'http') {
326
+ var hostAck = conn.ack_endpoint || null;
327
+ var peerAck = payload.ack_endpoint || null;
328
+ if (hostAck) {
329
+ _subscribeRemote(handle, hostAck);
330
+ } else if (peerAck && _ackEndpointAllowed(peerAck, conn.endpoint)) {
331
+ _subscribeRemote(handle, peerAck);
332
+ } else if (peerAck) {
333
+ /* Refused by name, never in silence: the import stands (the
334
+ tree is data and it is already registered) but the channel
335
+ that would have carried the bearer does not open, and the
336
+ host can see exactly that on the handle and on the event. */
337
+ handle.ack_refused = {
338
+ reason: 'ack_endpoint_cross_origin',
339
+ ack_endpoint: String(peerAck),
340
+ conn_origin: _originOf(conn.endpoint),
341
+ ack_origin: _originOf(peerAck, conn.endpoint),
342
+ };
343
+ console.warn('[nac-interop] refused the peer ack_endpoint: it is not the origin of '
344
+ + 'conn.endpoint, and the bearer would have travelled to it. Pass conn.ack_endpoint '
345
+ + 'to name one yourself.', handle.ack_refused);
346
+ document.dispatchEvent(new CustomEvent('nac:interop:ack_refused', {
347
+ detail: Object.assign({ namespace: namespace }, handle.ack_refused)
348
+ }));
349
+ }
350
+ }
351
+
352
+ document.dispatchEvent(new CustomEvent('nac:interop:imported', {
353
+ detail: { namespace: namespace, app_id: payload.app_id, plugins: importedPlugins }
354
+ }));
355
+
356
+ return handle;
357
+ }
358
+
359
+ function _subscribeRemote(handle, ackEndpoint) {
360
+ if (typeof EventSource === 'undefined') {
361
+ console.warn('[nac-interop] EventSource not available; ack subscription skipped');
362
+ return;
363
+ }
364
+ /* Bearer can't go in headers for EventSource; use ?bearer query
365
+ string per the spec. */
366
+ var url = ackEndpoint
367
+ + (ackEndpoint.indexOf('?') < 0 ? '?' : '&')
368
+ + 'bearer=' + encodeURIComponent(handle.bearer);
369
+ var es = new EventSource(url);
370
+ es.addEventListener('nac:action:succeeded', function (ev) {
371
+ _relayPeerEvent(handle, 'nac:action:succeeded', ev.data);
372
+ });
373
+ es.addEventListener('nac:action:failed', function (ev) {
374
+ _relayPeerEvent(handle, 'nac:action:failed', ev.data);
375
+ });
376
+ es.addEventListener('nac:tab:activated', function (ev) {
377
+ _relayPeerEvent(handle, 'nac:tab:activated', ev.data);
378
+ });
379
+ es.addEventListener('nac:field:changed', function (ev) {
380
+ _relayPeerEvent(handle, 'nac:field:changed', ev.data);
381
+ });
382
+ es.onerror = function (e) {
383
+ console.warn('[nac-interop] SSE error on', handle.namespace, e);
384
+ };
385
+ handle.sse = es;
386
+ }
387
+
388
+ function _relayPeerEvent(handle, eventName, dataStr) {
389
+ var detail;
390
+ try { detail = JSON.parse(dataStr); } catch (_) { detail = { raw: dataStr }; }
391
+ /* Namespace the action_id / field_id / tab_id so local
392
+ listeners see the remote: prefix. */
393
+ ['action_id', 'field_id', 'tab_id', 'option_id', 'plugin'].forEach(function (k) {
394
+ if (detail[k] && typeof detail[k] === 'string'
395
+ && detail[k].indexOf(REMOTE_PREFIX) !== 0) {
396
+ detail[k] = REMOTE_PREFIX + handle.namespace + ':' + detail[k];
397
+ }
398
+ });
399
+ detail.via_interop = true;
400
+ detail.is_trusted = false;
401
+ document.dispatchEvent(new CustomEvent(eventName, { detail: detail }));
402
+ }
403
+
404
+ function list_remote_apps() {
405
+ return Object.keys(_remotes).map(function (ns) {
406
+ var h = _remotes[ns];
407
+ return {
408
+ namespace: h.namespace,
409
+ app_id: h.app_id,
410
+ nac_version: h.nac_version,
411
+ imported_at: h.imported_at,
412
+ imported_plugins: h.imported_plugins.slice(),
413
+ stats: Object.assign({}, h._stats)
414
+ };
415
+ });
416
+ }
417
+
418
+ function disconnect_remote(namespace) {
419
+ _requireDocument('disconnect_remote');
420
+ var handle = _remotes[namespace];
421
+ if (!handle) return;
422
+ /* Unregister each namespaced plugin. */
423
+ handle.imported_plugins.forEach(function (slug) {
424
+ if (typeof global.NAC.unregister === 'function') {
425
+ try { global.NAC.unregister(slug); } catch (_) {}
426
+ }
427
+ });
428
+ /* Close SSE. */
429
+ if (handle.sse) { try { handle.sse.close(); } catch (_) {} }
430
+ delete _remotes[namespace];
431
+ document.dispatchEvent(new CustomEvent('nac:interop:disconnected', {
432
+ detail: { namespace: namespace, app_id: handle.app_id }
433
+ }));
434
+ }
435
+
436
+ /* ---------- HMAC helpers (SubtleCrypto-based) ---------- */
437
+
438
+ async function _hmacSign(secret, body) {
439
+ if (!secret || typeof secret !== 'string') return null;
440
+ if (!global.crypto || !global.crypto.subtle) return null;
441
+ var enc = new TextEncoder();
442
+ var key = await global.crypto.subtle.importKey(
443
+ 'raw',
444
+ enc.encode(secret),
445
+ { name: 'HMAC', hash: 'SHA-256' },
446
+ false,
447
+ ['sign']
448
+ );
449
+ var sig = await global.crypto.subtle.sign('HMAC', key, enc.encode(body));
450
+ var arr = new Uint8Array(sig);
451
+ var hex = '';
452
+ for (var i = 0; i < arr.length; i++) {
453
+ hex += arr[i].toString(16).padStart(2, '0');
454
+ }
455
+ return hex;
456
+ }
457
+
458
+ /* ---------- Proxy invoke ---------- */
459
+
460
+ async function _proxyInvoke(handle, peer_id, action_kind, args) {
461
+ handle._stats.invocations++;
462
+ var body = {
463
+ bearer: handle.bearer,
464
+ nac_id: peer_id,
465
+ action: { kind: action_kind, args: args || {} }
466
+ };
467
+ /* Optional HMAC on sensitive actions; the host can mark verbs
468
+ sensitive via window.__NAC_INTEROP_SENSITIVE_VERBS__. */
469
+ if (handle.hmac_secret) {
470
+ var canonical = JSON.stringify({
471
+ nac_id: body.nac_id, kind: body.action.kind, args: body.action.args
472
+ });
473
+ try { body.hmac = await _hmacSign(handle.hmac_secret, canonical); } catch (_) {}
474
+ }
475
+ var resp;
476
+ try {
477
+ resp = await fetch(handle.endpoint + '/nac.invoke', {
478
+ method: 'POST',
479
+ headers: { 'Content-Type': 'application/json' },
480
+ body: JSON.stringify(body)
481
+ });
482
+ } catch (e) {
483
+ handle._stats.failures++;
484
+ throw _err('network', 'nac.invoke network error: ' + e.message);
485
+ }
486
+ if (!resp.ok) {
487
+ handle._stats.failures++;
488
+ throw _err('http_' + resp.status, 'nac.invoke HTTP ' + resp.status);
489
+ }
490
+ var json;
491
+ try { json = await resp.json(); }
492
+ catch (e) {
493
+ handle._stats.failures++;
494
+ throw _err('parse', 'nac.invoke returned non-JSON');
495
+ }
496
+ if (json.ok === false) {
497
+ handle._stats.failures++;
498
+ throw _err((json.error && json.error.code) || 'peer_error',
499
+ (json.error && json.error.message) || 'peer rejected the invocation');
500
+ }
501
+ handle._stats.successes++;
502
+ return json.result || { ok: true };
503
+ }
504
+
505
+ /* ---------- Patch NAC public API to route remote: prefix ---------- */
506
+
507
+ function _wrap(fnName, kindForProxy, argMapper) {
508
+ var orig = global.NAC[fnName];
509
+ if (typeof orig !== 'function') return;
510
+ global.NAC[fnName] = async function () {
511
+ var args = Array.prototype.slice.call(arguments);
512
+ var firstArg = args[0];
513
+ var parsed = _parseRemote(firstArg);
514
+ if (!parsed) return orig.apply(global.NAC, args);
515
+ var handle = _remotes[parsed.namespace];
516
+ if (!handle) {
517
+ throw _err('not_found',
518
+ fnName + ': namespace "' + parsed.namespace + '" not imported (call NAC.import_remote_tree first)');
519
+ }
520
+ var peerArgs = (typeof argMapper === 'function') ? argMapper(args, parsed) : {};
521
+ try {
522
+ var result = await _proxyInvoke(handle, parsed.peer_id, kindForProxy, peerArgs);
523
+ _emitLocalAck(REMOTE_PREFIX + parsed.namespace + ':' + (peerArgs.plugin || parsed.peer_id.split('.')[0]),
524
+ firstArg, true, { result: result });
525
+ return result;
526
+ } catch (e) {
527
+ _emitLocalAck(REMOTE_PREFIX + parsed.namespace,
528
+ firstArg, false, { error: { code: e.code, message: e.message } });
529
+ throw e;
530
+ }
531
+ };
532
+ return orig;
533
+ }
534
+
535
+ _origClick = _wrap('click', 'click', function (args) { return { opts: args[1] || {} }; });
536
+ _origFill = _wrap('fill', 'fill', function (args) { return { value: args[1] }; });
537
+ _origSelect = _wrap('select', 'select', function (args) { return { value: args[1] }; });
538
+ _origGoToSection = _wrap('go_to_section', 'go_to_section', function () { return {}; });
539
+ _origEditField = _wrap('edit_field', 'edit_field', function () { return {}; });
540
+
541
+ /* tab(plugin, tab_key): if plugin starts with remote: prefix, parse and proxy. */
542
+ _origTab = global.NAC.tab;
543
+ if (typeof _origTab === 'function') {
544
+ global.NAC.tab = async function (plugin, tab_key) {
545
+ var parsedPlugin = _parseRemote(plugin);
546
+ if (!parsedPlugin) return _origTab.call(global.NAC, plugin, tab_key);
547
+ var handle = _remotes[parsedPlugin.namespace];
548
+ if (!handle) throw _err('not_found', 'tab: namespace "' + parsedPlugin.namespace + '" not imported');
549
+ /* tab_key may also have the prefix; strip it if so. */
550
+ var peerTabKey = tab_key;
551
+ var parsedTab = _parseRemote(tab_key);
552
+ if (parsedTab && parsedTab.namespace === parsedPlugin.namespace) {
553
+ peerTabKey = parsedTab.peer_id;
554
+ }
555
+ var result = await _proxyInvoke(handle, parsedPlugin.peer_id,
556
+ 'tab', { tab_key: peerTabKey });
557
+ _emitLocalAck(plugin, REMOTE_PREFIX + parsedPlugin.namespace + ':' + peerTabKey,
558
+ true, { result: result });
559
+ return result;
560
+ };
561
+ }
562
+
563
+ /* tab_by_label and click_by_verb also accept a plugin arg. */
564
+ _origTabByLabel = global.NAC.tab_by_label;
565
+ if (typeof _origTabByLabel === 'function') {
566
+ global.NAC.tab_by_label = async function (plugin, label, opts) {
567
+ var parsedPlugin = _parseRemote(plugin);
568
+ if (!parsedPlugin) return _origTabByLabel.call(global.NAC, plugin, label, opts);
569
+ var handle = _remotes[parsedPlugin.namespace];
570
+ if (!handle) throw _err('not_found', 'tab_by_label: namespace not imported');
571
+ return _proxyInvoke(handle, parsedPlugin.peer_id, 'tab_by_label', { label: label });
572
+ };
573
+ }
574
+
575
+ var _origClickByVerb = global.NAC.click_by_verb;
576
+ if (typeof _origClickByVerb === 'function') {
577
+ global.NAC.click_by_verb = async function (plugin, verb, opts) {
578
+ var parsedPlugin = _parseRemote(plugin);
579
+ if (!parsedPlugin) return _origClickByVerb.call(global.NAC, plugin, verb, opts);
580
+ var handle = _remotes[parsedPlugin.namespace];
581
+ if (!handle) throw _err('not_found', 'click_by_verb: namespace not imported');
582
+ return _proxyInvoke(handle, parsedPlugin.peer_id, 'click_by_verb', { verb: verb });
583
+ };
584
+ }
585
+
586
+ /* dt_* family: each takes table_id as first arg. */
587
+ ['dt_add_row', 'dt_remove_row', 'dt_edit_cell',
588
+ 'dt_commit', 'dt_discard', 'dt_read_aggregate'].forEach(function (fnName) {
589
+ var orig = global.NAC[fnName];
590
+ if (typeof orig !== 'function') return;
591
+ global.NAC[fnName] = function () {
592
+ var args = Array.prototype.slice.call(arguments);
593
+ var tableId = args[0];
594
+ var parsed = _parseRemote(tableId);
595
+ if (!parsed) return orig.apply(global.NAC, args);
596
+ var handle = _remotes[parsed.namespace];
597
+ if (!handle) throw _err('not_found', fnName + ': namespace not imported');
598
+ var argsPayload = {};
599
+ switch (fnName) {
600
+ case 'dt_add_row': argsPayload = { values: args[1] || {} }; break;
601
+ case 'dt_remove_row': argsPayload = { row_id: args[1] }; break;
602
+ case 'dt_edit_cell': argsPayload = { row_id: args[1], column: args[2], value: args[3] }; break;
603
+ case 'dt_commit': argsPayload = {}; break;
604
+ case 'dt_discard': argsPayload = {}; break;
605
+ case 'dt_read_aggregate':argsPayload = { agg_key: args[1], column: args[2] }; break;
606
+ }
607
+ return _proxyInvoke(handle, parsed.peer_id, fnName, argsPayload);
608
+ };
609
+ });
610
+
611
+ /* ---------- Expose on NAC ---------- */
612
+
613
+ global.NAC.export_tree = export_tree;
614
+ global.NAC.import_remote_tree = import_remote_tree;
615
+ global.NAC.list_remote_apps = list_remote_apps;
616
+ global.NAC.disconnect_remote = disconnect_remote;
617
+
618
+ /* Behind a switch since 2026-11-24. This was the only
619
+ unconditional console.log left in published code: an install
620
+ banner every page that loads this file printed, whether or not
621
+ anyone was debugging. It prints no user content -- unlike the
622
+ three in nac-chat-client.js -- so the cost was noise rather than
623
+ disclosure, but a library that writes to the host console
624
+ uninvited is still the host's decision to make, not ours.
625
+ window.NAC_INTEROP_DEBUG = true brings it back. The warn and
626
+ error calls in this file are untouched. */
627
+ if (global.NAC_INTEROP_DEBUG === true && global.console
628
+ && typeof global.console.log === 'function') {
629
+ global.console.log('[nac-interop] installed (v2.3 preview) on top of NAC ' + global.NAC.version);
630
+ }
631
+
632
+ /* The same guard its three siblings carry. Until 2.9.0 this file ended
633
+ with (window), so the ESM and CJS bundles of the package could not
634
+ even be LOADED outside a browser -- which is one reason it was never
635
+ published. */
636
+ })(typeof window !== 'undefined' ? window : globalThis);
637
+
638
+ module.exports = _g.NAC || _g.NACv2 || _g.NacChat;
639
+ module.exports.NAC = _g.NAC;
640
+ module.exports.NACv2 = _g.NACv2;
641
+ module.exports.NacChat = _g.NacChat;
@@ -0,0 +1,57 @@
1
+ // Generated by build.mjs -- do not edit. Source: js/nac-mcp-interop.js
2
+ // Cross-app navigation for @nac3/runtime. OPTIONAL: no conformance
3
+ // level requires it. Load after the runtime:
4
+ // import '@nac3/runtime';
5
+ // import '@nac3/runtime/mcp-interop';
6
+
7
+ export interface NacExportOptions {
8
+ /** 'full' (default), 'active_plugin', or 'plugin_slug:<slug>'. */
9
+ scope?: string;
10
+ include_dom_state?: boolean;
11
+ include_locales?: string[] | null;
12
+ }
13
+
14
+ export interface NacRemoteConnection {
15
+ endpoint: string;
16
+ bearer: string;
17
+ transport?: 'http' | 'stdio';
18
+ namespace?: string;
19
+ hmac_secret?: string | null;
20
+ auto_subscribe?: boolean;
21
+ }
22
+
23
+ export interface NacRemoteHandle {
24
+ namespace: string;
25
+ app_id?: string;
26
+ app_version?: string;
27
+ nac_version?: string;
28
+ imported_at: string;
29
+ imported_plugins: string[];
30
+ stats?: { invocations: number; successes: number; failures: number };
31
+ [k: string]: unknown;
32
+ }
33
+
34
+ /** The export payload. Its shape is versioned by docs/NAC_INTEROP_MCP.md. */
35
+ export interface NacExportV1 {
36
+ app_id?: string;
37
+ app_version?: string;
38
+ nac_version?: string;
39
+ manifests: Record<string, unknown>;
40
+ [k: string]: unknown;
41
+ }
42
+
43
+ /** Members this module attaches onto window.NAC. */
44
+ export interface NacMcpInterop {
45
+ /** Throws { code: 'no_document' } with no document (SPEC 19). */
46
+ export_tree(opts?: NacExportOptions): NacExportV1;
47
+ /** Throws { code: 'no_document' } with no document (SPEC 19). */
48
+ import_remote_tree(payload: NacExportV1, conn: NacRemoteConnection): NacRemoteHandle;
49
+ /** Works without a document: it reads state only. */
50
+ list_remote_apps(): NacRemoteHandle[];
51
+ /** Throws { code: 'no_document' } with no document (SPEC 19). */
52
+ disconnect_remote(namespace: string): void;
53
+ }
54
+
55
+ declare const _default: NacMcpInterop;
56
+ export default _default;
57
+ export const NAC: NacMcpInterop;