@agentproto/apps 0.19.0 → 0.20.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.
@@ -54,6 +54,10 @@ export interface SessionChatOutput {
54
54
  * Desktop) otherwise replay a dead token and 403 forever after a daemon
55
55
  * restart. Absent when the deep link is unavailable anyway. */
56
56
  embedToken?: string;
57
+ /** When NOT installed: the daemon's App Store deep link with the entry
58
+ * pre-selected (absolute, so it works from an MCP host iframe whose own
59
+ * origin is not the daemon's). */
60
+ storeUrl?: string;
57
61
  }
58
62
  export interface SessionChatOps {
59
63
  /** The daemon's own HTTP origin, e.g. "http://127.0.0.1:18790" — the
@@ -75,6 +79,9 @@ export interface SessionChatOps {
75
79
  * packages/vscode/src/commands/sessionView.logic.ts).
76
80
  */
77
81
  export declare function sessionChatAppUrl(httpBaseUrl: string, sessionId?: string): string;
82
+ /** The daemon's App Store (`GET /store`, store plan S6) with this app
83
+ * pre-selected for install. */
84
+ export declare function sessionChatStoreUrl(httpBaseUrl: string): string;
78
85
  /**
79
86
  * Factory: close over the daemon origin + the installed-ness check so
80
87
  * execute() needs nothing beyond the tool input (no registry access inside
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/session-chat/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAa,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,0BAA0B,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AAE7E,OAAO,EAAE,0BAA0B,EAAE,oBAAoB,EAAE,CAAA;AAC3D,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEzE,sEAAsE;AACtE,e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EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEzE,sEAAsE;AACtE,eAAO,MAAM,mBAAmB,0BAA0B,CAAA;AAE1D,eAAO,MAAM,sBAAsB;;iBAQjC,CAAA;AAEF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAA;AAErE,MAAM,WAAW,iBAAiB;IAChC;gDAC4C;IAC5C,SAAS,EAAE,OAAO,CAAA;IAClB,oEAAoE;IACpE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;IAClB;;;;;oEAKgE;IAChE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;uCAEmC;IACnC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B;0DACsD;IACtD,WAAW,EAAE,MAAM,CAAA;IACnB;;6EAEyE;IACzE,sBAAsB,CAAC,EAAE,MAAM,OAAO,CAAA;IACtC;;;+BAG2B;IAC3B,cAAc,CAAC,EAAE,MAAM,MAAM,CAAA;CAC9B;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAMjF;AAED;gCACgC;AAChC,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE/D;AAWD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,cAAc,GAClB,UAAU,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,CAmCjD;AAED,eAAO,MAAM,cAAc,EAAE,SAkC3B,CAAA"}
@@ -60,5 +60,5 @@
60
60
  */
61
61
  import type { SessionChatOutput } from "./index.js";
62
62
  export declare function sessionChatEmbedHtml(initData: Partial<SessionChatOutput>): string;
63
- export declare const SESSION_CHAT_FALLBACK_HTML = "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Session Chat \u2014 not installed</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3}\n#wrap{max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}\nh1{font-size:18px;margin-bottom:12px}\ncode{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}\np{margin:8px 0;color:#8b949e;font-size:13px}\n</style>\n</head>\n<body>\n<div id=\"wrap\">\n <h1>Session Chat is not installed</h1>\n <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;\n it does not bundle the chat UI itself.</p>\n <p>To use it, install the app into this daemon:</p>\n <p><code>agentproto app install @agentik/session-chat</code></p>\n <p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a\n <code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that\n session.</p>\n</div>\n</body>\n</html>";
63
+ export declare const SESSION_CHAT_FALLBACK_HTML = "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Session Chat \u2014 not installed</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3}\n#wrap{max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}\nh1{font-size:18px;margin-bottom:12px}\ncode{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}\np{margin:8px 0;color:#8b949e;font-size:13px}\n</style>\n</head>\n<body>\n<div id=\"wrap\">\n <h1>Session Chat is not installed</h1>\n <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;\n it does not bundle the chat UI itself.</p>\n <p>To use it, install the app into this daemon:</p>\n <p><code>agentproto app install @agentik/session-chat</code></p>\n <p>or open <a href=\"/store?install=%40agentik%2Fsession-chat\">the App Store</a>\n (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>\n <p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a\n <code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that\n session.</p>\n</div>\n</body>\n</html>";
64
64
  //# sourceMappingURL=panel.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"panel.d.ts","sourceRoot":"","sources":["../../src/session-chat/panel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AAIH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAOnD,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,MAAM,CA0XjF;AAED,eAAO,MAAM,0BAA0B,gqCA2B/B,CAAA"}
1
+ {"version":3,"file":"panel.d.ts","sourceRoot":"","sources":["../../src/session-chat/panel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AAIH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAOnD,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAgYjF;AAED,eAAO,MAAM,0BAA0B,m0CA6B/B,CAAA"}
@@ -217,6 +217,7 @@ function escapeAttr(text) {
217
217
  function sessionChatEmbedHtml(initData) {
218
218
  const url = typeof initData.url === "string" && initData.url ? initData.url : null;
219
219
  const notInstalled = initData.installed === false;
220
+ const storeUrl = typeof initData.storeUrl === "string" && initData.storeUrl ? initData.storeUrl : "/store?install=%40agentik%2Fsession-chat";
220
221
  const link = url != null ? `<a href="${escapeAttr(url)}" target="_blank" rel="noreferrer">open in a tab</a>` : notInstalled ? "app not installed" : "connecting\u2026";
221
222
  const iframe = url != null ? `<iframe id="chat" title="Session Chat"></iframe>` : "";
222
223
  return `<!DOCTYPE html>
@@ -259,6 +260,8 @@ html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:
259
260
  it does not bundle the chat UI itself.</p>
260
261
  <p>To use it, install the app into this daemon:</p>
261
262
  <p><code>agentproto app install @agentik/session-chat</code></p>
263
+ <p>or open <a href="${escapeAttr(storeUrl)}" target="_blank" rel="noreferrer">the App Store</a>
264
+ (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>
262
265
  </div></div>
263
266
  <script>
264
267
  window.__APP_INIT__ = ${JSON.stringify(initData)};
@@ -603,6 +606,8 @@ p{margin:8px 0;color:#8b949e;font-size:13px}
603
606
  it does not bundle the chat UI itself.</p>
604
607
  <p>To use it, install the app into this daemon:</p>
605
608
  <p><code>agentproto app install @agentik/session-chat</code></p>
609
+ <p>or open <a href="/store?install=%40agentik%2Fsession-chat">the App Store</a>
610
+ (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>
606
611
  <p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a
607
612
  <code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that
608
613
  session.</p>
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/panel-bridge.ts","../../src/session-chat/blob-embed.ts","../../src/session-chat/panel.ts"],"names":[],"mappings":";;;;;;;AA4FO,SAAS,kBAAkB,OAAA,EAAyB;AACzD,EAAA,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAAA,CAAA;AAwMxF;AAEO,IAAM,0BAAA,GAA6B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAAA","file":"panel.mjs","sourcesContent":["/**\n * Shared MCP Apps client bridge for agentproto panels.\n *\n * One spec-correct copy of the JSON-RPC-over-postMessage bridge that every\n * ui:// panel embeds in its <script> block. Mirrors the behaviour of\n * @agstudio/mcp-apps' mcpAppClientScript() — which we cannot import here:\n * agentproto is a standalone pnpm workspace with no @agstudio/* dependency\n * (same isolation invariant as mcp-apps-adapter.ts).\n *\n * Handshake (MCP Apps ext spec 2026-01-26, ext-apps McpUiInitializeRequest):\n * params REQUIRE `appInfo` (Implementation: {name, version}),\n * `appCapabilities`, and `protocolVersion`. Sending `clientInfo` instead\n * of `appInfo` fails the host's schema validation — hosts either reply\n * with an error or silently drop the request, so the panel's initBridge()\n * promise never resolves and the panel renders blank while every\n * server-side surface (tools, resources) works. That exact bug shipped in\n * 4 copy-pasted bridges; this module is the single corrected source.\n *\n * The script defines, in panel scope:\n * post / rpcRequest / rpcNotify — raw JSON-RPC plumbing\n * onHostNotification(cb) — subscribe to host-pushed\n * notifications (method, params)\n * initBridge() — ui/initialize → ui/notifications/initialized\n * callTool(name, args) — tools/call + JSON text unwrap\n * getHostContext() / onHostContext(cb) — host context (displayMode, theme, …),\n * captured from the initialize result and\n * merged on ui/notifications/host-context-changed\n * requestDisplayMode(mode) — ui/request-display-mode (inline|fullscreen|pip)\n *\n * Display-mode toggle: the bridge also mounts two floating buttons\n * (fullscreen + pip) in the top-right corner of every panel, shown only for\n * the modes the host actually advertises via hostContext.availableDisplayModes.\n * No auto-request: panels stay inline until the user clicks. The buttons\n * themselves are NOT implemented here — `@agentproto/app-client/display-mode`\n * is the one implementation, shared with the `window.McpApp` bridge injected\n * into installed apps (`packages/runtime/src/app-ui-apps.ts`); this module\n * only hands it `getHostContext`/`onHostContext`/`requestDisplayMode`. It\n * also leaves `window.AgentprotoUI.installDisplayMode` defined in the panel,\n * which is what a panel with its own header calls to place the toggle\n * inline instead (see that module's `mountToggle`).\n *\n * Standalone HTTP mode: `GET /apps/:appId/ui` (packages/runtime\n * http-server.ts) serves this exact script with NO postMessage host on the\n * other end of `window.parent` — it's a plain browser tab (or a VS Code\n * *HTTP-iframe* panel), so `window.parent === window` and nothing ever\n * answers `initBridge()`'s `ui/initialize` request, leaving every panel\n * stuck on \"Connecting to bridge…\" forever. `injectStandaloneAppBridge`\n * (app-ui-apps.ts) papers over exactly this for installed apps by injecting\n * `window.McpApp.connect() -> Promise<{callTool, ...}>`, a REST-backed\n * stand-in whose `callTool` POSTs to the sibling `./tool-call` route — but\n * this bridge never consumed `window.McpApp`, so builtin panels (the only\n * consumers of this module) were left hanging regardless.\n *\n * Fixed here by detecting that same standalone shape and short-circuiting\n * both `initBridge()` (resolves locally, no round trip) and `callTool()`\n * (routes through `window.McpApp.connect()` instead of `tools/call` over\n * postMessage). The detection requires BOTH `window.parent === window` (no\n * host to talk to — this is the actual condition standalone mode means) AND\n * `window.McpApp` being present with a `connect` function (the capability\n * this bridge needs from it): `window.McpApp` presence alone was considered\n * and rejected as the sole signal, even though it happens to also hold today\n * — the VS Code webview's `srcdoc` relay (packages/vscode\n * appPanel.ts/appPanelController.ts) answers this bridge's raw postMessage\n * JSON-RPC directly and never defines `window.McpApp` for a builtin panel\n * (only `createUiHtmlCache`'s `injectMcpAppBridge`, used for INSTALLED\n * apps' `ui.path` html, defines it) — but that's an accident of today's\n * wiring, not a guarantee; `window.parent === window` is the direct,\n * load-bearing signal (\"is there anyone to postMessage?\") and doesn't\n * depend on which injector happened to run. There is no host in standalone\n * mode, so `initBridge()` seeds a default `hostContext` of `{displayMode:\n * 'inline', availableDisplayModes: []}` — an empty `availableDisplayModes`\n * is what keeps the display-mode toggle buttons hidden (they only show for\n * modes `hostContext.availableDisplayModes` lists), rather than rendering\n * two buttons with nothing to switch to.\n *\n * The real postMessage-host path (a compliant MCP-Apps host, or the VS Code\n * srcdoc relay) is untouched byte-for-byte: same `rpcRequest`/`rpcNotify`\n * over `window.parent.postMessage`, same handshake, same display-mode\n * plumbing.\n *\n * Asymmetry not fixed here (flagged, not papered over): `window.McpApp`'s\n * `sendMessage`/`updateModelContext` (STANDALONE_REST_BRIDGE_SCRIPT,\n * app-ui-apps.ts) reject with \"no host (standalone mode)\", while\n * `appPanelController.ts`'s `ui/message`/`ui/update-model-context` handlers\n * accept-and-drop (`return {}`). This bridge doesn't currently expose either\n * call, so the difference is latent, but it's the last behavioural delta\n * between the two panel paths and worth a follow-up if this bridge ever\n * grows those methods.\n */\n\nimport { DISPLAY_MODE_SCRIPT_BODY } from \"@agentproto/app-client/display-mode\"\n\nexport function panelBridgeScript(appName: string): string {\n return `// ── MCP Apps bridge (shared: panel-bridge.ts) ──\n// JSON-RPC 2.0 over window.parent.postMessage · spec 2026-01-26\nvar _nextId = 1, _pending = {}, _notifyHandlers = [];\nvar _hostContext = null, _hostContextHandlers = [];\nvar _hostCaps = null;\nvar _standaloneApp = null;\nfunction _isStandalone(){\n return window.parent === window && !!window.McpApp && typeof window.McpApp.connect === 'function';\n}\n// ── Per-boot embed token (runtime embed-tokens.ts) ────────────────────────\n// Panels that iframe the daemon's standalone app host carry this proof so\n// GET /apps/:appId/ui?embed=1&et=... can drop its anti-framing headers for\n// MCP-Apps hosts whose widget context is an opaque origin (Claude Desktop).\n// registerMcpApps replaces the placeholder with a real per-boot token when\n// serving the panel as a resource; every other render (tests, standalone\n// tab, VS Code HTTP-iframe panel — the latter two already pass\n// iframeEmbedAllowed's origin checks) keeps the literal, and\n// withEmbedToken() then degrades to an identity function.\nwindow.__AGENPROTO_EMBED_TOKEN__ = \"__AGENPROTO_EMBED_TOKEN__\";\nfunction withEmbedToken(url){\n var t = window.__AGENPROTO_EMBED_TOKEN__;\n if (!t || t === '__AGENPROTO_EMBED_TOKEN__') return url;\n return url + (url.indexOf('?') >= 0 ? '&' : '?') + 'et=' + encodeURIComponent(t);\n}\nfunction post(msg){ window.parent.postMessage(msg, '*'); }\nfunction getHostContext(){ return _hostContext; }\nfunction getHostCapabilities(){ return _hostCaps; }\nfunction onHostContext(cb){\n _hostContextHandlers.push(cb);\n // Replay the last context so a late subscriber isn't stuck blind.\n if (_hostContext){ try { cb(_hostContext); } catch(_) {} }\n}\nfunction _setHostContext(ctx){\n if (!ctx || typeof ctx !== 'object') return;\n // ui/notifications/host-context-changed carries only the changed keys —\n // merge, matching the official ext-apps App behaviour.\n _hostContext = Object.assign({}, _hostContext || {}, ctx);\n for (var i = 0; i < _hostContextHandlers.length; i++){\n try { _hostContextHandlers[i](_hostContext); } catch(_) {}\n }\n}\nfunction rpcRequest(method, params){\n return new Promise(function(resolve, reject){\n var id = _nextId++;\n _pending[id] = {resolve: resolve, reject: reject};\n post({jsonrpc: '2.0', id: id, method: method, params: params || {}});\n });\n}\nfunction rpcNotify(method, params){ post({jsonrpc: '2.0', method: method, params: params || {}}); }\nfunction onHostNotification(cb){ _notifyHandlers.push(cb); }\nwindow.addEventListener('message', function(evt){\n var msg = evt.data;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') return;\n if (msg.id != null && msg.method == null){\n var p = _pending[msg.id];\n if (!p) return;\n delete _pending[msg.id];\n if (msg.error) p.reject(new Error(msg.error.message || ('rpc error ' + msg.error.code)));\n else p.resolve(msg.result);\n return;\n }\n if (msg.method){\n if (msg.method === 'ui/notifications/host-context-changed'){\n _setHostContext(msg.params || {});\n }\n for (var i = 0; i < _notifyHandlers.length; i++){\n try { _notifyHandlers[i](msg.method, msg.params || {}); } catch(_) {}\n }\n }\n});\nfunction initBridge(){\n if (_isStandalone()){\n return window.McpApp.connect().then(function(conn){\n _standaloneApp = conn;\n // No host to advertise a hostContext — default to inline with no\n // other modes available, which keeps the display-mode toggle buttons\n // hidden (they only show for modes hostContext.availableDisplayModes\n // lists) instead of rendering two buttons with nothing to switch to.\n _setHostContext({displayMode: 'inline', availableDisplayModes: []});\n });\n }\n return rpcRequest('ui/initialize', {\n appInfo: {name: ${JSON.stringify(appName)}, version: '0.1.0'},\n appCapabilities: {availableDisplayModes: ['inline', 'fullscreen', 'pip']},\n protocolVersion: '2026-01-26'\n }).then(function(result){\n // The initialize result carries the initial hostContext (displayMode +\n // availableDisplayModes) — capture it before notifying the host.\n if (result && result.hostContext) _setHostContext(result.hostContext);\n // McpUiInitializeResult.hostCapabilities (ext-apps spec) — e.g. openLinks,\n // \"Host supports opening external URLs\". Captured once, read via\n // getHostCapabilities() by panels that need to branch on it.\n if (result && result.hostCapabilities) _hostCaps = result.hostCapabilities;\n rpcNotify('ui/notifications/initialized', {});\n });\n}\nfunction requestDisplayMode(mode){\n return rpcRequest('ui/request-display-mode', {mode: mode});\n}\nfunction openLink(url){\n if (_standaloneApp && typeof _standaloneApp.openLink === 'function') return _standaloneApp.openLink(url);\n return rpcRequest('ui/open-link', {url: url});\n}\nfunction callTool(name, args){\n var raw = _standaloneApp\n ? _standaloneApp.callTool(name, args || {})\n : rpcRequest('tools/call', {name: name, arguments: args || {}});\n return raw.then(function(result){\n if (result.isError){\n var e = (result.content && result.content[0] && result.content[0].text) || 'tool error';\n throw new Error(e);\n }\n var text = (result.content && result.content[0] && result.content[0].text) || '{}';\n return JSON.parse(text);\n });\n}\n\n// ── Display-mode toggle (shared: @agentproto/app-client/display-mode) ──\n// The installer is inlined verbatim (it is self-contained and idempotent),\n// then handed this panel's own JSON-RPC plumbing. NO auto-request: the\n// panel stays inline until the user clicks, and the buttons only appear for\n// the modes the host advertises in hostContext.availableDisplayModes.\n${DISPLAY_MODE_SCRIPT_BODY}\nvar displayMode = window.AgentprotoUI.installDisplayMode({\n getHostContext: getHostContext,\n onHostContext: onHostContext,\n requestDisplayMode: requestDisplayMode\n});`\n}\n","/**\n * Blob pass-through for the session-chat widget (see ./panel.ts `mountBlob`).\n *\n * Claude Desktop and Codex apply their own CSP to an MCP-Apps widget frame:\n * `frame-src 'self' blob: data:`. Neither merges the resource's declared\n * `_meta.ui.csp.frameDomains` into it (measured 2026-09-18), so a direct\n * `<iframe src=\"http://127.0.0.1:18790/apps/@agentik/session-chat/ui?…\">` is\n * refused host-side before the request ever reaches the daemon. `blob:` IS\n * on that list — so the panel fetches the chat html itself (a fetch, not a\n * frame navigation; the per-boot `?et=` embed token gets it through the\n * daemon's origin gates and PNA preflight), rewrites it with the function\n * below, and mounts the result as a `blob:` document.\n *\n * What the rewrite has to fix, given that the document no longer lives on\n * the daemon origin:\n *\n * 1. `<base href=\"<deep link>\">` right after `<head>`, so every relative\n * url in the app (the injected standalone bridge's `./tool-call`, any\n * relative asset) resolves exactly as it would have on the daemon.\n * NOTE: the base is the document url itself (`…/session-chat/ui?…`),\n * not `…/ui/` — a trailing slash would add a path segment and make\n * `./tool-call` resolve to `…/ui/tool-call`, which routes nowhere.\n * 2. The blob document's origin is opaque (Claude's widget context is a\n * sandboxed frame; the blob inherits that) — every daemon request it\n * makes carries `Origin: null`, which the daemon's browser gates\n * (`guardBrowserOrigin`, `authorizeMcp`, `checkSessionsToken`) refuse\n * unless the request ALSO carries the embed token. The chat UI talks to\n * the daemon with absolute urls (`${DAEMON_URL}/mcp`, `/sessions/*`,\n * its SSE stream via `fetch`, `/sessions/:id/chat`) that we don't\n * control, so a small shim is injected ahead of every app script: it\n * wraps `window.fetch` / `window.EventSource` to append `et=` to any\n * request aimed at the daemon origin, and points\n * `window.__AGENTPROTO_BASEURL__` at the daemon origin the deep link\n * names (so a non-default port works too).\n * 3. The standalone bridge's `fetch(\"./tool-call\"` (runtime\n * app-ui-apps.ts `STANDALONE_REST_BRIDGE_SCRIPT`) is additionally\n * rewritten to the absolute tokened url — belt and braces on top of\n * the shim, and the one rewrite that is exact-string-testable.\n * 4. The shim's FIRST statement posts `{ type: \"agentproto-blob-boot\" }`\n * to its parent. A blob document inherits its creator's CSP, so if the\n * host's widget CSP ever kills inline scripts, that ack never arrives\n * and the panel tears the blob down and falls back to the direct frame\n * + launcher card (panel.ts `armBlobBootProbe`) instead of leaving a\n * silent blank. No CSP `<meta>` is added to the blob html: the\n * creator's CSP wins regardless, it would only be noise.\n *\n * Shipped as a JS string (same shape as ../panel-bridge.ts) so the panel\n * page embeds the exact code the test evaluates — no TS twin to drift from.\n */\n\n/** `postMessage` type the injected shim sends its parent on boot. */\nexport const BLOB_BOOT_MESSAGE_TYPE = \"agentproto-blob-boot\"\n\nexport function blobEmbedScript(): string {\n return `// ── Blob pass-through transform (shared: session-chat/blob-embed.ts) ──\nfunction _blobEscapeAttr(s){ return String(s).replace(/&/g, '&amp;').replace(/\"/g, '&quot;'); }\n// Rewrite the fetched chat html so it works as a blob: document: <base> on\n// the deep link, a fetch/EventSource shim that carries the embed token to\n// the daemon origin, and the standalone bridge's ./tool-call made absolute.\nfunction transformChatHtmlForBlob(html, url, token){\n var origin = new URL(url).origin;\n var tc = new URL('./tool-call', url);\n tc.searchParams.set('et', token);\n // The app-visible query for the blob doc: the deep link's search minus the\n // embed token (the token must not ride the app's visible params). The\n // blob document's own location has no params, so this is the ONLY channel\n // for ?session= / ?embed=1 — the app reads it via bootSearchParams().\n var bootUrl = new URL(url);\n bootUrl.searchParams.delete('et');\n var bootQuery = bootUrl.search;\n var shim = '<script>(function(){'\n + 'try { window.parent.postMessage({ type: ${JSON.stringify(BLOB_BOOT_MESSAGE_TYPE)} }, \"*\"); } catch (_) {}'\n + 'var ORIGIN = ' + JSON.stringify(origin) + ', TOKEN = ' + JSON.stringify(token) + ';'\n + 'window.__AGENTPROTO_BASEURL__ = ORIGIN;'\n + 'var _h = window.history, _rs = _h.replaceState.bind(_h), _ps = _h.pushState.bind(_h);'\n + 'function _sameOrLoc(u){'\n + 'try {'\n + 'var x = new URL(u == null ? window.location.href : u, document.baseURI);'\n + 'return x.origin === window.location.origin ? u : window.location.href;'\n + '} catch (_) { return window.location.href; }'\n + '}'\n + '_h.replaceState = function(s, t, u){'\n + 'try { _rs(s, t, _sameOrLoc(u)); } catch (_) { try { _rs(s, t, window.location.href); } catch (_) {} }'\n + '};'\n + '_h.pushState = function(s, t, u){'\n + 'try { _ps(s, t, _sameOrLoc(u)); } catch (_) { try { _ps(s, t, window.location.href); } catch (_) {} }'\n + '};'\n + 'window.__AGENTPROTO_BOOT_QUERY__ = ' + JSON.stringify(bootQuery) + ';'\n + 'function withEt(u){'\n + 'try {'\n + 'var x = new URL(String(u), document.baseURI);'\n + 'if (x.origin !== ORIGIN) return null;'\n + 'if (!x.searchParams.has(\"et\")) x.searchParams.set(\"et\", TOKEN);'\n + 'return x.href;'\n + '} catch (_) { return null; }'\n + '}'\n + 'var _fetch = window.fetch;'\n + 'if (typeof _fetch === \"function\") {'\n + 'window.fetch = function(input, init){'\n + 'var r;'\n + 'if (typeof Request !== \"undefined\" && input instanceof Request) {'\n + 'r = withEt(input.url);'\n + 'if (r) { try { input = new Request(r, input); } catch (_) {} }'\n + '} else {'\n + 'r = withEt(input);'\n + 'if (r) input = r;'\n + '}'\n + 'return _fetch.call(window, input, init);'\n + '};'\n + '}'\n + 'var _ES = window.EventSource;'\n + 'if (typeof _ES === \"function\") {'\n + 'window.EventSource = function(u, cfg){ return new _ES(withEt(u) || u, cfg); };'\n + 'window.EventSource.prototype = _ES.prototype;'\n + '}'\n + '})();<\\\\/script>';\n var head = '<base href=\"' + _blobEscapeAttr(url) + '\">' + shim;\n var m = html.match(/<head[^>]*>/i);\n var out = m\n ? html.slice(0, m.index + m[0].length) + head + html.slice(m.index + m[0].length)\n : head + html;\n return out.split('fetch(\"./tool-call\"').join('fetch(' + JSON.stringify(tc.href));\n}`\n}\n","/**\n * HTML bundles for the session-chat builtin widget — the thin bridge page\n * (`sessionChatEmbedHtml`) and the not-installed notice\n * (`SESSION_CHAT_FALLBACK_HTML`) served as the\n * `ui://agentproto_session_chat/view` resource by `registerMcpApps` (see\n * ../mcp-app-types.ts and runtime's mcp-apps-adapter.ts). Mounted via the\n * `agentproto_session_chat` tool defined in ./index.ts, AND bound to\n * `agent_start` (runtime agent-tools.ts `_meta.ui.resourceUri`) so a launch\n * card opens the chat of the session it just spawned.\n *\n * Deliberately NOT a chat UI reimplementation: the real chat lives in the\n * installed `@agentik/session-chat` app, served by the daemon's standalone\n * app host at `GET /apps/@agentik/session-chat/ui`. When the app is\n * installed, this page is a full-viewport iframe of that URL deep-linked\n * with `?session=<id>&embed=1` — the exact spelling the daemon's standalone\n * route relaxes its `frame-ancestors 'none'` for (see runtime\n * http-server.ts handleAppUiPage) and the VS Code chat-panel webview\n * already uses. No second chat bundle exists anywhere in agentproto/ts.\n *\n * Self-bootstrapping (same pattern as live-session/panel.ts): the static\n * ui:// resource is rendered ONCE at server-registration time with EMPTY\n * initData (mcp-apps-adapter.ts registerMcpApps), so the deep link can't\n * be baked in. The page resolves it at runtime, in priority order:\n * 1. `initData.url` when the html was rendered with a real tool output\n * (tests, and any host that re-renders per call) — iframe is inline.\n * 2. The host's `ui/notifications/tool-result` push of the tool call that\n * mounted the widget. An `agent_start` result IS the spawned session's\n * descriptor (`{ id: \"sess_…\", … }`) → the widget calls\n * `agentproto_session_chat({ sessionId })` over the bridge to turn that\n * id into the deep link; an `agentproto_session_chat` result already\n * carries `{ installed, url }` and mounts directly.\n * 3. Otherwise (opened bare from the catalog) `agentproto_session_chat({})`\n * → the app's session picker.\n * Both orders of (2) vs. bridge init are handled: a result that lands\n * before `initBridge()` resolves is held and applied once it does.\n *\n * Mount order (see `mount()` below):\n * 1. Blob pass-through, when a per-boot embed token is baked in (i.e. an\n * MCP-Apps host rendered this resource): fetch the chat html with the\n * token, rewrite it (./blob-embed.ts `transformChatHtmlForBlob`) and\n * mount it as a `blob:` document. Claude Desktop / Codex widget frames\n * run `frame-src 'self' blob: data:` and do not merge our declared\n * `csp.frameDomains`, so a direct daemon iframe is refused host-side —\n * `blob:` is the pass-through. The blob document must post a boot ack\n * within a settle window (`armBlobBootProbe`); a missing ack (host CSP\n * killed its inline scripts, or refused the blob frame) tears it down\n * and falls through to 2.\n * 2. Direct-src iframe of the deep link (VS Code HTTP-iframe panels, a\n * standalone tab — no token, and their origin already passes the\n * daemon's checks; or the blob path's fallback). If the host refuses\n * the frame, `armBlockProbe` removes it and the launcher card becomes\n * the interactive surface.\n *\n * A persistent header with the deep link stays visible above the iframe, so\n * if the frame is refused (older daemon without the embed relaxation, or a\n * host whose own CSP blocks daemon frames) the user still has a one-click\n * path to the chat in a tab. When the app is NOT installed the page is a\n * small readable notice pointing at `agentproto app install` — the\n * fallback branch, never a vendored UI.\n */\n\nimport { panelBridgeScript } from \"../panel-bridge.js\"\nimport { BLOB_BOOT_MESSAGE_TYPE, blobEmbedScript } from \"./blob-embed.js\"\nimport type { SessionChatOutput } from \"./index.js\"\n\n/** Only `&` and `\"` are significant inside a double-quoted attribute value. */\nfunction escapeAttr(text: string): string {\n return text.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\")\n}\n\nexport function sessionChatEmbedHtml(initData: Partial<SessionChatOutput>): string {\n const url = typeof initData.url === \"string\" && initData.url ? initData.url : null\n const notInstalled = initData.installed === false\n const link =\n url != null\n ? `<a href=\"${escapeAttr(url)}\" target=\"_blank\" rel=\"noreferrer\">open in a tab</a>`\n : notInstalled\n ? \"app not installed\"\n : \"connecting…\"\n const iframe =\n url != null\n // No inline src: the url mounts through the bridge script below, via\n // withEmbedToken(), so the frame never loads without the per-boot\n // embed proof — whichever render path (static resource or a host\n // re-render with a real initData) produced it.\n ? `<iframe id=\"chat\" title=\"Session Chat\"></iframe>`\n : \"\"\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Session Chat</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3;overflow:hidden}\n#bar{padding:6px 12px;font-size:12px;color:#8b949e;background:#161b22;border-bottom:1px solid #30363d}\n#bar a{color:#58a6ff}\n#mode{color:#6e7681}\n#stage{position:relative;height:calc(100% - 29px)}\n#chat{position:absolute;inset:0;z-index:2;border:0;display:block;width:100%;height:100%}\n#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}\n#card h2{font-size:15px;font-weight:600}\n#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}\n#card p{font-size:12px;color:#8b949e;max-width:420px;line-height:1.5}\n#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}\n#card a:hover{border-color:#58a6ff}\n#notice{display:none;max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}\n#notice.show{display:block}\n#notice h1{font-size:18px;margin-bottom:12px}\n#notice code{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}\n#notice p{margin:8px 0;color:#8b949e;font-size:13px}\n</style>\n</head>\n<body>\n<div id=\"bar\">Session Chat &#183; <span id=\"link\">${link}</span><span id=\"mode\"></span></div>\n<div id=\"stage\">${iframe}<div id=\"card\">\n <h2>Session Chat</h2>\n <div id=\"card-session\" class=\"sid\">&#8212;</div>\n <p>Full embed isn't supported by this host &#8212; the chat opens in a browser tab.</p>\n <a id=\"card-open\" href=\"#\" target=\"_blank\" rel=\"noreferrer\">Open chat</a>\n</div><div id=\"notice\"${notInstalled ? ' class=\"show\"' : \"\"}>\n <h1>Session Chat is not installed</h1>\n <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;\n it does not bundle the chat UI itself.</p>\n <p>To use it, install the app into this daemon:</p>\n <p><code>agentproto app install @agentik/session-chat</code></p>\n</div></div>\n<script>\nwindow.__APP_INIT__ = ${JSON.stringify(initData)};\n\n${panelBridgeScript(\"agentproto-session-chat\")}\n\n${blobEmbedScript()}\n\n// ── Session-chat launcher logic ──────────────────────────────────────────\nvar mountedUrl = (window.__APP_INIT__ && window.__APP_INIT__.url) || null;\nvar pinnedSessionId = null; // session named by the host's tool-result push\nvar pendingUrl = null; // url pushed by the host before the bridge was up\nvar pendingNotInstalled = false;\nvar bridged = false;\nvar cardUrl = null; // deep link once resolved (drives the card button)\nvar cardSessionEl = document.getElementById('card-session');\nvar cardOpenEl = document.getElementById('card-open');\nvar mountGen = 0; // bumps per mount(); async work checks it before touching the DOM\nvar blobUrl = null; // live object url of the blob-mounted chat, if any\nvar blobBootTimer = null;\nvar blobBootOk = false;\n\nfunction escapeHtml(text) {\n return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\"/g, '&quot;');\n}\n\nfunction setMode(text) {\n document.getElementById('mode').textContent = text ? ' \\\\u00b7 ' + text : '';\n // The chat app is live inside the frame — the launcher bar (title, deep\n // link, mount mode) is noise on top of the real surface. Hide it and let\n // the frame own the full height. Only a failed mount (launcher card /\n // not-installed notice) shows the bar again.\n var bar = document.getElementById('bar');\n var stage = document.getElementById('stage');\n if (bar && stage) {\n bar.style.display = text ? 'none' : '';\n stage.style.height = text ? '100%' : 'calc(100% - 29px)';\n }\n}\n\n// One fresh #chat frame on the stage (over the card), the previous one gone.\nfunction newFrame() {\n var stage = document.getElementById('stage');\n var old = document.getElementById('chat');\n if (old) old.remove();\n var frame = document.createElement('iframe');\n frame.id = 'chat';\n frame.title = 'Session Chat';\n stage.insertBefore(frame, stage.firstChild);\n return frame;\n}\n\nfunction revokeBlob() {\n if (blobBootTimer) { clearTimeout(blobBootTimer); blobBootTimer = null; }\n if (blobUrl) {\n try { URL.revokeObjectURL(blobUrl); } catch (_) {}\n blobUrl = null;\n }\n}\n\nfunction mount(url) {\n if (!url || url === mountedUrl) return;\n mountedUrl = url;\n var gen = ++mountGen;\n revokeBlob();\n document.getElementById('notice').className = '';\n setCardUrl(url);\n document.getElementById('link').innerHTML =\n '<a href=\"' + escapeHtml(url) + '\" target=\"_blank\" rel=\"noreferrer\">open in a tab</a>';\n var tokened = withEmbedToken(url);\n if (tokened === url) {\n // No per-boot token baked in (standalone tab, VS Code HTTP-iframe panel):\n // the direct frame already passes the daemon's origin checks, and the\n // blob path's daemon calls would have nothing to carry — skip it.\n mountDirect(url);\n return;\n }\n mountBlob(url, tokened, gen).catch(function (err) {\n if (gen !== mountGen) return;\n // The fetch itself was refused (host connect-src not merging our\n // connectDomains, PNA, daemon down, …) — probe answered: no blob path.\n console.warn('[session-chat] blob mount failed, falling back to a direct frame:',\n err && err.message ? err.message : String(err));\n mountDirect(url);\n });\n}\n\n// Direct-src iframe of the deep link, with the block probe → launcher card\n// fallback. The terminal mount path when the blob one is unavailable.\nfunction mountDirect(url) {\n var frame = newFrame();\n frame.src = withEmbedToken(url);\n setMode('direct frame');\n armBlockProbe(frame);\n}\n\n// Blob pass-through: fetch the chat html through the embed token, rewrite it\n// for life as a blob: document (transformChatHtmlForBlob, blob-embed.ts) and\n// mount it — blob: passes a host frame-src that refuses the daemon origin.\nfunction mountBlob(url, tokened, gen) {\n return fetch(tokened, { credentials: 'omit' }).then(function (res) {\n if (!res.ok) throw new Error('HTTP ' + res.status);\n return res.text();\n }).then(function (html) {\n if (gen !== mountGen) return;\n var doc = transformChatHtmlForBlob(html, url, window.__AGENPROTO_EMBED_TOKEN__);\n blobUrl = URL.createObjectURL(new Blob([doc], { type: 'text/html' }));\n var frame = newFrame();\n armBlobBootProbe(frame, url, gen);\n frame.src = blobUrl;\n setMode('embedded');\n });\n}\n\n// The blob document's shim posts a boot ack as its first statement. No ack\n// within the settle window means the host refused the blob frame or its\n// inherited CSP killed the document's inline scripts — surface that through\n// the direct-frame path (whose own probe ends on the launcher card) rather\n// than leaving a silent blank.\nwindow.addEventListener('message', function (evt) {\n var d = evt.data;\n if (!d || typeof d !== 'object' || d.type !== ${JSON.stringify(BLOB_BOOT_MESSAGE_TYPE)}) return;\n var frame = document.getElementById('chat');\n if (!frame || evt.source !== frame.contentWindow) return;\n blobBootOk = true;\n if (blobBootTimer) { clearTimeout(blobBootTimer); blobBootTimer = null; }\n});\n\nfunction armBlobBootProbe(frame, url, gen) {\n blobBootOk = false;\n blobBootTimer = setTimeout(function () {\n blobBootTimer = null;\n if (gen !== mountGen || blobBootOk) return;\n console.warn('[session-chat] blob document never booted (host CSP?), falling back to a direct frame');\n revokeBlob();\n frame.remove();\n mountDirect(url);\n }, 5000);\n}\n\nfunction showNotInstalled() {\n var old = document.getElementById('chat');\n if (old) old.remove();\n revokeBlob();\n setMode('');\n mountedUrl = null;\n document.getElementById('card').style.display = 'none';\n document.getElementById('notice').className = 'show';\n document.getElementById('link').textContent = 'app not installed';\n}\n\n// The body of an ext-apps tool-result notification, whichever wrapping\n// shape the host uses (params IS the CallToolResult, or nests it under\n// params.result). null for error results / non-JSON text.\nfunction parseToolResultBody(params) {\n if (!params || typeof params !== 'object') return null;\n var res = (params.result && typeof params.result === 'object') ? params.result : params;\n if (res.isError) return null;\n var content = Array.isArray(res.content) ? res.content : [];\n var item = content[0];\n if (!item || item.type !== 'text' || typeof item.text !== 'string') return null;\n try { return JSON.parse(item.text); } catch (_) { return null; }\n}\n\n// INLINED COPY of live-session/logic.ts extractToolResultSessionId — keep\n// in sync. \\`sessionId\\` (an agentproto_session_chat / live_session result)\n// wins over \\`id\\` (an agent_start result: the spawned session descriptor).\nfunction extractToolResultSessionId(params) {\n var body = parseToolResultBody(params);\n if (!body) return null;\n if (typeof body.sessionId === 'string' && body.sessionId) return body.sessionId;\n if (typeof body.id === 'string' && body.id) return body.id;\n return null;\n}\n\n// ── Embed-token refresh ──────────────────────────────────────────────────\n// The token baked into this page by registerMcpApps dies with the daemon\n// boot that minted it (runtime embed-tokens.ts), but hosts cache the\n// rendered widget: Claude Desktop keeps a conversation's srcdoc, so after\n// any daemon restart the cached page replays a dead token and every daemon\n// call 403s — the blob fetch fails, the direct frame is refused, and the\n// user is left on the launcher card forever. Every tool result carries a\n// live token (SessionChatOutput.embedToken), so adopt it before mounting.\n//\n// Only a render that WAS baked refreshes. A standalone tab or VS Code\n// HTTP-iframe panel still holds the literal placeholder and passes the\n// daemon's origin checks on its own; handing it a token would switch it\n// onto the blob path for no reason.\nfunction adoptEmbedToken(body) {\n var cur = window.__AGENPROTO_EMBED_TOKEN__;\n if (!cur || cur === '__AGENPROTO_EMBED_TOKEN__') return;\n if (!body || typeof body.embedToken !== 'string' || !body.embedToken) return;\n window.__AGENPROTO_EMBED_TOKEN__ = body.embedToken;\n}\n\n// Turn a session id into the installed app's deep link over the bridge.\nfunction resolveSession(sessionId) {\n noteSession(sessionId);\n return callTool('agentproto_session_chat', sessionId ? { sessionId: sessionId } : {})\n .then(function(out) {\n adoptEmbedToken(out);\n if (out && out.installed && typeof out.url === 'string' && out.url) mount(out.url);\n else showNotInstalled();\n })\n .catch(function(err) {\n document.getElementById('link').textContent = 'bridge error: ' + (err && err.message ? err.message : String(err));\n });\n}\n\n// ── Launcher card (the frame-blocked fallback UI) ────────────────────────\n// The iframe mounts OVER the card. When the host's own CSP refuses the\n// frame (Claude Desktop / Codex widget frames run frame-src 'self' blob:\n// data: and do not yet merge csp.frameDomains), the frame stays on a\n// same-origin about:blank — readable, unlike the loaded cross-origin chat —\n// and is removed after a settle window so the card becomes the interactive\n// surface.\n//\n// The anchor carries target=\"_blank\" rel=\"noreferrer\" as the fallback path,\n// but that is a plain no-op in hosts that sandbox the widget iframe without\n// allow-popups (observed in Claude Desktop's side chat) — a normal click\n// on such a host does nothing. Where the host advertises the capability\n// (McpUiInitializeResult.hostCapabilities.openLinks in the ext-apps spec,\n// captured by the bridge's getHostCapabilities()), route through the\n// host-mediated ui/open-link request instead, which is not subject to the\n// iframe's popup sandboxing.\ncardOpenEl.addEventListener('click', function (evt) {\n if (!cardUrl) { evt.preventDefault(); return; }\n if (getHostCapabilities() && getHostCapabilities().openLinks) {\n evt.preventDefault();\n openLink(cardUrl).catch(function () { window.open(cardUrl, '_blank'); });\n }\n});\n\nfunction noteSession(id) {\n if (id && cardSessionEl) cardSessionEl.textContent = id;\n}\n\nfunction setCardUrl(u) {\n if (!u) return;\n cardUrl = u;\n cardOpenEl.setAttribute('href', u);\n}\n\n// A blocked frame never leaves about:blank (same-origin with this page —\n// readable); the loaded chat is cross-origin (the probe throws). A readable\n// frame that is STILL blank when the settle window closes = blocked.\nfunction isBlank(frame) {\n try { return frame.contentWindow.location.href === 'about:blank'; } catch (_) { return false; }\n}\n\nfunction armBlockProbe(frame) {\n var settle = null;\n function probe() {\n if (settle) { clearTimeout(settle); settle = null; }\n if (!isBlank(frame)) return;\n // Still on about:blank right now — arm the settle window, but\n // re-check when it closes: a slow (not blocked) load may have landed\n // in the meantime, and only a frame STILL blank after the window gets\n // removed. load firing in between clears this timeout above.\n settle = setTimeout(function () {\n settle = null;\n if (isBlank(frame)) frame.remove();\n }, 2000);\n }\n setTimeout(function () {\n frame.addEventListener('load', probe);\n probe();\n }, 100);\n}\n\n// A url baked at render time (a host that re-renders per call with a real\n// initData) mounts on boot — through the same blob-first path as every\n// other mount, since the same opaque widget context frames it. The\n// pre-rendered #chat frame is replaced by mount()'s own.\nif (mountedUrl) {\n var bootUrl = mountedUrl;\n mountedUrl = null;\n adoptEmbedToken(window.__APP_INIT__);\n mount(bootUrl);\n}\n\n// The host pushes the triggering tool call's result (ext-apps\n// ui/notifications/tool-result). For agent_start that result IS the spawned\n// session's descriptor — pin the widget to THAT session.\nonHostNotification(function(method, params) {\n if (method !== 'ui/notifications/tool-result') return;\n var body = parseToolResultBody(params);\n if (!body) return;\n if (typeof body.url === 'string' && body.url && body.installed !== false) {\n // Adopt now, not at mount time: the token doesn't depend on the bridge.\n adoptEmbedToken(body);\n if (bridged) mount(body.url); else pendingUrl = body.url;\n return;\n }\n if (body.installed === false) {\n if (bridged) showNotInstalled(); else pendingNotInstalled = true;\n return;\n }\n var id = extractToolResultSessionId(params);\n if (!id || id === pinnedSessionId) return;\n pinnedSessionId = id;\n noteSession(id);\n if (bridged) resolveSession(id);\n});\n\ninitBridge().then(function() {\n bridged = true;\n if (pendingUrl) { mount(pendingUrl); pendingUrl = null; return; }\n if (pendingNotInstalled) { showNotInstalled(); return; }\n if (mountedUrl) return; // rendered with a real url\n var init = window.__APP_INIT__ || {};\n if (init.installed === false) { showNotInstalled(); return; }\n // No url baked in (static ui:// render): resolve over the bridge — the\n // pinned session when the host named one, else the app's picker.\n return resolveSession(pinnedSessionId);\n}).catch(function(err) {\n document.getElementById('link').textContent = 'bridge error: ' + (err && err.message ? err.message : String(err));\n});\n</script>\n</body>\n</html>`\n}\n\nexport const SESSION_CHAT_FALLBACK_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Session Chat — not installed</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3}\n#wrap{max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}\nh1{font-size:18px;margin-bottom:12px}\ncode{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}\np{margin:8px 0;color:#8b949e;font-size:13px}\n</style>\n</head>\n<body>\n<div id=\"wrap\">\n <h1>Session Chat is not installed</h1>\n <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;\n it does not bundle the chat UI itself.</p>\n <p>To use it, install the app into this daemon:</p>\n <p><code>agentproto app install @agentik/session-chat</code></p>\n <p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a\n <code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that\n session.</p>\n</div>\n</body>\n</html>`\n"]}
1
+ {"version":3,"sources":["../../src/panel-bridge.ts","../../src/session-chat/blob-embed.ts","../../src/session-chat/panel.ts"],"names":[],"mappings":";;;;;;;AA4FO,SAAS,kBAAkB,OAAA,EAAyB;AACzD,EAAA,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAA,EAkFa,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwC3C,wBAAwB;AAAA;AAAA;AAAA;AAAA;AAAA,GAAA,CAAA;AAM1B;;;AC1KO,IAAM,sBAAA,GAAyB,sBAAA;AAE/B,SAAS,eAAA,GAA0B;A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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAAA","file":"panel.mjs","sourcesContent":["/**\n * Shared MCP Apps client bridge for agentproto panels.\n *\n * One spec-correct copy of the JSON-RPC-over-postMessage bridge that every\n * ui:// panel embeds in its <script> block. Mirrors the behaviour of\n * @agstudio/mcp-apps' mcpAppClientScript() — which we cannot import here:\n * agentproto is a standalone pnpm workspace with no @agstudio/* dependency\n * (same isolation invariant as mcp-apps-adapter.ts).\n *\n * Handshake (MCP Apps ext spec 2026-01-26, ext-apps McpUiInitializeRequest):\n * params REQUIRE `appInfo` (Implementation: {name, version}),\n * `appCapabilities`, and `protocolVersion`. Sending `clientInfo` instead\n * of `appInfo` fails the host's schema validation — hosts either reply\n * with an error or silently drop the request, so the panel's initBridge()\n * promise never resolves and the panel renders blank while every\n * server-side surface (tools, resources) works. That exact bug shipped in\n * 4 copy-pasted bridges; this module is the single corrected source.\n *\n * The script defines, in panel scope:\n * post / rpcRequest / rpcNotify — raw JSON-RPC plumbing\n * onHostNotification(cb) — subscribe to host-pushed\n * notifications (method, params)\n * initBridge() — ui/initialize → ui/notifications/initialized\n * callTool(name, args) — tools/call + JSON text unwrap\n * getHostContext() / onHostContext(cb) — host context (displayMode, theme, …),\n * captured from the initialize result and\n * merged on ui/notifications/host-context-changed\n * requestDisplayMode(mode) — ui/request-display-mode (inline|fullscreen|pip)\n *\n * Display-mode toggle: the bridge also mounts two floating buttons\n * (fullscreen + pip) in the top-right corner of every panel, shown only for\n * the modes the host actually advertises via hostContext.availableDisplayModes.\n * No auto-request: panels stay inline until the user clicks. The buttons\n * themselves are NOT implemented here — `@agentproto/app-client/display-mode`\n * is the one implementation, shared with the `window.McpApp` bridge injected\n * into installed apps (`packages/runtime/src/app-ui-apps.ts`); this module\n * only hands it `getHostContext`/`onHostContext`/`requestDisplayMode`. It\n * also leaves `window.AgentprotoUI.installDisplayMode` defined in the panel,\n * which is what a panel with its own header calls to place the toggle\n * inline instead (see that module's `mountToggle`).\n *\n * Standalone HTTP mode: `GET /apps/:appId/ui` (packages/runtime\n * http-server.ts) serves this exact script with NO postMessage host on the\n * other end of `window.parent` — it's a plain browser tab (or a VS Code\n * *HTTP-iframe* panel), so `window.parent === window` and nothing ever\n * answers `initBridge()`'s `ui/initialize` request, leaving every panel\n * stuck on \"Connecting to bridge…\" forever. `injectStandaloneAppBridge`\n * (app-ui-apps.ts) papers over exactly this for installed apps by injecting\n * `window.McpApp.connect() -> Promise<{callTool, ...}>`, a REST-backed\n * stand-in whose `callTool` POSTs to the sibling `./tool-call` route — but\n * this bridge never consumed `window.McpApp`, so builtin panels (the only\n * consumers of this module) were left hanging regardless.\n *\n * Fixed here by detecting that same standalone shape and short-circuiting\n * both `initBridge()` (resolves locally, no round trip) and `callTool()`\n * (routes through `window.McpApp.connect()` instead of `tools/call` over\n * postMessage). The detection requires BOTH `window.parent === window` (no\n * host to talk to — this is the actual condition standalone mode means) AND\n * `window.McpApp` being present with a `connect` function (the capability\n * this bridge needs from it): `window.McpApp` presence alone was considered\n * and rejected as the sole signal, even though it happens to also hold today\n * — the VS Code webview's `srcdoc` relay (packages/vscode\n * appPanel.ts/appPanelController.ts) answers this bridge's raw postMessage\n * JSON-RPC directly and never defines `window.McpApp` for a builtin panel\n * (only `createUiHtmlCache`'s `injectMcpAppBridge`, used for INSTALLED\n * apps' `ui.path` html, defines it) — but that's an accident of today's\n * wiring, not a guarantee; `window.parent === window` is the direct,\n * load-bearing signal (\"is there anyone to postMessage?\") and doesn't\n * depend on which injector happened to run. There is no host in standalone\n * mode, so `initBridge()` seeds a default `hostContext` of `{displayMode:\n * 'inline', availableDisplayModes: []}` — an empty `availableDisplayModes`\n * is what keeps the display-mode toggle buttons hidden (they only show for\n * modes `hostContext.availableDisplayModes` lists), rather than rendering\n * two buttons with nothing to switch to.\n *\n * The real postMessage-host path (a compliant MCP-Apps host, or the VS Code\n * srcdoc relay) is untouched byte-for-byte: same `rpcRequest`/`rpcNotify`\n * over `window.parent.postMessage`, same handshake, same display-mode\n * plumbing.\n *\n * Asymmetry not fixed here (flagged, not papered over): `window.McpApp`'s\n * `sendMessage`/`updateModelContext` (STANDALONE_REST_BRIDGE_SCRIPT,\n * app-ui-apps.ts) reject with \"no host (standalone mode)\", while\n * `appPanelController.ts`'s `ui/message`/`ui/update-model-context` handlers\n * accept-and-drop (`return {}`). This bridge doesn't currently expose either\n * call, so the difference is latent, but it's the last behavioural delta\n * between the two panel paths and worth a follow-up if this bridge ever\n * grows those methods.\n */\n\nimport { DISPLAY_MODE_SCRIPT_BODY } from \"@agentproto/app-client/display-mode\"\n\nexport function panelBridgeScript(appName: string): string {\n return `// ── MCP Apps bridge (shared: panel-bridge.ts) ──\n// JSON-RPC 2.0 over window.parent.postMessage · spec 2026-01-26\nvar _nextId = 1, _pending = {}, _notifyHandlers = [];\nvar _hostContext = null, _hostContextHandlers = [];\nvar _hostCaps = null;\nvar _standaloneApp = null;\nfunction _isStandalone(){\n return window.parent === window && !!window.McpApp && typeof window.McpApp.connect === 'function';\n}\n// ── Per-boot embed token (runtime embed-tokens.ts) ────────────────────────\n// Panels that iframe the daemon's standalone app host carry this proof so\n// GET /apps/:appId/ui?embed=1&et=... can drop its anti-framing headers for\n// MCP-Apps hosts whose widget context is an opaque origin (Claude Desktop).\n// registerMcpApps replaces the placeholder with a real per-boot token when\n// serving the panel as a resource; every other render (tests, standalone\n// tab, VS Code HTTP-iframe panel — the latter two already pass\n// iframeEmbedAllowed's origin checks) keeps the literal, and\n// withEmbedToken() then degrades to an identity function.\nwindow.__AGENPROTO_EMBED_TOKEN__ = \"__AGENPROTO_EMBED_TOKEN__\";\nfunction withEmbedToken(url){\n var t = window.__AGENPROTO_EMBED_TOKEN__;\n if (!t || t === '__AGENPROTO_EMBED_TOKEN__') return url;\n return url + (url.indexOf('?') >= 0 ? '&' : '?') + 'et=' + encodeURIComponent(t);\n}\nfunction post(msg){ window.parent.postMessage(msg, '*'); }\nfunction getHostContext(){ return _hostContext; }\nfunction getHostCapabilities(){ return _hostCaps; }\nfunction onHostContext(cb){\n _hostContextHandlers.push(cb);\n // Replay the last context so a late subscriber isn't stuck blind.\n if (_hostContext){ try { cb(_hostContext); } catch(_) {} }\n}\nfunction _setHostContext(ctx){\n if (!ctx || typeof ctx !== 'object') return;\n // ui/notifications/host-context-changed carries only the changed keys —\n // merge, matching the official ext-apps App behaviour.\n _hostContext = Object.assign({}, _hostContext || {}, ctx);\n for (var i = 0; i < _hostContextHandlers.length; i++){\n try { _hostContextHandlers[i](_hostContext); } catch(_) {}\n }\n}\nfunction rpcRequest(method, params){\n return new Promise(function(resolve, reject){\n var id = _nextId++;\n _pending[id] = {resolve: resolve, reject: reject};\n post({jsonrpc: '2.0', id: id, method: method, params: params || {}});\n });\n}\nfunction rpcNotify(method, params){ post({jsonrpc: '2.0', method: method, params: params || {}}); }\nfunction onHostNotification(cb){ _notifyHandlers.push(cb); }\nwindow.addEventListener('message', function(evt){\n var msg = evt.data;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') return;\n if (msg.id != null && msg.method == null){\n var p = _pending[msg.id];\n if (!p) return;\n delete _pending[msg.id];\n if (msg.error) p.reject(new Error(msg.error.message || ('rpc error ' + msg.error.code)));\n else p.resolve(msg.result);\n return;\n }\n if (msg.method){\n if (msg.method === 'ui/notifications/host-context-changed'){\n _setHostContext(msg.params || {});\n }\n for (var i = 0; i < _notifyHandlers.length; i++){\n try { _notifyHandlers[i](msg.method, msg.params || {}); } catch(_) {}\n }\n }\n});\nfunction initBridge(){\n if (_isStandalone()){\n return window.McpApp.connect().then(function(conn){\n _standaloneApp = conn;\n // No host to advertise a hostContext — default to inline with no\n // other modes available, which keeps the display-mode toggle buttons\n // hidden (they only show for modes hostContext.availableDisplayModes\n // lists) instead of rendering two buttons with nothing to switch to.\n _setHostContext({displayMode: 'inline', availableDisplayModes: []});\n });\n }\n return rpcRequest('ui/initialize', {\n appInfo: {name: ${JSON.stringify(appName)}, version: '0.1.0'},\n appCapabilities: {availableDisplayModes: ['inline', 'fullscreen', 'pip']},\n protocolVersion: '2026-01-26'\n }).then(function(result){\n // The initialize result carries the initial hostContext (displayMode +\n // availableDisplayModes) — capture it before notifying the host.\n if (result && result.hostContext) _setHostContext(result.hostContext);\n // McpUiInitializeResult.hostCapabilities (ext-apps spec) — e.g. openLinks,\n // \"Host supports opening external URLs\". Captured once, read via\n // getHostCapabilities() by panels that need to branch on it.\n if (result && result.hostCapabilities) _hostCaps = result.hostCapabilities;\n rpcNotify('ui/notifications/initialized', {});\n });\n}\nfunction requestDisplayMode(mode){\n return rpcRequest('ui/request-display-mode', {mode: mode});\n}\nfunction openLink(url){\n if (_standaloneApp && typeof _standaloneApp.openLink === 'function') return _standaloneApp.openLink(url);\n return rpcRequest('ui/open-link', {url: url});\n}\nfunction callTool(name, args){\n var raw = _standaloneApp\n ? _standaloneApp.callTool(name, args || {})\n : rpcRequest('tools/call', {name: name, arguments: args || {}});\n return raw.then(function(result){\n if (result.isError){\n var e = (result.content && result.content[0] && result.content[0].text) || 'tool error';\n throw new Error(e);\n }\n var text = (result.content && result.content[0] && result.content[0].text) || '{}';\n return JSON.parse(text);\n });\n}\n\n// ── Display-mode toggle (shared: @agentproto/app-client/display-mode) ──\n// The installer is inlined verbatim (it is self-contained and idempotent),\n// then handed this panel's own JSON-RPC plumbing. NO auto-request: the\n// panel stays inline until the user clicks, and the buttons only appear for\n// the modes the host advertises in hostContext.availableDisplayModes.\n${DISPLAY_MODE_SCRIPT_BODY}\nvar displayMode = window.AgentprotoUI.installDisplayMode({\n getHostContext: getHostContext,\n onHostContext: onHostContext,\n requestDisplayMode: requestDisplayMode\n});`\n}\n","/**\n * Blob pass-through for the session-chat widget (see ./panel.ts `mountBlob`).\n *\n * Claude Desktop and Codex apply their own CSP to an MCP-Apps widget frame:\n * `frame-src 'self' blob: data:`. Neither merges the resource's declared\n * `_meta.ui.csp.frameDomains` into it (measured 2026-09-18), so a direct\n * `<iframe src=\"http://127.0.0.1:18790/apps/@agentik/session-chat/ui?…\">` is\n * refused host-side before the request ever reaches the daemon. `blob:` IS\n * on that list — so the panel fetches the chat html itself (a fetch, not a\n * frame navigation; the per-boot `?et=` embed token gets it through the\n * daemon's origin gates and PNA preflight), rewrites it with the function\n * below, and mounts the result as a `blob:` document.\n *\n * What the rewrite has to fix, given that the document no longer lives on\n * the daemon origin:\n *\n * 1. `<base href=\"<deep link>\">` right after `<head>`, so every relative\n * url in the app (the injected standalone bridge's `./tool-call`, any\n * relative asset) resolves exactly as it would have on the daemon.\n * NOTE: the base is the document url itself (`…/session-chat/ui?…`),\n * not `…/ui/` — a trailing slash would add a path segment and make\n * `./tool-call` resolve to `…/ui/tool-call`, which routes nowhere.\n * 2. The blob document's origin is opaque (Claude's widget context is a\n * sandboxed frame; the blob inherits that) — every daemon request it\n * makes carries `Origin: null`, which the daemon's browser gates\n * (`guardBrowserOrigin`, `authorizeMcp`, `checkSessionsToken`) refuse\n * unless the request ALSO carries the embed token. The chat UI talks to\n * the daemon with absolute urls (`${DAEMON_URL}/mcp`, `/sessions/*`,\n * its SSE stream via `fetch`, `/sessions/:id/chat`) that we don't\n * control, so a small shim is injected ahead of every app script: it\n * wraps `window.fetch` / `window.EventSource` to append `et=` to any\n * request aimed at the daemon origin, and points\n * `window.__AGENTPROTO_BASEURL__` at the daemon origin the deep link\n * names (so a non-default port works too).\n * 3. The standalone bridge's `fetch(\"./tool-call\"` (runtime\n * app-ui-apps.ts `STANDALONE_REST_BRIDGE_SCRIPT`) is additionally\n * rewritten to the absolute tokened url — belt and braces on top of\n * the shim, and the one rewrite that is exact-string-testable.\n * 4. The shim's FIRST statement posts `{ type: \"agentproto-blob-boot\" }`\n * to its parent. A blob document inherits its creator's CSP, so if the\n * host's widget CSP ever kills inline scripts, that ack never arrives\n * and the panel tears the blob down and falls back to the direct frame\n * + launcher card (panel.ts `armBlobBootProbe`) instead of leaving a\n * silent blank. No CSP `<meta>` is added to the blob html: the\n * creator's CSP wins regardless, it would only be noise.\n *\n * Shipped as a JS string (same shape as ../panel-bridge.ts) so the panel\n * page embeds the exact code the test evaluates — no TS twin to drift from.\n */\n\n/** `postMessage` type the injected shim sends its parent on boot. */\nexport const BLOB_BOOT_MESSAGE_TYPE = \"agentproto-blob-boot\"\n\nexport function blobEmbedScript(): string {\n return `// ── Blob pass-through transform (shared: session-chat/blob-embed.ts) ──\nfunction _blobEscapeAttr(s){ return String(s).replace(/&/g, '&amp;').replace(/\"/g, '&quot;'); }\n// Rewrite the fetched chat html so it works as a blob: document: <base> on\n// the deep link, a fetch/EventSource shim that carries the embed token to\n// the daemon origin, and the standalone bridge's ./tool-call made absolute.\nfunction transformChatHtmlForBlob(html, url, token){\n var origin = new URL(url).origin;\n var tc = new URL('./tool-call', url);\n tc.searchParams.set('et', token);\n // The app-visible query for the blob doc: the deep link's search minus the\n // embed token (the token must not ride the app's visible params). The\n // blob document's own location has no params, so this is the ONLY channel\n // for ?session= / ?embed=1 — the app reads it via bootSearchParams().\n var bootUrl = new URL(url);\n bootUrl.searchParams.delete('et');\n var bootQuery = bootUrl.search;\n var shim = '<script>(function(){'\n + 'try { window.parent.postMessage({ type: ${JSON.stringify(BLOB_BOOT_MESSAGE_TYPE)} }, \"*\"); } catch (_) {}'\n + 'var ORIGIN = ' + JSON.stringify(origin) + ', TOKEN = ' + JSON.stringify(token) + ';'\n + 'window.__AGENTPROTO_BASEURL__ = ORIGIN;'\n + 'var _h = window.history, _rs = _h.replaceState.bind(_h), _ps = _h.pushState.bind(_h);'\n + 'function _sameOrLoc(u){'\n + 'try {'\n + 'var x = new URL(u == null ? window.location.href : u, document.baseURI);'\n + 'return x.origin === window.location.origin ? u : window.location.href;'\n + '} catch (_) { return window.location.href; }'\n + '}'\n + '_h.replaceState = function(s, t, u){'\n + 'try { _rs(s, t, _sameOrLoc(u)); } catch (_) { try { _rs(s, t, window.location.href); } catch (_) {} }'\n + '};'\n + '_h.pushState = function(s, t, u){'\n + 'try { _ps(s, t, _sameOrLoc(u)); } catch (_) { try { _ps(s, t, window.location.href); } catch (_) {} }'\n + '};'\n + 'window.__AGENTPROTO_BOOT_QUERY__ = ' + JSON.stringify(bootQuery) + ';'\n + 'function withEt(u){'\n + 'try {'\n + 'var x = new URL(String(u), document.baseURI);'\n + 'if (x.origin !== ORIGIN) return null;'\n + 'if (!x.searchParams.has(\"et\")) x.searchParams.set(\"et\", TOKEN);'\n + 'return x.href;'\n + '} catch (_) { return null; }'\n + '}'\n + 'var _fetch = window.fetch;'\n + 'if (typeof _fetch === \"function\") {'\n + 'window.fetch = function(input, init){'\n + 'var r;'\n + 'if (typeof Request !== \"undefined\" && input instanceof Request) {'\n + 'r = withEt(input.url);'\n + 'if (r) { try { input = new Request(r, input); } catch (_) {} }'\n + '} else {'\n + 'r = withEt(input);'\n + 'if (r) input = r;'\n + '}'\n + 'return _fetch.call(window, input, init);'\n + '};'\n + '}'\n + 'var _ES = window.EventSource;'\n + 'if (typeof _ES === \"function\") {'\n + 'window.EventSource = function(u, cfg){ return new _ES(withEt(u) || u, cfg); };'\n + 'window.EventSource.prototype = _ES.prototype;'\n + '}'\n + '})();<\\\\/script>';\n var head = '<base href=\"' + _blobEscapeAttr(url) + '\">' + shim;\n var m = html.match(/<head[^>]*>/i);\n var out = m\n ? html.slice(0, m.index + m[0].length) + head + html.slice(m.index + m[0].length)\n : head + html;\n return out.split('fetch(\"./tool-call\"').join('fetch(' + JSON.stringify(tc.href));\n}`\n}\n","/**\n * HTML bundles for the session-chat builtin widget — the thin bridge page\n * (`sessionChatEmbedHtml`) and the not-installed notice\n * (`SESSION_CHAT_FALLBACK_HTML`) served as the\n * `ui://agentproto_session_chat/view` resource by `registerMcpApps` (see\n * ../mcp-app-types.ts and runtime's mcp-apps-adapter.ts). Mounted via the\n * `agentproto_session_chat` tool defined in ./index.ts, AND bound to\n * `agent_start` (runtime agent-tools.ts `_meta.ui.resourceUri`) so a launch\n * card opens the chat of the session it just spawned.\n *\n * Deliberately NOT a chat UI reimplementation: the real chat lives in the\n * installed `@agentik/session-chat` app, served by the daemon's standalone\n * app host at `GET /apps/@agentik/session-chat/ui`. When the app is\n * installed, this page is a full-viewport iframe of that URL deep-linked\n * with `?session=<id>&embed=1` — the exact spelling the daemon's standalone\n * route relaxes its `frame-ancestors 'none'` for (see runtime\n * http-server.ts handleAppUiPage) and the VS Code chat-panel webview\n * already uses. No second chat bundle exists anywhere in agentproto/ts.\n *\n * Self-bootstrapping (same pattern as live-session/panel.ts): the static\n * ui:// resource is rendered ONCE at server-registration time with EMPTY\n * initData (mcp-apps-adapter.ts registerMcpApps), so the deep link can't\n * be baked in. The page resolves it at runtime, in priority order:\n * 1. `initData.url` when the html was rendered with a real tool output\n * (tests, and any host that re-renders per call) — iframe is inline.\n * 2. The host's `ui/notifications/tool-result` push of the tool call that\n * mounted the widget. An `agent_start` result IS the spawned session's\n * descriptor (`{ id: \"sess_…\", … }`) → the widget calls\n * `agentproto_session_chat({ sessionId })` over the bridge to turn that\n * id into the deep link; an `agentproto_session_chat` result already\n * carries `{ installed, url }` and mounts directly.\n * 3. Otherwise (opened bare from the catalog) `agentproto_session_chat({})`\n * → the app's session picker.\n * Both orders of (2) vs. bridge init are handled: a result that lands\n * before `initBridge()` resolves is held and applied once it does.\n *\n * Mount order (see `mount()` below):\n * 1. Blob pass-through, when a per-boot embed token is baked in (i.e. an\n * MCP-Apps host rendered this resource): fetch the chat html with the\n * token, rewrite it (./blob-embed.ts `transformChatHtmlForBlob`) and\n * mount it as a `blob:` document. Claude Desktop / Codex widget frames\n * run `frame-src 'self' blob: data:` and do not merge our declared\n * `csp.frameDomains`, so a direct daemon iframe is refused host-side —\n * `blob:` is the pass-through. The blob document must post a boot ack\n * within a settle window (`armBlobBootProbe`); a missing ack (host CSP\n * killed its inline scripts, or refused the blob frame) tears it down\n * and falls through to 2.\n * 2. Direct-src iframe of the deep link (VS Code HTTP-iframe panels, a\n * standalone tab — no token, and their origin already passes the\n * daemon's checks; or the blob path's fallback). If the host refuses\n * the frame, `armBlockProbe` removes it and the launcher card becomes\n * the interactive surface.\n *\n * A persistent header with the deep link stays visible above the iframe, so\n * if the frame is refused (older daemon without the embed relaxation, or a\n * host whose own CSP blocks daemon frames) the user still has a one-click\n * path to the chat in a tab. When the app is NOT installed the page is a\n * small readable notice pointing at `agentproto app install` — the\n * fallback branch, never a vendored UI.\n */\n\nimport { panelBridgeScript } from \"../panel-bridge.js\"\nimport { BLOB_BOOT_MESSAGE_TYPE, blobEmbedScript } from \"./blob-embed.js\"\nimport type { SessionChatOutput } from \"./index.js\"\n\n/** Only `&` and `\"` are significant inside a double-quoted attribute value. */\nfunction escapeAttr(text: string): string {\n return text.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\")\n}\n\nexport function sessionChatEmbedHtml(initData: Partial<SessionChatOutput>): string {\n const url = typeof initData.url === \"string\" && initData.url ? initData.url : null\n const notInstalled = initData.installed === false\n const storeUrl =\n typeof initData.storeUrl === \"string\" && initData.storeUrl\n ? initData.storeUrl\n : \"/store?install=%40agentik%2Fsession-chat\"\n const link =\n url != null\n ? `<a href=\"${escapeAttr(url)}\" target=\"_blank\" rel=\"noreferrer\">open in a tab</a>`\n : notInstalled\n ? \"app not installed\"\n : \"connecting…\"\n const iframe =\n url != null\n // No inline src: the url mounts through the bridge script below, via\n // withEmbedToken(), so the frame never loads without the per-boot\n // embed proof — whichever render path (static resource or a host\n // re-render with a real initData) produced it.\n ? `<iframe id=\"chat\" title=\"Session Chat\"></iframe>`\n : \"\"\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Session Chat</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3;overflow:hidden}\n#bar{padding:6px 12px;font-size:12px;color:#8b949e;background:#161b22;border-bottom:1px solid #30363d}\n#bar a{color:#58a6ff}\n#mode{color:#6e7681}\n#stage{position:relative;height:calc(100% - 29px)}\n#chat{position:absolute;inset:0;z-index:2;border:0;display:block;width:100%;height:100%}\n#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}\n#card h2{font-size:15px;font-weight:600}\n#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}\n#card p{font-size:12px;color:#8b949e;max-width:420px;line-height:1.5}\n#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}\n#card a:hover{border-color:#58a6ff}\n#notice{display:none;max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}\n#notice.show{display:block}\n#notice h1{font-size:18px;margin-bottom:12px}\n#notice code{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}\n#notice p{margin:8px 0;color:#8b949e;font-size:13px}\n</style>\n</head>\n<body>\n<div id=\"bar\">Session Chat &#183; <span id=\"link\">${link}</span><span id=\"mode\"></span></div>\n<div id=\"stage\">${iframe}<div id=\"card\">\n <h2>Session Chat</h2>\n <div id=\"card-session\" class=\"sid\">&#8212;</div>\n <p>Full embed isn't supported by this host &#8212; the chat opens in a browser tab.</p>\n <a id=\"card-open\" href=\"#\" target=\"_blank\" rel=\"noreferrer\">Open chat</a>\n</div><div id=\"notice\"${notInstalled ? ' class=\"show\"' : \"\"}>\n <h1>Session Chat is not installed</h1>\n <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;\n it does not bundle the chat UI itself.</p>\n <p>To use it, install the app into this daemon:</p>\n <p><code>agentproto app install @agentik/session-chat</code></p>\n <p>or open <a href=\"${escapeAttr(storeUrl)}\" target=\"_blank\" rel=\"noreferrer\">the App Store</a>\n (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>\n</div></div>\n<script>\nwindow.__APP_INIT__ = ${JSON.stringify(initData)};\n\n${panelBridgeScript(\"agentproto-session-chat\")}\n\n${blobEmbedScript()}\n\n// ── Session-chat launcher logic ──────────────────────────────────────────\nvar mountedUrl = (window.__APP_INIT__ && window.__APP_INIT__.url) || null;\nvar pinnedSessionId = null; // session named by the host's tool-result push\nvar pendingUrl = null; // url pushed by the host before the bridge was up\nvar pendingNotInstalled = false;\nvar bridged = false;\nvar cardUrl = null; // deep link once resolved (drives the card button)\nvar cardSessionEl = document.getElementById('card-session');\nvar cardOpenEl = document.getElementById('card-open');\nvar mountGen = 0; // bumps per mount(); async work checks it before touching the DOM\nvar blobUrl = null; // live object url of the blob-mounted chat, if any\nvar blobBootTimer = null;\nvar blobBootOk = false;\n\nfunction escapeHtml(text) {\n return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\"/g, '&quot;');\n}\n\nfunction setMode(text) {\n document.getElementById('mode').textContent = text ? ' \\\\u00b7 ' + text : '';\n // The chat app is live inside the frame — the launcher bar (title, deep\n // link, mount mode) is noise on top of the real surface. Hide it and let\n // the frame own the full height. Only a failed mount (launcher card /\n // not-installed notice) shows the bar again.\n var bar = document.getElementById('bar');\n var stage = document.getElementById('stage');\n if (bar && stage) {\n bar.style.display = text ? 'none' : '';\n stage.style.height = text ? '100%' : 'calc(100% - 29px)';\n }\n}\n\n// One fresh #chat frame on the stage (over the card), the previous one gone.\nfunction newFrame() {\n var stage = document.getElementById('stage');\n var old = document.getElementById('chat');\n if (old) old.remove();\n var frame = document.createElement('iframe');\n frame.id = 'chat';\n frame.title = 'Session Chat';\n stage.insertBefore(frame, stage.firstChild);\n return frame;\n}\n\nfunction revokeBlob() {\n if (blobBootTimer) { clearTimeout(blobBootTimer); blobBootTimer = null; }\n if (blobUrl) {\n try { URL.revokeObjectURL(blobUrl); } catch (_) {}\n blobUrl = null;\n }\n}\n\nfunction mount(url) {\n if (!url || url === mountedUrl) return;\n mountedUrl = url;\n var gen = ++mountGen;\n revokeBlob();\n document.getElementById('notice').className = '';\n setCardUrl(url);\n document.getElementById('link').innerHTML =\n '<a href=\"' + escapeHtml(url) + '\" target=\"_blank\" rel=\"noreferrer\">open in a tab</a>';\n var tokened = withEmbedToken(url);\n if (tokened === url) {\n // No per-boot token baked in (standalone tab, VS Code HTTP-iframe panel):\n // the direct frame already passes the daemon's origin checks, and the\n // blob path's daemon calls would have nothing to carry — skip it.\n mountDirect(url);\n return;\n }\n mountBlob(url, tokened, gen).catch(function (err) {\n if (gen !== mountGen) return;\n // The fetch itself was refused (host connect-src not merging our\n // connectDomains, PNA, daemon down, …) — probe answered: no blob path.\n console.warn('[session-chat] blob mount failed, falling back to a direct frame:',\n err && err.message ? err.message : String(err));\n mountDirect(url);\n });\n}\n\n// Direct-src iframe of the deep link, with the block probe → launcher card\n// fallback. The terminal mount path when the blob one is unavailable.\nfunction mountDirect(url) {\n var frame = newFrame();\n frame.src = withEmbedToken(url);\n setMode('direct frame');\n armBlockProbe(frame);\n}\n\n// Blob pass-through: fetch the chat html through the embed token, rewrite it\n// for life as a blob: document (transformChatHtmlForBlob, blob-embed.ts) and\n// mount it — blob: passes a host frame-src that refuses the daemon origin.\nfunction mountBlob(url, tokened, gen) {\n return fetch(tokened, { credentials: 'omit' }).then(function (res) {\n if (!res.ok) throw new Error('HTTP ' + res.status);\n return res.text();\n }).then(function (html) {\n if (gen !== mountGen) return;\n var doc = transformChatHtmlForBlob(html, url, window.__AGENPROTO_EMBED_TOKEN__);\n blobUrl = URL.createObjectURL(new Blob([doc], { type: 'text/html' }));\n var frame = newFrame();\n armBlobBootProbe(frame, url, gen);\n frame.src = blobUrl;\n setMode('embedded');\n });\n}\n\n// The blob document's shim posts a boot ack as its first statement. No ack\n// within the settle window means the host refused the blob frame or its\n// inherited CSP killed the document's inline scripts — surface that through\n// the direct-frame path (whose own probe ends on the launcher card) rather\n// than leaving a silent blank.\nwindow.addEventListener('message', function (evt) {\n var d = evt.data;\n if (!d || typeof d !== 'object' || d.type !== ${JSON.stringify(BLOB_BOOT_MESSAGE_TYPE)}) return;\n var frame = document.getElementById('chat');\n if (!frame || evt.source !== frame.contentWindow) return;\n blobBootOk = true;\n if (blobBootTimer) { clearTimeout(blobBootTimer); blobBootTimer = null; }\n});\n\nfunction armBlobBootProbe(frame, url, gen) {\n blobBootOk = false;\n blobBootTimer = setTimeout(function () {\n blobBootTimer = null;\n if (gen !== mountGen || blobBootOk) return;\n console.warn('[session-chat] blob document never booted (host CSP?), falling back to a direct frame');\n revokeBlob();\n frame.remove();\n mountDirect(url);\n }, 5000);\n}\n\nfunction showNotInstalled() {\n var old = document.getElementById('chat');\n if (old) old.remove();\n revokeBlob();\n setMode('');\n mountedUrl = null;\n document.getElementById('card').style.display = 'none';\n document.getElementById('notice').className = 'show';\n document.getElementById('link').textContent = 'app not installed';\n}\n\n// The body of an ext-apps tool-result notification, whichever wrapping\n// shape the host uses (params IS the CallToolResult, or nests it under\n// params.result). null for error results / non-JSON text.\nfunction parseToolResultBody(params) {\n if (!params || typeof params !== 'object') return null;\n var res = (params.result && typeof params.result === 'object') ? params.result : params;\n if (res.isError) return null;\n var content = Array.isArray(res.content) ? res.content : [];\n var item = content[0];\n if (!item || item.type !== 'text' || typeof item.text !== 'string') return null;\n try { return JSON.parse(item.text); } catch (_) { return null; }\n}\n\n// INLINED COPY of live-session/logic.ts extractToolResultSessionId — keep\n// in sync. \\`sessionId\\` (an agentproto_session_chat / live_session result)\n// wins over \\`id\\` (an agent_start result: the spawned session descriptor).\nfunction extractToolResultSessionId(params) {\n var body = parseToolResultBody(params);\n if (!body) return null;\n if (typeof body.sessionId === 'string' && body.sessionId) return body.sessionId;\n if (typeof body.id === 'string' && body.id) return body.id;\n return null;\n}\n\n// ── Embed-token refresh ──────────────────────────────────────────────────\n// The token baked into this page by registerMcpApps dies with the daemon\n// boot that minted it (runtime embed-tokens.ts), but hosts cache the\n// rendered widget: Claude Desktop keeps a conversation's srcdoc, so after\n// any daemon restart the cached page replays a dead token and every daemon\n// call 403s — the blob fetch fails, the direct frame is refused, and the\n// user is left on the launcher card forever. Every tool result carries a\n// live token (SessionChatOutput.embedToken), so adopt it before mounting.\n//\n// Only a render that WAS baked refreshes. A standalone tab or VS Code\n// HTTP-iframe panel still holds the literal placeholder and passes the\n// daemon's origin checks on its own; handing it a token would switch it\n// onto the blob path for no reason.\nfunction adoptEmbedToken(body) {\n var cur = window.__AGENPROTO_EMBED_TOKEN__;\n if (!cur || cur === '__AGENPROTO_EMBED_TOKEN__') return;\n if (!body || typeof body.embedToken !== 'string' || !body.embedToken) return;\n window.__AGENPROTO_EMBED_TOKEN__ = body.embedToken;\n}\n\n// Turn a session id into the installed app's deep link over the bridge.\nfunction resolveSession(sessionId) {\n noteSession(sessionId);\n return callTool('agentproto_session_chat', sessionId ? { sessionId: sessionId } : {})\n .then(function(out) {\n adoptEmbedToken(out);\n if (out && out.installed && typeof out.url === 'string' && out.url) mount(out.url);\n else showNotInstalled();\n })\n .catch(function(err) {\n document.getElementById('link').textContent = 'bridge error: ' + (err && err.message ? err.message : String(err));\n });\n}\n\n// ── Launcher card (the frame-blocked fallback UI) ────────────────────────\n// The iframe mounts OVER the card. When the host's own CSP refuses the\n// frame (Claude Desktop / Codex widget frames run frame-src 'self' blob:\n// data: and do not yet merge csp.frameDomains), the frame stays on a\n// same-origin about:blank — readable, unlike the loaded cross-origin chat —\n// and is removed after a settle window so the card becomes the interactive\n// surface.\n//\n// The anchor carries target=\"_blank\" rel=\"noreferrer\" as the fallback path,\n// but that is a plain no-op in hosts that sandbox the widget iframe without\n// allow-popups (observed in Claude Desktop's side chat) — a normal click\n// on such a host does nothing. Where the host advertises the capability\n// (McpUiInitializeResult.hostCapabilities.openLinks in the ext-apps spec,\n// captured by the bridge's getHostCapabilities()), route through the\n// host-mediated ui/open-link request instead, which is not subject to the\n// iframe's popup sandboxing.\ncardOpenEl.addEventListener('click', function (evt) {\n if (!cardUrl) { evt.preventDefault(); return; }\n if (getHostCapabilities() && getHostCapabilities().openLinks) {\n evt.preventDefault();\n openLink(cardUrl).catch(function () { window.open(cardUrl, '_blank'); });\n }\n});\n\nfunction noteSession(id) {\n if (id && cardSessionEl) cardSessionEl.textContent = id;\n}\n\nfunction setCardUrl(u) {\n if (!u) return;\n cardUrl = u;\n cardOpenEl.setAttribute('href', u);\n}\n\n// A blocked frame never leaves about:blank (same-origin with this page —\n// readable); the loaded chat is cross-origin (the probe throws). A readable\n// frame that is STILL blank when the settle window closes = blocked.\nfunction isBlank(frame) {\n try { return frame.contentWindow.location.href === 'about:blank'; } catch (_) { return false; }\n}\n\nfunction armBlockProbe(frame) {\n var settle = null;\n function probe() {\n if (settle) { clearTimeout(settle); settle = null; }\n if (!isBlank(frame)) return;\n // Still on about:blank right now — arm the settle window, but\n // re-check when it closes: a slow (not blocked) load may have landed\n // in the meantime, and only a frame STILL blank after the window gets\n // removed. load firing in between clears this timeout above.\n settle = setTimeout(function () {\n settle = null;\n if (isBlank(frame)) frame.remove();\n }, 2000);\n }\n setTimeout(function () {\n frame.addEventListener('load', probe);\n probe();\n }, 100);\n}\n\n// A url baked at render time (a host that re-renders per call with a real\n// initData) mounts on boot — through the same blob-first path as every\n// other mount, since the same opaque widget context frames it. The\n// pre-rendered #chat frame is replaced by mount()'s own.\nif (mountedUrl) {\n var bootUrl = mountedUrl;\n mountedUrl = null;\n adoptEmbedToken(window.__APP_INIT__);\n mount(bootUrl);\n}\n\n// The host pushes the triggering tool call's result (ext-apps\n// ui/notifications/tool-result). For agent_start that result IS the spawned\n// session's descriptor — pin the widget to THAT session.\nonHostNotification(function(method, params) {\n if (method !== 'ui/notifications/tool-result') return;\n var body = parseToolResultBody(params);\n if (!body) return;\n if (typeof body.url === 'string' && body.url && body.installed !== false) {\n // Adopt now, not at mount time: the token doesn't depend on the bridge.\n adoptEmbedToken(body);\n if (bridged) mount(body.url); else pendingUrl = body.url;\n return;\n }\n if (body.installed === false) {\n if (bridged) showNotInstalled(); else pendingNotInstalled = true;\n return;\n }\n var id = extractToolResultSessionId(params);\n if (!id || id === pinnedSessionId) return;\n pinnedSessionId = id;\n noteSession(id);\n if (bridged) resolveSession(id);\n});\n\ninitBridge().then(function() {\n bridged = true;\n if (pendingUrl) { mount(pendingUrl); pendingUrl = null; return; }\n if (pendingNotInstalled) { showNotInstalled(); return; }\n if (mountedUrl) return; // rendered with a real url\n var init = window.__APP_INIT__ || {};\n if (init.installed === false) { showNotInstalled(); return; }\n // No url baked in (static ui:// render): resolve over the bridge — the\n // pinned session when the host named one, else the app's picker.\n return resolveSession(pinnedSessionId);\n}).catch(function(err) {\n document.getElementById('link').textContent = 'bridge error: ' + (err && err.message ? err.message : String(err));\n});\n</script>\n</body>\n</html>`\n}\n\nexport const SESSION_CHAT_FALLBACK_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Session Chat — not installed</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3}\n#wrap{max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}\nh1{font-size:18px;margin-bottom:12px}\ncode{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}\np{margin:8px 0;color:#8b949e;font-size:13px}\n</style>\n</head>\n<body>\n<div id=\"wrap\">\n <h1>Session Chat is not installed</h1>\n <p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app &#8212;\n it does not bundle the chat UI itself.</p>\n <p>To use it, install the app into this daemon:</p>\n <p><code>agentproto app install @agentik/session-chat</code></p>\n <p>or open <a href=\"/store?install=%40agentik%2Fsession-chat\">the App Store</a>\n (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>\n <p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a\n <code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that\n session.</p>\n</div>\n</body>\n</html>`\n"]}
@@ -219,6 +219,7 @@ function escapeAttr(text) {
219
219
  function sessionChatEmbedHtml(initData) {
220
220
  const url = typeof initData.url === "string" && initData.url ? initData.url : null;
221
221
  const notInstalled = initData.installed === false;
222
+ const storeUrl = typeof initData.storeUrl === "string" && initData.storeUrl ? initData.storeUrl : "/store?install=%40agentik%2Fsession-chat";
222
223
  const link = url != null ? `<a href="${escapeAttr(url)}" target="_blank" rel="noreferrer">open in a tab</a>` : notInstalled ? "app not installed" : "connecting\u2026";
223
224
  const iframe = url != null ? `<iframe id="chat" title="Session Chat"></iframe>` : "";
224
225
  return `<!DOCTYPE html>
@@ -261,6 +262,8 @@ html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:
261
262
  it does not bundle the chat UI itself.</p>
262
263
  <p>To use it, install the app into this daemon:</p>
263
264
  <p><code>agentproto app install @agentik/session-chat</code></p>
265
+ <p>or open <a href="${escapeAttr(storeUrl)}" target="_blank" rel="noreferrer">the App Store</a>
266
+ (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>
264
267
  </div></div>
265
268
  <script>
266
269
  window.__APP_INIT__ = ${JSON.stringify(initData)};
@@ -605,6 +608,8 @@ p{margin:8px 0;color:#8b949e;font-size:13px}
605
608
  it does not bundle the chat UI itself.</p>
606
609
  <p>To use it, install the app into this daemon:</p>
607
610
  <p><code>agentproto app install @agentik/session-chat</code></p>
611
+ <p>or open <a href="/store?install=%40agentik%2Fsession-chat">the App Store</a>
612
+ (the daemon's <code>/store</code> panel, with the entry pre-selected).</p>
608
613
  <p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a
609
614
  <code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that
610
615
  session.</p>
@@ -626,6 +631,9 @@ function sessionChatAppUrl(httpBaseUrl, sessionId) {
626
631
  params.set("embed", "1");
627
632
  return `${base}?${params.toString()}`;
628
633
  }
634
+ function sessionChatStoreUrl(httpBaseUrl) {
635
+ return `${httpBaseUrl.replace(/\/+$/, "")}/store?install=${encodeURIComponent(SESSION_CHAT_APP_ID)}`;
636
+ }
629
637
  function daemonOrigin(httpBaseUrl) {
630
638
  return new URL(httpBaseUrl).origin;
631
639
  }
@@ -637,7 +645,7 @@ function makeSessionChatApp(ops) {
637
645
  description: "Open the Session Chat app \u2014 a chat-thread view of any agentproto daemon session: full transcript replay, live follow-over SSE, and a composer that sends prompts into the same session. Requires the `@agentik/session-chat` app to be installed; without it the panel shows install instructions. Pass `sessionId` to deep-link straight into a known session.",
638
646
  inputSchema: sessionChatInputSchema,
639
647
  execute: async (input) => {
640
- if (!installed) return { installed, url: null };
648
+ if (!installed) return { installed, url: null, storeUrl: sessionChatStoreUrl(ops.httpBaseUrl) };
641
649
  const token = ops.mintEmbedToken?.();
642
650
  return {
643
651
  installed,
@@ -693,6 +701,6 @@ var sessionChatApp = defineApp({
693
701
  }
694
702
  });
695
703
 
696
- export { BLOB_BOOT_MESSAGE_TYPE, SESSION_CHAT_APP_ID, SESSION_CHAT_FALLBACK_HTML, blobEmbedScript, makeSessionChatApp, sessionChatApp, sessionChatAppUrl, sessionChatEmbedHtml, sessionChatInputSchema };
704
+ export { BLOB_BOOT_MESSAGE_TYPE, SESSION_CHAT_APP_ID, SESSION_CHAT_FALLBACK_HTML, blobEmbedScript, makeSessionChatApp, sessionChatApp, sessionChatAppUrl, sessionChatEmbedHtml, sessionChatInputSchema, sessionChatStoreUrl };
697
705
  //# sourceMappingURL=session-chat.mjs.map
698
706
  //# sourceMappingURL=session-chat.mjs.map