@agentproto/apps 0.11.0 → 0.12.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.
Files changed (42) hide show
  1. package/dist/agents-overview/panel.mjs +25 -0
  2. package/dist/agents-overview/panel.mjs.map +1 -1
  3. package/dist/agents-overview.mjs +25 -0
  4. package/dist/agents-overview.mjs.map +1 -1
  5. package/dist/bureau-sessions/panel.mjs +25 -0
  6. package/dist/bureau-sessions/panel.mjs.map +1 -1
  7. package/dist/bureau-sessions.mjs +25 -0
  8. package/dist/bureau-sessions.mjs.map +1 -1
  9. package/dist/index.mjs +494 -12
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/live-session/panel.mjs +25 -0
  12. package/dist/live-session/panel.mjs.map +1 -1
  13. package/dist/live-session.mjs +25 -0
  14. package/dist/live-session.mjs.map +1 -1
  15. package/dist/panel-bridge.d.ts.map +1 -1
  16. package/dist/session-chat/blob-embed.d.ts +53 -0
  17. package/dist/session-chat/blob-embed.d.ts.map +1 -0
  18. package/dist/session-chat/index.d.ts +13 -0
  19. package/dist/session-chat/index.d.ts.map +1 -1
  20. package/dist/session-chat/panel.d.ts +38 -2
  21. package/dist/session-chat/panel.d.ts.map +1 -1
  22. package/dist/session-chat/panel.mjs +609 -6
  23. package/dist/session-chat/panel.mjs.map +1 -1
  24. package/dist/session-chat.mjs +631 -13
  25. package/dist/session-chat.mjs.map +1 -1
  26. package/dist/session-story/panel.mjs +25 -0
  27. package/dist/session-story/panel.mjs.map +1 -1
  28. package/dist/session-story.mjs +25 -0
  29. package/dist/session-story.mjs.map +1 -1
  30. package/dist/sessions-panel/panel.mjs +25 -0
  31. package/dist/sessions-panel/panel.mjs.map +1 -1
  32. package/dist/sessions-panel.mjs +25 -0
  33. package/dist/sessions-panel.mjs.map +1 -1
  34. package/dist/work-board/panel.d.ts +1 -1
  35. package/dist/work-board/panel.d.ts.map +1 -1
  36. package/dist/work-board/panel.generated.d.ts +1 -1
  37. package/dist/work-board/panel.generated.d.ts.map +1 -1
  38. package/dist/work-board/panel.mjs +25 -0
  39. package/dist/work-board/panel.mjs.map +1 -1
  40. package/dist/work-board.mjs +25 -0
  41. package/dist/work-board.mjs.map +1 -1
  42. package/package.json +1 -1
@@ -3,14 +3,275 @@
3
3
  * Ready-made agentproto apps (teams of agents + workflows) built on app-kit.
4
4
  */
5
5
 
