@agentproto/apps 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/agents-overview/panel.mjs +14 -67
  2. package/dist/agents-overview/panel.mjs.map +1 -1
  3. package/dist/agents-overview.mjs +13 -68
  4. package/dist/agents-overview.mjs.map +1 -1
  5. package/dist/bin/sync.d.ts.map +1 -1
  6. package/dist/bin/sync.mjs +2374 -2
  7. package/dist/bin/sync.mjs.map +1 -1
  8. package/dist/bureau-sessions/panel.mjs +14 -67
  9. package/dist/bureau-sessions/panel.mjs.map +1 -1
  10. package/dist/bureau-sessions.mjs +13 -68
  11. package/dist/bureau-sessions.mjs.map +1 -1
  12. package/dist/config/fragment.d.ts +50 -0
  13. package/dist/config/fragment.d.ts.map +1 -0
  14. package/dist/config/index.d.ts +23 -0
  15. package/dist/config/index.d.ts.map +1 -0
  16. package/dist/config/ui.d.ts +43 -0
  17. package/dist/config/ui.d.ts.map +1 -0
  18. package/dist/config.mjs +2373 -0
  19. package/dist/config.mjs.map +1 -0
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +2706 -138
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/live-session/logic.d.ts +2 -0
  25. package/dist/live-session/logic.d.ts.map +1 -1
  26. package/dist/live-session/panel.d.ts.map +1 -1
  27. package/dist/live-session/panel.mjs +27 -74
  28. package/dist/live-session/panel.mjs.map +1 -1
  29. package/dist/live-session.mjs +26 -75
  30. package/dist/live-session.mjs.map +1 -1
  31. package/dist/panel-bridge.d.ts +11 -6
  32. package/dist/panel-bridge.d.ts.map +1 -1
  33. package/dist/session-chat/index.d.ts.map +1 -1
  34. package/dist/session-chat/panel.mjs +14 -67
  35. package/dist/session-chat/panel.mjs.map +1 -1
  36. package/dist/session-chat.mjs +28 -69
  37. package/dist/session-chat.mjs.map +1 -1
  38. package/dist/session-story/panel.mjs +14 -67
  39. package/dist/session-story/panel.mjs.map +1 -1
  40. package/dist/session-story.mjs +13 -68
  41. package/dist/session-story.mjs.map +1 -1
  42. package/dist/session-viewer/ui.d.ts.map +1 -1
  43. package/dist/session-viewer.mjs +10 -0
  44. package/dist/session-viewer.mjs.map +1 -1
  45. package/dist/sessions-panel/panel.d.ts.map +1 -1
  46. package/dist/sessions-panel/panel.mjs +15 -67
  47. package/dist/sessions-panel/panel.mjs.map +1 -1
  48. package/dist/sessions-panel.mjs +14 -68
  49. package/dist/sessions-panel.mjs.map +1 -1
  50. package/dist/work-board/panel.d.ts +1 -1
  51. package/dist/work-board/panel.d.ts.map +1 -1
  52. package/dist/work-board/panel.generated.d.ts +1 -1
  53. package/dist/work-board/panel.generated.d.ts.map +1 -1
  54. package/dist/work-board/panel.mjs +293 -62
  55. package/dist/work-board/panel.mjs.map +1 -1
  56. package/dist/work-board.mjs +293 -62
  57. package/dist/work-board.mjs.map +1 -1
  58. package/package.json +12 -4
  59. package/repo-maintenance/.agentproto/APP.md +22 -0
  60. package/repo-maintenance/.agentproto/agents/repo-maintenance-reviewer/AGENT.md +142 -0
  61. package/repo-maintenance/.agentproto/workflows/maintain/WORKFLOW.md +262 -0
  62. package/repo-maintenance/.agentproto/workflows/maintain/entry.mjs +672 -0
  63. package/repo-maintenance/README.md +79 -0
  64. package/repo-maintenance/routines/repo-maintenance-daily/ROUTINE.md +77 -0
  65. package/repo-maintenance/routines/repo-maintenance-weekly/ROUTINE.md +82 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/panel-bridge.ts","../../src/session-chat/blob-embed.ts","../../src/session-chat/panel.ts"],"names":[],"mappings":";;;;;;AAqFO,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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AAA;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;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 injects 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 * — same pattern as guilde's canvas.app.ts canvasShellHtml() (the reference\n * implementation that renders correctly in Claude hosts). No auto-request:\n * panels stay inline until the user clicks.\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 `#dm`/`#pin` 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\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 #dm/#pin 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 buttons (NO auto-request) ──────────────────────\n// Injected by the shared bridge so every panel gets them without touching\n// its own markup. Mirrors guilde canvas.app.ts canvasShellHtml(): the\n// panel stays inline by default; the user expands on demand. Buttons only\n// appear for modes the host advertises in hostContext.availableDisplayModes.\n(function(){\n function mount(){\n var style = document.createElement('style');\n style.textContent = '#dm,#pin{display:none;position:fixed;top:8px;z-index:10;'\n + 'border:1px solid #d0d0d0;background:#fff;color:#1a1a1a;'\n + 'font:600 13px/1 system-ui,sans-serif;padding:7px 12px;border-radius:6px;'\n + 'cursor:pointer;box-shadow:0 1px 4px rgba(0,0,0,.18)}'\n + '#dm{right:8px}#pin{right:118px}'\n + '#dm:hover,#pin:hover{background:#f2f2f2;border-color:#b0b0b0}'\n + '@media (prefers-color-scheme:dark){'\n + '#dm,#pin{border-color:#555;background:#2a2a2a;color:#f0f0f0;box-shadow:0 1px 4px rgba(0,0,0,.5)}'\n + '#dm:hover,#pin:hover{background:#333;border-color:#777}}';\n document.head.appendChild(style);\n\n var btn = document.createElement('button');\n btn.id = 'dm'; btn.type = 'button'; btn.title = \"Basculer l'affichage\";\n var pin = document.createElement('button');\n pin.id = 'pin'; pin.type = 'button'; pin.title = 'Épingler sur le côté (pip)';\n document.body.appendChild(pin);\n document.body.appendChild(btn);\n\n function has(avail, m){ return !!avail && avail.indexOf(m) >= 0; }\n\n // Re-sync button visibility + label from the current host context.\n function syncBtn(ctx){\n ctx = ctx || {};\n var avail = ctx.availableDisplayModes;\n // Diagnostic: what does THIS host actually advertise? (inline/fullscreen/pip)\n console.log('[mcp-app] displayMode=', ctx.displayMode,\n 'availableDisplayModes=', avail);\n\n // Fullscreen toggle button.\n if (has(avail, 'fullscreen')){\n btn.style.display = 'block';\n btn.textContent = (ctx.displayMode === 'fullscreen') ? '⤡ Réduire' : '⤢ Agrandir';\n } else { btn.style.display = 'none'; }\n\n // Dedicated pip (\"pinned on side\") button — only if the host advertises pip.\n if (has(avail, 'pip')){\n pin.style.display = 'block';\n pin.textContent = (ctx.displayMode === 'pip') ? '⤡ Détacher' : '📌 Épingler';\n } else { pin.style.display = 'none'; }\n }\n\n onHostContext(syncBtn);\n\n btn.addEventListener('click', function(){\n var ctx = getHostContext() || {};\n var inPanel = (ctx.displayMode === 'fullscreen' || ctx.displayMode === 'pip');\n requestDisplayMode(inPanel ? 'inline' : 'fullscreen').catch(function(){});\n });\n\n pin.addEventListener('click', function(){\n var ctx = getHostContext() || {};\n requestDisplayMode(ctx.displayMode === 'pip' ? 'inline' : 'pip').catch(function(){});\n });\n }\n if (document.body) mount();\n else document.addEventListener('DOMContentLoaded', mount);\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;AA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AA;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,13 +1,12 @@
