@agentproto/apps 0.9.3 → 0.11.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.
- package/README.md +12 -10
- package/dist/agents-overview/panel.mjs +18 -1
- package/dist/agents-overview/panel.mjs.map +1 -1
- package/dist/agents-overview.mjs +18 -1
- package/dist/agents-overview.mjs.map +1 -1
- package/dist/bureau-sessions/panel.mjs +18 -1
- package/dist/bureau-sessions/panel.mjs.map +1 -1
- package/dist/bureau-sessions.mjs +18 -1
- package/dist/bureau-sessions.mjs.map +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +777 -2
- package/dist/index.mjs.map +1 -1
- package/dist/live-session/panel.mjs +18 -1
- package/dist/live-session/panel.mjs.map +1 -1
- package/dist/live-session.mjs +18 -1
- package/dist/live-session.mjs.map +1 -1
- package/dist/mcp-app-types.d.ts +4 -0
- package/dist/mcp-app-types.d.ts.map +1 -1
- package/dist/panel-bridge.d.ts +48 -0
- package/dist/panel-bridge.d.ts.map +1 -1
- package/dist/session-chat/index.d.ts +72 -0
- package/dist/session-chat/index.d.ts.map +1 -0
- package/dist/session-chat/panel.d.ts +28 -0
- package/dist/session-chat/panel.d.ts.map +1 -0
- package/dist/session-chat/panel.mjs +65 -0
- package/dist/session-chat/panel.mjs.map +1 -0
- package/dist/session-chat.mjs +113 -0
- package/dist/session-chat.mjs.map +1 -0
- package/dist/session-story/panel.mjs +18 -1
- package/dist/session-story/panel.mjs.map +1 -1
- package/dist/session-story.mjs +18 -1
- package/dist/session-story.mjs.map +1 -1
- package/dist/sessions-panel/panel.mjs +18 -1
- package/dist/sessions-panel/panel.mjs.map +1 -1
- package/dist/sessions-panel.mjs +18 -1
- package/dist/sessions-panel.mjs.map +1 -1
- package/dist/work-board/index.d.ts +67 -0
- package/dist/work-board/index.d.ts.map +1 -0
- package/dist/work-board/panel.d.ts +72 -0
- package/dist/work-board/panel.d.ts.map +1 -0
- package/dist/work-board/panel.generated.d.ts +13 -0
- package/dist/work-board/panel.generated.d.ts.map +1 -0
- package/dist/work-board/panel.mjs +637 -0
- package/dist/work-board/panel.mjs.map +1 -0
- package/dist/work-board.mjs +669 -0
- package/dist/work-board.mjs.map +1 -0
- package/package.json +32 -8
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { defineApp } from '@agentproto/app-kit';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @agentproto/apps v0.1.0
|
|
6
|
+
* Ready-made agentproto apps (teams of agents + workflows) built on app-kit.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
// src/session-chat/panel.ts
|
|
11
|
+
function escapeAttr(text) {
|
|
12
|
+
return text.replace(/&/g, "&").replace(/"/g, """);
|
|
13
|
+
}
|
|
14
|
+
function sessionChatEmbedHtml(initData) {
|
|
15
|
+
const url = initData.url;
|
|
16
|
+
const link = url != null ? `<a href="${escapeAttr(url)}" target="_blank" rel="noreferrer">open in a tab</a>` : "app not installed";
|
|
17
|
+
const iframe = url != null ? `<iframe id="chat" title="Session Chat" src="${escapeAttr(url)}"></iframe>` : "";
|
|
18
|
+
return `<!DOCTYPE html>
|
|
19
|
+
<html lang="en">
|
|
20
|
+
<head>
|
|
21
|
+
<meta charset="UTF-8">
|
|
22
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
23
|
+
<title>Session Chat</title>
|
|
24
|
+
<style>
|
|
25
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
26
|
+
html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3;overflow:hidden}
|
|
27
|
+
#bar{padding:6px 12px;font-size:12px;color:#8b949e;background:#161b22;border-bottom:1px solid #30363d}
|
|
28
|
+
#bar a{color:#58a6ff}
|
|
29
|
+
#chat{border:0;display:block;width:100%;height:calc(100% - 29px)}
|
|
30
|
+
</style>
|
|
31
|
+
</head>
|
|
32
|
+
<body>
|
|
33
|
+
<div id="bar">Session Chat · ${link}</div>
|
|
34
|
+
${iframe}
|
|
35
|
+
</body>
|
|
36
|
+
</html>`;
|
|
37
|
+
}
|
|
38
|
+
var SESSION_CHAT_FALLBACK_HTML = `<!DOCTYPE html>
|
|
39
|
+
<html lang="en">
|
|
40
|
+
<head>
|
|
41
|
+
<meta charset="UTF-8">
|
|
42
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
43
|
+
<title>Session Chat \u2014 not installed</title>
|
|
44
|
+
<style>
|
|
45
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
46
|
+
html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:#0d1117;color:#e6edf3}
|
|
47
|
+
#wrap{max-width:560px;margin:0 auto;padding:48px 24px;line-height:1.6}
|
|
48
|
+
h1{font-size:18px;margin-bottom:12px}
|
|
49
|
+
code{background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:13px}
|
|
50
|
+
p{margin:8px 0;color:#8b949e;font-size:13px}
|
|
51
|
+
</style>
|
|
52
|
+
</head>
|
|
53
|
+
<body>
|
|
54
|
+
<div id="wrap">
|
|
55
|
+
<h1>Session Chat is not installed</h1>
|
|
56
|
+
<p>This panel is a thin launcher for the <code>@agentik/session-chat</code> app —
|
|
57
|
+
it does not bundle the chat UI itself.</p>
|
|
58
|
+
<p>To use it, install the app into this daemon:</p>
|
|
59
|
+
<p><code>agentproto app install @agentik/session-chat</code></p>
|
|
60
|
+
<p>Once installed, call <code>agentproto_session_chat</code> again (optionally with a
|
|
61
|
+
<code>sessionId</code>) and the panel will embed the app's chat UI deep-linked to that
|
|
62
|
+
session.</p>
|
|
63
|
+
</div>
|
|
64
|
+
</body>
|
|
65
|
+
</html>`;
|
|
66
|
+
|
|
67
|
+
// src/session-chat/index.ts
|
|
68
|
+
var SESSION_CHAT_APP_ID = "@agentik/session-chat";
|
|
69
|
+
var sessionChatInputSchema = z.object({
|
|
70
|
+
sessionId: z.string().optional().describe(
|
|
71
|
+
"Deep-link the chat to an existing session by id (e.g. `sess_xxx`). Omit to open the app with its session picker."
|
|
72
|
+
)
|
|
73
|
+
});
|
|
74
|
+
function sessionChatAppUrl(httpBaseUrl, sessionId) {
|
|
75
|
+
const base = `${httpBaseUrl.replace(/\/+$/, "")}/apps/${SESSION_CHAT_APP_ID}/ui`;
|
|
76
|
+
const params = new URLSearchParams();
|
|
77
|
+
if (sessionId) params.set("session", sessionId);
|
|
78
|
+
params.set("embed", "1");
|
|
79
|
+
return `${base}?${params.toString()}`;
|
|
80
|
+
}
|
|
81
|
+
function frameOrigin(httpBaseUrl) {
|
|
82
|
+
return new URL(httpBaseUrl).origin;
|
|
83
|
+
}
|
|
84
|
+
function makeSessionChatApp(ops) {
|
|
85
|
+
const installed = ops.isSessionChatInstalled?.() ?? false;
|
|
86
|
+
return {
|
|
87
|
+
id: "agentproto_session_chat",
|
|
88
|
+
title: "Session Chat",
|
|
89
|
+
description: "Open the Session Chat app \u2014 a chat-thread view of any agentproto daemon session: full transcript replay, live follow-over SSE, and a composer that sends prompts into the same session. Requires the `@agentik/session-chat` app to be installed; without it the panel shows install instructions. Pass `sessionId` to deep-link straight into a known session.",
|
|
90
|
+
inputSchema: sessionChatInputSchema,
|
|
91
|
+
execute: async (input) => ({
|
|
92
|
+
installed,
|
|
93
|
+
url: installed ? sessionChatAppUrl(ops.httpBaseUrl, input.sessionId) : null
|
|
94
|
+
}),
|
|
95
|
+
html: (initData) => sessionChatEmbedHtml(initData),
|
|
96
|
+
csp: { frameDomains: [frameOrigin(ops.httpBaseUrl)] }
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
var sessionChatApp = defineApp({
|
|
100
|
+
id: "@agentproto/session-chat-widget",
|
|
101
|
+
name: "Session Chat",
|
|
102
|
+
description: "Open the Session Chat app \u2014 a chat-thread view of any agentproto daemon session, deep-linked by sessionId. A thin builtin launcher for the installed @agentik/session-chat app.",
|
|
103
|
+
agents: [],
|
|
104
|
+
ui: {
|
|
105
|
+
html: SESSION_CHAT_FALLBACK_HTML,
|
|
106
|
+
title: "Session Chat",
|
|
107
|
+
tools: ["session_list", "agent_start", "adapter_list", "conversation_read"]
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
export { SESSION_CHAT_APP_ID, SESSION_CHAT_FALLBACK_HTML, makeSessionChatApp, sessionChatApp, sessionChatAppUrl, sessionChatEmbedHtml, sessionChatInputSchema };
|
|
112
|
+
//# sourceMappingURL=session-chat.mjs.map
|
|
113
|
+
//# sourceMappingURL=session-chat.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/session-chat/panel.ts","../src/session-chat/index.ts"],"names":[],"mappings":";;;;;;;;;;AA4BA,SAAS,WAAW,IAAA,EAAsB;AACxC,EAAA,OAAO,KAAK,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,MAAM,QAAQ,CAAA;AAC3D;AAEO,SAAS,qBAAqB,QAAA,EAAqC;AACxE,EAAA,MAAM,MAAM,QAAA,CAAS,GAAA;AACrB,EAAA,MAAM,OACJ,GAAA,IAAO,IAAA,GACH,YAAY,UAAA,CAAW,GAAG,CAAC,CAAA,oDAAA,CAAA,GAC3B,mBAAA;AACN,EAAA,MAAM,SACJ,GAAA,IAAO,IAAA,GACH,+CAA+C,UAAA,CAAW,GAAG,CAAC,CAAA,WAAA,CAAA,GAC9D,EAAA;AACN,EAAA,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAAA,EAe2B,IAAI,CAAA;AAAA,EACtC,MAAM;AAAA;AAAA,OAAA,CAAA;AAGR;AAEO,IAAM,0BAAA,GAA6B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,oBAAA,CAAqB,QAAQ,CAAA;AAAA,IACpE,GAAA,EAAK,EAAE,YAAA,EAAc,CAAC,YAAY,GAAA,CAAI,WAAW,CAAC,CAAA;AAAE,GACtD;AACF;AAEO,IAAM,iBAA4B,SAAA,CAAU;AAAA,EACjD,EAAA,EAAI,iCAAA;AAAA,EACJ,IAAA,EAAM,cAAA;AAAA,EACN,WAAA,EACE,sLAAA;AAAA,EAEF,QAAQ,EAAC;AAAA,EACT,EAAA,EAAI;AAAA,IACF,IAAA,EAAM,0BAAA;AAAA,IACN,KAAA,EAAO,cAAA;AAAA,IACP,KAAA,EAAO,CAAC,cAAA,EAAgB,aAAA,EAAe,gBAAgB,mBAAmB;AAAA;AAE9E,CAAC","file":"session-chat.mjs","sourcesContent":["/**\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.\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 * 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 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, \"&\").replace(/\"/g, \""\")\n}\n\nexport function sessionChatEmbedHtml(initData: SessionChatOutput): string {\n const url = initData.url\n const link =\n url != null\n ? `<a href=\"${escapeAttr(url)}\" target=\"_blank\" rel=\"noreferrer\">open in a tab</a>`\n : \"app not installed\"\n const iframe =\n url != null\n ? `<iframe id=\"chat\" title=\"Session Chat\" src=\"${escapeAttr(url)}\"></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#chat{border:0;display:block;width:100%;height:calc(100% - 29px)}\n</style>\n</head>\n<body>\n<div id=\"bar\">Session Chat · ${link}</div>\n${iframe}\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 —\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","/**\n * McpApp definition for the session-chat builtin widget — a thin launcher\n * for the installed `@agentik/session-chat` app's UI, exposed as a BUILTIN\n * daemon panel so MCP-Apps clients (and the VS Code appPanel surface) can\n * open the chat from `app_catalog` without installing anything into the\n * MCP surface itself.\n *\n * Uses the AgnoMcpApp contract (a local McpApp-compatible shape that does\n * NOT depend on @agstudio/mcp-apps or Mastra), same as sessions-panel /\n * live-session — the host (@agentproto/runtime) wires this factory's output\n * via `registerMcpApps` from its mcp-apps-adapter.ts at boot time, with the\n * mounted list assembled in runtime's builtin-apps.ts.\n *\n * Serving approach (decided; see the PR description for the tradeoffs):\n * (a) App installed → the tool returns the app's standalone deep-link\n * (`GET /apps/@agentik/session-chat/ui?session=<id>&embed=1`) and the\n * panel HTML is a thin full-viewport iframe of it. No duplicate chat\n * bundle: the UI is the studio-built app, served by the daemon's\n * standalone app host. The daemon relaxes that route's\n * `frame-ancestors 'none'` only when `?embed=1` is present.\n * (b) App NOT installed → the panel HTML is a small readable notice\n * pointing at `agentproto app install`. Never a vendored/reimplemented\n * chat UI.\n *\n * This module also exports `sessionChatApp`, a real `defineApp()`\n * `AppHandle` (`agents: []`, UI-only) — the catalog/emit/`app_install`\n * path. Its `ui.html` is the fallback notice, since `AppUiDefinition.ui.html`\n * is a plain static string and can't know at emit time whether the sibling\n * app is installed; the live-mounted `makeSessionChatApp` below is the one\n * that resolves installed-ness per boot.\n */\n\nimport { z } from \"zod\"\nimport { defineApp, type AppHandle } from \"@agentproto/app-kit\"\nimport type { AgnoMcpApp } from \"../mcp-app-types.js\"\nimport { SESSION_CHAT_FALLBACK_HTML, sessionChatEmbedHtml } from \"./panel.js\"\n\nexport { SESSION_CHAT_FALLBACK_HTML, sessionChatEmbedHtml }\n\n/** The installed studio app this builtin widget is a launcher for. */\nexport const SESSION_CHAT_APP_ID = \"@agentik/session-chat\"\n\nexport const sessionChatInputSchema = z.object({\n sessionId: z\n .string()\n .optional()\n .describe(\n \"Deep-link the chat to an existing session by id (e.g. `sess_xxx`). \" +\n \"Omit to open the app with its session picker.\",\n ),\n})\n\nexport type SessionChatInput = z.infer<typeof sessionChatInputSchema>\n\nexport interface SessionChatOutput {\n /** Whether the `@agentik/session-chat` app is installed (with a UI) on\n * the daemon this widget is mounted on. */\n installed: boolean\n /** The app's standalone deep-link url when installed, else null. */\n url: string | null\n}\n\nexport interface SessionChatOps {\n /** The daemon's own HTTP origin, e.g. \"http://127.0.0.1:18790\" — the\n * standalone app host the chat UI is served from. */\n httpBaseUrl: string\n /** Whether the `@agentik/session-chat` app is installed with a `ui`\n * block. The runtime supplies this from its AppRegistry; optional so\n * tests/consumers without a registry can omit it (treated as false). */\n isSessionChatInstalled?: () => boolean\n}\n\n/**\n * Deep-link into the installed app's standalone UI — the same url shape the\n * VS Code chat-panel webview iframes (`chatPanelUrl` in\n * packages/vscode/src/commands/sessionView.logic.ts).\n */\nexport function sessionChatAppUrl(httpBaseUrl: string, sessionId?: string): string {\n const base = `${httpBaseUrl.replace(/\\/+$/, \"\")}/apps/${SESSION_CHAT_APP_ID}/ui`\n const params = new URLSearchParams()\n if (sessionId) params.set(\"session\", sessionId)\n params.set(\"embed\", \"1\")\n return `${base}?${params.toString()}`\n}\n\n/** The daemon origin the widget's host-iframe CSP must allow as a frame\n * target (same derivation as live-session's connectDomains entry). */\nfunction frameOrigin(httpBaseUrl: string): string {\n return new URL(httpBaseUrl).origin\n}\n\n/**\n * Factory: close over the daemon origin + the installed-ness check so\n * execute() needs nothing beyond the tool input (no registry access inside\n * the app itself — mirrors live-session/index.ts).\n */\nexport function makeSessionChatApp(\n ops: SessionChatOps,\n): AgnoMcpApp<SessionChatInput, SessionChatOutput> {\n const installed = ops.isSessionChatInstalled?.() ?? false\n return {\n id: \"agentproto_session_chat\",\n title: \"Session Chat\",\n description:\n \"Open the Session Chat app — a chat-thread view of any agentproto \" +\n \"daemon session: full transcript replay, live follow-over SSE, and a \" +\n \"composer that sends prompts into the same session. Requires the \" +\n \"`@agentik/session-chat` app to be installed; without it the panel \" +\n \"shows install instructions. Pass `sessionId` to deep-link straight \" +\n \"into a known session.\",\n inputSchema: sessionChatInputSchema,\n execute: async input => ({\n installed,\n url: installed ? sessionChatAppUrl(ops.httpBaseUrl, input.sessionId) : null,\n }),\n html: (initData: SessionChatOutput) => sessionChatEmbedHtml(initData),\n csp: { frameDomains: [frameOrigin(ops.httpBaseUrl)] },\n }\n}\n\nexport const sessionChatApp: AppHandle = defineApp({\n id: \"@agentproto/session-chat-widget\",\n name: \"Session Chat\",\n description:\n \"Open the Session Chat app — a chat-thread view of any agentproto daemon session, deep-linked \" +\n \"by sessionId. A thin builtin launcher for the installed @agentik/session-chat app.\",\n agents: [],\n ui: {\n html: SESSION_CHAT_FALLBACK_HTML,\n title: \"Session Chat\",\n tools: [\"session_list\", \"agent_start\", \"adapter_list\", \"conversation_read\"],\n },\n})\n"]}
|
|
@@ -9,6 +9,10 @@ function panelBridgeScript(appName) {
|
|
|
9
9
|
// JSON-RPC 2.0 over window.parent.postMessage \xB7 spec 2026-01-26
|
|
10
10
|
var _nextId = 1, _pending = {}, _notifyHandlers = [];
|
|
11
11
|
var _hostContext = null, _hostContextHandlers = [];
|
|
12
|
+
var _standaloneApp = null;
|
|
13
|
+
function _isStandalone(){
|
|
14
|
+
return window.parent === window && !!window.McpApp && typeof window.McpApp.connect === 'function';
|
|
15
|
+
}
|
|
12
16
|
function post(msg){ window.parent.postMessage(msg, '*'); }
|
|
13
17
|
function getHostContext(){ return _hostContext; }
|
|
14
18
|
function onHostContext(cb){
|
|
@@ -55,6 +59,16 @@ window.addEventListener('message', function(evt){
|
|
|
55
59
|
}
|
|
56
60
|
});
|
|
57
61
|
function initBridge(){
|
|
62
|
+
if (_isStandalone()){
|
|
63
|
+
return window.McpApp.connect().then(function(conn){
|
|
64
|
+
_standaloneApp = conn;
|
|
65
|
+
// No host to advertise a hostContext \u2014 default to inline with no
|
|
66
|
+
// other modes available, which keeps the #dm/#pin toggle buttons
|
|
67
|
+
// hidden (they only show for modes hostContext.availableDisplayModes
|
|
68
|
+
// lists) instead of rendering two buttons with nothing to switch to.
|
|
69
|
+
_setHostContext({displayMode: 'inline', availableDisplayModes: []});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
58
72
|
return rpcRequest('ui/initialize', {
|
|
59
73
|
appInfo: {name: ${JSON.stringify(appName)}, version: '0.1.0'},
|
|
60
74
|
appCapabilities: {availableDisplayModes: ['inline', 'fullscreen', 'pip']},
|
|
@@ -70,7 +84,10 @@ function requestDisplayMode(mode){
|
|
|
70
84
|
return rpcRequest('ui/request-display-mode', {mode: mode});
|
|
71
85
|
}
|
|
72
86
|
function callTool(name, args){
|
|
73
|
-
|
|
87
|
+
var raw = _standaloneApp
|
|
88
|
+
? _standaloneApp.callTool(name, args || {})
|
|
89
|
+
: rpcRequest('tools/call', {name: name, arguments: args || {}});
|
|
90
|
+
return raw.then(function(result){
|
|
74
91
|
if (result.isError){
|
|
75
92
|
var e = (result.content && result.content[0] && result.content[0].text) || 'tool error';
|
|
76
93
|
throw new Error(e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/panel-bridge.ts","../../src/session-story/panel.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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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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\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 session story panel — the\n * `SESSION_STORY_PANEL_HTML` served as the `ui://agentproto_session_story/view`\n * resource. Mounted via the `agentproto_session_story` tool defined in\n * ./index.ts. Also consumed directly by packages/vscode's story webview\n * (`storyPanel.ts`), which relays this same HTML into a VS Code editor tab.\n *\n * Ported 1:1 from the validated mockup at docs/session-story-mockup.html —\n * same CSS, same DOM structure/classes, same interaction model (anchored\n * side panel, sticky collapsible chapter headers, Simple/Tech toggle,\n * composer with local chapter-routing classification). Fake data is\n * replaced with live data pulled through the MCP Apps postMessage bridge.\n *\n * The HTML must stay fully self-contained (CSP: inline CSS/JS only, no\n * CDN, no external fonts) — see runtime's mcp-apps-adapter.ts and the other\n * panels in this app family (sessions-panel, agents-overview) for the same\n * constraint. Because of that, this file cannot `import` the pure\n * `buildStory` module from @agentproto/runtime's session-story.ts (a\n * separate, CLI-facing heuristics module that stays in runtime — it isn't\n * a dependency of this panel) — the folding/chaptering heuristics are\n * ported to vanilla JS below (`buildStoryJs`), mirroring session-story.ts\n * function-for-function so the two stay easy to diff.\n *\n * Protocol: MCP Apps ext spec 2026-01-26\n * – Bridge: JSON-RPC 2.0 over window.parent.postMessage\n * – Handshake: ui/initialize → host result → ui/notifications/initialized\n * – Data: tools/call → session_list (status/picker) + agent_export\n * (timeline, re-fetched on turn boundaries) + agent_prompt (composer)\n */\n\nimport { panelBridgeScript } from \"../panel-bridge.js\"\n\nexport const SESSION_STORY_PANEL_HTML = `<!doctype html>\n<html lang=\"fr\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>session story</title>\n<style>\n :root {\n color-scheme: light;\n --bg:#faf8f5; --panel:#fffdfa; --line:#ece5da; --line-soft:#f2ede3;\n --ink:#241f1a; --ink-mute:#7d7060; --ink-faint:#a9997f; --ink-ghost:#b3a893;\n --accent:#0d7a4f; --accent-soft:#e8f4ec;\n --gold:#a6701b; --gold-soft:#fff2dc;\n --blue:#1d4e80; --blue-soft:#e9f1fb;\n --violet:#5b3fa6; --violet-soft:#ede9ff;\n --sel:#fbeccd; --red:#b3261e; --red-soft:#fbeae8;\n }\n * { box-sizing:border-box; }\n html,body { height:100%; }\n body { margin:0; font-family:ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",sans-serif; background:var(--bg); color:var(--ink); -webkit-font-smoothing:antialiased; }\n .app { height:100vh; display:flex; flex-direction:column; }\n .hidden { display:none !important; }\n\n /* ── picker screen ── */\n #pickerScreen { height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:14px; padding:24px; }\n #pickerScreen h1 { font-size:15px; font-weight:700; }\n #pickerList { width:min(520px,90vw); max-height:60vh; overflow-y:auto; border:1px solid var(--line); border-radius:12px; background:var(--panel); }\n .pk-item { padding:10px 14px; border-bottom:1px solid var(--line-soft); cursor:pointer; display:flex; align-items:center; gap:10px; }\n .pk-item:last-child { border-bottom:none; }\n .pk-item:hover { background:var(--line-soft); }\n .pk-name { flex:1; min-width:0; font-size:13px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .pk-meta { flex:none; font-size:10.5px; color:var(--ink-faint); font-weight:600; }\n .pk-empty { padding:24px; text-align:center; color:var(--ink-mute); font-size:12.5px; }\n .badge { display:inline-block; padding:1px 8px; border-radius:999px; font-size:10px; font-weight:700; }\n .badge.running { background:var(--accent-soft); color:var(--accent); }\n .badge.starting { background:var(--blue-soft); color:var(--blue); }\n .badge.exited { background:var(--line-soft); color:var(--ink-faint); }\n .badge.killed, .badge.error { background:var(--red-soft); color:var(--red); }\n\n /* ── big picture : mission + plan de sous-tâches ── */\n .hero { flex:none; padding:13px 20px 0; border-bottom:1px solid var(--line); background:var(--panel); }\n .hero-top { display:flex; align-items:center; gap:13px; }\n .pulse { width:10px; height:10px; border-radius:50%; background:var(--accent); flex:none;\n box-shadow:0 0 0 0 rgba(13,122,79,.35); animation:pulse 2.4s infinite; }\n .pulse.off { background:var(--ink-ghost); animation:none; }\n @keyframes pulse { 70% { box-shadow:0 0 0 9px rgba(13,122,79,0); } 100% { box-shadow:0 0 0 0 rgba(13,122,79,0); } }\n .who { min-width:0; flex:1; }\n .who .h1 { font-size:14.5px; font-weight:700; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .who .h2 { font-size:12px; color:var(--ink-mute); margin-top:1px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .modewrap { display:flex; border:1px solid var(--line); border-radius:9px; overflow:hidden; flex:none; }\n .modewrap button { border:none; background:var(--panel); color:var(--ink-mute); font-size:11px; font-weight:700; padding:6px 11px; cursor:pointer; }\n .modewrap button.on { background:var(--ink); color:#fdf9f2; }\n button.sim, a.sim { border:1px solid var(--line); background:var(--panel); color:var(--ink-mute); font-weight:700;\n font-size:11.5px; border-radius:8px; padding:6px 12px; cursor:pointer; flex:none; }\n button.sim.on { background:var(--ink); border-color:var(--ink); color:#fdf9f2; }\n a.sim { display:inline-flex; align-items:center; text-decoration:none; }\n a.sim:hover { border-color:var(--ink-ghost); color:var(--ink); }\n\n /* plan strip : les sous-tâches, l'avancement d'un coup d'œil */\n .plan { display:flex; gap:6px; overflow-x:auto; padding:11px 0 12px; scrollbar-width:none; }\n .plan::-webkit-scrollbar { display:none; }\n .pt { flex:none; display:flex; align-items:center; gap:6px; font-size:11.5px; font-weight:700; padding:5px 11px;\n border-radius:999px; border:1px solid var(--line); background:var(--bg); color:var(--ink-mute); cursor:pointer; white-space:nowrap; }\n .pt:hover { border-color:var(--ink-ghost); }\n .pt .st { font-size:10px; }\n .pt.done { color:var(--accent); background:var(--accent-soft); border-color:transparent; }\n .pt.cur { color:var(--gold); background:var(--gold-soft); border-color:transparent; }\n .pt.cur .st { animation:blink 1.6s infinite; }\n @keyframes blink { 50% { opacity:.35; } }\n\n /* ── corps ── */\n .body { flex:1; display:flex; min-height:0; }\n .feedcol { flex:1; min-width:320px; display:flex; flex-direction:column; }\n .feed { flex:1; overflow-y:auto; padding:4px 14px 10px; display:flex; flex-direction:column; scroll-behavior:smooth; }\n .fspacer { flex:1; }\n\n /* chapitres */\n .chap { flex:none; position:sticky; top:0; z-index:5; margin:8px -4px 2px; padding:7px 12px; display:flex; align-items:center; gap:9px;\n background:color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter:blur(6px);\n border-radius:9px; cursor:pointer; font-size:11.5px; font-weight:800; letter-spacing:.03em; color:var(--ink-mute); }\n .chap:hover { color:var(--ink); }\n .chap .cst { flex:none; width:17px; height:17px; border-radius:50%; display:grid; place-items:center; font-size:9.5px; font-weight:900; }\n .chap.done .cst { background:var(--accent-soft); color:var(--accent); }\n .chap.cur .cst { background:var(--gold-soft); color:var(--gold); }\n .chap .cnum { color:var(--ink-ghost); font-weight:700; }\n .chap .csum { flex:1; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .chap .cmeta { flex:none; font-size:10.5px; color:var(--ink-ghost); font-weight:600; }\n .chap .cchev { flex:none; color:var(--ink-ghost); transition:transform .15s; }\n .chap.open .cchev { transform:rotate(90deg); }\n\n .row { flex:none; min-height:44px; margin:1px 0 1px 10px; padding:5px 12px 5px 10px; display:flex; align-items:center; gap:11px;\n cursor:pointer; border-radius:10px; border-left:3px solid transparent; transition:background .12s; }\n .row:hover { background:var(--line-soft); }\n .row[aria-selected=\"true\"] { background:var(--sel); border-left-color:var(--gold); }\n .row .ico { width:24px; height:24px; border-radius:8px; flex:none; display:grid; place-items:center; font-size:11.5px; font-weight:800; }\n .ico.k-text { background:var(--blue-soft); color:var(--blue); }\n .ico.k-edit { background:var(--gold-soft); color:var(--gold); }\n .ico.k-bash { background:var(--accent-soft); color:var(--accent); }\n .ico.k-read { background:var(--violet-soft); color:var(--violet); }\n .ico.k-user { background:var(--ink); color:#fdf9f2; }\n .row .mid { flex:1; min-width:0; }\n .row .sum { display:block; font-size:13.5px; line-height:1.35; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .row .raw1 { display:block; font-size:10.5px; color:var(--ink-faint); font-family:ui-monospace,Menlo,monospace;\n white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:1px; }\n body:not(.tech) .row .raw1 { display:none; }\n .row .route { display:inline-block; font-size:10px; font-weight:800; padding:1px 8px; border-radius:999px; margin-top:2px; }\n .route.cont { background:var(--blue-soft); color:var(--blue); }\n .route.newt { background:var(--gold-soft); color:var(--gold); }\n .row .cnt { flex:none; font-size:10px; font-weight:800; color:var(--gold); background:var(--gold-soft); padding:2px 7px; border-radius:999px; }\n .row .ts { flex:none; font-size:10.5px; color:var(--ink-ghost); font-variant-numeric:tabular-nums; }\n @keyframes slidein { from { opacity:0; transform:translateY(6px); } }\n .row.new { animation:slidein .25s ease-out; }\n\n /* ── panneau ancré ── */\n .panel { flex:none; width:0; overflow:hidden; border-left:1px solid transparent; background:var(--panel);\n display:flex; flex-direction:column; transition:width .22s ease, border-color .22s; }\n .panel.open { width:min(430px,46vw); border-left-color:var(--line); }\n .panel-inner { width:min(430px,46vw); flex:1; display:flex; flex-direction:column; min-height:0; }\n .phead { flex:none; padding:14px 16px 12px; border-bottom:1px solid var(--line); display:flex; align-items:flex-start; gap:11px; }\n .phead .ico { width:28px; height:28px; font-size:13px; border-radius:9px; }\n .phead .tt { min-width:0; flex:1; }\n .phead .t { font-size:14px; font-weight:700; line-height:1.4; }\n .phead .s { font-size:11px; color:var(--ink-faint); margin-top:3px; font-variant-numeric:tabular-nums; }\n .pnav { display:flex; gap:4px; flex:none; }\n .pnav button { width:26px; height:26px; border:1px solid var(--line); background:var(--panel); border-radius:8px;\n color:var(--ink-mute); font-size:12px; cursor:pointer; display:grid; place-items:center; }\n .pnav button:disabled { opacity:.3; cursor:default; }\n .pbody { flex:1; overflow-y:auto; padding:16px; display:flex; flex-direction:column; gap:14px; }\n .plain { font-size:14px; line-height:1.7; }\n .plain .why { margin-top:8px; font-size:12.5px; color:var(--ink-mute); line-height:1.6; }\n .facts { display:flex; flex-wrap:wrap; gap:6px; }\n .fact { font-size:11px; font-weight:700; background:var(--bg); border:1px solid var(--line); color:var(--ink-mute); padding:4px 10px; border-radius:999px; }\n .fact.ok { background:var(--accent-soft); border-color:transparent; color:var(--accent); }\n details.techbox { border:1px solid var(--line); border-radius:12px; background:var(--bg); overflow:hidden; }\n details.techbox summary { list-style:none; cursor:pointer; padding:10px 14px; font-size:11.5px; font-weight:800;\n letter-spacing:.04em; text-transform:uppercase; color:var(--ink-faint); display:flex; align-items:center; gap:8px; }\n details.techbox summary::-webkit-details-marker { display:none; }\n details.techbox summary::after { content:\"▸\"; margin-left:auto; transition:transform .15s; }\n details.techbox[open] summary::after { transform:rotate(90deg); }\n .techlist { padding:0 12px 12px; display:flex; flex-direction:column; gap:8px; }\n .titem { border:1px solid var(--line); border-radius:10px; background:var(--panel); overflow:hidden; }\n .titem .th { padding:8px 12px; font-size:11.5px; font-weight:700; color:var(--ink-mute); display:flex; align-items:center; gap:8px; }\n .titem .th .copy { margin-left:auto; border:none; background:none; color:var(--ink-ghost); font-size:11px; cursor:pointer; padding:2px 4px; border-radius:5px; }\n .titem .th .copy:hover { color:var(--ink); background:var(--line-soft); }\n .titem pre { margin:0; border-top:1px solid var(--line-soft); font-family:ui-monospace,Menlo,monospace; font-size:11.5px;\n line-height:1.55; color:#4a4236; padding:9px 12px; overflow:auto; max-height:240px; white-space:pre-wrap; word-break:break-word; }\n .d-text { font-size:13.5px; line-height:1.7; }\n .d-text p { margin:0 0 8px; }\n .d-text p:last-child { margin-bottom:0; }\n .d-text h1, .d-text h2, .d-text h3, .d-text h4, .d-text h5, .d-text h6 { margin:12px 0 6px; line-height:1.3; }\n .d-text h1:first-child, .d-text h2:first-child, .d-text h3:first-child { margin-top:0; }\n .d-text ul, .d-text ol { margin:0 0 8px; padding-left:20px; }\n .d-text code { font-family:ui-monospace,Menlo,monospace; font-size:12.5px; background:var(--bg); border-radius:4px; padding:1px 5px; }\n .d-text pre { margin:0 0 8px; background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:9px 12px; overflow:auto; }\n .d-text pre code { background:none; border-radius:0; padding:0; }\n .d-text table { border-collapse:collapse; margin:0 0 8px; font-size:12.5px; }\n .d-text th, .d-text td { border:1px solid var(--line); padding:4px 8px; text-align:left; }\n .d-text a { color:var(--blue); }\n .pfoot { flex:none; border-top:1px solid var(--line); padding:9px 16px; font-size:11px; color:var(--ink-ghost); display:flex; gap:10px; }\n .kbd { font-family:ui-monospace,Menlo,monospace; font-size:10px; border:1px solid var(--line); border-bottom-width:2px;\n border-radius:5px; padding:1px 5px; background:var(--panel); color:var(--ink-mute); }\n\n /* ── boîte d'envoi + routage IA ── */\n .composer { flex:none; border-top:1px solid var(--line); background:var(--panel); padding:10px 14px; }\n .composer .cbar { display:flex; gap:8px; }\n .composer textarea { flex:1; resize:none; border:1px solid var(--line); border-radius:10px; padding:9px 12px; font:inherit; font-size:13px; max-height:110px; background:var(--bg); }\n .composer textarea:focus { outline:2px solid #241f1a22; }\n .composer textarea:disabled { opacity:.5; cursor:not-allowed; }\n .composer button { border:none; border-radius:10px; padding:0 16px; background:var(--ink); color:#fdf9f2; font-weight:700; font-size:13px; cursor:pointer; }\n .composer button:disabled { opacity:.4; cursor:not-allowed; }\n .composer .routing { font-size:11px; color:var(--ink-faint); padding:6px 2px 0; min-height:22px; }\n .composer .routing .r-cont { color:var(--blue); font-weight:700; }\n .composer .routing .r-newt { color:var(--gold); font-weight:700; }\n #statusbar { flex:none; padding:4px 20px; font-size:10.5px; color:var(--ink-ghost); border-top:1px solid var(--line-soft); }\n</style>\n</head>\n<body>\n<div id=\"pickerScreen\">\n <h1>Choisis une session</h1>\n <div id=\"pickerList\"><div class=\"pk-empty\">Connexion…</div></div>\n</div>\n\n<div class=\"app hidden\" id=\"storyScreen\">\n <div class=\"hero\">\n <div class=\"hero-top\">\n <span class=\"pulse\" id=\"pulse\"></span>\n <div class=\"who\">\n <div class=\"h1\" id=\"heroTitle\"></div>\n <div class=\"h2\" id=\"heroSub\"></div>\n </div>\n <div class=\"modewrap\"><button id=\"modeSimple\" class=\"on\" type=\"button\">Simple</button><button id=\"modeTech\" type=\"button\">Tech</button></div>\n <a class=\"sim\" id=\"fullPanelLink\" href=\"#\" target=\"_blank\" rel=\"noopener\" title=\"Ouvrir le panneau complet (Terminal/Chat/JSON/TTY)\">↗ panneau complet</a>\n <button class=\"sim\" id=\"switchBtn\" type=\"button\">⇆ changer</button>\n </div>\n <div class=\"plan\" id=\"plan\"></div>\n </div>\n\n <div class=\"body\">\n <div class=\"feedcol\">\n <div class=\"feed\" id=\"feed\"><div class=\"fspacer\"></div><div id=\"rows\"></div></div>\n <div class=\"composer\">\n <div class=\"cbar\">\n <textarea id=\"msgBox\" rows=\"1\" placeholder=\"Écris à l'agent… (la surcouche classe ton message : suite de la sous-tâche ou nouvelle sous-tâche)\"></textarea>\n <button id=\"sendBtn\" type=\"button\">Envoyer</button>\n </div>\n <div class=\"routing\" id=\"routing\"></div>\n </div>\n </div>\n\n <aside class=\"panel\" id=\"panel\" aria-label=\"Détail de l'étape\">\n <div class=\"panel-inner\">\n <div class=\"phead\">\n <span class=\"ico\" id=\"pIco\"></span>\n <div class=\"tt\"><div class=\"t\" id=\"pTitle\"></div><div class=\"s\" id=\"pSub\"></div></div>\n <div class=\"pnav\"><button id=\"pPrev\" type=\"button\">↑</button><button id=\"pNext\" type=\"button\">↓</button><button id=\"pClose\" type=\"button\">✕</button></div>\n </div>\n <div class=\"pbody\" id=\"pBody\"></div>\n <div class=\"pfoot\"><span class=\"kbd\">↑</span><span class=\"kbd\">↓</span> naviguer · <span class=\"kbd\">Esc</span> fermer</div>\n </div>\n </aside>\n </div>\n <div id=\"statusbar\"></div>\n</div>\n\n<script>\nvar $=function(id){ return document.getElementById(id); };\nvar esc=function(s){ return String(s==null?\"\":s).replace(/[&<>]/g,function(c){ return {\"&\":\"&\",\"<\":\"<\",\">\":\">\"}[c]; }); };\n\n// ============================================================\n// renderMd — vanilla-JS port of markdown-lite.ts. Kept\n// function-for-function identical so the two are easy to diff (same\n// self-contained-panel constraint as buildStoryJs below): headers,\n// bold/italic, inline/fenced code, bullet/numbered lists, pipe tables and\n// links, with every raw text run HTML-escaped before any generated tag\n// wraps it.\n// ============================================================\nfunction escHtmlMd(s){ return String(s).replace(/[&<>\"]/g,function(c){ if(c==='&') return '&'; if(c==='<') return '<'; if(c==='>') return '>'; return '"'; }); }\nfunction renderInlineMd(text){\n var out=escHtmlMd(text);\n out=out.replace(/\\`([^\\`]+)\\`/g,function(_m,code){ return '<code>'+code+'</code>'; });\n out=out.replace(/\\\\[([^\\\\]]+)\\\\]\\\\((https?:\\\\/\\\\/[^\\\\s)]+)\\\\)/g,function(_m,label,url){ return '<a href=\"'+url+'\" target=\"_blank\" rel=\"noopener noreferrer\">'+label+'</a>'; });\n out=out.replace(/\\\\*\\\\*([^*]+)\\\\*\\\\*/g,'<strong>$1</strong>');\n out=out.replace(/(^|[^*])\\\\*([^*]+)\\\\*(?!\\\\*)/g,'$1<em>$2</em>');\n return out;\n}\nfunction isTableSepMd(line){ return /^\\\\s*\\\\|?\\\\s*:?-+:?\\\\s*(\\\\|\\\\s*:?-+:?\\\\s*)+\\\\|?\\\\s*$/.test(line); }\nfunction splitRowMd(line){ return line.trim().replace(/^\\\\|/,'').replace(/\\\\|$/,'').split('|').map(function(c){ return c.trim(); }); }\nfunction renderMd(md){\n var lines=String(md==null?'':md).replace(/\\\\r\\\\n?/g,'\\\\n').split('\\\\n');\n var out=[], para=[], list=null;\n function flushPara(){ if(para.length){ out.push('<p>'+para.map(renderInlineMd).join('<br>')+'</p>'); para=[]; } }\n function flushList(){ if(list){ var tag=list.ordered?'ol':'ul'; out.push('<'+tag+'>'+list.items.map(function(i){ return '<li>'+renderInlineMd(i)+'</li>'; }).join('')+'</'+tag+'>'); list=null; } }\n function flushAll(){ flushPara(); flushList(); }\n var i=0;\n while(i<lines.length){\n var line=lines[i];\n if(/^\\\\s*\\`\\`\\`/.test(line)){\n flushAll();\n var code=[]; i+=1;\n while(i<lines.length && !/^\\\\s*\\`\\`\\`/.test(lines[i])){ code.push(lines[i]); i+=1; }\n i+=1;\n out.push('<pre><code>'+escHtmlMd(code.join('\\\\n'))+'</code></pre>');\n continue;\n }\n var header=line.match(/^(#{1,6})\\\\s+(.*)$/);\n if(header){\n flushAll();\n var level=header[1].length;\n out.push('<h'+level+'>'+renderInlineMd(header[2].trim())+'</h'+level+'>');\n i+=1;\n continue;\n }\n if(/^\\\\s*\\\\|/.test(line) && i+1<lines.length && isTableSepMd(lines[i+1])){\n flushAll();\n var headCells=splitRowMd(line);\n i+=2;\n var bodyRows=[];\n while(i<lines.length && /^\\\\s*\\\\|/.test(lines[i])){ bodyRows.push(splitRowMd(lines[i])); i+=1; }\n out.push('<table><thead><tr>'+headCells.map(function(c){ return '<th>'+renderInlineMd(c)+'</th>'; }).join('')+'</tr></thead><tbody>'\n +bodyRows.map(function(r){ return '<tr>'+r.map(function(c){ return '<td>'+renderInlineMd(c)+'</td>'; }).join('')+'</tr>'; }).join('')+'</tbody></table>');\n continue;\n }\n var bullet=line.match(/^\\\\s*[-*+]\\\\s+(.*)$/);\n var numbered=line.match(/^\\\\s*\\\\d+\\\\.\\\\s+(.*)$/);\n if(bullet || numbered){\n flushPara();\n var ordered=!!numbered;\n var item=(bullet||numbered)[1];\n if(!list || list.ordered!==ordered){ flushList(); list={ordered:ordered,items:[]}; }\n list.items.push(item);\n i+=1;\n continue;\n }\n if(line.trim()===''){ flushAll(); i+=1; continue; }\n flushList();\n para.push(line);\n i+=1;\n }\n flushAll();\n return out.join('');\n}\n\n${panelBridgeScript(\"agentproto-session-story-panel\")}\n// Best-effort: some hosts forward the triggering tool call's arguments as\n// a notification so the panel can auto-open the right session. Purely\n// additive — the session picker is the reliable path when this never\n// arrives.\nvar pendingSessionId=null;\nonHostNotification(function(method, params){\n if(/tool-input|tool-call/.test(method)){\n var args=(params && (params.arguments || params.input)) || {};\n if(args && args.sessionId) pendingSessionId=args.sessionId;\n }\n});\n\n// ============================================================\n// buildStory — vanilla-JS port of session-story.ts. Kept\n// function-for-function identical so the two are easy to diff; the panel\n// resource must be fully self-contained (no bundler/dynamic import), so it\n// cannot import the TS module directly.\n// ============================================================\n\nvar SALIENT_KEYS=[\"file_path\",\"path\",\"filePath\",\"file\",\"command\",\"pattern\",\"query\",\"q\",\"url\",\"todos\",\"description\",\"prompt\"];\nfunction truncateStr(v,max){ var o=String(v).replace(/\\\\s+/g,' ').trim(); return o.length>max? o.slice(0,max-1)+'…':o; }\nfunction formatArgValue(v){\n if(typeof v==='string') return v;\n if(Array.isArray(v)) return v.length+' item'+(v.length===1?'':'s');\n if(v && typeof v==='object') return JSON.stringify(v);\n return String(v);\n}\nfunction pickSalient(args){\n for(var i=0;i<SALIENT_KEYS.length;i++){\n var k=SALIENT_KEYS[i], v=args[k];\n if(v!==undefined && v!==null && v!=='') return formatArgValue(v);\n }\n return null;\n}\nfunction formatToolCall(name,args){\n name=name||'tool';\n args=(args && typeof args==='object' && !Array.isArray(args)) ? args : {};\n var salient=pickSalient(args);\n if(salient!==null){\n if(name.toLowerCase().indexOf(salient.toLowerCase())>=0) return truncateStr(name,120);\n return truncateStr(name+' '+salient,120);\n }\n if(Object.keys(args).length===0) return name;\n return truncateStr(name+' '+JSON.stringify(args),120);\n}\nfunction extractText(v){\n if(v==null) return null;\n if(typeof v==='string') return v;\n if(Array.isArray(v)){\n var parts=v.map(extractText).filter(function(x){ return x!=null; });\n return parts.length? parts.join('\\\\n') : null;\n }\n if(typeof v==='object'){\n if(typeof v.text==='string') return v.text;\n if(typeof v.message==='string') return v.message;\n if(Array.isArray(v.content)) return extractText(v.content);\n if(typeof v.error==='string') return v.error;\n if(v.error && typeof v.error==='object' && typeof v.error.message==='string') return v.error.message;\n return null;\n }\n return null;\n}\nfunction formatToolResult(toolName,result,isError){\n var text=extractText(result);\n if(isError){\n var message=text!=null? text : (result!=null? JSON.stringify(result) : 'failed');\n var firstLine=String(message).split(/\\\\r?\\\\n/)[0] || message;\n return truncateStr(firstLine,160);\n }\n if(text==null) return null;\n var trimmed=text.trim();\n if(!trimmed) return null;\n var lines=trimmed.split(/\\\\r?\\\\n/);\n if(lines.length>1){\n var bytes=new TextEncoder().encode(trimmed).length;\n return lines.length+' lines, '+bytes+'B';\n }\n return truncateStr(lines[0],160);\n}\n\nfunction classifyKind(toolCalls){\n if(!toolCalls || toolCalls.length===0) return 'text';\n var names=toolCalls.map(function(t){ return t.name.toLowerCase(); });\n if(names.some(function(n){ return /edit|write/.test(n); })) return 'edit';\n if(names.some(function(n){ return /bash|terminal|command/.test(n); })) return 'bash';\n if(names.some(function(n){ return /read|grep|glob/.test(n); })) return 'read';\n return 'text';\n}\nvar NEW_CHAPTER_RE=/\\\\b(aussi|autre|ensuite|nouveau|nouvelle|plut[oô]t|maintenant|apr[eè]s ça|il faudrait|peux[- ]tu|on pourrait|ajoute|g[eè]re)\\\\b/iu;\nfunction classifyRoute(text){\n var newt=NEW_CHAPTER_RE.test(text);\n if(!newt) return {route:'cont'};\n var title=text.replace(/[.?!].*$/,'').slice(0,42);\n return {route:'newt', title:title};\n}\nfunction formatTsJs(ts){\n if(ts===undefined || ts===null || isNaN(ts)) return '';\n return new Date(ts).toISOString().slice(11,19);\n}\nfunction firstMeaningfulLine(text){\n if(!text) return undefined;\n var lines=text.split('\\\\n').map(function(l){ return l.trim(); }).filter(function(l){ return l.length>0; });\n return lines[0];\n}\nfunction lineCountOf(text){\n var n=(text||'').split('\\\\n').filter(function(l){ return l.trim().length>0; }).length;\n return n||1;\n}\nfunction parseArgsJson(s){ try{ return JSON.parse(s); }catch(e){ return {}; } }\n\nfunction foldToolStep(assistant,toolResults){\n var toolCalls=assistant.toolCalls||[];\n var kind=classifyKind(toolCalls);\n var count=toolCalls.length||1;\n var items=[], facts=[];\n if(assistant.text && assistant.text.trim()) items.push({text:assistant.text.trim()});\n toolCalls.forEach(function(tc,i){\n var args=parseArgsJson(tc.args);\n var h=formatToolCall(tc.name,args);\n var resultMsg=toolResults[i];\n var resultText=(resultMsg && resultMsg.text) || '';\n var isError=resultText.indexOf('[error]')===0;\n var r=isError? resultText.slice(7).trim() : resultText;\n items.push({h:h,r:r});\n var fact=formatToolResult(tc.name,r,isError);\n if(fact) facts.push(fact);\n });\n var firstLine=firstMeaningfulLine(assistant.text);\n var firstToolCall=toolCalls[0];\n var sum=firstLine!==undefined? firstLine : (firstToolCall? formatToolCall(firstToolCall.name,parseArgsJson(firstToolCall.args)) : '…');\n var raw1;\n if(toolCalls.length===0) raw1='assistant · '+lineCountOf(assistant.text)+' ligne(s)';\n else if(toolCalls.length===1) raw1=formatToolCall(firstToolCall.name,parseArgsJson(firstToolCall.args));\n else raw1=(firstToolCall? firstToolCall.name : 'tool')+' ×'+toolCalls.length;\n return {kind:kind, ts:formatTsJs(assistant.ts), sum:sum, raw1:raw1, count:count, facts:facts, items:items};\n}\nfunction foldUserStep(msg){\n var text=msg.text||'';\n return {kind:'user', ts:formatTsJs(msg.ts), sum:'« '+truncateStr(text,80)+' »', raw1:'user · '+lineCountOf(text)+' ligne(s)', count:1, facts:[], items:[{text:text}], userText:text};\n}\nfunction foldOrphanToolStep(msg){\n var text=msg.text||'';\n var isError=text.indexOf('[error]')===0;\n var r=isError? text.slice(7).trim() : text;\n var name=msg.toolName||'tool';\n var fact=formatToolResult(name,r,isError);\n return {kind:classifyKind([{name:name}]), ts:formatTsJs(msg.ts), sum: msg.toolName? (msg.toolName+' · résultat') : \"Résultat d'outil\", raw1: msg.toolName||'tool', count:1, facts: fact?[fact]:[], items:[{h:name,r:r}]};\n}\nfunction foldSystemStep(msg){\n var text=msg.text||'';\n var line=firstMeaningfulLine(text);\n return {kind:'text', ts:formatTsJs(msg.ts), sum: line!==undefined? line : text, raw1:'system', count:1, facts:[], items: text?[{text:text}]:[]};\n}\nfunction foldMessages(messages){\n var steps=[], i=0;\n while(i<messages.length){\n var msg=messages[i];\n if(msg.role==='user'){ steps.push(foldUserStep(msg)); i+=1; continue; }\n if(msg.role==='assistant'){\n var j=i+1, toolResults=[];\n while(j<messages.length && messages[j].role==='tool'){ toolResults.push(messages[j]); j+=1; }\n steps.push(foldToolStep(msg,toolResults)); i=j; continue;\n }\n if(msg.role==='tool'){ steps.push(foldOrphanToolStep(msg)); i+=1; continue; }\n steps.push(foldSystemStep(msg)); i+=1;\n }\n return steps;\n}\nfunction buildStoryJs(messages){\n var folded=foldMessages(messages||[]);\n var chapters=[], steps=[];\n var currentChapterId, sawFirstUser=false;\n function closeCurrent(){ var cur=chapters.filter(function(c){ return c.id===currentChapterId; })[0]; if(cur) cur.status='done'; }\n function openChapter(title){ var id='c'+(chapters.length+1); chapters.push({id:id,title:title,status:'cur'}); return id; }\n folded.forEach(function(step){\n var route;\n if(step.kind==='user' && step.userText!==undefined){\n if(!sawFirstUser){ sawFirstUser=true; currentChapterId=openChapter('Cadrage'); }\n else {\n var verdict=classifyRoute(step.userText);\n route=verdict.route;\n if(verdict.route==='newt'){ closeCurrent(); currentChapterId=openChapter(verdict.title||'Nouvelle sous-tâche'); }\n }\n } else if(currentChapterId===undefined){ currentChapterId=openChapter('Cadrage'); }\n var out={chap:currentChapterId, kind:step.kind, ts:step.ts, sum:step.sum, raw1:step.raw1, count:step.count, facts:step.facts, items:step.items};\n if(route) out.route=route;\n steps.push(out);\n });\n return {chapters:chapters, steps:steps};\n}\n\n// ============================================================\n// App state\n// ============================================================\nvar sessions=[];\nvar activeSessionId=null;\nvar story={chapters:[], steps:[]};\nvar open={};\nvar selected=-1;\nvar lastSeenOutputAt=null;\nvar pollTimer=null, polling=false;\nvar ICONS={text:[\"k-text\",\"A\"],edit:[\"k-edit\",\"✎\"],bash:[\"k-bash\",\"▸\"],read:[\"k-read\",\"⌕\"],user:[\"k-user\",\"T\"]};\nvar icoSpec=function(k){ return ICONS[k]||ICONS.text; };\nvar chapOf=function(id){ return story.chapters.filter(function(c){ return c.id===id; })[0]; };\nvar curChap=function(){ return story.chapters.filter(function(c){ return c.status==='cur'; })[0] || story.chapters[story.chapters.length-1]; };\n\nfunction setStatus(msg){ $('statusbar').textContent=msg; }\nfunction nowTs(){ return new Date().toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit',second:'2-digit'}); }\n\nfunction titleOf(s){\n return s.label || s.name || (s.command? s.command.split(/\\\\s+/)[0].split('/').pop() : null) || s.id.slice(0,8);\n}\n\n// ============================================================\n// Picker screen\n// ============================================================\nfunction renderPicker(){\n var el=$('pickerList');\n if(!sessions.length){ el.innerHTML='<div class=\"pk-empty\">Aucune session</div>'; return; }\n var html='';\n sessions.forEach(function(s){\n html+='<div class=\"pk-item\" data-id=\"'+esc(s.id)+'\">'\n + '<span class=\"pk-name\">'+esc(titleOf(s))+'</span>'\n + '<span class=\"badge '+esc(s.status)+'\">'+esc(s.status)+'</span>'\n + '<span class=\"pk-meta\">'+esc(s.kind||'')+'</span>'\n + '</div>';\n });\n el.innerHTML=html;\n Array.prototype.forEach.call(el.querySelectorAll('.pk-item'), function(row){\n row.onclick=function(){ openSession(row.getAttribute('data-id')); };\n });\n}\n\nfunction showPicker(){\n activeSessionId=null;\n $('pickerScreen').classList.remove('hidden');\n $('storyScreen').classList.add('hidden');\n renderPicker();\n}\n\nfunction openSession(id){\n activeSessionId=id;\n story={chapters:[], steps:[]};\n open={};\n selected=-1;\n lastSeenOutputAt=null;\n $('pickerScreen').classList.add('hidden');\n $('storyScreen').classList.remove('hidden');\n $('fullPanelLink').href='https://cli.agentproto.sh/panel?session='+encodeURIComponent(id);\n closePanel();\n loadStory().then(renderAll);\n}\n\n// ============================================================\n// Story loading\n// ============================================================\nfunction activeSession(){ return sessions.filter(function(s){ return s.id===activeSessionId; })[0]; }\n\nfunction loadStory(){\n return callTool('agent_export', {sessionId:activeSessionId, format:'json'}).then(function(data){\n var messages=(data && data.messages) || [];\n story=buildStoryJs(messages);\n // Default open state: only the last (current) chapter is expanded.\n var last=story.chapters[story.chapters.length-1];\n if(last && !(last.id in open)) open[last.id]=true;\n }).catch(function(e){\n setStatus('Erreur export : '+e.message);\n });\n}\n\nfunction canSend(){\n var s=activeSession();\n return !!s && s.kind==='agent-cli' && s.status==='running';\n}\n\nfunction renderComposer(){\n var s=activeSession();\n var box=$('msgBox'), btn=$('sendBtn');\n var enabled=canSend();\n box.disabled=!enabled;\n btn.disabled=!enabled;\n if(!s){ box.placeholder='Session introuvable.'; }\n else if(!enabled) box.placeholder='Lecture seule — session '+esc(s.status)+'.';\n else box.placeholder=\"Écris à l'agent… (la surcouche classe ton message : suite de la sous-tâche ou nouvelle sous-tâche)\";\n}\n\nfunction renderHero(){\n var s=activeSession();\n $('heroTitle').textContent=s? titleOf(s) : (activeSessionId||'');\n var firstUser=story.steps.filter(function(st){ return st.kind==='user'; })[0];\n var mission=firstUser? firstUser.userText || (firstUser.items[0] && firstUser.items[0].text) : null;\n $('heroSub').textContent=mission? truncateStr(mission,200) : 'Aucun message pour le moment.';\n var p=$('pulse');\n p.classList.toggle('off', !(s && (s.status==='running' || s.status==='starting')));\n renderComposer();\n}\n\nfunction renderAll(){\n renderHero();\n renderPlan();\n renderRows('bottom');\n}\n\n// ============================================================\n// big picture strip\n// ============================================================\nfunction renderPlan(){\n var done=story.chapters.filter(function(c){ return c.status==='done'; }).length;\n $('plan').innerHTML=story.chapters.map(function(c,i){\n return '<span class=\"pt '+c.status+'\" data-c=\"'+esc(c.id)+'\"><span class=\"st\">'+(c.status==='done'?'✓':'●')+'</span>'+(i+1)+'. '+esc(c.title)+'</span>';\n }).join('') + '<span class=\"pt\" style=\"cursor:default\"><b>'+done+'/'+story.chapters.length+'</b> faites</span>';\n Array.prototype.forEach.call($('plan').querySelectorAll('.pt[data-c]'), function(el){\n el.onclick=function(){ open[el.getAttribute('data-c')]=true; renderRows(); jumpToChap(el.getAttribute('data-c')); };\n });\n}\nfunction jumpToChap(cid){\n var el=document.querySelector('.chap[data-c=\"'+cid+'\"]');\n if(el) el.scrollIntoView({block:'start',behavior:'smooth'});\n}\n\n// ============================================================\n// feed segmenté par chapitres\n// ============================================================\nfunction rowHtml(s,i,isNew){\n var spec=icoSpec(s.kind), cls=spec[0], ch=spec[1];\n var route=s.route? '<span class=\"route '+(s.route==='newt'?'newt':'cont')+'\">'+(s.route==='newt'?'★ nouvelle sous-tâche':'↳ suite')+'</span>' : '';\n return '<div class=\"row '+(isNew?'new':'')+'\" aria-selected=\"'+(i===selected)+'\" data-i=\"'+i+'\">'\n + '<span class=\"ico '+cls+'\">'+ch+'</span>'\n + '<span class=\"mid\"><span class=\"sum\">'+esc(s.sum)+'</span><span class=\"raw1\">'+esc(s.raw1||'')+'</span>'+route+'</span>'\n + (s.count>1? '<span class=\"cnt\">×'+s.count+'</span>':'') + '<span class=\"ts\">'+esc(s.ts||'')+'</span>'\n + '</div>';\n}\nfunction renderRows(keepScroll,newIdx){\n var feed=$('feed');\n var prevH=feed.scrollHeight, prevTop=feed.scrollTop;\n var html='';\n story.chapters.forEach(function(c,ci){\n var chapSteps=[];\n story.steps.forEach(function(s,i){ if(s.chap===c.id) chapSteps.push({s:s,i:i}); });\n if(!chapSteps.length) return;\n var isOpen=!!open[c.id];\n html+='<div class=\"chap '+c.status+' '+(isOpen?'open':'')+'\" data-c=\"'+esc(c.id)+'\">'\n + '<span class=\"cst\">'+(c.status==='done'?'✓':'●')+'</span><span class=\"cnum\">'+(ci+1)+'.</span>'\n + '<span class=\"csum\">'+esc(c.title)+'</span>'\n + '<span class=\"cmeta\">'+chapSteps.length+' étape'+(chapSteps.length>1?'s':'')+'</span><span class=\"cchev\">▸</span>'\n + '</div>';\n if(isOpen) html += chapSteps.map(function(x){ return rowHtml(x.s,x.i,x.i===newIdx); }).join('');\n });\n $('rows').innerHTML=html;\n Array.prototype.forEach.call(document.querySelectorAll('.row'), function(el){\n el.onclick=function(){ selectStep(Number(el.getAttribute('data-i'))); };\n });\n Array.prototype.forEach.call(document.querySelectorAll('.chap'), function(el){\n el.onclick=function(){ var c=el.getAttribute('data-c'); open[c]=!open[c]; renderRows(); };\n });\n if(keepScroll==='bottom') feed.scrollTop=feed.scrollHeight;\n else if(keepScroll==='preserve') feed.scrollTop=feed.scrollHeight-prevH+prevTop;\n}\n\n// ============================================================\n// panneau ancré\n// ============================================================\nfunction selectStep(i){\n selected=i;\n var s=story.steps[i]; if(!s) return;\n open[s.chap]=true;\n $('panel').classList.add('open');\n var spec=icoSpec(s.kind), cls=spec[0], ch=spec[1];\n var ico=$('pIco'); ico.className='ico '+cls; ico.textContent=ch;\n $('pTitle').textContent=s.sum;\n var c=chapOf(s.chap);\n $('pSub').textContent=(s.ts? s.ts+' · ':'')+(c? ('sous-tâche : '+c.title) : '');\n var facts=(s.facts||[]).map(function(f){\n return '<span class=\"fact '+(/✓|exit 0|passed|0 match/.test(f)?'ok':'')+'\">'+esc(f)+'</span>';\n }).join('');\n var tech=(s.items||[]).map(function(it,k){\n return it.text!==undefined\n ? '<div class=\"d-text\">'+renderMd(it.text)+'</div>'\n : '<div class=\"titem\"><div class=\"th\">'+esc(it.h)+'<button class=\"copy\" data-k=\"'+k+'\" type=\"button\">⧉</button></div><pre>'+esc(it.r)+'</pre></div>';\n }).join('');\n $('pBody').innerHTML=''\n + '<div class=\"plain\"><div>'+esc(s.sum)+'.</div><div class=\"why\">'+esc(s.why||'')+'</div></div>'\n + (facts? '<div class=\"facts\">'+facts+'</div>':'')\n + '<details class=\"techbox\" '+(document.body.classList.contains('tech')?'open':'')+'>'\n + '<summary>Détail technique · '+(s.items||[]).length+'</summary><div class=\"techlist\">'+tech+'</div>'\n + '</details>';\n Array.prototype.forEach.call($('pBody').querySelectorAll('.copy'), function(btn){\n btn.onclick=function(e){\n e.stopPropagation();\n var it=(s.items||[])[Number(btn.getAttribute('data-k'))];\n var payload=(it.h||'')+'\\\\n'+(it.r||it.text||'');\n if(navigator.clipboard) navigator.clipboard.writeText(payload).catch(function(){});\n btn.textContent='✓'; setTimeout(function(){ btn.textContent='⧉'; },900);\n };\n });\n $('pPrev').disabled=i<=0; $('pNext').disabled=i>=story.steps.length-1;\n renderRows();\n var el=document.querySelector('.row[data-i=\"'+i+'\"]');\n if(el) el.scrollIntoView({block:'nearest',behavior:'smooth'});\n}\nfunction closePanel(){ selected=-1; var p=$('panel'); if(p) p.classList.remove('open'); renderRows(); }\n$('pClose').addEventListener('click',closePanel);\n$('pPrev').addEventListener('click',function(){ if(selected>0) selectStep(selected-1); });\n$('pNext').addEventListener('click',function(){ if(selected<story.steps.length-1) selectStep(selected+1); });\ndocument.addEventListener('keydown',function(e){\n if(e.key==='Escape'){ closePanel(); return; }\n if($('storyScreen').classList.contains('hidden')) return;\n if(selected<0 || e.target.tagName==='TEXTAREA') return;\n if(e.key==='ArrowUp'){ e.preventDefault(); if(selected>0) selectStep(selected-1); }\n if(e.key==='ArrowDown'){ e.preventDefault(); if(selected<story.steps.length-1) selectStep(selected+1); }\n});\n\n// ============================================================\n// Simple / Tech modes\n// ============================================================\nfunction setMode(tech){\n document.body.classList.toggle('tech',tech);\n $('modeTech').classList.toggle('on',tech);\n $('modeSimple').classList.toggle('on',!tech);\n if(selected>=0) selectStep(selected);\n}\n$('modeSimple').addEventListener('click',function(){ setMode(false); });\n$('modeTech').addEventListener('click',function(){ setMode(true); });\n$('switchBtn').addEventListener('click', function(){ if(pollTimer) clearTimeout(pollTimer); showPicker(); doPoll(); });\n\n// ============================================================\n// composer — local chapter-routing classification + agent_prompt\n// ============================================================\n$('sendBtn').addEventListener('click', sendMsg);\n$('msgBox').addEventListener('keydown', function(e){\n if(e.key==='Enter' && !e.shiftKey){ e.preventDefault(); sendMsg(); }\n});\nfunction sendMsg(){\n if(!canSend()) return;\n var box=$('msgBox'), text=box.value.trim();\n if(!text) return;\n box.value='';\n var cur=curChap();\n var r=cur? classifyRoute(text) : {route:'cont'};\n var chapId=cur? cur.id : null;\n if(r.route==='newt' && cur){\n cur.status='done';\n var id='c'+(story.chapters.length+1);\n story.chapters.push({id:id, title:r.title||'Nouvelle sous-tâche', status:'cur'});\n chapId=id; open[id]=true;\n $('routing').innerHTML='✦ classé : <span class=\"r-newt\">★ nouvelle sous-tâche « '+esc(r.title||'')+' »</span>';\n } else {\n $('routing').innerHTML='✦ classé : <span class=\"r-cont\">↳ suite de « '+esc(cur? cur.title : '')+' »</span>';\n }\n setTimeout(function(){ $('routing').textContent=''; },5000);\n story.steps.push({\n chap:chapId, kind:'user', ts:nowTs(),\n sum:'« '+text.slice(0,80)+(text.length>80?'…':'')+' »',\n raw1:'user · '+text.split('\\\\n').length+' ligne(s)',\n route:r.route, facts:[], items:[{text:text}], userText:text,\n });\n renderPlan(); renderRows('bottom', story.steps.length-1);\n callTool('agent_prompt', {sessionId:activeSessionId, prompt:text}).catch(function(e){\n setStatus('Envoi échoué : '+e.message);\n });\n}\n\n// ============================================================\n// Poll — session_list every ~5s; re-fetch agent_export only on turn\n// boundaries (lastOutputAt changed for the active session).\n// ============================================================\nvar POLL_MS=5000;\nfunction loadSessions(){\n return callTool('session_list', {kind:'all'}).then(function(data){\n sessions=data.sessions||[];\n if($('pickerScreen') && !$('pickerScreen').classList.contains('hidden')) renderPicker();\n }).catch(function(e){ setStatus('Erreur : '+e.message); });\n}\nfunction doPoll(){\n if(polling) return;\n polling=true;\n loadSessions().then(function(){\n if(!activeSessionId){ polling=false; pollTimer=setTimeout(doPoll,POLL_MS); return; }\n var s=activeSession();\n if(!s){ polling=false; pollTimer=setTimeout(doPoll,POLL_MS); return; }\n renderHero();\n var changed=s.lastOutputAt && s.lastOutputAt!==lastSeenOutputAt;\n if(changed){\n lastSeenOutputAt=s.lastOutputAt;\n loadStory().then(function(){ renderPlan(); renderRows('bottom'); polling=false; pollTimer=setTimeout(doPoll,POLL_MS); });\n } else {\n polling=false; pollTimer=setTimeout(doPoll,POLL_MS);\n }\n }).catch(function(){ polling=false; pollTimer=setTimeout(doPoll,POLL_MS); });\n}\n\n// ============================================================\n// Boot\n// ============================================================\ninitBridge().then(loadSessions).then(function(){\n setTimeout(function(){\n var target=pendingSessionId && sessions.some(function(s){ return s.id===pendingSessionId; })\n ? pendingSessionId\n : null;\n if(!target){\n var agentSessions=sessions.filter(function(s){ return s.kind==='agent-cli'; });\n if(agentSessions.length===1) target=agentSessions[0].id;\n }\n if(target) openSession(target); else showPicker();\n pollTimer=setTimeout(doPoll,POLL_MS);\n }, 50);\n}).catch(function(e){\n setStatus('Bridge : '+e.message);\n $('pickerList').innerHTML='<div class=\"pk-empty\">Échec connexion bridge : '+esc(e.message)+'</div>';\n});\n</script>\n</body>\n</html>`\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/panel-bridge.ts","../../src/session-story/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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,EAiEa,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAAA,CAAA;AA4F7C;;;ACnNO,IAAM,wBAAA,GAA2B,CAA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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 _standaloneApp = null;\nfunction _isStandalone(){\n return window.parent === window && !!window.McpApp && typeof window.McpApp.connect === 'function';\n}\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 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 rpcNotify('ui/notifications/initialized', {});\n });\n}\nfunction requestDisplayMode(mode){\n return rpcRequest('ui/request-display-mode', {mode: mode});\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 * HTML bundle for the agentproto session story panel — the\n * `SESSION_STORY_PANEL_HTML` served as the `ui://agentproto_session_story/view`\n * resource. Mounted via the `agentproto_session_story` tool defined in\n * ./index.ts. Also consumed directly by packages/vscode's story webview\n * (`storyPanel.ts`), which relays this same HTML into a VS Code editor tab.\n *\n * Ported 1:1 from the validated mockup at docs/session-story-mockup.html —\n * same CSS, same DOM structure/classes, same interaction model (anchored\n * side panel, sticky collapsible chapter headers, Simple/Tech toggle,\n * composer with local chapter-routing classification). Fake data is\n * replaced with live data pulled through the MCP Apps postMessage bridge.\n *\n * The HTML must stay fully self-contained (CSP: inline CSS/JS only, no\n * CDN, no external fonts) — see runtime's mcp-apps-adapter.ts and the other\n * panels in this app family (sessions-panel, agents-overview) for the same\n * constraint. Because of that, this file cannot `import` the pure\n * `buildStory` module from @agentproto/runtime's session-story.ts (a\n * separate, CLI-facing heuristics module that stays in runtime — it isn't\n * a dependency of this panel) — the folding/chaptering heuristics are\n * ported to vanilla JS below (`buildStoryJs`), mirroring session-story.ts\n * function-for-function so the two stay easy to diff.\n *\n * Protocol: MCP Apps ext spec 2026-01-26\n * – Bridge: JSON-RPC 2.0 over window.parent.postMessage\n * – Handshake: ui/initialize → host result → ui/notifications/initialized\n * – Data: tools/call → session_list (status/picker) + agent_export\n * (timeline, re-fetched on turn boundaries) + agent_prompt (composer)\n */\n\nimport { panelBridgeScript } from \"../panel-bridge.js\"\n\nexport const SESSION_STORY_PANEL_HTML = `<!doctype html>\n<html lang=\"fr\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>session story</title>\n<style>\n :root {\n color-scheme: light;\n --bg:#faf8f5; --panel:#fffdfa; --line:#ece5da; --line-soft:#f2ede3;\n --ink:#241f1a; --ink-mute:#7d7060; --ink-faint:#a9997f; --ink-ghost:#b3a893;\n --accent:#0d7a4f; --accent-soft:#e8f4ec;\n --gold:#a6701b; --gold-soft:#fff2dc;\n --blue:#1d4e80; --blue-soft:#e9f1fb;\n --violet:#5b3fa6; --violet-soft:#ede9ff;\n --sel:#fbeccd; --red:#b3261e; --red-soft:#fbeae8;\n }\n * { box-sizing:border-box; }\n html,body { height:100%; }\n body { margin:0; font-family:ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",sans-serif; background:var(--bg); color:var(--ink); -webkit-font-smoothing:antialiased; }\n .app { height:100vh; display:flex; flex-direction:column; }\n .hidden { display:none !important; }\n\n /* ── picker screen ── */\n #pickerScreen { height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:14px; padding:24px; }\n #pickerScreen h1 { font-size:15px; font-weight:700; }\n #pickerList { width:min(520px,90vw); max-height:60vh; overflow-y:auto; border:1px solid var(--line); border-radius:12px; background:var(--panel); }\n .pk-item { padding:10px 14px; border-bottom:1px solid var(--line-soft); cursor:pointer; display:flex; align-items:center; gap:10px; }\n .pk-item:last-child { border-bottom:none; }\n .pk-item:hover { background:var(--line-soft); }\n .pk-name { flex:1; min-width:0; font-size:13px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .pk-meta { flex:none; font-size:10.5px; color:var(--ink-faint); font-weight:600; }\n .pk-empty { padding:24px; text-align:center; color:var(--ink-mute); font-size:12.5px; }\n .badge { display:inline-block; padding:1px 8px; border-radius:999px; font-size:10px; font-weight:700; }\n .badge.running { background:var(--accent-soft); color:var(--accent); }\n .badge.starting { background:var(--blue-soft); color:var(--blue); }\n .badge.exited { background:var(--line-soft); color:var(--ink-faint); }\n .badge.killed, .badge.error { background:var(--red-soft); color:var(--red); }\n\n /* ── big picture : mission + plan de sous-tâches ── */\n .hero { flex:none; padding:13px 20px 0; border-bottom:1px solid var(--line); background:var(--panel); }\n .hero-top { display:flex; align-items:center; gap:13px; }\n .pulse { width:10px; height:10px; border-radius:50%; background:var(--accent); flex:none;\n box-shadow:0 0 0 0 rgba(13,122,79,.35); animation:pulse 2.4s infinite; }\n .pulse.off { background:var(--ink-ghost); animation:none; }\n @keyframes pulse { 70% { box-shadow:0 0 0 9px rgba(13,122,79,0); } 100% { box-shadow:0 0 0 0 rgba(13,122,79,0); } }\n .who { min-width:0; flex:1; }\n .who .h1 { font-size:14.5px; font-weight:700; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .who .h2 { font-size:12px; color:var(--ink-mute); margin-top:1px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .modewrap { display:flex; border:1px solid var(--line); border-radius:9px; overflow:hidden; flex:none; }\n .modewrap button { border:none; background:var(--panel); color:var(--ink-mute); font-size:11px; font-weight:700; padding:6px 11px; cursor:pointer; }\n .modewrap button.on { background:var(--ink); color:#fdf9f2; }\n button.sim, a.sim { border:1px solid var(--line); background:var(--panel); color:var(--ink-mute); font-weight:700;\n font-size:11.5px; border-radius:8px; padding:6px 12px; cursor:pointer; flex:none; }\n button.sim.on { background:var(--ink); border-color:var(--ink); color:#fdf9f2; }\n a.sim { display:inline-flex; align-items:center; text-decoration:none; }\n a.sim:hover { border-color:var(--ink-ghost); color:var(--ink); }\n\n /* plan strip : les sous-tâches, l'avancement d'un coup d'œil */\n .plan { display:flex; gap:6px; overflow-x:auto; padding:11px 0 12px; scrollbar-width:none; }\n .plan::-webkit-scrollbar { display:none; }\n .pt { flex:none; display:flex; align-items:center; gap:6px; font-size:11.5px; font-weight:700; padding:5px 11px;\n border-radius:999px; border:1px solid var(--line); background:var(--bg); color:var(--ink-mute); cursor:pointer; white-space:nowrap; }\n .pt:hover { border-color:var(--ink-ghost); }\n .pt .st { font-size:10px; }\n .pt.done { color:var(--accent); background:var(--accent-soft); border-color:transparent; }\n .pt.cur { color:var(--gold); background:var(--gold-soft); border-color:transparent; }\n .pt.cur .st { animation:blink 1.6s infinite; }\n @keyframes blink { 50% { opacity:.35; } }\n\n /* ── corps ── */\n .body { flex:1; display:flex; min-height:0; }\n .feedcol { flex:1; min-width:320px; display:flex; flex-direction:column; }\n .feed { flex:1; overflow-y:auto; padding:4px 14px 10px; display:flex; flex-direction:column; scroll-behavior:smooth; }\n .fspacer { flex:1; }\n\n /* chapitres */\n .chap { flex:none; position:sticky; top:0; z-index:5; margin:8px -4px 2px; padding:7px 12px; display:flex; align-items:center; gap:9px;\n background:color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter:blur(6px);\n border-radius:9px; cursor:pointer; font-size:11.5px; font-weight:800; letter-spacing:.03em; color:var(--ink-mute); }\n .chap:hover { color:var(--ink); }\n .chap .cst { flex:none; width:17px; height:17px; border-radius:50%; display:grid; place-items:center; font-size:9.5px; font-weight:900; }\n .chap.done .cst { background:var(--accent-soft); color:var(--accent); }\n .chap.cur .cst { background:var(--gold-soft); color:var(--gold); }\n .chap .cnum { color:var(--ink-ghost); font-weight:700; }\n .chap .csum { flex:1; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .chap .cmeta { flex:none; font-size:10.5px; color:var(--ink-ghost); font-weight:600; }\n .chap .cchev { flex:none; color:var(--ink-ghost); transition:transform .15s; }\n .chap.open .cchev { transform:rotate(90deg); }\n\n .row { flex:none; min-height:44px; margin:1px 0 1px 10px; padding:5px 12px 5px 10px; display:flex; align-items:center; gap:11px;\n cursor:pointer; border-radius:10px; border-left:3px solid transparent; transition:background .12s; }\n .row:hover { background:var(--line-soft); }\n .row[aria-selected=\"true\"] { background:var(--sel); border-left-color:var(--gold); }\n .row .ico { width:24px; height:24px; border-radius:8px; flex:none; display:grid; place-items:center; font-size:11.5px; font-weight:800; }\n .ico.k-text { background:var(--blue-soft); color:var(--blue); }\n .ico.k-edit { background:var(--gold-soft); color:var(--gold); }\n .ico.k-bash { background:var(--accent-soft); color:var(--accent); }\n .ico.k-read { background:var(--violet-soft); color:var(--violet); }\n .ico.k-user { background:var(--ink); color:#fdf9f2; }\n .row .mid { flex:1; min-width:0; }\n .row .sum { display:block; font-size:13.5px; line-height:1.35; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }\n .row .raw1 { display:block; font-size:10.5px; color:var(--ink-faint); font-family:ui-monospace,Menlo,monospace;\n white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:1px; }\n body:not(.tech) .row .raw1 { display:none; }\n .row .route { display:inline-block; font-size:10px; font-weight:800; padding:1px 8px; border-radius:999px; margin-top:2px; }\n .route.cont { background:var(--blue-soft); color:var(--blue); }\n .route.newt { background:var(--gold-soft); color:var(--gold); }\n .row .cnt { flex:none; font-size:10px; font-weight:800; color:var(--gold); background:var(--gold-soft); padding:2px 7px; border-radius:999px; }\n .row .ts { flex:none; font-size:10.5px; color:var(--ink-ghost); font-variant-numeric:tabular-nums; }\n @keyframes slidein { from { opacity:0; transform:translateY(6px); } }\n .row.new { animation:slidein .25s ease-out; }\n\n /* ── panneau ancré ── */\n .panel { flex:none; width:0; overflow:hidden; border-left:1px solid transparent; background:var(--panel);\n display:flex; flex-direction:column; transition:width .22s ease, border-color .22s; }\n .panel.open { width:min(430px,46vw); border-left-color:var(--line); }\n .panel-inner { width:min(430px,46vw); flex:1; display:flex; flex-direction:column; min-height:0; }\n .phead { flex:none; padding:14px 16px 12px; border-bottom:1px solid var(--line); display:flex; align-items:flex-start; gap:11px; }\n .phead .ico { width:28px; height:28px; font-size:13px; border-radius:9px; }\n .phead .tt { min-width:0; flex:1; }\n .phead .t { font-size:14px; font-weight:700; line-height:1.4; }\n .phead .s { font-size:11px; color:var(--ink-faint); margin-top:3px; font-variant-numeric:tabular-nums; }\n .pnav { display:flex; gap:4px; flex:none; }\n .pnav button { width:26px; height:26px; border:1px solid var(--line); background:var(--panel); border-radius:8px;\n color:var(--ink-mute); font-size:12px; cursor:pointer; display:grid; place-items:center; }\n .pnav button:disabled { opacity:.3; cursor:default; }\n .pbody { flex:1; overflow-y:auto; padding:16px; display:flex; flex-direction:column; gap:14px; }\n .plain { font-size:14px; line-height:1.7; }\n .plain .why { margin-top:8px; font-size:12.5px; color:var(--ink-mute); line-height:1.6; }\n .facts { display:flex; flex-wrap:wrap; gap:6px; }\n .fact { font-size:11px; font-weight:700; background:var(--bg); border:1px solid var(--line); color:var(--ink-mute); padding:4px 10px; border-radius:999px; }\n .fact.ok { background:var(--accent-soft); border-color:transparent; color:var(--accent); }\n details.techbox { border:1px solid var(--line); border-radius:12px; background:var(--bg); overflow:hidden; }\n details.techbox summary { list-style:none; cursor:pointer; padding:10px 14px; font-size:11.5px; font-weight:800;\n letter-spacing:.04em; text-transform:uppercase; color:var(--ink-faint); display:flex; align-items:center; gap:8px; }\n details.techbox summary::-webkit-details-marker { display:none; }\n details.techbox summary::after { content:\"▸\"; margin-left:auto; transition:transform .15s; }\n details.techbox[open] summary::after { transform:rotate(90deg); }\n .techlist { padding:0 12px 12px; display:flex; flex-direction:column; gap:8px; }\n .titem { border:1px solid var(--line); border-radius:10px; background:var(--panel); overflow:hidden; }\n .titem .th { padding:8px 12px; font-size:11.5px; font-weight:700; color:var(--ink-mute); display:flex; align-items:center; gap:8px; }\n .titem .th .copy { margin-left:auto; border:none; background:none; color:var(--ink-ghost); font-size:11px; cursor:pointer; padding:2px 4px; border-radius:5px; }\n .titem .th .copy:hover { color:var(--ink); background:var(--line-soft); }\n .titem pre { margin:0; border-top:1px solid var(--line-soft); font-family:ui-monospace,Menlo,monospace; font-size:11.5px;\n line-height:1.55; color:#4a4236; padding:9px 12px; overflow:auto; max-height:240px; white-space:pre-wrap; word-break:break-word; }\n .d-text { font-size:13.5px; line-height:1.7; }\n .d-text p { margin:0 0 8px; }\n .d-text p:last-child { margin-bottom:0; }\n .d-text h1, .d-text h2, .d-text h3, .d-text h4, .d-text h5, .d-text h6 { margin:12px 0 6px; line-height:1.3; }\n .d-text h1:first-child, .d-text h2:first-child, .d-text h3:first-child { margin-top:0; }\n .d-text ul, .d-text ol { margin:0 0 8px; padding-left:20px; }\n .d-text code { font-family:ui-monospace,Menlo,monospace; font-size:12.5px; background:var(--bg); border-radius:4px; padding:1px 5px; }\n .d-text pre { margin:0 0 8px; background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:9px 12px; overflow:auto; }\n .d-text pre code { background:none; border-radius:0; padding:0; }\n .d-text table { border-collapse:collapse; margin:0 0 8px; font-size:12.5px; }\n .d-text th, .d-text td { border:1px solid var(--line); padding:4px 8px; text-align:left; }\n .d-text a { color:var(--blue); }\n .pfoot { flex:none; border-top:1px solid var(--line); padding:9px 16px; font-size:11px; color:var(--ink-ghost); display:flex; gap:10px; }\n .kbd { font-family:ui-monospace,Menlo,monospace; font-size:10px; border:1px solid var(--line); border-bottom-width:2px;\n border-radius:5px; padding:1px 5px; background:var(--panel); color:var(--ink-mute); }\n\n /* ── boîte d'envoi + routage IA ── */\n .composer { flex:none; border-top:1px solid var(--line); background:var(--panel); padding:10px 14px; }\n .composer .cbar { display:flex; gap:8px; }\n .composer textarea { flex:1; resize:none; border:1px solid var(--line); border-radius:10px; padding:9px 12px; font:inherit; font-size:13px; max-height:110px; background:var(--bg); }\n .composer textarea:focus { outline:2px solid #241f1a22; }\n .composer textarea:disabled { opacity:.5; cursor:not-allowed; }\n .composer button { border:none; border-radius:10px; padding:0 16px; background:var(--ink); color:#fdf9f2; font-weight:700; font-size:13px; cursor:pointer; }\n .composer button:disabled { opacity:.4; cursor:not-allowed; }\n .composer .routing { font-size:11px; color:var(--ink-faint); padding:6px 2px 0; min-height:22px; }\n .composer .routing .r-cont { color:var(--blue); font-weight:700; }\n .composer .routing .r-newt { color:var(--gold); font-weight:700; }\n #statusbar { flex:none; padding:4px 20px; font-size:10.5px; color:var(--ink-ghost); border-top:1px solid var(--line-soft); }\n</style>\n</head>\n<body>\n<div id=\"pickerScreen\">\n <h1>Choisis une session</h1>\n <div id=\"pickerList\"><div class=\"pk-empty\">Connexion…</div></div>\n</div>\n\n<div class=\"app hidden\" id=\"storyScreen\">\n <div class=\"hero\">\n <div class=\"hero-top\">\n <span class=\"pulse\" id=\"pulse\"></span>\n <div class=\"who\">\n <div class=\"h1\" id=\"heroTitle\"></div>\n <div class=\"h2\" id=\"heroSub\"></div>\n </div>\n <div class=\"modewrap\"><button id=\"modeSimple\" class=\"on\" type=\"button\">Simple</button><button id=\"modeTech\" type=\"button\">Tech</button></div>\n <a class=\"sim\" id=\"fullPanelLink\" href=\"#\" target=\"_blank\" rel=\"noopener\" title=\"Ouvrir le panneau complet (Terminal/Chat/JSON/TTY)\">↗ panneau complet</a>\n <button class=\"sim\" id=\"switchBtn\" type=\"button\">⇆ changer</button>\n </div>\n <div class=\"plan\" id=\"plan\"></div>\n </div>\n\n <div class=\"body\">\n <div class=\"feedcol\">\n <div class=\"feed\" id=\"feed\"><div class=\"fspacer\"></div><div id=\"rows\"></div></div>\n <div class=\"composer\">\n <div class=\"cbar\">\n <textarea id=\"msgBox\" rows=\"1\" placeholder=\"Écris à l'agent… (la surcouche classe ton message : suite de la sous-tâche ou nouvelle sous-tâche)\"></textarea>\n <button id=\"sendBtn\" type=\"button\">Envoyer</button>\n </div>\n <div class=\"routing\" id=\"routing\"></div>\n </div>\n </div>\n\n <aside class=\"panel\" id=\"panel\" aria-label=\"Détail de l'étape\">\n <div class=\"panel-inner\">\n <div class=\"phead\">\n <span class=\"ico\" id=\"pIco\"></span>\n <div class=\"tt\"><div class=\"t\" id=\"pTitle\"></div><div class=\"s\" id=\"pSub\"></div></div>\n <div class=\"pnav\"><button id=\"pPrev\" type=\"button\">↑</button><button id=\"pNext\" type=\"button\">↓</button><button id=\"pClose\" type=\"button\">✕</button></div>\n </div>\n <div class=\"pbody\" id=\"pBody\"></div>\n <div class=\"pfoot\"><span class=\"kbd\">↑</span><span class=\"kbd\">↓</span> naviguer · <span class=\"kbd\">Esc</span> fermer</div>\n </div>\n </aside>\n </div>\n <div id=\"statusbar\"></div>\n</div>\n\n<script>\nvar $=function(id){ return document.getElementById(id); };\nvar esc=function(s){ return String(s==null?\"\":s).replace(/[&<>]/g,function(c){ return {\"&\":\"&\",\"<\":\"<\",\">\":\">\"}[c]; }); };\n\n// ============================================================\n// renderMd — vanilla-JS port of markdown-lite.ts. Kept\n// function-for-function identical so the two are easy to diff (same\n// self-contained-panel constraint as buildStoryJs below): headers,\n// bold/italic, inline/fenced code, bullet/numbered lists, pipe tables and\n// links, with every raw text run HTML-escaped before any generated tag\n// wraps it.\n// ============================================================\nfunction escHtmlMd(s){ return String(s).replace(/[&<>\"]/g,function(c){ if(c==='&') return '&'; if(c==='<') return '<'; if(c==='>') return '>'; return '"'; }); }\nfunction renderInlineMd(text){\n var out=escHtmlMd(text);\n out=out.replace(/\\`([^\\`]+)\\`/g,function(_m,code){ return '<code>'+code+'</code>'; });\n out=out.replace(/\\\\[([^\\\\]]+)\\\\]\\\\((https?:\\\\/\\\\/[^\\\\s)]+)\\\\)/g,function(_m,label,url){ return '<a href=\"'+url+'\" target=\"_blank\" rel=\"noopener noreferrer\">'+label+'</a>'; });\n out=out.replace(/\\\\*\\\\*([^*]+)\\\\*\\\\*/g,'<strong>$1</strong>');\n out=out.replace(/(^|[^*])\\\\*([^*]+)\\\\*(?!\\\\*)/g,'$1<em>$2</em>');\n return out;\n}\nfunction isTableSepMd(line){ return /^\\\\s*\\\\|?\\\\s*:?-+:?\\\\s*(\\\\|\\\\s*:?-+:?\\\\s*)+\\\\|?\\\\s*$/.test(line); }\nfunction splitRowMd(line){ return line.trim().replace(/^\\\\|/,'').replace(/\\\\|$/,'').split('|').map(function(c){ return c.trim(); }); }\nfunction renderMd(md){\n var lines=String(md==null?'':md).replace(/\\\\r\\\\n?/g,'\\\\n').split('\\\\n');\n var out=[], para=[], list=null;\n function flushPara(){ if(para.length){ out.push('<p>'+para.map(renderInlineMd).join('<br>')+'</p>'); para=[]; } }\n function flushList(){ if(list){ var tag=list.ordered?'ol':'ul'; out.push('<'+tag+'>'+list.items.map(function(i){ return '<li>'+renderInlineMd(i)+'</li>'; }).join('')+'</'+tag+'>'); list=null; } }\n function flushAll(){ flushPara(); flushList(); }\n var i=0;\n while(i<lines.length){\n var line=lines[i];\n if(/^\\\\s*\\`\\`\\`/.test(line)){\n flushAll();\n var code=[]; i+=1;\n while(i<lines.length && !/^\\\\s*\\`\\`\\`/.test(lines[i])){ code.push(lines[i]); i+=1; }\n i+=1;\n out.push('<pre><code>'+escHtmlMd(code.join('\\\\n'))+'</code></pre>');\n continue;\n }\n var header=line.match(/^(#{1,6})\\\\s+(.*)$/);\n if(header){\n flushAll();\n var level=header[1].length;\n out.push('<h'+level+'>'+renderInlineMd(header[2].trim())+'</h'+level+'>');\n i+=1;\n continue;\n }\n if(/^\\\\s*\\\\|/.test(line) && i+1<lines.length && isTableSepMd(lines[i+1])){\n flushAll();\n var headCells=splitRowMd(line);\n i+=2;\n var bodyRows=[];\n while(i<lines.length && /^\\\\s*\\\\|/.test(lines[i])){ bodyRows.push(splitRowMd(lines[i])); i+=1; }\n out.push('<table><thead><tr>'+headCells.map(function(c){ return '<th>'+renderInlineMd(c)+'</th>'; }).join('')+'</tr></thead><tbody>'\n +bodyRows.map(function(r){ return '<tr>'+r.map(function(c){ return '<td>'+renderInlineMd(c)+'</td>'; }).join('')+'</tr>'; }).join('')+'</tbody></table>');\n continue;\n }\n var bullet=line.match(/^\\\\s*[-*+]\\\\s+(.*)$/);\n var numbered=line.match(/^\\\\s*\\\\d+\\\\.\\\\s+(.*)$/);\n if(bullet || numbered){\n flushPara();\n var ordered=!!numbered;\n var item=(bullet||numbered)[1];\n if(!list || list.ordered!==ordered){ flushList(); list={ordered:ordered,items:[]}; }\n list.items.push(item);\n i+=1;\n continue;\n }\n if(line.trim()===''){ flushAll(); i+=1; continue; }\n flushList();\n para.push(line);\n i+=1;\n }\n flushAll();\n return out.join('');\n}\n\n${panelBridgeScript(\"agentproto-session-story-panel\")}\n// Best-effort: some hosts forward the triggering tool call's arguments as\n// a notification so the panel can auto-open the right session. Purely\n// additive — the session picker is the reliable path when this never\n// arrives.\nvar pendingSessionId=null;\nonHostNotification(function(method, params){\n if(/tool-input|tool-call/.test(method)){\n var args=(params && (params.arguments || params.input)) || {};\n if(args && args.sessionId) pendingSessionId=args.sessionId;\n }\n});\n\n// ============================================================\n// buildStory — vanilla-JS port of session-story.ts. Kept\n// function-for-function identical so the two are easy to diff; the panel\n// resource must be fully self-contained (no bundler/dynamic import), so it\n// cannot import the TS module directly.\n// ============================================================\n\nvar SALIENT_KEYS=[\"file_path\",\"path\",\"filePath\",\"file\",\"command\",\"pattern\",\"query\",\"q\",\"url\",\"todos\",\"description\",\"prompt\"];\nfunction truncateStr(v,max){ var o=String(v).replace(/\\\\s+/g,' ').trim(); return o.length>max? o.slice(0,max-1)+'…':o; }\nfunction formatArgValue(v){\n if(typeof v==='string') return v;\n if(Array.isArray(v)) return v.length+' item'+(v.length===1?'':'s');\n if(v && typeof v==='object') return JSON.stringify(v);\n return String(v);\n}\nfunction pickSalient(args){\n for(var i=0;i<SALIENT_KEYS.length;i++){\n var k=SALIENT_KEYS[i], v=args[k];\n if(v!==undefined && v!==null && v!=='') return formatArgValue(v);\n }\n return null;\n}\nfunction formatToolCall(name,args){\n name=name||'tool';\n args=(args && typeof args==='object' && !Array.isArray(args)) ? args : {};\n var salient=pickSalient(args);\n if(salient!==null){\n if(name.toLowerCase().indexOf(salient.toLowerCase())>=0) return truncateStr(name,120);\n return truncateStr(name+' '+salient,120);\n }\n if(Object.keys(args).length===0) return name;\n return truncateStr(name+' '+JSON.stringify(args),120);\n}\nfunction extractText(v){\n if(v==null) return null;\n if(typeof v==='string') return v;\n if(Array.isArray(v)){\n var parts=v.map(extractText).filter(function(x){ return x!=null; });\n return parts.length? parts.join('\\\\n') : null;\n }\n if(typeof v==='object'){\n if(typeof v.text==='string') return v.text;\n if(typeof v.message==='string') return v.message;\n if(Array.isArray(v.content)) return extractText(v.content);\n if(typeof v.error==='string') return v.error;\n if(v.error && typeof v.error==='object' && typeof v.error.message==='string') return v.error.message;\n return null;\n }\n return null;\n}\nfunction formatToolResult(toolName,result,isError){\n var text=extractText(result);\n if(isError){\n var message=text!=null? text : (result!=null? JSON.stringify(result) : 'failed');\n var firstLine=String(message).split(/\\\\r?\\\\n/)[0] || message;\n return truncateStr(firstLine,160);\n }\n if(text==null) return null;\n var trimmed=text.trim();\n if(!trimmed) return null;\n var lines=trimmed.split(/\\\\r?\\\\n/);\n if(lines.length>1){\n var bytes=new TextEncoder().encode(trimmed).length;\n return lines.length+' lines, '+bytes+'B';\n }\n return truncateStr(lines[0],160);\n}\n\nfunction classifyKind(toolCalls){\n if(!toolCalls || toolCalls.length===0) return 'text';\n var names=toolCalls.map(function(t){ return t.name.toLowerCase(); });\n if(names.some(function(n){ return /edit|write/.test(n); })) return 'edit';\n if(names.some(function(n){ return /bash|terminal|command/.test(n); })) return 'bash';\n if(names.some(function(n){ return /read|grep|glob/.test(n); })) return 'read';\n return 'text';\n}\nvar NEW_CHAPTER_RE=/\\\\b(aussi|autre|ensuite|nouveau|nouvelle|plut[oô]t|maintenant|apr[eè]s ça|il faudrait|peux[- ]tu|on pourrait|ajoute|g[eè]re)\\\\b/iu;\nfunction classifyRoute(text){\n var newt=NEW_CHAPTER_RE.test(text);\n if(!newt) return {route:'cont'};\n var title=text.replace(/[.?!].*$/,'').slice(0,42);\n return {route:'newt', title:title};\n}\nfunction formatTsJs(ts){\n if(ts===undefined || ts===null || isNaN(ts)) return '';\n return new Date(ts).toISOString().slice(11,19);\n}\nfunction firstMeaningfulLine(text){\n if(!text) return undefined;\n var lines=text.split('\\\\n').map(function(l){ return l.trim(); }).filter(function(l){ return l.length>0; });\n return lines[0];\n}\nfunction lineCountOf(text){\n var n=(text||'').split('\\\\n').filter(function(l){ return l.trim().length>0; }).length;\n return n||1;\n}\nfunction parseArgsJson(s){ try{ return JSON.parse(s); }catch(e){ return {}; } }\n\nfunction foldToolStep(assistant,toolResults){\n var toolCalls=assistant.toolCalls||[];\n var kind=classifyKind(toolCalls);\n var count=toolCalls.length||1;\n var items=[], facts=[];\n if(assistant.text && assistant.text.trim()) items.push({text:assistant.text.trim()});\n toolCalls.forEach(function(tc,i){\n var args=parseArgsJson(tc.args);\n var h=formatToolCall(tc.name,args);\n var resultMsg=toolResults[i];\n var resultText=(resultMsg && resultMsg.text) || '';\n var isError=resultText.indexOf('[error]')===0;\n var r=isError? resultText.slice(7).trim() : resultText;\n items.push({h:h,r:r});\n var fact=formatToolResult(tc.name,r,isError);\n if(fact) facts.push(fact);\n });\n var firstLine=firstMeaningfulLine(assistant.text);\n var firstToolCall=toolCalls[0];\n var sum=firstLine!==undefined? firstLine : (firstToolCall? formatToolCall(firstToolCall.name,parseArgsJson(firstToolCall.args)) : '…');\n var raw1;\n if(toolCalls.length===0) raw1='assistant · '+lineCountOf(assistant.text)+' ligne(s)';\n else if(toolCalls.length===1) raw1=formatToolCall(firstToolCall.name,parseArgsJson(firstToolCall.args));\n else raw1=(firstToolCall? firstToolCall.name : 'tool')+' ×'+toolCalls.length;\n return {kind:kind, ts:formatTsJs(assistant.ts), sum:sum, raw1:raw1, count:count, facts:facts, items:items};\n}\nfunction foldUserStep(msg){\n var text=msg.text||'';\n return {kind:'user', ts:formatTsJs(msg.ts), sum:'« '+truncateStr(text,80)+' »', raw1:'user · '+lineCountOf(text)+' ligne(s)', count:1, facts:[], items:[{text:text}], userText:text};\n}\nfunction foldOrphanToolStep(msg){\n var text=msg.text||'';\n var isError=text.indexOf('[error]')===0;\n var r=isError? text.slice(7).trim() : text;\n var name=msg.toolName||'tool';\n var fact=formatToolResult(name,r,isError);\n return {kind:classifyKind([{name:name}]), ts:formatTsJs(msg.ts), sum: msg.toolName? (msg.toolName+' · résultat') : \"Résultat d'outil\", raw1: msg.toolName||'tool', count:1, facts: fact?[fact]:[], items:[{h:name,r:r}]};\n}\nfunction foldSystemStep(msg){\n var text=msg.text||'';\n var line=firstMeaningfulLine(text);\n return {kind:'text', ts:formatTsJs(msg.ts), sum: line!==undefined? line : text, raw1:'system', count:1, facts:[], items: text?[{text:text}]:[]};\n}\nfunction foldMessages(messages){\n var steps=[], i=0;\n while(i<messages.length){\n var msg=messages[i];\n if(msg.role==='user'){ steps.push(foldUserStep(msg)); i+=1; continue; }\n if(msg.role==='assistant'){\n var j=i+1, toolResults=[];\n while(j<messages.length && messages[j].role==='tool'){ toolResults.push(messages[j]); j+=1; }\n steps.push(foldToolStep(msg,toolResults)); i=j; continue;\n }\n if(msg.role==='tool'){ steps.push(foldOrphanToolStep(msg)); i+=1; continue; }\n steps.push(foldSystemStep(msg)); i+=1;\n }\n return steps;\n}\nfunction buildStoryJs(messages){\n var folded=foldMessages(messages||[]);\n var chapters=[], steps=[];\n var currentChapterId, sawFirstUser=false;\n function closeCurrent(){ var cur=chapters.filter(function(c){ return c.id===currentChapterId; })[0]; if(cur) cur.status='done'; }\n function openChapter(title){ var id='c'+(chapters.length+1); chapters.push({id:id,title:title,status:'cur'}); return id; }\n folded.forEach(function(step){\n var route;\n if(step.kind==='user' && step.userText!==undefined){\n if(!sawFirstUser){ sawFirstUser=true; currentChapterId=openChapter('Cadrage'); }\n else {\n var verdict=classifyRoute(step.userText);\n route=verdict.route;\n if(verdict.route==='newt'){ closeCurrent(); currentChapterId=openChapter(verdict.title||'Nouvelle sous-tâche'); }\n }\n } else if(currentChapterId===undefined){ currentChapterId=openChapter('Cadrage'); }\n var out={chap:currentChapterId, kind:step.kind, ts:step.ts, sum:step.sum, raw1:step.raw1, count:step.count, facts:step.facts, items:step.items};\n if(route) out.route=route;\n steps.push(out);\n });\n return {chapters:chapters, steps:steps};\n}\n\n// ============================================================\n// App state\n// ============================================================\nvar sessions=[];\nvar activeSessionId=null;\nvar story={chapters:[], steps:[]};\nvar open={};\nvar selected=-1;\nvar lastSeenOutputAt=null;\nvar pollTimer=null, polling=false;\nvar ICONS={text:[\"k-text\",\"A\"],edit:[\"k-edit\",\"✎\"],bash:[\"k-bash\",\"▸\"],read:[\"k-read\",\"⌕\"],user:[\"k-user\",\"T\"]};\nvar icoSpec=function(k){ return ICONS[k]||ICONS.text; };\nvar chapOf=function(id){ return story.chapters.filter(function(c){ return c.id===id; })[0]; };\nvar curChap=function(){ return story.chapters.filter(function(c){ return c.status==='cur'; })[0] || story.chapters[story.chapters.length-1]; };\n\nfunction setStatus(msg){ $('statusbar').textContent=msg; }\nfunction nowTs(){ return new Date().toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit',second:'2-digit'}); }\n\nfunction titleOf(s){\n return s.label || s.name || (s.command? s.command.split(/\\\\s+/)[0].split('/').pop() : null) || s.id.slice(0,8);\n}\n\n// ============================================================\n// Picker screen\n// ============================================================\nfunction renderPicker(){\n var el=$('pickerList');\n if(!sessions.length){ el.innerHTML='<div class=\"pk-empty\">Aucune session</div>'; return; }\n var html='';\n sessions.forEach(function(s){\n html+='<div class=\"pk-item\" data-id=\"'+esc(s.id)+'\">'\n + '<span class=\"pk-name\">'+esc(titleOf(s))+'</span>'\n + '<span class=\"badge '+esc(s.status)+'\">'+esc(s.status)+'</span>'\n + '<span class=\"pk-meta\">'+esc(s.kind||'')+'</span>'\n + '</div>';\n });\n el.innerHTML=html;\n Array.prototype.forEach.call(el.querySelectorAll('.pk-item'), function(row){\n row.onclick=function(){ openSession(row.getAttribute('data-id')); };\n });\n}\n\nfunction showPicker(){\n activeSessionId=null;\n $('pickerScreen').classList.remove('hidden');\n $('storyScreen').classList.add('hidden');\n renderPicker();\n}\n\nfunction openSession(id){\n activeSessionId=id;\n story={chapters:[], steps:[]};\n open={};\n selected=-1;\n lastSeenOutputAt=null;\n $('pickerScreen').classList.add('hidden');\n $('storyScreen').classList.remove('hidden');\n $('fullPanelLink').href='https://cli.agentproto.sh/panel?session='+encodeURIComponent(id);\n closePanel();\n loadStory().then(renderAll);\n}\n\n// ============================================================\n// Story loading\n// ============================================================\nfunction activeSession(){ return sessions.filter(function(s){ return s.id===activeSessionId; })[0]; }\n\nfunction loadStory(){\n return callTool('agent_export', {sessionId:activeSessionId, format:'json'}).then(function(data){\n var messages=(data && data.messages) || [];\n story=buildStoryJs(messages);\n // Default open state: only the last (current) chapter is expanded.\n var last=story.chapters[story.chapters.length-1];\n if(last && !(last.id in open)) open[last.id]=true;\n }).catch(function(e){\n setStatus('Erreur export : '+e.message);\n });\n}\n\nfunction canSend(){\n var s=activeSession();\n return !!s && s.kind==='agent-cli' && s.status==='running';\n}\n\nfunction renderComposer(){\n var s=activeSession();\n var box=$('msgBox'), btn=$('sendBtn');\n var enabled=canSend();\n box.disabled=!enabled;\n btn.disabled=!enabled;\n if(!s){ box.placeholder='Session introuvable.'; }\n else if(!enabled) box.placeholder='Lecture seule — session '+esc(s.status)+'.';\n else box.placeholder=\"Écris à l'agent… (la surcouche classe ton message : suite de la sous-tâche ou nouvelle sous-tâche)\";\n}\n\nfunction renderHero(){\n var s=activeSession();\n $('heroTitle').textContent=s? titleOf(s) : (activeSessionId||'');\n var firstUser=story.steps.filter(function(st){ return st.kind==='user'; })[0];\n var mission=firstUser? firstUser.userText || (firstUser.items[0] && firstUser.items[0].text) : null;\n $('heroSub').textContent=mission? truncateStr(mission,200) : 'Aucun message pour le moment.';\n var p=$('pulse');\n p.classList.toggle('off', !(s && (s.status==='running' || s.status==='starting')));\n renderComposer();\n}\n\nfunction renderAll(){\n renderHero();\n renderPlan();\n renderRows('bottom');\n}\n\n// ============================================================\n// big picture strip\n// ============================================================\nfunction renderPlan(){\n var done=story.chapters.filter(function(c){ return c.status==='done'; }).length;\n $('plan').innerHTML=story.chapters.map(function(c,i){\n return '<span class=\"pt '+c.status+'\" data-c=\"'+esc(c.id)+'\"><span class=\"st\">'+(c.status==='done'?'✓':'●')+'</span>'+(i+1)+'. '+esc(c.title)+'</span>';\n }).join('') + '<span class=\"pt\" style=\"cursor:default\"><b>'+done+'/'+story.chapters.length+'</b> faites</span>';\n Array.prototype.forEach.call($('plan').querySelectorAll('.pt[data-c]'), function(el){\n el.onclick=function(){ open[el.getAttribute('data-c')]=true; renderRows(); jumpToChap(el.getAttribute('data-c')); };\n });\n}\nfunction jumpToChap(cid){\n var el=document.querySelector('.chap[data-c=\"'+cid+'\"]');\n if(el) el.scrollIntoView({block:'start',behavior:'smooth'});\n}\n\n// ============================================================\n// feed segmenté par chapitres\n// ============================================================\nfunction rowHtml(s,i,isNew){\n var spec=icoSpec(s.kind), cls=spec[0], ch=spec[1];\n var route=s.route? '<span class=\"route '+(s.route==='newt'?'newt':'cont')+'\">'+(s.route==='newt'?'★ nouvelle sous-tâche':'↳ suite')+'</span>' : '';\n return '<div class=\"row '+(isNew?'new':'')+'\" aria-selected=\"'+(i===selected)+'\" data-i=\"'+i+'\">'\n + '<span class=\"ico '+cls+'\">'+ch+'</span>'\n + '<span class=\"mid\"><span class=\"sum\">'+esc(s.sum)+'</span><span class=\"raw1\">'+esc(s.raw1||'')+'</span>'+route+'</span>'\n + (s.count>1? '<span class=\"cnt\">×'+s.count+'</span>':'') + '<span class=\"ts\">'+esc(s.ts||'')+'</span>'\n + '</div>';\n}\nfunction renderRows(keepScroll,newIdx){\n var feed=$('feed');\n var prevH=feed.scrollHeight, prevTop=feed.scrollTop;\n var html='';\n story.chapters.forEach(function(c,ci){\n var chapSteps=[];\n story.steps.forEach(function(s,i){ if(s.chap===c.id) chapSteps.push({s:s,i:i}); });\n if(!chapSteps.length) return;\n var isOpen=!!open[c.id];\n html+='<div class=\"chap '+c.status+' '+(isOpen?'open':'')+'\" data-c=\"'+esc(c.id)+'\">'\n + '<span class=\"cst\">'+(c.status==='done'?'✓':'●')+'</span><span class=\"cnum\">'+(ci+1)+'.</span>'\n + '<span class=\"csum\">'+esc(c.title)+'</span>'\n + '<span class=\"cmeta\">'+chapSteps.length+' étape'+(chapSteps.length>1?'s':'')+'</span><span class=\"cchev\">▸</span>'\n + '</div>';\n if(isOpen) html += chapSteps.map(function(x){ return rowHtml(x.s,x.i,x.i===newIdx); }).join('');\n });\n $('rows').innerHTML=html;\n Array.prototype.forEach.call(document.querySelectorAll('.row'), function(el){\n el.onclick=function(){ selectStep(Number(el.getAttribute('data-i'))); };\n });\n Array.prototype.forEach.call(document.querySelectorAll('.chap'), function(el){\n el.onclick=function(){ var c=el.getAttribute('data-c'); open[c]=!open[c]; renderRows(); };\n });\n if(keepScroll==='bottom') feed.scrollTop=feed.scrollHeight;\n else if(keepScroll==='preserve') feed.scrollTop=feed.scrollHeight-prevH+prevTop;\n}\n\n// ============================================================\n// panneau ancré\n// ============================================================\nfunction selectStep(i){\n selected=i;\n var s=story.steps[i]; if(!s) return;\n open[s.chap]=true;\n $('panel').classList.add('open');\n var spec=icoSpec(s.kind), cls=spec[0], ch=spec[1];\n var ico=$('pIco'); ico.className='ico '+cls; ico.textContent=ch;\n $('pTitle').textContent=s.sum;\n var c=chapOf(s.chap);\n $('pSub').textContent=(s.ts? s.ts+' · ':'')+(c? ('sous-tâche : '+c.title) : '');\n var facts=(s.facts||[]).map(function(f){\n return '<span class=\"fact '+(/✓|exit 0|passed|0 match/.test(f)?'ok':'')+'\">'+esc(f)+'</span>';\n }).join('');\n var tech=(s.items||[]).map(function(it,k){\n return it.text!==undefined\n ? '<div class=\"d-text\">'+renderMd(it.text)+'</div>'\n : '<div class=\"titem\"><div class=\"th\">'+esc(it.h)+'<button class=\"copy\" data-k=\"'+k+'\" type=\"button\">⧉</button></div><pre>'+esc(it.r)+'</pre></div>';\n }).join('');\n $('pBody').innerHTML=''\n + '<div class=\"plain\"><div>'+esc(s.sum)+'.</div><div class=\"why\">'+esc(s.why||'')+'</div></div>'\n + (facts? '<div class=\"facts\">'+facts+'</div>':'')\n + '<details class=\"techbox\" '+(document.body.classList.contains('tech')?'open':'')+'>'\n + '<summary>Détail technique · '+(s.items||[]).length+'</summary><div class=\"techlist\">'+tech+'</div>'\n + '</details>';\n Array.prototype.forEach.call($('pBody').querySelectorAll('.copy'), function(btn){\n btn.onclick=function(e){\n e.stopPropagation();\n var it=(s.items||[])[Number(btn.getAttribute('data-k'))];\n var payload=(it.h||'')+'\\\\n'+(it.r||it.text||'');\n if(navigator.clipboard) navigator.clipboard.writeText(payload).catch(function(){});\n btn.textContent='✓'; setTimeout(function(){ btn.textContent='⧉'; },900);\n };\n });\n $('pPrev').disabled=i<=0; $('pNext').disabled=i>=story.steps.length-1;\n renderRows();\n var el=document.querySelector('.row[data-i=\"'+i+'\"]');\n if(el) el.scrollIntoView({block:'nearest',behavior:'smooth'});\n}\nfunction closePanel(){ selected=-1; var p=$('panel'); if(p) p.classList.remove('open'); renderRows(); }\n$('pClose').addEventListener('click',closePanel);\n$('pPrev').addEventListener('click',function(){ if(selected>0) selectStep(selected-1); });\n$('pNext').addEventListener('click',function(){ if(selected<story.steps.length-1) selectStep(selected+1); });\ndocument.addEventListener('keydown',function(e){\n if(e.key==='Escape'){ closePanel(); return; }\n if($('storyScreen').classList.contains('hidden')) return;\n if(selected<0 || e.target.tagName==='TEXTAREA') return;\n if(e.key==='ArrowUp'){ e.preventDefault(); if(selected>0) selectStep(selected-1); }\n if(e.key==='ArrowDown'){ e.preventDefault(); if(selected<story.steps.length-1) selectStep(selected+1); }\n});\n\n// ============================================================\n// Simple / Tech modes\n// ============================================================\nfunction setMode(tech){\n document.body.classList.toggle('tech',tech);\n $('modeTech').classList.toggle('on',tech);\n $('modeSimple').classList.toggle('on',!tech);\n if(selected>=0) selectStep(selected);\n}\n$('modeSimple').addEventListener('click',function(){ setMode(false); });\n$('modeTech').addEventListener('click',function(){ setMode(true); });\n$('switchBtn').addEventListener('click', function(){ if(pollTimer) clearTimeout(pollTimer); showPicker(); doPoll(); });\n\n// ============================================================\n// composer — local chapter-routing classification + agent_prompt\n// ============================================================\n$('sendBtn').addEventListener('click', sendMsg);\n$('msgBox').addEventListener('keydown', function(e){\n if(e.key==='Enter' && !e.shiftKey){ e.preventDefault(); sendMsg(); }\n});\nfunction sendMsg(){\n if(!canSend()) return;\n var box=$('msgBox'), text=box.value.trim();\n if(!text) return;\n box.value='';\n var cur=curChap();\n var r=cur? classifyRoute(text) : {route:'cont'};\n var chapId=cur? cur.id : null;\n if(r.route==='newt' && cur){\n cur.status='done';\n var id='c'+(story.chapters.length+1);\n story.chapters.push({id:id, title:r.title||'Nouvelle sous-tâche', status:'cur'});\n chapId=id; open[id]=true;\n $('routing').innerHTML='✦ classé : <span class=\"r-newt\">★ nouvelle sous-tâche « '+esc(r.title||'')+' »</span>';\n } else {\n $('routing').innerHTML='✦ classé : <span class=\"r-cont\">↳ suite de « '+esc(cur? cur.title : '')+' »</span>';\n }\n setTimeout(function(){ $('routing').textContent=''; },5000);\n story.steps.push({\n chap:chapId, kind:'user', ts:nowTs(),\n sum:'« '+text.slice(0,80)+(text.length>80?'…':'')+' »',\n raw1:'user · '+text.split('\\\\n').length+' ligne(s)',\n route:r.route, facts:[], items:[{text:text}], userText:text,\n });\n renderPlan(); renderRows('bottom', story.steps.length-1);\n callTool('agent_prompt', {sessionId:activeSessionId, prompt:text}).catch(function(e){\n setStatus('Envoi échoué : '+e.message);\n });\n}\n\n// ============================================================\n// Poll — session_list every ~5s; re-fetch agent_export only on turn\n// boundaries (lastOutputAt changed for the active session).\n// ============================================================\nvar POLL_MS=5000;\nfunction loadSessions(){\n return callTool('session_list', {kind:'all'}).then(function(data){\n sessions=data.sessions||[];\n if($('pickerScreen') && !$('pickerScreen').classList.contains('hidden')) renderPicker();\n }).catch(function(e){ setStatus('Erreur : '+e.message); });\n}\nfunction doPoll(){\n if(polling) return;\n polling=true;\n loadSessions().then(function(){\n if(!activeSessionId){ polling=false; pollTimer=setTimeout(doPoll,POLL_MS); return; }\n var s=activeSession();\n if(!s){ polling=false; pollTimer=setTimeout(doPoll,POLL_MS); return; }\n renderHero();\n var changed=s.lastOutputAt && s.lastOutputAt!==lastSeenOutputAt;\n if(changed){\n lastSeenOutputAt=s.lastOutputAt;\n loadStory().then(function(){ renderPlan(); renderRows('bottom'); polling=false; pollTimer=setTimeout(doPoll,POLL_MS); });\n } else {\n polling=false; pollTimer=setTimeout(doPoll,POLL_MS);\n }\n }).catch(function(){ polling=false; pollTimer=setTimeout(doPoll,POLL_MS); });\n}\n\n// ============================================================\n// Boot\n// ============================================================\ninitBridge().then(loadSessions).then(function(){\n setTimeout(function(){\n var target=pendingSessionId && sessions.some(function(s){ return s.id===pendingSessionId; })\n ? pendingSessionId\n : null;\n if(!target){\n var agentSessions=sessions.filter(function(s){ return s.kind==='agent-cli'; });\n if(agentSessions.length===1) target=agentSessions[0].id;\n }\n if(target) openSession(target); else showPicker();\n pollTimer=setTimeout(doPoll,POLL_MS);\n }, 50);\n}).catch(function(e){\n setStatus('Bridge : '+e.message);\n $('pickerList').innerHTML='<div class=\"pk-empty\">Échec connexion bridge : '+esc(e.message)+'</div>';\n});\n</script>\n</body>\n</html>`\n"]}
|
package/dist/session-story.mjs
CHANGED
|
@@ -13,6 +13,10 @@ function panelBridgeScript(appName) {
|
|
|
13
13
|
// JSON-RPC 2.0 over window.parent.postMessage \xB7 spec 2026-01-26
|
|
14
14
|
var _nextId = 1, _pending = {}, _notifyHandlers = [];
|
|
15
15
|
var _hostContext = null, _hostContextHandlers = [];
|
|
16
|
+
var _standaloneApp = null;
|
|
17
|
+
function _isStandalone(){
|
|
18
|
+
return window.parent === window && !!window.McpApp && typeof window.McpApp.connect === 'function';
|
|
19
|
+
}
|
|
16
20
|
function post(msg){ window.parent.postMessage(msg, '*'); }
|
|
17
21
|
function getHostContext(){ return _hostContext; }
|
|
18
22
|
function onHostContext(cb){
|
|
@@ -59,6 +63,16 @@ window.addEventListener('message', function(evt){
|
|
|
59
63
|
}
|
|
60
64
|
});
|
|
61
65
|
function initBridge(){
|
|
66
|
+
if (_isStandalone()){
|
|
67
|
+
return window.McpApp.connect().then(function(conn){
|
|
68
|
+
_standaloneApp = conn;
|
|
69
|
+
// No host to advertise a hostContext \u2014 default to inline with no
|
|
70
|
+
// other modes available, which keeps the #dm/#pin toggle buttons
|
|
71
|
+
// hidden (they only show for modes hostContext.availableDisplayModes
|
|
72
|
+
// lists) instead of rendering two buttons with nothing to switch to.
|
|
73
|
+
_setHostContext({displayMode: 'inline', availableDisplayModes: []});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
62
76
|
return rpcRequest('ui/initialize', {
|
|
63
77
|
appInfo: {name: ${JSON.stringify(appName)}, version: '0.1.0'},
|
|
64
78
|
appCapabilities: {availableDisplayModes: ['inline', 'fullscreen', 'pip']},
|
|
@@ -74,7 +88,10 @@ function requestDisplayMode(mode){
|
|
|
74
88
|
return rpcRequest('ui/request-display-mode', {mode: mode});
|
|
75
89
|
}
|
|
76
90
|
function callTool(name, args){
|
|
77
|
-
|
|
91
|
+
var raw = _standaloneApp
|
|
92
|
+
? _standaloneApp.callTool(name, args || {})
|
|
93
|
+
: rpcRequest('tools/call', {name: name, arguments: args || {}});
|
|
94
|
+
return raw.then(function(result){
|
|
78
95
|
if (result.isError){
|
|
79
96
|
var e = (result.content && result.content[0] && result.content[0].text) || 'tool error';
|
|
80
97
|
throw new Error(e);
|