6
+ // src/panel-bridge.ts
7
+ function panelBridgeScript(appName) {
8
+ return `// \u2500\u2500 MCP Apps bridge (shared: panel-bridge.ts) \u2500\u2500
9
+ // JSON-RPC 2.0 over window.parent.postMessage \xB7 spec 2026-01-26
10
+ var _nextId = 1, _pending = {}, _notifyHandlers = [];
11
+ var _hostContext = null, _hostContextHandlers = [];
12
+ var _hostCaps = null;
13
+ var _standaloneApp = null;
14
+ function _isStandalone(){
15
+ return window.parent === window && !!window.McpApp && typeof window.McpApp.connect === 'function';
16
+ }
17
+ // \u2500\u2500 Per-boot embed token (runtime embed-tokens.ts) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
18
+ // Panels that iframe the daemon's standalone app host carry this proof so
19
+ // GET /apps/:appId/ui?embed=1&et=... can drop its anti-framing headers for
20
+ // MCP-Apps hosts whose widget context is an opaque origin (Claude Desktop).
21
+ // registerMcpApps replaces the placeholder with a real per-boot token when
22
+ // serving the panel as a resource; every other render (tests, standalone
23
+ // tab, VS Code HTTP-iframe panel \u2014 the latter two already pass
24
+ // iframeEmbedAllowed's origin checks) keeps the literal, and
25
+ // withEmbedToken() then degrades to an identity function.
26
+ window.__AGENPROTO_EMBED_TOKEN__ = "__AGENPROTO_EMBED_TOKEN__";
27
+ function withEmbedToken(url){
28
+ var t = window.__AGENPROTO_EMBED_TOKEN__;
29
+ if (!t || t === '__AGENPROTO_EMBED_TOKEN__') return url;
30
+ return url + (url.indexOf('?') >= 0 ? '&' : '?') + 'et=' + encodeURIComponent(t);
31
+ }
32
+ function post(msg){ window.parent.postMessage(msg, '*'); }
33
+ function getHostContext(){ return _hostContext; }
34
+ function getHostCapabilities(){ return _hostCaps; }
35
+ function onHostContext(cb){
36
+ _hostContextHandlers.push(cb);
37
+ // Replay the last context so a late subscriber isn't stuck blind.
38
+ if (_hostContext){ try { cb(_hostContext); } catch(_) {} }
39
+ }
40
+ function _setHostContext(ctx){
41
+ if (!ctx || typeof ctx !== 'object') return;
42
+ // ui/notifications/host-context-changed carries only the changed keys \u2014
43
+ // merge, matching the official ext-apps App behaviour.
44
+ _hostContext = Object.assign({}, _hostContext || {}, ctx);
45
+ for (var i = 0; i < _hostContextHandlers.length; i++){
46
+ try { _hostContextHandlers[i](_hostContext); } catch(_) {}
47
+ }
48
+ }
49
+ function rpcRequest(method, params){
50
+ return new Promise(function(resolve, reject){
51
+ var id = _nextId++;
52
+ _pending[id] = {resolve: resolve, reject: reject};
53
+ post({jsonrpc: '2.0', id: id, method: method, params: params || {}});
54
+ });
55
+ }
56
+ function rpcNotify(method, params){ post({jsonrpc: '2.0', method: method, params: params || {}}); }
57
+ function onHostNotification(cb){ _notifyHandlers.push(cb); }
58
+ window.addEventListener('message', function(evt){
59
+ var msg = evt.data;
60
+ if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') return;
61
+ if (msg.id != null && msg.method == null){
62
+ var p = _pending[msg.id];
63
+ if (!p) return;
64
+ delete _pending[msg.id];
65
+ if (msg.error) p.reject(new Error(msg.error.message || ('rpc error ' + msg.error.code)));
66
+ else p.resolve(msg.result);
67
+ return;
68
+ }
69
+ if (msg.method){
70
+ if (msg.method === 'ui/notifications/host-context-changed'){
71
+ _setHostContext(msg.params || {});
72
+ }
73
+ for (var i = 0; i < _notifyHandlers.length; i++){
74
+ try { _notifyHandlers[i](msg.method, msg.params || {}); } catch(_) {}
75
+ }
76
+ }
77
+ });
78
+ function initBridge(){
79
+ if (_isStandalone()){
80
+ return window.McpApp.connect().then(function(conn){
81
+ _standaloneApp = conn;
82
+ // No host to advertise a hostContext \u2014 default to inline with no
83
+ // other modes available, which keeps the #dm/#pin toggle buttons
84
+ // hidden (they only show for modes hostContext.availableDisplayModes
85
+ // lists) instead of rendering two buttons with nothing to switch to.
86
+ _setHostContext({displayMode: 'inline', availableDisplayModes: []});
87
+ });
88
+ }
89
+ return rpcRequest('ui/initialize', {
90
+ appInfo: {name: ${JSON.stringify(appName)}, version: '0.1.0'},
91
+ appCapabilities: {availableDisplayModes: ['inline', 'fullscreen', 'pip']},
92
+ protocolVersion: '2026-01-26'
93
+ }).then(function(result){
94
+ // The initialize result carries the initial hostContext (displayMode +
95
+ // availableDisplayModes) \u2014 capture it before notifying the host.
96
+ if (result && result.hostContext) _setHostContext(result.hostContext);
97
+ // McpUiInitializeResult.hostCapabilities (ext-apps spec) \u2014 e.g. openLinks,
98
+ // "Host supports opening external URLs". Captured once, read via
99
+ // getHostCapabilities() by panels that need to branch on it.
100
+ if (result && result.hostCapabilities) _hostCaps = result.hostCapabilities;
101
+ rpcNotify('ui/notifications/initialized', {});
102
+ });
103
+ }
104
+ function requestDisplayMode(mode){
105
+ return rpcRequest('ui/request-display-mode', {mode: mode});
106
+ }
107
+ function openLink(url){
108
+ if (_standaloneApp && typeof _standaloneApp.openLink === 'function') return _standaloneApp.openLink(url);
109
+ return rpcRequest('ui/open-link', {url: url});
110
+ }
111
+ function callTool(name, args){
112
+ var raw = _standaloneApp
113
+ ? _standaloneApp.callTool(name, args || {})
114
+ : rpcRequest('tools/call', {name: name, arguments: args || {}});
115
+ return raw.then(function(result){
116
+ if (result.isError){
117
+ var e = (result.content && result.content[0] && result.content[0].text) || 'tool error';
118
+ throw new Error(e);
119
+ }
120
+ var text = (result.content && result.content[0] && result.content[0].text) || '{}';
121
+ return JSON.parse(text);
122
+ });
123
+ }
124
+
125
+ // \u2500\u2500 Display-mode toggle buttons (NO auto-request) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
126
+ // Injected by the shared bridge so every panel gets them without touching
127
+ // its own markup. Mirrors guilde canvas.app.ts canvasShellHtml(): the
128
+ // panel stays inline by default; the user expands on demand. Buttons only
129
+ // appear for modes the host advertises in hostContext.availableDisplayModes.
130
+ (function(){
131
+ function mount(){
132
+ var style = document.createElement('style');
133
+ style.textContent = '#dm,#pin{display:none;position:fixed;top:8px;z-index:10;'
134
+ + 'border:1px solid #d0d0d0;background:#fff;color:#1a1a1a;'
135
+ + 'font:600 13px/1 system-ui,sans-serif;padding:7px 12px;border-radius:6px;'
136
+ + 'cursor:pointer;box-shadow:0 1px 4px rgba(0,0,0,.18)}'
137
+ + '#dm{right:8px}#pin{right:118px}'
138
+ + '#dm:hover,#pin:hover{background:#f2f2f2;border-color:#b0b0b0}'
139
+ + '@media (prefers-color-scheme:dark){'
140
+ + '#dm,#pin{border-color:#555;background:#2a2a2a;color:#f0f0f0;box-shadow:0 1px 4px rgba(0,0,0,.5)}'
141
+ + '#dm:hover,#pin:hover{background:#333;border-color:#777}}';
142
+ document.head.appendChild(style);
143
+
144
+ var btn = document.createElement('button');
145
+ btn.id = 'dm'; btn.type = 'button'; btn.title = "Basculer l'affichage";
146
+ var pin = document.createElement('button');
147
+ pin.id = 'pin'; pin.type = 'button'; pin.title = '\xC9pingler sur le c\xF4t\xE9 (pip)';
148
+ document.body.appendChild(pin);
149
+ document.body.appendChild(btn);
150
+
151
+ function has(avail, m){ return !!avail && avail.indexOf(m) >= 0; }
152
+
153
+ // Re-sync button visibility + label from the current host context.
154
+ function syncBtn(ctx){
155
+ ctx = ctx || {};
156
+ var avail = ctx.availableDisplayModes;
157
+ // Diagnostic: what does THIS host actually advertise? (inline/fullscreen/pip)
158
+ console.log('[mcp-app] displayMode=', ctx.displayMode,
159
+ 'availableDisplayModes=', avail);
160
+
161
+ // Fullscreen toggle button.
162
+ if (has(avail, 'fullscreen')){
163
+ btn.style.display = 'block';
164
+ btn.textContent = (ctx.displayMode === 'fullscreen') ? '\u2921 R\xE9duire' : '\u2922 Agrandir';
165
+ } else { btn.style.display = 'none'; }
166
+
167
+ // Dedicated pip ("pinned on side") button \u2014 only if the host advertises pip.
168
+ if (has(avail, 'pip')){
169
+ pin.style.display = 'block';
170
+ pin.textContent = (ctx.displayMode === 'pip') ? '\u2921 D\xE9tacher' : '\u{1F4CC} \xC9pingler';
171
+ } else { pin.style.display = 'none'; }
172
+ }
173
+
174
+ onHostContext(syncBtn);
175
+
176
+ btn.addEventListener('click', function(){
177
+ var ctx = getHostContext() || {};
178
+ var inPanel = (ctx.displayMode === 'fullscreen' || ctx.displayMode === 'pip');
179
+ requestDisplayMode(inPanel ? 'inline' : 'fullscreen').catch(function(){});
180
+ });
181
+
182
+ pin.addEventListener('click', function(){
183
+ var ctx = getHostContext() || {};
184
+ requestDisplayMode(ctx.displayMode === 'pip' ? 'inline' : 'pip').catch(function(){});
185
+ });
186
+ }
187
+ if (document.body) mount();
188
+ else document.addEventListener('DOMContentLoaded', mount);
189
+ })();`;
190
+ }
191
+
192
+ // src/session-chat/blob-embed.ts
193
+ var BLOB_BOOT_MESSAGE_TYPE = "agentproto-blob-boot";
194
+ function blobEmbedScript() {
195
+ return `// \u2500\u2500 Blob pass-through transform (shared: session-chat/blob-embed.ts) \u2500\u2500
196
+ function _blobEscapeAttr(s){ return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); }
197
+ // Rewrite the fetched chat html so it works as a blob: document: <base> on
198
+ // the deep link, a fetch/EventSource shim that carries the embed token to
199
+ // the daemon origin, and the standalone bridge's ./tool-call made absolute.
200
+ function transformChatHtmlForBlob(html, url, token){
201
+ var origin = new URL(url).origin;
202
+ var tc = new URL('./tool-call', url);
203
+ tc.searchParams.set('et', token);
204
+ // The app-visible query for the blob doc: the deep link's search minus the
205
+ // embed token (the token must not ride the app's visible params). The
206
+ // blob document's own location has no params, so this is the ONLY channel
207
+ // for ?session= / ?embed=1 \u2014 the app reads it via bootSearchParams().
208
+ var bootUrl = new URL(url);
209
+ bootUrl.searchParams.delete('et');
210
+ var bootQuery = bootUrl.search;
211
+ var shim = '<script>(function(){'
212
+ + 'try { window.parent.postMessage({ type: ${JSON.stringify(BLOB_BOOT_MESSAGE_TYPE)} }, "*"); } catch (_) {}'
213
+ + 'var ORIGIN = ' + JSON.stringify(origin) + ', TOKEN = ' + JSON.stringify(token) + ';'
214
+ + 'window.__AGENTPROTO_BASEURL__ = ORIGIN;'
215
+ + 'var _h = window.history, _rs = _h.replaceState.bind(_h), _ps = _h.pushState.bind(_h);'
216
+ + 'function _sameOrLoc(u){'
217
+ + 'try {'
218
+ + 'var x = new URL(u == null ? window.location.href : u, document.baseURI);'
219
+ + 'return x.origin === window.location.origin ? u : window.location.href;'
220
+ + '} catch (_) { return window.location.href; }'
221
+ + '}'
222
+ + '_h.replaceState = function(s, t, u){'
223
+ + 'try { _rs(s, t, _sameOrLoc(u)); } catch (_) { try { _rs(s, t, window.location.href); } catch (_) {} }'
224
+ + '};'
225
+ + '_h.pushState = function(s, t, u){'
226
+ + 'try { _ps(s, t, _sameOrLoc(u)); } catch (_) { try { _ps(s, t, window.location.href); } catch (_) {} }'
227
+ + '};'
228
+ + 'window.__AGENTPROTO_BOOT_QUERY__ = ' + JSON.stringify(bootQuery) + ';'
229
+ + 'function withEt(u){'
230
+ + 'try {'
231
+ + 'var x = new URL(String(u), document.baseURI);'
232
+ + 'if (x.origin !== ORIGIN) return null;'
233
+ + 'if (!x.searchParams.has("et")) x.searchParams.set("et", TOKEN);'
234
+ + 'return x.href;'
235
+ + '} catch (_) { return null; }'
236
+ + '}'
237
+ + 'var _fetch = window.fetch;'
238
+ + 'if (typeof _fetch === "function") {'
239
+ + 'window.fetch = function(input, init){'
240
+ + 'var r;'
241
+ + 'if (typeof Request !== "undefined" && input instanceof Request) {'
242
+ + 'r = withEt(input.url);'
243
+ + 'if (r) { try { input = new Request(r, input); } catch (_) {} }'
244
+ + '} else {'
245
+ + 'r = withEt(input);'
246
+ + 'if (r) input = r;'
247
+ + '}'
248
+ + 'return _fetch.call(window, input, init);'
249
+ + '};'
250
+ + '}'
251
+ + 'var _ES = window.EventSource;'
252
+ + 'if (typeof _ES === "function") {'
253
+ + 'window.EventSource = function(u, cfg){ return new _ES(withEt(u) || u, cfg); };'
254
+ + 'window.EventSource.prototype = _ES.prototype;'
255
+ + '}'
256
+ + '})();<\\/script>';
257
+ var head = '<base href="' + _blobEscapeAttr(url) + '">' + shim;
258
+ var m = html.match(/<head[^>]*>/i);
259
+ var out = m
260
+ ? html.slice(0, m.index + m[0].length) + head + html.slice(m.index + m[0].length)
261
+ : head + html;
262
+ return out.split('fetch("./tool-call"').join('fetch(' + JSON.stringify(tc.href));
263
+ }`;
264
+ }
265
+
6
266
  // src/session-chat/panel.ts