1
1
  import { z } from 'zod';
2
2
  import { defineApp } from '@agentproto/app-kit';
3
+ import { DISPLAY_MODE_SCRIPT_BODY } from '@agentproto/app-client/display-mode';
3
4
 
4
5
  /**
5
6
  * @agentproto/apps v0.1.0
6
7
  * Ready-made agentproto apps (teams of agents + workflows) built on app-kit.
7
8
  */
8
9
 
9
-
10
- // src/panel-bridge.ts
11
10
  function panelBridgeScript(appName) {
12
11
  return `// \u2500\u2500 MCP Apps bridge (shared: panel-bridge.ts) \u2500\u2500
13
12
  // JSON-RPC 2.0 over window.parent.postMessage \xB7 spec 2026-01-26
@@ -84,7 +83,7 @@ function initBridge(){
84
83
  return window.McpApp.connect().then(function(conn){
85
84
  _standaloneApp = conn;
86
85
  // No host to advertise a hostContext \u2014 default to inline with no
87
- // other modes available, which keeps the #dm/#pin toggle buttons
86
+ // other modes available, which keeps the display-mode toggle buttons
88
87
  // hidden (they only show for modes hostContext.availableDisplayModes
89
88
  // lists) instead of rendering two buttons with nothing to switch to.
90
89
  _setHostContext({displayMode: 'inline', availableDisplayModes: []});
@@ -126,71 +125,17 @@ function callTool(name, args){
126
125
  });
127
126
  }
128
127
 
129
- // \u2500\u2500 Display-mode toggle buttons (NO auto-request) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
130
- // Injected by the shared bridge so every panel gets them without touching
131
- // its own markup. Mirrors guilde canvas.app.ts canvasShellHtml(): the
132
- // panel stays inline by default; the user expands on demand. Buttons only
133
- // appear for modes the host advertises in hostContext.availableDisplayModes.
134
- (function(){
135
- function mount(){
136
- var style = document.createElement('style');
137
- style.textContent = '#dm,#pin{display:none;position:fixed;top:8px;z-index:10;'
138
- + 'border:1px solid #d0d0d0;background:#fff;color:#1a1a1a;'
139
- + 'font:600 13px/1 system-ui,sans-serif;padding:7px 12px;border-radius:6px;'
140
- + 'cursor:pointer;box-shadow:0 1px 4px rgba(0,0,0,.18)}'
141
- + '#dm{right:8px}#pin{right:118px}'
142
- + '#dm:hover,#pin:hover{background:#f2f2f2;border-color:#b0b0b0}'
143
- + '@media (prefers-color-scheme:dark){'
144
- + '#dm,#pin{border-color:#555;background:#2a2a2a;color:#f0f0f0;box-shadow:0 1px 4px rgba(0,0,0,.5)}'
145
- + '#dm:hover,#pin:hover{background:#333;border-color:#777}}';
146
- document.head.appendChild(style);
147
-
148
- var btn = document.createElement('button');
149
- btn.id = 'dm'; btn.type = 'button'; btn.title = "Basculer l'affichage";
150
- var pin = document.createElement('button');
151
- pin.id = 'pin'; pin.type = 'button'; pin.title = '\xC9pingler sur le c\xF4t\xE9 (pip)';
152
- document.body.appendChild(pin);
153
- document.body.appendChild(btn);
154
-
155
- function has(avail, m){ return !!avail && avail.indexOf(m) >= 0; }
156
-
157
- // Re-sync button visibility + label from the current host context.
158
- function syncBtn(ctx){
159
- ctx = ctx || {};
160
- var avail = ctx.availableDisplayModes;
161
- // Diagnostic: what does THIS host actually advertise? (inline/fullscreen/pip)
162
- console.log('[mcp-app] displayMode=', ctx.displayMode,
163
- 'availableDisplayModes=', avail);
164
-
165
- // Fullscreen toggle button.
166
- if (has(avail, 'fullscreen')){
167
- btn.style.display = 'block';
168
- btn.textContent = (ctx.displayMode === 'fullscreen') ? '\u2921 R\xE9duire' : '\u2922 Agrandir';
169
- } else { btn.style.display = 'none'; }
170
-
171
- // Dedicated pip ("pinned on side") button \u2014 only if the host advertises pip.
172
- if (has(avail, 'pip')){
173
- pin.style.display = 'block';
174
- pin.textContent = (ctx.displayMode === 'pip') ? '\u2921 D\xE9tacher' : '\u{1F4CC} \xC9pingler';
175
- } else { pin.style.display = 'none'; }
176
- }
177
-
178
- onHostContext(syncBtn);
179
-
180
- btn.addEventListener('click', function(){
181
- var ctx = getHostContext() || {};
182
- var inPanel = (ctx.displayMode === 'fullscreen' || ctx.displayMode === 'pip');
183
- requestDisplayMode(inPanel ? 'inline' : 'fullscreen').catch(function(){});
184
- });
185
-
186
- pin.addEventListener('click', function(){
187
- var ctx = getHostContext() || {};
188
- requestDisplayMode(ctx.displayMode === 'pip' ? 'inline' : 'pip').catch(function(){});
189
- });
190
- }
191
- if (document.body) mount();
192
- else document.addEventListener('DOMContentLoaded', mount);
193
- })();`;
128
+ // \u2500\u2500 Display-mode toggle (shared: @agentproto/app-client/display-mode) \u2500\u2500
129
+ // The installer is inlined verbatim (it is self-contained and idempotent),
130
+ // then handed this panel's own JSON-RPC plumbing. NO auto-request: the
131
+ // panel stays inline until the user clicks, and the buttons only appear for
132
+ // the modes the host advertises in hostContext.availableDisplayModes.
133
+ ${DISPLAY_MODE_SCRIPT_BODY}
134
+ var displayMode = window.AgentprotoUI.installDisplayMode({
135
+ getHostContext: getHostContext,
136
+ onHostContext: onHostContext,
137
+ requestDisplayMode: requestDisplayMode
138
+ });`;
194
139
  }
195
140
 
196
141
  // src/session-chat/blob-embed.ts
@@ -722,7 +667,21 @@ var sessionChatApp = defineApp({
722
667
  ui: {
723
668
  html: SESSION_CHAT_FALLBACK_HTML,
724
669
  title: "Session Chat",
725
- tools: ["session_list", "agent_start", "adapter_list", "conversation_read"]
670
+ // `session_restart` is what makes an ENDED session (completed / killed /
671
+ // exited / crashed) recoverable from the chat instead of a dead end: the
672
+ // UI offers "Restart session" in place of the composer, and the tool
673
+ // resumes the same conversation (ACP-level resume via the adapter session
674
+ // id, fresh spawn as fallback) and returns a NEW session id the chat
675
+ // navigates to. Kept in step with the installed app's own allowlist
676
+ // (`@agentik/session-chat`'s APP.md `ui.tools`) — a tool missing from
677
+ // EITHER list is refused for the surface that reads it.
678
+ tools: [
679
+ "session_list",
680
+ "agent_start",
681
+ "adapter_list",
682
+ "conversation_read",
683
+ "session_restart"
684
+ ]
726
685
  }
727
686
  });
728
687