@agentproto/apps 0.8.0 → 0.9.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 (60) hide show
  1. package/README.md +29 -1
  2. package/dist/agents-overview/index.d.ts +54 -0
  3. package/dist/agents-overview/index.d.ts.map +1 -0
  4. package/dist/agents-overview/panel.d.ts +14 -0
  5. package/dist/agents-overview/panel.d.ts.map +1 -0
  6. package/dist/agents-overview/panel.mjs +306 -0
  7. package/dist/agents-overview/panel.mjs.map +1 -0
  8. package/dist/agents-overview.mjs +336 -0
  9. package/dist/agents-overview.mjs.map +1 -0
  10. package/dist/bin/sync.mjs +25 -11
  11. package/dist/bin/sync.mjs.map +1 -1
  12. package/dist/bureau-sessions/index.d.ts +52 -0
  13. package/dist/bureau-sessions/index.d.ts.map +1 -0
  14. package/dist/bureau-sessions/panel.d.ts +10 -0
  15. package/dist/bureau-sessions/panel.d.ts.map +1 -0
  16. package/dist/bureau-sessions/panel.mjs +297 -0
  17. package/dist/bureau-sessions/panel.mjs.map +1 -0
  18. package/dist/bureau-sessions.mjs +329 -0
  19. package/dist/bureau-sessions.mjs.map +1 -0
  20. package/dist/content-team/workflows/produce-content.d.ts +14 -2
  21. package/dist/content-team/workflows/produce-content.d.ts.map +1 -1
  22. package/dist/content-team/workflows/produce-cover.d.ts +13 -1
  23. package/dist/content-team/workflows/produce-cover.d.ts.map +1 -1
  24. package/dist/content-team.mjs +25 -11
  25. package/dist/content-team.mjs.map +1 -1
  26. package/dist/index.d.ts +24 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.mjs +2635 -12
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/live-session/index.d.ts +46 -0
  31. package/dist/live-session/index.d.ts.map +1 -0
  32. package/dist/live-session/logic.d.ts +125 -0
  33. package/dist/live-session/logic.d.ts.map +1 -0
  34. package/dist/live-session/panel.d.ts +61 -0
  35. package/dist/live-session/panel.d.ts.map +1 -0
  36. package/dist/live-session/panel.mjs +993 -0
  37. package/dist/live-session/panel.mjs.map +1 -0
  38. package/dist/live-session.mjs +1032 -0
  39. package/dist/live-session.mjs.map +1 -0
  40. package/dist/mcp-app-types.d.ts +33 -0
  41. package/dist/mcp-app-types.d.ts.map +1 -0
  42. package/dist/panel-bridge.d.ts +38 -0
  43. package/dist/panel-bridge.d.ts.map +1 -0
  44. package/dist/session-story/index.d.ts +66 -0
  45. package/dist/session-story/index.d.ts.map +1 -0
  46. package/dist/session-story/panel.d.ts +31 -0
  47. package/dist/session-story/panel.d.ts.map +1 -0
  48. package/dist/session-story/panel.mjs +970 -0
  49. package/dist/session-story/panel.mjs.map +1 -0
  50. package/dist/session-story.mjs +1002 -0
  51. package/dist/session-story.mjs.map +1 -0
  52. package/dist/sessions-panel/index.d.ts +51 -0
  53. package/dist/sessions-panel/index.d.ts.map +1 -0
  54. package/dist/sessions-panel/panel.d.ts +20 -0
  55. package/dist/sessions-panel/panel.d.ts.map +1 -0
  56. package/dist/sessions-panel/panel.mjs +511 -0
  57. package/dist/sessions-panel/panel.mjs.map +1 -0
  58. package/dist/sessions-panel.mjs +545 -0
  59. package/dist/sessions-panel.mjs.map +1 -0
  60. package/package.json +57 -6
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/panel-bridge.ts","../src/live-session/panel.ts","../src/live-session/index.ts"],"names":[],"mappings":";;;;;;;;;;AAqCO,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,oBAAA,EA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AAAE,GACtC;AACF;AAEA,IAAM,qBAAA,GAAwB,wBAAA;AAEvB,IAAM,iBAA4B,SAAA,CAAU;AAAA,EACjD,EAAA,EAAI,0BAAA;AAAA,EACJ,IAAA,EAAM,cAAA;AAAA,EACN,WAAA,EACE,kLAAA;AAAA,EAEF,QAAQ,EAAC;AAAA,EACT,EAAA,EAAI;AAAA,IACF,IAAA,EAAM,iBAAA,CAAkB,EAAE,WAAA,EAAa,uBAAuB,CAAA;AAAA,IAC9D,KAAA,EAAO,cAAA;AAAA,IACP,KAAA,EAAO,CAAC,kBAAA,EAAoB,oBAAA,EAAsB,cAAc;AAAA;AAEpE,CAAC","file":"live-session.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\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 = [];\nfunction post(msg){ window.parent.postMessage(msg, '*'); }\nfunction getHostContext(){ return _hostContext; }\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 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 rpcNotify('ui/notifications/initialized', {});\n });\n}\nfunction requestDisplayMode(mode){\n return rpcRequest('ui/request-display-mode', {mode: mode});\n}\nfunction callTool(name, args){\n return rpcRequest('tools/call', {name: name, arguments: args || {}}).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 * HTML bundle for the agentproto live-session widget — `LIVE_SESSION_HTML`,\n * a two-pane panel (left: live session tree, right: streaming timeline)\n * that lets a host attach to any running agent session and watch it work in\n * real time. Mounted via the `live_session` tool defined in ./index.ts.\n *\n * Kept in its own module, importing nothing beyond plain TS, so a consumer\n * that only needs the HTML (e.g. packages/vscode's story-panel-style\n * webviews, or a future live-session webview) can import it via the\n * `@agentproto/apps/live-session/panel` subpath without pulling in\n * `@agentproto/app-kit` (and therefore `@mastra/core`) the way importing\n * from `./index.js` would.\n *\n * Forked structurally from terminal-panel-app.ts: same \"static ui://\n * resource renders with empty initData, widget self-bootstraps via\n * tools/call\" pattern. Unlike the terminal (one WebSocket, one PTY), this\n * widget has two independent data needs — a polled tree snapshot and a\n * per-session event timeline — so it layers on top of the bridge rather\n * than replacing it with a single socket.\n *\n * Data paths (see `.plans/CONTRACT.md` §WP-B):\n * LEFT (tree): poll `app_session_tree` via `callTool` every ~2s.\n * RIGHT (timeline): PRIMARY = `EventSource` on `/sessions/:id/events/stream`\n * (opportunistic — falls back if it doesn't open/emit\n * within ~2.5s); FALLBACK = poll `app_session_events`\n * via `callTool` every ~1.5s, advancing `since`.\n * Both app_* tools are registered by WP-A (`app-pull-tools.ts`) and are\n * `visibility: [\"app\"]`-only, i.e. reachable solely over this bridge.\n *\n * The timeline reducer lives in `live-session/logic.ts` as a pure,\n * dependency-free module so it's unit-testable outside the browser. This\n * file inlines a hand-kept COPY of that same logic into the HTML bundle\n * (see \"INLINED REDUCER COPY\" below) since the widget ships as one\n * self-contained script with no bundler step. Keep the two in sync. Its MCP\n * Apps handshake comes from the shared spec-correct panel bridge.\n *\n * Rendering (WP1): the timeline body is patched INCREMENTALLY — a\n * text-delta that merges into the last row patches only that row's text\n * node (found via `data-row-id`); every other new row is appended with one\n * `insertAdjacentHTML`. A full `innerHTML` reset happens only on session\n * start/`setFocus()` and on display-mode switches. Auto-scroll decision is\n * `isNearBottom` (inlined copy, SPEC §2) captured BEFORE any DOM mutation:\n * stick to bottom when the user was at the bottom, otherwise preserve the\n * read position exactly and surface a \"new messages\" pill.\n *\n * Compact mode (WP3/WP4): when `hostContext.displayMode === 'inline'` (or\n * the viewport is under ~640px) the tree pane collapses into a header\n * `<select>` (WP4) and the timeline renders through `groupAdjacentToolCalls`\n * (inlined copy, SPEC §3) with a colour rail and collapsible tool-call\n * groups. `setFocus()` remains the only session-switch entry point.\n */\n\nimport { panelBridgeScript } from \"../panel-bridge.js\"\n\nexport type LiveSessionOutput = {\n /** Echoes the input id, or undefined to let the widget self-discover a\n * focus session client-side from `app_session_tree`. */\n sessionId?: string\n /** The daemon's own HTTP origin — connection recipe for both the SSE\n * stream and the bridge's `tools/call` fallback. */\n httpBaseUrl: string\n}\n\n// ── HTML bundle (zero CDN, self-contained) ──────────────────────────────────\n\nexport function LIVE_SESSION_HTML(initData: LiveSessionOutput): string {\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>agentproto live session</title>\n<style>\n*{box-sizing:border-box;margin:0;padding:0}\n:root{\n --bg:#0d1117;--bg2:#161b22;--bg3:#21262d;--border:#30363d;\n --text:#e6edf3;--text2:#8b949e;--text3:#6e7681;\n --green:#3fb950;--yellow:#d29922;--red:#f85149;--blue:#58a6ff;--purple:#bc8cff;\n}\nhtml,body{height:100%;font-family:ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;font-size:13px;background:var(--bg);color:var(--text);overflow:hidden}\n#app{display:flex;height:100%}\n#tree-pane{width:280px;flex-shrink:0;display:flex;flex-direction:column;border-right:1px solid var(--border);background:var(--bg2)}\n#tree-head{padding:10px 12px;border-bottom:1px solid var(--border);font-weight:600;font-size:12px;color:var(--text2);text-transform:uppercase;letter-spacing:.04em;flex-shrink:0}\n#tree-body{flex:1;overflow-y:auto;padding:6px}\n#timeline-pane{flex:1;display:flex;flex-direction:column;min-width:0;position:relative}\n#timeline-head{padding:10px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;flex-shrink:0}\n#timeline-head .focus-id{font-weight:600;font-size:13px;font-family:Menlo,Monaco,monospace}\n#head-summary{margin-left:auto;font-size:11px;color:var(--text2);display:flex;align-items:center;gap:4px;white-space:nowrap;overflow:hidden;min-width:0}\n#head-summary .sdot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:3px;vertical-align:1px}\n#head-summary .sdot.running{background:var(--green)}\n#head-summary .sdot.grey{background:var(--text3)}\n#head-summary .sdot.error{background:var(--red)}\n#usage-chip{font-size:10.5px;font-family:Menlo,Monaco,monospace;background:var(--bg3);border-radius:4px;padding:1px 6px;color:var(--text)}\n#status-line{margin-left:8px;font-size:11px;color:var(--text2);flex-shrink:0}\n#timeline-body{flex:1;overflow-y:auto;padding:10px 14px;display:flex;flex-direction:column;gap:8px}\n#head-selector{display:none;max-width:42%;font:inherit;font-size:12px;background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:2px 4px}\n#new-pill{display:none;position:absolute;right:14px;bottom:12px;z-index:6;background:var(--blue);color:#0d1117;border:none;font-size:11px;font-weight:700;padding:5px 11px;border-radius:12px;cursor:pointer;box-shadow:0 1px 4px rgba(0,0,0,.4)}\n#new-pill.show{display:block}\n\n/* WP3 compact mode — colour rail + tighter rows; only under body.compact-mode\n (displayMode 'inline' or narrow viewport). fullscreen/pip keep the cards. */\nbody.compact-mode #tree-pane{display:none}\nbody.compact-mode #head-selector{display:inline-block}\nbody.compact-mode #focus-id-label{display:none}\nbody.compact-mode .row{border-radius:6px;padding:5px 8px;border-left-width:3px}\nbody.compact-mode .row.text{border-left-color:var(--blue)}\nbody.compact-mode .row.tool-call{border-left-color:var(--yellow)}\nbody.compact-mode .row.turn-end{border-left-color:var(--purple)}\nbody.compact-mode .row .body{font-size:12px;margin-top:3px}\nbody.compact-mode .row .rhead{font-size:10px}\ndetails.tool-group{border:1px solid var(--border);border-radius:8px;background:var(--bg2);padding:5px 8px;border-left:3px solid var(--yellow)}\ndetails.tool-group>summary{cursor:pointer;font-size:11px;color:var(--text2);font-weight:600;list-style:none}\ndetails.tool-group[open]>summary{margin-bottom:6px}\ndetails.tool-group .row{margin-top:5px}\n\n.tnode{border-radius:6px;cursor:pointer;padding:5px 8px;margin:1px 0;display:flex;align-items:center;gap:7px;font-size:12px}\n.tnode:hover{background:var(--bg3)}\n.tnode.focus{background:var(--bg3);outline:1px solid var(--blue)}\n.tnode .dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}\n.dot.running{background:var(--green)}\n.dot.grey{background:var(--text3)}\n.dot.error{background:var(--red)}\n.tnode .label{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:Menlo,Monaco,monospace}\n.tnode .badge{font-size:9px;font-weight:700;color:var(--purple);border:1px solid var(--purple);border-radius:3px;padding:0 4px;flex-shrink:0}\n.tchildren{margin-left:14px;border-left:1px solid var(--border);padding-left:4px}\n#tree-empty{padding:12px;color:var(--text3);font-size:12px}\n\n.row{border:1px solid var(--border);border-radius:8px;background:var(--bg2);padding:8px 10px}\n.row .rhead{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--text2)}\n.row .kind{font-weight:700;text-transform:uppercase;letter-spacing:.03em;font-size:10px}\n.row.text .kind{color:var(--blue)}\n.row.tool-call .kind{color:var(--yellow)}\n.row.turn-end .kind{color:var(--purple)}\n.row .body{margin-top:5px;font-size:12.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word}\n.row.text .body{font-family:inherit}\n.row.tool-call .toolname{font-family:Menlo,Monaco,monospace;font-weight:600}\n.status-badge{font-size:9px;font-weight:700;border-radius:3px;padding:1px 5px;margin-left:6px}\n.status-badge.pending{background:var(--bg3);color:var(--text2)}\n.status-badge.ok{background:#0f3d20;color:var(--green)}\n.status-badge.error{background:#3d1418;color:var(--red)}\n.row details{margin-top:6px}\n.row summary{cursor:pointer;font-size:11px;color:var(--text2)}\n.row pre{margin-top:4px;font-family:Menlo,Monaco,monospace;font-size:11px;white-space:pre-wrap;word-break:break-word;color:var(--text2);background:var(--bg);border-radius:5px;padding:6px 8px;max-height:200px;overflow:auto}\n.chip{display:inline-block;font-size:10.5px;font-family:Menlo,Monaco,monospace;background:var(--bg3);border-radius:4px;padding:2px 6px}\n#timeline-empty{color:var(--text3);font-size:12px;padding:8px 2px}\n</style>\n</head>\n<body>\n<div id=\"app\">\n <div id=\"tree-pane\">\n <div id=\"tree-head\">Sessions</div>\n <div id=\"tree-body\"><div id=\"tree-empty\">Loading…</div></div>\n </div>\n <div id=\"timeline-pane\">\n <div id=\"timeline-head\">\n <span class=\"focus-id\" id=\"focus-id-label\">—</span>\n <select id=\"head-selector\" title=\"Sessions\"></select>\n <span id=\"head-summary\"></span>\n <span id=\"status-line\">connecting…</span>\n </div>\n <div id=\"timeline-body\"><div id=\"timeline-empty\">No session focused yet.</div></div>\n <button id=\"new-pill\" type=\"button\">↓ New messages</button>\n </div>\n</div>\n<script>\nwindow.__APP_INIT__ = ${JSON.stringify(initData)};\n\n${panelBridgeScript(\"agentproto-live-session\")}\n\n// ============================================================\n// INLINED REDUCER COPY — hand-kept mirror of live-session/logic.ts.\n// Plain JS, same semantics: coalesce consecutive text-delta of the same\n// session (and rejoin an unterminated mid-line fragment split by an\n// interleaved record — see the TS module's text-delta arm), pair\n// tool-call/tool-result by toolCallId, pass through turn-end, keep usage\n// as STATE (SPEC §1: usage leaves the timeline — a usage_update record\n// never produces a row), ignore unknown kinds. Keep in sync with the TS\n// module; the TS module is the one the test suite imports.\n// ============================================================\n\nfunction initialTimelineState() {\n return { rows: [], usage: null };\n}\n\nfunction rowId(record, rows) {\n return record.seq != null ? (record.kind + '-' + record.seq) : (record.kind + '-' + rows.length);\n}\n\n// Fold a text-delta record into an existing row (fresh object), keeping the\n// row's \"partial\" hint in step with the latest record — see mergeTextDelta in\n// the TS module.\nfunction mergeTextDelta(row, record) {\n var merged = Object.assign({}, row, {\n text: row.text + (record.text || ''),\n seq: record.seq,\n ts: record.ts,\n });\n if (record.partial === true) merged.partial = true;\n else delete merged.partial;\n return merged;\n}\n\nfunction reduceEvent(state, record) {\n switch (record.kind) {\n case 'text-delta': {\n var last = state.rows[state.rows.length - 1];\n if (last && last.kind === 'text' && last.sessionId === record.sessionId) {\n return { rows: state.rows.slice(0, -1).concat([mergeTextDelta(last, record)]), usage: state.usage };\n }\n // Debounce can flush an unterminated mid-word fragment (flagged\n // partial), let a tool-call land, then flush the continuation — look\n // back within the same turn (bounded by this session's last turn-end)\n // for that session's most recent text row and continue it in place.\n // Only the explicit partial flag glues: a non-partial record with no\n // trailing newline is the writer's normal end-of-text-block shape.\n for (var i = state.rows.length - 1; i >= 0; i--) {\n var prior = state.rows[i];\n if (prior.sessionId !== record.sessionId) continue;\n if (prior.kind === 'turn-end') break;\n if (prior.kind !== 'text') continue;\n if (prior.partial === true) {\n var patched = state.rows.slice();\n patched[i] = mergeTextDelta(prior, record);\n return { rows: patched, usage: state.usage };\n }\n break;\n }\n var row = {\n kind: 'text', id: rowId(record, state.rows), seq: record.seq, ts: record.ts,\n sessionId: record.sessionId, text: record.text || '',\n };\n if (record.partial === true) row.partial = true;\n return { rows: state.rows.concat([row]), usage: state.usage };\n }\n case 'tool-call': {\n var row = {\n kind: 'tool-call', id: rowId(record, state.rows), seq: record.seq, ts: record.ts,\n sessionId: record.sessionId, toolCallId: record.toolCallId || '',\n toolName: record.toolName || 'unknown', arguments: record.arguments, status: 'pending',\n };\n return { rows: state.rows.concat([row]), usage: state.usage };\n }\n case 'tool-result': {\n var idx = -1;\n for (var i = 0; i < state.rows.length; i++) {\n if (state.rows[i].kind === 'tool-call' && state.rows[i].toolCallId === record.toolCallId) idx = i;\n }\n if (idx === -1) {\n var row = {\n kind: 'tool-call', id: rowId(record, state.rows), seq: record.seq, ts: record.ts,\n sessionId: record.sessionId, toolCallId: record.toolCallId || '', toolName: 'unknown',\n status: record.isError ? 'error' : 'ok', result: record.result,\n };\n return { rows: state.rows.concat([row]), usage: state.usage };\n }\n var updated = Object.assign({}, state.rows[idx], {\n status: record.isError ? 'error' : 'ok', result: record.result,\n });\n var rows = state.rows.slice();\n rows[idx] = updated;\n return { rows: rows, usage: state.usage };\n }\n case 'turn-end': {\n var row = {\n kind: 'turn-end', id: rowId(record, state.rows), seq: record.seq, ts: record.ts,\n sessionId: record.sessionId, reason: record.reason,\n };\n return { rows: state.rows.concat([row]), usage: state.usage };\n }\n case 'usage_update': {\n // Usage is state, not a row (SPEC §1) — last-write-wins, no merge with\n // the prior snapshot. state.rows is reused as-is (it didn't change).\n return {\n rows: state.rows,\n usage: {\n size: record.size, used: record.used, cost: record.cost,\n tokensIn: record.tokensIn, tokensOut: record.tokensOut,\n seq: record.seq, ts: record.ts,\n },\n };\n }\n default:\n return state;\n }\n}\n\n// ============================================================\n// INLINED PURE HELPERS — exact copies of live-session/logic.ts's\n// isNearBottom (SPEC §2) and groupAdjacentToolCalls (SPEC §3). Same names,\n// same signatures, same default thresholds; plain JS because the widget\n// has no import step.\n// ============================================================\n\nvar SCROLL_STICK_THRESHOLD_PX = 24;\n\nfunction isNearBottom(scrollHeight, scrollTop, clientHeight, threshold) {\n if (threshold == null) threshold = SCROLL_STICK_THRESHOLD_PX;\n return scrollHeight - scrollTop - clientHeight <= threshold;\n}\n\nvar TOOL_CALL_GROUP_THRESHOLD = 2;\n\n// Collapse runs of \\`threshold\\`+ adjacent tool-call rows into one\n// {kind:'tool-group', rows:[...]} entry; everything else passes through as\n// individual {kind:'row', row} entries, same order as the input.\nfunction groupAdjacentToolCalls(rows, threshold) {\n if (threshold == null) threshold = TOOL_CALL_GROUP_THRESHOLD;\n var out = [];\n var run = [];\n function flushRun() {\n if (!run.length) return;\n if (run.length >= threshold) out.push({ kind: 'tool-group', rows: run });\n else for (var j = 0; j < run.length; j++) out.push({ kind: 'row', row: run[j] });\n run = [];\n }\n for (var i = 0; i < rows.length; i++) {\n if (rows[i].kind === 'tool-call') { run.push(rows[i]); continue; }\n flushRun();\n out.push({ kind: 'row', row: rows[i] });\n }\n flushRun();\n return out;\n}\n\n// ============================================================\n// Rendering helpers\n// ============================================================\n\nfunction escHtml(s) {\n return String(s == null ? '' : s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');\n}\n\nfunction safeJson(v) {\n try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); }\n}\n\nfunction statusDotClass(status) {\n if (status === 'running' || status === 'starting') return 'running';\n if (status === 'error' || status === 'killed') return 'error';\n return 'grey';\n}\n\n// SPEC §4 (non-contract guidance): 52524 → \"52.5k\", >=1e6 → \"M\" suffix,\n// one decimal, trailing .0 vanishes because the value stays a number.\n// cost → \"$\" + toFixed(2). Read from timelineState.usage.\nfunction fmtCompactNum(n) {\n if (typeof n !== 'number' || !isFinite(n)) return null;\n if (n >= 1000000) return (Math.round(n / 100000) / 10) + 'M';\n if (n >= 1000) return (Math.round(n / 100) / 10) + 'k';\n return String(n);\n}\n\nfunction usageChipText(usage) {\n if (!usage) return '';\n var bits = [];\n if (usage.used != null && usage.size != null) {\n bits.push(fmtCompactNum(usage.used) + '/' + fmtCompactNum(usage.size));\n } else if (usage.used != null) {\n bits.push(fmtCompactNum(usage.used));\n }\n if (typeof usage.cost === 'number') bits.push('$' + usage.cost.toFixed(2));\n return bits.join(' · ');\n}\n\n// WP5: elapsed seconds since the timeline's first row (running only).\nfunction elapsedText(rows, status) {\n if (status !== 'running' && status !== 'starting') return null;\n if (!rows.length || rows[0].ts == null) return null;\n var ms = new Date(rows[0].ts).getTime();\n if (!isFinite(ms)) return null;\n return Math.max(0, Math.round((Date.now() - ms) / 1000)) + 's';\n}\n\n// ============================================================\n// LEFT pane — live tree\n// ============================================================\n\nvar currentTree = [];\nvar focusId = (window.__APP_INIT__ && window.__APP_INIT__.sessionId) || null;\n// Where the current focus came from: 'pinned' (the tool result that mounted\n// this widget named a session — never auto-switched away), 'auto' (self-\n// discovered newest running session, a guess the host may still correct),\n// 'user' (explicit click/selector choice — outranks everything).\nvar focusSource = focusId ? 'pinned' : null;\nvar bootDone = false;\nvar treeTimer = null;\n\n// INLINED COPY of live-session/logic.ts extractToolResultSessionId —\n// keep in sync (same convention as the reducer copy below).\nfunction extractToolResultSessionId(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 {\n var body = JSON.parse(item.text);\n if (body && typeof body.sessionId === 'string' && body.sessionId) return body.sessionId;\n if (body && typeof body.id === 'string' && body.id) return body.id;\n } catch (_) {}\n return null;\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 instead of leaving\n// pollTree() to self-discover the newest running one, which made every\n// agent_start card show the latest started session rather than its own.\nonHostNotification(function(method, params) {\n if (method !== 'ui/notifications/tool-result') return;\n var id = extractToolResultSessionId(params);\n if (!id || focusSource === 'user' || id === focusId) return;\n focusSource = 'pinned';\n if (bootDone) setFocus(id);\n else focusId = id; // boot's own startTimeline(focusId) picks it up\n});\n\nfunction findNode(nodes, id) {\n for (var i = 0; i < nodes.length; i++) {\n if (nodes[i].id === id) return nodes[i];\n var found = findNode(nodes[i].children || [], id);\n if (found) return found;\n }\n return null;\n}\n\nfunction flattenDfs(nodes, out) {\n out = out || [];\n for (var i = 0; i < nodes.length; i++) {\n out.push(nodes[i]);\n flattenDfs(nodes[i].children || [], out);\n }\n return out;\n}\n\nfunction pickInitialFocus(tree) {\n var flat = flattenDfs(tree);\n var alive = flat.filter(function(n) { return n.status === 'running' || n.status === 'starting'; });\n if (alive.length) return alive[alive.length - 1].id;\n return tree.length ? tree[0].id : null;\n}\n\nfunction renderTreeNode(node, depth) {\n var childrenHtml = (node.children || []).map(function(c) { return renderTreeNode(c, depth + 1); }).join('');\n var badge = node.isOrchestrator ? '<span class=\"badge\">orch</span>' : '';\n var cls = 'tnode' + (node.id === focusId ? ' focus' : '');\n return '<div class=\"' + cls + '\" data-id=\"' + escHtml(node.id) + '\">' +\n '<span class=\"dot ' + statusDotClass(node.status) + '\"></span>' +\n '<span class=\"label\">' + escHtml(node.label || node.id) + '</span>' + badge +\n '</div>' +\n (childrenHtml ? '<div class=\"tchildren\">' + childrenHtml + '</div>' : '');\n}\n\n// WP4: compact header <select> mirrors the tree; still routes through\n// setFocus() — the only session-switch entry point.\nfunction renderHeadSelector() {\n var sel = document.getElementById('head-selector');\n var flat = flattenDfs(currentTree);\n while (sel.firstChild) sel.removeChild(sel.firstChild);\n if (!flat.length) return;\n for (var i = 0; i < flat.length; i++) {\n var n = flat[i];\n var o = document.createElement('option');\n o.value = n.id;\n o.textContent = (n.id === focusId ? '● ' : '') + (n.label || n.id);\n sel.appendChild(o);\n }\n sel.value = focusId || '';\n}\n\nfunction renderTree() {\n var body = document.getElementById('tree-body');\n var root = focusId ? findNode(currentTree, focusId) : null;\n var renderNodes = root ? [root] : currentTree;\n if (!renderNodes.length) {\n body.innerHTML = '<div id=\"tree-empty\">No sessions.</div>';\n renderHeadSelector();\n return;\n }\n body.innerHTML = renderNodes.map(function(n) { return renderTreeNode(n, 0); }).join('');\n var els = body.querySelectorAll('.tnode');\n els.forEach(function(el) {\n el.addEventListener('click', function() {\n var id = el.getAttribute('data-id');\n if (id === focusId) return;\n focusSource = 'user';\n setFocus(id);\n });\n });\n renderHeadSelector();\n}\n\nfunction pollTree() {\n callTool('app_session_tree', {}).then(function(res) {\n currentTree = res.tree || [];\n if (!focusId) {\n focusId = pickInitialFocus(currentTree);\n if (focusId) { focusSource = 'auto'; startTimeline(focusId); }\n }\n renderTree();\n updateHeader();\n }).catch(function() {\n // Leave the last-known tree rendered; the next poll may recover.\n });\n}\n\n// ============================================================\n// RIGHT pane — timeline for focusId\n// ============================================================\n\nvar timelineState = initialTimelineState();\nvar sincePtr = 0;\nvar activeSource = null; // {type:'sse', es} | {type:'poll', timer}\nvar compactMode = false; // WP3: hostContext.displayMode === 'inline' (or narrow)\n\nfunction setStatus(msg) {\n document.getElementById('status-line').textContent = msg;\n}\n\nfunction isCompact() {\n return (getHostContext() && getHostContext().displayMode === 'inline') ||\n (typeof window !== 'undefined' && window.innerWidth < 640);\n}\n\n// WP3/WP4: apply the compact/expanded split. Only re-renders the timeline\n// when the mode actually flips (scroll + <details> state survive otherwise).\nfunction applyDisplayMode() {\n var c = isCompact();\n document.body.classList.toggle('compact-mode', c);\n if (c !== compactMode) {\n compactMode = c;\n renderTimelineFull();\n renderTree();\n }\n}\n\n// WP5 + WP2: one header line — \\`● running · 3 tools · 52.5k/200k · $0.04 · 12s\\`\n// (status dot from the focus node, tool count from the rows, usage from\n// timelineState.usage — no usage_update row anymore) + transport status.\nfunction updateHeader() {\n document.getElementById('focus-id-label').textContent = focusId || '—';\n var rows = timelineState.rows || [];\n var usage = timelineState.usage;\n var tools = 0;\n for (var i = 0; i < rows.length; i++) if (rows[i].kind === 'tool-call') tools++;\n var node = focusId ? findNode(currentTree, focusId) : null;\n var st = node ? node.status : null;\n var parts = [];\n if (st) parts.push('<span class=\"sdot ' + statusDotClass(st) + '\"></span>' + escHtml(st));\n if (tools) parts.push(tools + (tools === 1 ? ' tool' : ' tools'));\n var chip = usageChipText(usage);\n if (chip) parts.push('<span id=\"usage-chip\" class=\"chip\">' + escHtml(chip) + '</span>');\n var el = elapsedText(rows, st);\n if (el) parts.push(escHtml(el));\n document.getElementById('head-summary').innerHTML = parts.length ? parts.join(' · ') : '';\n}\n\nfunction captureDetailsOpenFlags(body) {\n var dets = body.querySelectorAll('details');\n var flags = [];\n for (var i = 0; i < dets.length; i++) flags.push(dets[i].open);\n return flags;\n}\n\nfunction restoreDetailsOpenFlags(body, flags) {\n var dets = body.querySelectorAll('details');\n for (var i = 0; i < dets.length && i < flags.length; i++) {\n if (flags[i]) dets[i].open = true;\n }\n}\n\n// Full rebuild — used ONLY for the first paint of a session, a setFocus()\n// session switch (SPEC §2: full reset is correct there), a display-mode\n// flip, and as the fallback for shapes the incremental patcher can't patch.\n// A display-mode flip re-renders the SAME content (WP3: \"réactif... sans\n// perdre le scroll ni l'état des <details>\"), so open <details> and the\n// exact scroll offset (not just the at-bottom decision) survive the rebuild.\nfunction renderTimelineFull() {\n var body = document.getElementById('timeline-body');\n var wasAtBottom = isNearBottom(body.scrollHeight, body.scrollTop, body.clientHeight);\n var savedScrollTop = body.scrollTop;\n var flags = captureDetailsOpenFlags(body);\n body.innerHTML = buildTimelineHtml();\n restoreDetailsOpenFlags(body, flags);\n body.scrollTop = wasAtBottom ? body.scrollHeight : savedScrollTop;\n updateHeader();\n}\n\nfunction buildTimelineHtml() {\n var rows = timelineState.rows;\n if (!rows.length) return '<div id=\"timeline-empty\">No events yet.</div>';\n if (compactMode) {\n var entries = groupAdjacentToolCalls(rows);\n var html = '';\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i];\n if (e.kind === 'tool-group') {\n html += '<details class=\"tool-group\"><summary>▸ ' + e.rows.length + ' tool calls</summary>' +\n e.rows.map(renderRow).join('') + '</details>';\n } else {\n html += renderRow(e.row);\n }\n }\n return html;\n }\n return rows.map(renderRow).join('');\n}\n\n// ── WP1 incremental patch (dense mode) ─────────────────────────────────\n// One record, one minimal DOM mutation. The common case (text-delta merged\n// into the LAST rendered row) patches just that row's text node. Anything\n// else appends via insertAdjacentHTML. Only rare in-place replacements\n// (tool-result merge, partial-lookback re-merge) swap ONE element's HTML.\nfunction applyRecordToDom(prevRows) {\n var body = document.getElementById('timeline-body');\n // Capture \"stuck to bottom?\" BEFORE any mutation (SPEC §2).\n var wasAtBottom = isNearBottom(body.scrollHeight, body.scrollTop, body.clientHeight);\n var rows = timelineState.rows;\n\n if (compactMode) {\n // Inline mode: smaller rows — full grouped rebuild, preserving\n // wasAtBottom/scrollTop and <details> open-state. Only touch the DOM\n // (and the scroll/pill decision) when the rows actually changed — a\n // usage_update leaves rows === prevRows, so it must fall through to the\n // header-only path below, same as the dense-mode branch.\n if (rows !== prevRows) {\n var flags = captureDetailsOpenFlags(body);\n body.innerHTML = buildTimelineHtml();\n restoreDetailsOpenFlags(body, flags);\n if (wasAtBottom) body.scrollTop = body.scrollHeight;\n else showNewPill();\n }\n updateHeader();\n return;\n }\n\n var appended = rows.length > prevRows.length;\n if (prevRows.length === 0 || (appended && !samePrefix(prevRows, rows))) {\n // First real paint of this session (empty placeholder present) or an\n // unexpected shape — full reset is correct/cheapest.\n body.innerHTML = buildTimelineHtml();\n body.scrollTop = body.scrollHeight;\n updateHeader();\n return;\n }\n\n if (appended) {\n body.insertAdjacentHTML('beforeend', renderRow(rows[rows.length - 1]));\n } else if (rows.length === prevRows.length && rows.length > 0) {\n // Exactly one row object replaced (tool-result merge, partial-text\n // re-merge via the reducer's lookback). Patch that one element only.\n // Scan from the tail: the hot path (a text-delta merged into the LAST\n // row, the dominant streaming case) is found in O(1) this way instead\n // of walking the whole array — the rare mid-array lookback re-merge\n // still resolves correctly, just slower.\n var idx = -1;\n for (var i = rows.length - 1; i >= 0; i--) {\n if (rows[i] !== prevRows[i]) { idx = i; break; }\n }\n var patched = false;\n if (idx >= 0) {\n var row = rows[idx];\n var el = body.querySelector('[data-row-id=\"' + escHtml(row.id) + '\"]');\n if (el) {\n if (row.kind === 'text' && idx === rows.length - 1) {\n // High-frequency case: patch the existing text node in place.\n var b = el.querySelector('.body');\n if (b) { b.textContent = row.text; patched = true; }\n }\n if (!patched) { el.outerHTML = renderRow(row); patched = true; }\n }\n }\n if (!patched) {\n // Multiple rows changed at once (shouldn't happen per-record) — rebuild.\n body.innerHTML = buildTimelineHtml();\n if (wasAtBottom) body.scrollTop = body.scrollHeight;\n updateHeader();\n return;\n }\n } else {\n // rows unchanged (usage_update) — header only.\n updateHeader();\n return;\n }\n\n // Scroll decision AFTER the mutation: stick or leave the position alone.\n if (wasAtBottom) body.scrollTop = body.scrollHeight;\n else showNewPill();\n updateHeader();\n}\n\nfunction samePrefix(prevRows, rows) {\n for (var i = 0; i < prevRows.length; i++) {\n if (prevRows[i] !== rows[i]) return false;\n }\n return true;\n}\n\nfunction showNewPill() {\n document.getElementById('new-pill').classList.add('show');\n}\n\nfunction hideNewPill() {\n document.getElementById('new-pill').classList.remove('show');\n}\n\nfunction renderRow(row) {\n if (row.kind === 'text') {\n return '<div class=\"row text\" data-row-id=\"' + escHtml(row.id) + '\"><div class=\"rhead\"><span class=\"kind\">text</span></div>' +\n '<div class=\"body\">' + escHtml(row.text) + '</div></div>';\n }\n if (row.kind === 'tool-call') {\n var badgeCls = row.status === 'pending' ? 'pending' : row.status;\n var badgeText = row.status === 'pending' ? 'pending' : (row.status === 'ok' ? 'ok' : 'error');\n var resultHtml = row.status !== 'pending'\n ? '<details><summary>result</summary><pre>' + escHtml(safeJson(row.result)) + '</pre></details>'\n : '';\n return '<div class=\"row tool-call\" data-row-id=\"' + escHtml(row.id) + '\"><div class=\"rhead\"><span class=\"kind\">tool</span>' +\n '<span class=\"toolname\">' + escHtml(row.toolName) + '</span>' +\n '<span class=\"status-badge ' + badgeCls + '\">' + badgeText + '</span></div>' +\n '<details><summary>arguments</summary><pre>' + escHtml(safeJson(row.arguments)) + '</pre></details>' +\n resultHtml + '</div>';\n }\n if (row.kind === 'turn-end') {\n return '<div class=\"row turn-end\" data-row-id=\"' + escHtml(row.id) + '\"><div class=\"rhead\"><span class=\"kind\">turn end</span>' +\n '<span class=\"chip\">' + escHtml(row.reason || '—') + '</span></div></div>';\n }\n return '';\n}\n\nfunction teardownTimeline() {\n if (activeSource) {\n if (activeSource.type === 'sse' && activeSource.es) {\n try { activeSource.es.close(); } catch (e) {}\n }\n // Both the poll re-arm timer AND the SSE open/first-message fallback\n // timer must be cleared, or a focus switch within the 2.5s window leaves\n // a stale timer that fires startPolling for the abandoned session.\n if (activeSource.timer) clearTimeout(activeSource.timer);\n if (activeSource.fallbackTimer) clearTimeout(activeSource.fallbackTimer);\n }\n activeSource = null;\n}\n\nfunction attemptSSE(id) {\n var settled = false;\n var es;\n try {\n es = new EventSource(window.__APP_INIT__.httpBaseUrl + '/sessions/' + encodeURIComponent(id) + '/events/stream');\n } catch (e) {\n startPolling(id);\n return;\n }\n var src = { type: 'sse', es: es, fallbackTimer: null };\n activeSource = src;\n // Every callback below re-checks focusId===id AND that src is still the\n // live source: a focus switch tears down src and starts a new one, so a\n // late open/message/error from this abandoned EventSource must be a no-op\n // rather than mutating the new focus's timeline or clobbering activeSource.\n function stale() { return activeSource !== src || focusId !== id; }\n src.fallbackTimer = setTimeout(function() {\n if (settled || stale()) return;\n settled = true;\n try { es.close(); } catch (e) {}\n startPolling(id);\n }, 2500);\n es.addEventListener('open', function() {\n if (settled || stale()) return;\n settled = true;\n clearTimeout(src.fallbackTimer);\n setStatus('streaming via SSE');\n });\n es.onmessage = function(evt) {\n if (stale()) return;\n if (!settled) {\n settled = true;\n clearTimeout(src.fallbackTimer);\n setStatus('streaming via SSE');\n }\n var rec;\n try { rec = JSON.parse(evt.data); } catch (e) { return; }\n var prev = timelineState;\n timelineState = reduceEvent(timelineState, rec);\n if (typeof rec.seq === 'number' && rec.seq > sincePtr) sincePtr = rec.seq;\n if (timelineState !== prev) applyRecordToDom(prev.rows);\n };\n es.onerror = function() {\n if (stale()) return;\n if (!settled) {\n settled = true;\n clearTimeout(src.fallbackTimer);\n try { es.close(); } catch (e) {}\n startPolling(id);\n } else {\n // Do not leave EventSource to perform its native reconnect: this\n // endpoint replays from since=0 when no cursor is provided, so a\n // transparent reconnect would duplicate every row already reduced.\n // The bridge poll resumes from sincePtr instead and preserves the\n // exactly-once cursor contract.\n try { es.close(); } catch (e) {}\n startPolling(id);\n }\n };\n}\n\nfunction startPolling(id) {\n activeSource = { type: 'poll', timer: null };\n setStatus('polling');\n function tick() {\n if (!activeSource || activeSource.type !== 'poll' || focusId !== id) return;\n callTool('app_session_events', { sessionId: id, since: sincePtr }).then(function(res) {\n var events = res.events || [];\n for (var i = 0; i < events.length; i++) {\n var prev = timelineState;\n timelineState = reduceEvent(timelineState, events[i]);\n if (timelineState !== prev) applyRecordToDom(prev.rows);\n }\n if (typeof res.nextSeq === 'number') sincePtr = res.nextSeq;\n setStatus('polling');\n if (activeSource) activeSource.timer = setTimeout(tick, 1500);\n }).catch(function() {\n setStatus('disconnected');\n if (activeSource) activeSource.timer = setTimeout(tick, 1500);\n });\n }\n tick();\n}\n\nfunction startTimeline(id) {\n teardownTimeline();\n timelineState = initialTimelineState();\n sincePtr = 0;\n hideNewPill();\n renderTimelineFull();\n setStatus('connecting…');\n attemptSSE(id);\n}\n\nfunction setFocus(id) {\n focusId = id;\n renderTree();\n startTimeline(id);\n}\n\n// ============================================================\n// Boot\n// ============================================================\n\ninitBridge().then(function() {\n var init = window.__APP_INIT__ || {};\n if (init.httpBaseUrl) return init;\n // Static ui:// resources render once at server-registration time with\n // EMPTY initData (mcp-apps-adapter.ts registerMcpApps) — fall back to\n // calling the tool ourselves over the bridge, same as the other panels.\n return callTool('live_session', {}).then(function(result) {\n window.__APP_INIT__ = result;\n return result;\n });\n}).then(function(init) {\n // Only override the focus when live_session itself named a session AND a\n // tool-result notification didn't already pin one while the fallback\n // tools/call above was in flight — the host's push names the exact\n // session this widget was mounted for, so it outranks the fallback's\n // (argument-less, hence session-less in practice) self-call.\n if (init.sessionId && focusSource !== 'pinned') {\n focusId = init.sessionId;\n focusSource = 'pinned';\n }\n onHostContext(function() {\n applyDisplayMode();\n updateHeader();\n });\n document.getElementById('head-selector').addEventListener('change', function(evt) {\n var id = evt.target.value;\n if (id && id !== focusId) { focusSource = 'user'; setFocus(id); }\n });\n document.getElementById('new-pill').addEventListener('click', function() {\n var body = document.getElementById('timeline-body');\n body.scrollTop = body.scrollHeight;\n hideNewPill();\n });\n document.getElementById('timeline-body').addEventListener('scroll', function() {\n // User scrolled back near the bottom — the pill is stale, hide it.\n var el = document.getElementById('timeline-body');\n if (isNearBottom(el.scrollHeight, el.scrollTop, el.clientHeight)) hideNewPill();\n });\n window.addEventListener('resize', function() {\n var c = isCompact();\n if (c !== compactMode) { applyDisplayMode(); }\n });\n applyDisplayMode();\n bootDone = true;\n pollTree();\n treeTimer = setInterval(pollTree, 2000);\n setInterval(updateHeader, 1000); // keep the WP5 elapsed clock fresh\n if (focusId) startTimeline(focusId);\n}).catch(function(e) {\n setStatus('Bridge error: ' + e.message);\n});\n</script>\n</body>\n</html>`\n}\n","/**\n * McpApp definition for the live-session widget — a two-pane panel (left:\n * live session tree, right: streaming timeline) that lets a host attach to\n * any running agent session and watch it work in real time.\n *\n * The HTML bundle itself (`LIVE_SESSION_HTML`, its wire protocol, the\n * inlined timeline-reducer copy, compact-mode rendering, …) lives in\n * ./panel.ts, which imports nothing beyond plain TS — see that file for the\n * full protocol/rendering doc. Kept separate so a consumer that only needs\n * the HTML can import `@agentproto/apps/live-session/panel` without pulling\n * in `@agentproto/app-kit` (and therefore `@mastra/core`) the way importing\n * from this file would.\n *\n * This module also exports `liveSessionApp`, a real `defineApp()`\n * `AppHandle` (`agents: []`, UI-only) — the catalog/emit/`app_install` path.\n * Its `ui.html` is a static snapshot (`LIVE_SESSION_HTML` called with the\n * default `httpBaseUrl`) since `AppUiDefinition.ui.html` must be a plain\n * string; it's separate from `makeLiveSessionApp` above, which the daemon\n * mounts directly at boot with the real daemon origin baked in per-call.\n */\n\nimport { z } from \"zod\"\nimport { defineApp, type AppHandle } from \"@agentproto/app-kit\"\nimport type { AgnoMcpApp } from \"../mcp-app-types.js\"\nimport { LIVE_SESSION_HTML, type LiveSessionOutput } from \"./panel.js\"\n\nexport { LIVE_SESSION_HTML }\nexport type { LiveSessionOutput }\n\nexport const liveSessionInputSchema = z.object({\n sessionId: z\n .string()\n .optional()\n .describe(\n \"Attach the widget to an existing session by id or name. Omit to \" +\n \"self-discover the newest running session from the tree.\",\n ),\n})\n\nexport type LiveSessionInput = z.infer<typeof liveSessionInputSchema>\n\nexport interface LiveSessionOps {\n /** The daemon's own HTTP origin, e.g. \"http://127.0.0.1:18790\". Defaults\n * to the daemon's documented default port (`index.ts:776`) so the app\n * works out of the box in the common single-daemon case. */\n httpBaseUrl?: string\n}\n\n/**\n * Factory: close over the daemon's own HTTP origin so execute() needs\n * nothing beyond the tool input (no registry access — mirrors\n * sessions-panel/index.ts and runtime's terminal-panel-app.ts; the app_*\n * tools this widget calls over the bridge are what actually touch the\n * registry).\n */\nexport function makeLiveSessionApp(\n ops?: LiveSessionOps,\n): AgnoMcpApp<LiveSessionInput, LiveSessionOutput> {\n const httpBaseUrl = ops?.httpBaseUrl ?? \"http://127.0.0.1:18790\"\n // `new URL(...).origin` normalises the base URL to the exact connectDomains\n // entry the CSP allowlist needs (same derivation as terminal-panel-app.ts's\n // wsOrigin), covering both the SSE EventSource and any bridge fallback.\n const httpOrigin = new URL(httpBaseUrl).origin\n\n return {\n id: \"live_session\",\n title: \"Live Session\",\n description:\n \"Open the live session widget — a two-pane view of a running agent \" +\n \"session: a live tree on the left, a streaming timeline (text, tool \" +\n \"calls/results, turn-end) on the right. Omit `sessionId` to \" +\n \"attach to the newest running session; pass one to attach directly.\",\n inputSchema: liveSessionInputSchema,\n execute: async input => ({\n sessionId: input.sessionId,\n httpBaseUrl,\n }),\n html: (initData: LiveSessionOutput) => LIVE_SESSION_HTML(initData),\n csp: { connectDomains: [httpOrigin] },\n }\n}\n\nconst DEFAULT_HTTP_BASE_URL = \"http://127.0.0.1:18790\"\n\nexport const liveSessionApp: AppHandle = defineApp({\n id: \"@agentproto/live-session\",\n name: \"Live Session\",\n description:\n \"Open the live session widget — a two-pane view of a running agent session: a live tree on \" +\n \"the left, a streaming timeline (text, tool calls/results, turn-end) on the right.\",\n agents: [],\n ui: {\n html: LIVE_SESSION_HTML({ httpBaseUrl: DEFAULT_HTTP_BASE_URL }),\n title: \"Live Session\",\n tools: [\"app_session_tree\", \"app_session_events\", \"live_session\"],\n },\n})\n"]}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Local McpApp-compatible shape used by agentproto's built-in daemon panels
3
+ * (sessions-panel, agents-overview, bureau-sessions, session-story,
4
+ * live-session). Mirrors @agstudio/mcp-apps McpApp<TIn,TOut> without
5
+ * importing it — agentproto is a separate pnpm workspace with no
6
+ * @agstudio/* dependency (same isolation invariant as the runtime's
7
+ * mcp-apps-adapter.ts, which registers instances of this shape on an
8
+ * McpServer and is the canonical consumer of this type).
9
+ */
10
+ import type { z } from "zod";
11
+ export interface AgnoMcpApp<TInput = unknown, TOutput = unknown> {
12
+ id: string;
13
+ title: string;
14
+ description?: string;
15
+ /** Must be a z.object({...}) so registerMcpApps can extract .shape. */
16
+ inputSchema: z.ZodObject<z.ZodRawShape>;
17
+ execute?: (input: TInput) => Promise<TOutput>;
18
+ html: string | ((initData: TOutput) => string);
19
+ /** Content-Security-Policy hints for the sandboxed host iframe, threaded
20
+ * by `registerMcpApps` into the ui:// RESOURCE's `_meta.ui.csp` (spec
21
+ * 2026-01-26 — CSP is resource-only, the tool's `_meta.ui` never carries
22
+ * it). Omit for apps that need no outbound connections beyond the host
23
+ * bridge (e.g. sessions-panel/agents-overview/bureau-sessions, which
24
+ * only ever talk to the host via postMessage). Apps that open their own
25
+ * WebSocket/fetch from inside the iframe (e.g. live-session's SSE, or
26
+ * runtime's terminal-panel-app.ts) must declare the exact origin(s) they
27
+ * connect to here. */
28
+ csp?: {
29
+ connectDomains?: string[];
30
+ resourceDomains?: string[];
31
+ };
32
+ }
33
+ //# sourceMappingURL=mcp-app-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-app-types.d.ts","sourceRoot":"","sources":["../src/mcp-app-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAG5B,MAAM,WAAW,UAAU,CAAC,MAAM,GAAG,OAAO,EAAE,OAAO,GAAG,OAAO;IAC7D,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,uEAAuE;IACvE,WAAW,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAA;IACvC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7C,IAAI,EAAE,MAAM,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,KAAK,MAAM,CAAC,CAAA;IAC9C;;;;;;;;2BAQuB;IACvB,GAAG,CAAC,EAAE;QAAE,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAA;CAChE"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Shared MCP Apps client bridge for agentproto panels.
3
+ *
4
+ * One spec-correct copy of the JSON-RPC-over-postMessage bridge that every
5
+ * ui:// panel embeds in its <script> block. Mirrors the behaviour of
6
+ * @agstudio/mcp-apps' mcpAppClientScript() — which we cannot import here:
7
+ * agentproto is a standalone pnpm workspace with no @agstudio/* dependency
8
+ * (same isolation invariant as mcp-apps-adapter.ts).
9
+ *
10
+ * Handshake (MCP Apps ext spec 2026-01-26, ext-apps McpUiInitializeRequest):
11
+ * params REQUIRE `appInfo` (Implementation: {name, version}),
12
+ * `appCapabilities`, and `protocolVersion`. Sending `clientInfo` instead
13
+ * of `appInfo` fails the host's schema validation — hosts either reply
14
+ * with an error or silently drop the request, so the panel's initBridge()
15
+ * promise never resolves and the panel renders blank while every
16
+ * server-side surface (tools, resources) works. That exact bug shipped in
17
+ * 4 copy-pasted bridges; this module is the single corrected source.
18
+ *
19
+ * The script defines, in panel scope:
20
+ * post / rpcRequest / rpcNotify — raw JSON-RPC plumbing
21
+ * onHostNotification(cb) — subscribe to host-pushed
22
+ * notifications (method, params)
23
+ * initBridge() — ui/initialize → ui/notifications/initialized
24
+ * callTool(name, args) — tools/call + JSON text unwrap
25
+ * getHostContext() / onHostContext(cb) — host context (displayMode, theme, …),
26
+ * captured from the initialize result and
27
+ * merged on ui/notifications/host-context-changed
28
+ * requestDisplayMode(mode) — ui/request-display-mode (inline|fullscreen|pip)
29
+ *
30
+ * Display-mode toggle: the bridge also injects two floating buttons
31
+ * (fullscreen + pip) in the top-right corner of every panel, shown only for
32
+ * the modes the host actually advertises via hostContext.availableDisplayModes
33
+ * — same pattern as guilde's canvas.app.ts canvasShellHtml() (the reference
34
+ * implementation that renders correctly in Claude hosts). No auto-request:
35
+ * panels stay inline until the user clicks.
36
+ */
37
+ export declare function panelBridgeScript(appName: string): string;
38
+ //# sourceMappingURL=panel-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"panel-bridge.d.ts","sourceRoot":"","sources":["../src/panel-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CA6IzD"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * McpApp definition for the agentproto "session story" panel.
3
+ *
4
+ * A per-session readable timeline: a one-sentence mission + a plan strip of
5
+ * inferred sub-task "chapters", a feed of steps segmented by chapter, and an
6
+ * anchored side panel with plain-language + technical detail. Ported 1:1
7
+ * from the validated mockup at docs/session-story-mockup.html.
8
+ *
9
+ * Uses the AgnoMcpApp contract (a local McpApp-compatible shape that does
10
+ * NOT depend on @agstudio/mcp-apps). The host (@agentproto/runtime) wires
11
+ * this factory's output via `registerMcpApps` at boot time — see runtime's
12
+ * builtin-apps.ts.
13
+ *
14
+ * Protocol flow:
15
+ * 1. Tool `agentproto_session_story` is called by the host, optionally
16
+ * with a `sessionId`.
17
+ * 2. execute() returns just enough for the panel to boot: when a
18
+ * `sessionId` is given, it echoes that back and skips the sessions
19
+ * list entirely — the panel's own JS never reads the initial snapshot,
20
+ * it always re-fetches via `session_list` over the postMessage bridge
21
+ * on boot (see panel.ts's `loadSessions()`/boot sequence), so shipping
22
+ * the full list here would just be dead payload. When no `sessionId`
23
+ * is given (the picker case) it still returns the full sessions
24
+ * snapshot, since the model/host may surface it before the panel's
25
+ * own bridge call lands.
26
+ * 3. The HTML panel opens a JSON-RPC bridge (postMessage) and drives
27
+ * everything else live: `session_list` for status polling,
28
+ * `agent_export` for the transcript (folded into chapters/steps with a
29
+ * JS port of @agentproto/runtime's session-story.ts heuristics — the
30
+ * panel HTML is fully self-contained, so it cannot import that TS
31
+ * module directly), and `agent_prompt` for the composer.
32
+ *
33
+ * This module also exports `sessionStoryApp`, a real `defineApp()`
34
+ * `AppHandle` (`agents: []`, UI-only) — the catalog/emit/`app_install` path.
35
+ * It's separate from `makeSessionStoryPanelApp` above, which the daemon
36
+ * mounts directly at boot: that factory closes over LIVE `listSessions`,
37
+ * something a static emitted `ui.html` snapshot can't carry.
38
+ */
39
+ import { z } from "zod";
40
+ import { type AppHandle } from "@agentproto/app-kit";
41
+ import { SESSION_STORY_PANEL_HTML } from "./panel.js";
42
+ import type { AgnoMcpApp } from "../mcp-app-types.js";
43
+ export { SESSION_STORY_PANEL_HTML };
44
+ export declare const sessionStoryInputSchema: z.ZodObject<{
45
+ sessionId: z.ZodOptional<z.ZodString>;
46
+ }, z.core.$strip>;
47
+ export type SessionStoryInput = z.infer<typeof sessionStoryInputSchema>;
48
+ export type SessionStoryOutput<TSession = unknown> = {
49
+ sessions: TSession[];
50
+ sessionId?: string;
51
+ } | {
52
+ sessionId: string;
53
+ };
54
+ /** Generic over the host's own session-descriptor shape — see
55
+ * sessions-panel/index.ts's SessionsPanelOps for why. */
56
+ export interface SessionStoryOps<TSession = unknown> {
57
+ listSessions(filter?: "running" | "all"): TSession[];
58
+ }
59
+ export type { AgnoMcpApp };
60
+ /**
61
+ * Factory: close over the sessions registry so execute() doesn't need
62
+ * an AppContext (agentproto has no userId/guildId concept).
63
+ */
64
+ export declare function makeSessionStoryPanelApp<TSession = unknown>(ops: SessionStoryOps<TSession>): AgnoMcpApp<SessionStoryInput, SessionStoryOutput<TSession>>;
65
+ export declare const sessionStoryApp: AppHandle;
66
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/session-story/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAa,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AACrD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAKrD,OAAO,EAAE,wBAAwB,EAAE,CAAA;AAEnC,eAAO,MAAM,uBAAuB;;iBAQlC,CAAA;AAEF,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAA;AACvE,MAAM,MAAM,kBAAkB,CAAC,QAAQ,GAAG,OAAO,IAC7C;IAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,CAAA;AAEzB;0DAC0D;AAC1D,MAAM,WAAW,eAAe,CAAC,QAAQ,GAAG,OAAO;IACjD,YAAY,CAAC,MAAM,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,EAAE,CAAA;CACrD;AAED,YAAY,EAAE,UAAU,EAAE,CAAA;AAE1B;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,GAAG,OAAO,EACzD,GAAG,EAAE,eAAe,CAAC,QAAQ,CAAC,GAC7B,UAAU,CAAC,iBAAiB,EAAE,kBAAkB,CAAC,QAAQ,CAAC,CAAC,CAkB7D;AAED,eAAO,MAAM,eAAe,EAAE,SAa5B,CAAA"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * HTML bundle for the agentproto session story panel — the
3
+ * `SESSION_STORY_PANEL_HTML` served as the `ui://agentproto_session_story/view`
4
+ * resource. Mounted via the `agentproto_session_story` tool defined in
5
+ * ./index.ts. Also consumed directly by packages/vscode's story webview
6
+ * (`storyPanel.ts`), which relays this same HTML into a VS Code editor tab.
7
+ *
8
+ * Ported 1:1 from the validated mockup at docs/session-story-mockup.html —
9
+ * same CSS, same DOM structure/classes, same interaction model (anchored
10
+ * side panel, sticky collapsible chapter headers, Simple/Tech toggle,
11
+ * composer with local chapter-routing classification). Fake data is
12
+ * replaced with live data pulled through the MCP Apps postMessage bridge.
13
+ *
14
+ * The HTML must stay fully self-contained (CSP: inline CSS/JS only, no
15
+ * CDN, no external fonts) — see runtime's mcp-apps-adapter.ts and the other
16
+ * panels in this app family (sessions-panel, agents-overview) for the same
17
+ * constraint. Because of that, this file cannot `import` the pure
18
+ * `buildStory` module from @agentproto/runtime's session-story.ts (a
19
+ * separate, CLI-facing heuristics module that stays in runtime — it isn't
20
+ * a dependency of this panel) — the folding/chaptering heuristics are
21
+ * ported to vanilla JS below (`buildStoryJs`), mirroring session-story.ts
22
+ * function-for-function so the two stay easy to diff.
23
+ *
24
+ * Protocol: MCP Apps ext spec 2026-01-26
25
+ * – Bridge: JSON-RPC 2.0 over window.parent.postMessage
26
+ * – Handshake: ui/initialize → host result → ui/notifications/initialized
27
+ * – Data: tools/call → session_list (status/picker) + agent_export
28
+ * (timeline, re-fetched on turn boundaries) + agent_prompt (composer)
29
+ */
30
+ export declare const SESSION_STORY_PANEL_HTML: string;
31
+ //# sourceMappingURL=panel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"panel.d.ts","sourceRoot":"","sources":["../../src/session-story/panel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAIH,eAAO,MAAM,wBAAwB,QA+yB7B,CAAA"}