7
267
  function escapeAttr(text) {
8
268
  return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
9
269
  }
10
270
  function sessionChatEmbedHtml(initData) {
11
- const url = initData.url;
12
- const link = url != null ? `<a href="${escapeAttr(url)}" target="_blank" rel="noreferrer">open in a tab</a>` : "app not installed";
13
- const iframe = url != null ? `<iframe id="chat" title="Session Chat" src="${escapeAttr(url)}"></iframe>` : "";
271
+ const url = typeof initData.url === "string" && initData.url ? initData.url : null;
272
+ const notInstalled = initData.installed === false;
273
+ const link = url != null ? `<a href="${escapeAttr(url)}" target="_blank" rel="noreferrer">open in a tab</a>` : notInstalled ? "app not installed" : "connecting\u2026";
274
+ const iframe = url != null ? `<iframe id="chat" title="Session Chat"></iframe>` : "";
14
275
  return `<!DOCTYPE html>
15
276
  <html lang="en">
16
277
  <head>
@@ -22,12 +283,354 @@ function sessionChatEmbedHtml(initData) {
22
283
  html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3;overflow:hidden}
23
284
  #bar{padding:6px 12px;font-size:12px;color:#8b949e;background:#161b22;border-bottom:1px solid #30363d}
24
285
  #bar a{color:#58a6ff}
25
- #chat{border:0;display:block;width:100%;height:calc(100% - 29px)}
286
+ #mode{color:#6e7681}
287
+ #stage{position:relative;height:calc(100% - 29px)}
288
+ #chat{position:absolute;inset:0;z-index:2;border:0;display:block;width:100%;height:100%}
289
+ #card{position:absolute;inset:0;z-index:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;text-align:center;padding:24px}
290
+ #card h2{font-size:15px;font-weight:600}
291
+ #card .sid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:#8b949e;background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 8px}
292
+ #card p{font-size:12px;color:#8b949e;max-width:420px;line-height:1.5}
293
+ #card a{display:inline-block;margin-top:2px;border:1px solid #30363d;background:#161b22;color:#58a6ff;font-size:13px;padding:7px 14px;border-radius:6px;text-decoration:none}
294
+ #card a:hover{border-color:#58a6ff}
295
+ #notice{display:none;max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}
296
+ #notice.show{display:block}
297
+ #notice h1{font-size:18px;margin-bottom:12px}
298
+ #notice code{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}
299
+ #notice p{margin:8px 0;color:#8b949e;font-size:13px}
26
300
  </style>
27
301
  </head>
28
302
  <body>
29
- <div id="bar">Session Chat &#183; ${link}</div>
30
- ${iframe}
303
+ <div id="bar">Session Chat &#183; <span id="link">${link}</span><span id="mode"></span></div>
304
+ <div id="stage">${iframe}<div id="card">
305
+ <h2>Session Chat</h2>
306
+ <div id="card-session" class="sid">&#8212;</div>
307
+ <p>Full embed isn't supported by this host &#8212; the chat opens in a browser tab.</p>
308
+ <a id="card-open" href="#" target="_blank" rel="noreferrer">Open chat</a>
309
+ </div><div id="notice"${notInstalled ? ' class="show"' : ""}>
310
+ <h1>Session Chat is not installed</h1>
311
+ <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;
312
+ it does not bundle the chat UI itself.</p>
313
+ <p>To use it, install the app into this daemon:</p>
314
+ <p><code>agentproto app install @agentik/session-chat</code></p>
315
+ </div></div>
316
+ <script>
317
+ window.__APP_INIT__ = ${JSON.stringify(initData)};
318
+
319
+ ${panelBridgeScript("agentproto-session-chat")}
320
+
321
+ ${blobEmbedScript()}
322
+
323
+ // \u2500\u2500 Session-chat launcher logic \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
324
+ var mountedUrl = (window.__APP_INIT__ && window.__APP_INIT__.url) || null;
325
+ var pinnedSessionId = null; // session named by the host's tool-result push
326
+ var pendingUrl = null; // url pushed by the host before the bridge was up
327
+ var pendingNotInstalled = false;
328
+ var bridged = false;
329
+ var cardUrl = null; // deep link once resolved (drives the card button)
330
+ var cardSessionEl = document.getElementById('card-session');
331
+ var cardOpenEl = document.getElementById('card-open');
332
+ var mountGen = 0; // bumps per mount(); async work checks it before touching the DOM
333
+ var blobUrl = null; // live object url of the blob-mounted chat, if any
334
+ var blobBootTimer = null;
335
+ var blobBootOk = false;
336
+
337
+ function escapeHtml(text) {
338
+ return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
339
+ }
340
+
341
+ function setMode(text) {
342
+ document.getElementById('mode').textContent = text ? ' \\u00b7 ' + text : '';
343
+ // The chat app is live inside the frame \u2014 the launcher bar (title, deep
344
+ // link, mount mode) is noise on top of the real surface. Hide it and let
345
+ // the frame own the full height. Only a failed mount (launcher card /
346
+ // not-installed notice) shows the bar again.
347
+ var bar = document.getElementById('bar');
348
+ var stage = document.getElementById('stage');
349
+ if (bar && stage) {
350
+ bar.style.display = text ? 'none' : '';
351
+ stage.style.height = text ? '100%' : 'calc(100% - 29px)';
352
+ }
353
+ }
354
+
355
+ // One fresh #chat frame on the stage (over the card), the previous one gone.
356
+ function newFrame() {
357
+ var stage = document.getElementById('stage');
358
+ var old = document.getElementById('chat');
359
+ if (old) old.remove();
360
+ var frame = document.createElement('iframe');
361
+ frame.id = 'chat';
362
+ frame.title = 'Session Chat';
363
+ stage.insertBefore(frame, stage.firstChild);
364
+ return frame;
365
+ }
366
+
367
+ function revokeBlob() {
368
+ if (blobBootTimer) { clearTimeout(blobBootTimer); blobBootTimer = null; }
369
+ if (blobUrl) {
370
+ try { URL.revokeObjectURL(blobUrl); } catch (_) {}
371
+ blobUrl = null;
372
+ }
373
+ }
374
+
375
+ function mount(url) {
376
+ if (!url || url === mountedUrl) return;
377
+ mountedUrl = url;
378
+ var gen = ++mountGen;
379
+ revokeBlob();
380
+ document.getElementById('notice').className = '';
381
+ setCardUrl(url);
382
+ document.getElementById('link').innerHTML =
383
+ '<a href="' + escapeHtml(url) + '" target="_blank" rel="noreferrer">open in a tab</a>';
384
+ var tokened = withEmbedToken(url);
385
+ if (tokened === url) {
386
+ // No per-boot token baked in (standalone tab, VS Code HTTP-iframe panel):
387
+ // the direct frame already passes the daemon's origin checks, and the
388
+ // blob path's daemon calls would have nothing to carry \u2014 skip it.
389
+ mountDirect(url);
390
+ return;
391
+ }
392
+ mountBlob(url, tokened, gen).catch(function (err) {
393
+ if (gen !== mountGen) return;
394
+ // The fetch itself was refused (host connect-src not merging our
395
+ // connectDomains, PNA, daemon down, \u2026) \u2014 probe answered: no blob path.
396
+ console.warn('[session-chat] blob mount failed, falling back to a direct frame:',
397
+ err && err.message ? err.message : String(err));
398
+ mountDirect(url);
399
+ });
400
+ }
401
+
402
+ // Direct-src iframe of the deep link, with the block probe \u2192 launcher card
403
+ // fallback. The terminal mount path when the blob one is unavailable.
404
+ function mountDirect(url) {
405
+ var frame = newFrame();
406
+ frame.src = withEmbedToken(url);
407
+ setMode('direct frame');
408
+ armBlockProbe(frame);
409
+ }
410
+
411
+ // Blob pass-through: fetch the chat html through the embed token, rewrite it
412
+ // for life as a blob: document (transformChatHtmlForBlob, blob-embed.ts) and
413
+ // mount it \u2014 blob: passes a host frame-src that refuses the daemon origin.
414
+ function mountBlob(url, tokened, gen) {
415
+ return fetch(tokened, { credentials: 'omit' }).then(function (res) {
416
+ if (!res.ok) throw new Error('HTTP ' + res.status);
417
+ return res.text();
418
+ }).then(function (html) {
419
+ if (gen !== mountGen) return;
420
+ var doc = transformChatHtmlForBlob(html, url, window.__AGENPROTO_EMBED_TOKEN__);
421
+ blobUrl = URL.createObjectURL(new Blob([doc], { type: 'text/html' }));
422
+ var frame = newFrame();
423
+ armBlobBootProbe(frame, url, gen);
424
+ frame.src = blobUrl;
425
+ setMode('embedded');
426
+ });
427
+ }
428
+
429
+ // The blob document's shim posts a boot ack as its first statement. No ack
430
+ // within the settle window means the host refused the blob frame or its
431
+ // inherited CSP killed the document's inline scripts \u2014 surface that through
432
+ // the direct-frame path (whose own probe ends on the launcher card) rather
433
+ // than leaving a silent blank.
434
+ window.addEventListener('message', function (evt) {
435
+ var d = evt.data;
436
+ if (!d || typeof d !== 'object' || d.type !== ${JSON.stringify(BLOB_BOOT_MESSAGE_TYPE)}) return;
437
+ var frame = document.getElementById('chat');
438
+ if (!frame || evt.source !== frame.contentWindow) return;
439
+ blobBootOk = true;
440
+ if (blobBootTimer) { clearTimeout(blobBootTimer); blobBootTimer = null; }
441
+ });
442
+
443
+ function armBlobBootProbe(frame, url, gen) {
444
+ blobBootOk = false;
445
+ blobBootTimer = setTimeout(function () {
446
+ blobBootTimer = null;
447
+ if (gen !== mountGen || blobBootOk) return;
448
+ console.warn('[session-chat] blob document never booted (host CSP?), falling back to a direct frame');
449
+ revokeBlob();
450
+ frame.remove();
451
+ mountDirect(url);
452
+ }, 5000);
453
+ }
454
+
455
+ function showNotInstalled() {
456
+ var old = document.getElementById('chat');
457
+ if (old) old.remove();
458
+ revokeBlob();
459
+ setMode('');
460
+ mountedUrl = null;
461
+ document.getElementById('card').style.display = 'none';
462
+ document.getElementById('notice').className = 'show';
463
+ document.getElementById('link').textContent = 'app not installed';
464
+ }
465
+
466
+ // The body of an ext-apps tool-result notification, whichever wrapping
467
+ // shape the host uses (params IS the CallToolResult, or nests it under
468
+ // params.result). null for error results / non-JSON text.
469
+ function parseToolResultBody(params) {
470
+ if (!params || typeof params !== 'object') return null;
471
+ var res = (params.result && typeof params.result === 'object') ? params.result : params;
472
+ if (res.isError) return null;
473
+ var content = Array.isArray(res.content) ? res.content : [];
474
+ var item = content[0];
475
+ if (!item || item.type !== 'text' || typeof item.text !== 'string') return null;
476
+ try { return JSON.parse(item.text); } catch (_) { return null; }
477
+ }
478
+
479
+ // INLINED COPY of live-session/logic.ts extractToolResultSessionId \u2014 keep
480
+ // in sync. \`sessionId\` (an agentproto_session_chat / live_session result)
481
+ // wins over \`id\` (an agent_start result: the spawned session descriptor).
482
+ function extractToolResultSessionId(params) {
483
+ var body = parseToolResultBody(params);
484
+ if (!body) return null;
485
+ if (typeof body.sessionId === 'string' && body.sessionId) return body.sessionId;
486
+ if (typeof body.id === 'string' && body.id) return body.id;
487
+ return null;
488
+ }
489
+
490
+ // \u2500\u2500 Embed-token refresh \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
491
+ // The token baked into this page by registerMcpApps dies with the daemon
492
+ // boot that minted it (runtime embed-tokens.ts), but hosts cache the
493
+ // rendered widget: Claude Desktop keeps a conversation's srcdoc, so after
494
+ // any daemon restart the cached page replays a dead token and every daemon
495
+ // call 403s \u2014 the blob fetch fails, the direct frame is refused, and the
496
+ // user is left on the launcher card forever. Every tool result carries a
497
+ // live token (SessionChatOutput.embedToken), so adopt it before mounting.
498
+ //
499
+ // Only a render that WAS baked refreshes. A standalone tab or VS Code
500
+ // HTTP-iframe panel still holds the literal placeholder and passes the
501
+ // daemon's origin checks on its own; handing it a token would switch it
502
+ // onto the blob path for no reason.
503
+ function adoptEmbedToken(body) {
504
+ var cur = window.__AGENPROTO_EMBED_TOKEN__;
505
+ if (!cur || cur === '__AGENPROTO_EMBED_TOKEN__') return;
506
+ if (!body || typeof body.embedToken !== 'string' || !body.embedToken) return;
507
+ window.__AGENPROTO_EMBED_TOKEN__ = body.embedToken;
508
+ }
509
+
510
+ // Turn a session id into the installed app's deep link over the bridge.
511
+ function resolveSession(sessionId) {
512
+ noteSession(sessionId);
513
+ return callTool('agentproto_session_chat', sessionId ? { sessionId: sessionId } : {})
514
+ .then(function(out) {
515
+ adoptEmbedToken(out);
516
+ if (out && out.installed && typeof out.url === 'string' && out.url) mount(out.url);
517
+ else showNotInstalled();
518
+ })
519
+ .catch(function(err) {
520
+ document.getElementById('link').textContent = 'bridge error: ' + (err && err.message ? err.message : String(err));
521
+ });
522
+ }
523
+
524
+ // \u2500\u2500 Launcher card (the frame-blocked fallback UI) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
525
+ // The iframe mounts OVER the card. When the host's own CSP refuses the
526
+ // frame (Claude Desktop / Codex widget frames run frame-src 'self' blob:
527
+ // data: and do not yet merge csp.frameDomains), the frame stays on a
528
+ // same-origin about:blank \u2014 readable, unlike the loaded cross-origin chat \u2014
529
+ // and is removed after a settle window so the card becomes the interactive
530
+ // surface.
531
+ //
532
+ // The anchor carries target="_blank" rel="noreferrer" as the fallback path,
533
+ // but that is a plain no-op in hosts that sandbox the widget iframe without
534
+ // allow-popups (observed in Claude Desktop's side chat) \u2014 a normal click
535
+ // on such a host does nothing. Where the host advertises the capability
536
+ // (McpUiInitializeResult.hostCapabilities.openLinks in the ext-apps spec,
537
+ // captured by the bridge's getHostCapabilities()), route through the
538
+ // host-mediated ui/open-link request instead, which is not subject to the
539
+ // iframe's popup sandboxing.
540
+ cardOpenEl.addEventListener('click', function (evt) {
541
+ if (!cardUrl) { evt.preventDefault(); return; }
542
+ if (getHostCapabilities() && getHostCapabilities().openLinks) {
543
+ evt.preventDefault();
544
+ openLink(cardUrl).catch(function () { window.open(cardUrl, '_blank'); });
545
+ }
546
+ });
547
+
548
+ function noteSession(id) {
549
+ if (id && cardSessionEl) cardSessionEl.textContent = id;
550
+ }
551
+
552
+ function setCardUrl(u) {
553
+ if (!u) return;
554
+ cardUrl = u;
555
+ cardOpenEl.setAttribute('href', u);
556
+ }
557
+
558
+ // A blocked frame never leaves about:blank (same-origin with this page \u2014
559
+ // readable); the loaded chat is cross-origin (the probe throws). A readable
560
+ // frame that is STILL blank when the settle window closes = blocked.
561
+ function isBlank(frame) {
562
+ try { return frame.contentWindow.location.href === 'about:blank'; } catch (_) { return false; }
563
+ }
564
+
565
+ function armBlockProbe(frame) {
566
+ var settle = null;
567
+ function probe() {
568
+ if (settle) { clearTimeout(settle); settle = null; }
569
+ if (!isBlank(frame)) return;
570
+ // Still on about:blank right now \u2014 arm the settle window, but
571
+ // re-check when it closes: a slow (not blocked) load may have landed
572
+ // in the meantime, and only a frame STILL blank after the window gets
573
+ // removed. load firing in between clears this timeout above.
574
+ settle = setTimeout(function () {
575
+ settle = null;
576
+ if (isBlank(frame)) frame.remove();
577
+ }, 2000);
578
+ }
579
+ setTimeout(function () {
580
+ frame.addEventListener('load', probe);
581
+ probe();
582
+ }, 100);
583
+ }
584
+
585
+ // A url baked at render time (a host that re-renders per call with a real
586
+ // initData) mounts on boot \u2014 through the same blob-first path as every
587
+ // other mount, since the same opaque widget context frames it. The
588
+ // pre-rendered #chat frame is replaced by mount()'s own.
589
+ if (mountedUrl) {
590
+ var bootUrl = mountedUrl;
591
+ mountedUrl = null;
592
+ adoptEmbedToken(window.__APP_INIT__);
593
+ mount(bootUrl);
594
+ }
595
+
596
+ // The host pushes the triggering tool call's result (ext-apps
597
+ // ui/notifications/tool-result). For agent_start that result IS the spawned
598
+ // session's descriptor \u2014 pin the widget to THAT session.
599
+ onHostNotification(function(method, params) {
600
+ if (method !== 'ui/notifications/tool-result') return;
601
+ var body = parseToolResultBody(params);
602
+ if (!body) return;
603
+ if (typeof body.url === 'string' && body.url && body.installed !== false) {
604
+ // Adopt now, not at mount time: the token doesn't depend on the bridge.
605
+ adoptEmbedToken(body);
606
+ if (bridged) mount(body.url); else pendingUrl = body.url;
607
+ return;
608
+ }
609
+ if (body.installed === false) {
610
+ if (bridged) showNotInstalled(); else pendingNotInstalled = true;
611
+ return;
612
+ }
613
+ var id = extractToolResultSessionId(params);
614
+ if (!id || id === pinnedSessionId) return;
615
+ pinnedSessionId = id;
616
+ noteSession(id);
617
+ if (bridged) resolveSession(id);
618
+ });
619
+
620
+ initBridge().then(function() {
621
+ bridged = true;
622
+ if (pendingUrl) { mount(pendingUrl); pendingUrl = null; return; }
623
+ if (pendingNotInstalled) { showNotInstalled(); return; }
624
+ if (mountedUrl) return; // rendered with a real url
625
+ var init = window.__APP_INIT__ || {};
626
+ if (init.installed === false) { showNotInstalled(); return; }
627
+ // No url baked in (static ui:// render): resolve over the bridge \u2014 the
628
+ // pinned session when the host named one, else the app's picker.
629
+ return resolveSession(pinnedSessionId);
630
+ }).catch(function(err) {
631
+ document.getElementById('link').textContent = 'bridge error: ' + (err && err.message ? err.message : String(err));
632
+ });
633
+ </script>
31
634
  </body>
32
635
  </html>`;
33
636
  }