@botiverse/porthole 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +83 -0
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +51 -0
  4. package/dist/conformance/entry.d.ts +19 -7
  5. package/dist/conformance/entry.js +39 -12
  6. package/dist/conformance/harness.js +8 -8
  7. package/dist/conformance/host-kit.d.ts +48 -13
  8. package/dist/conformance/host-kit.js +140 -28
  9. package/dist/conformance/index.d.ts +1 -1
  10. package/dist/conformance/index.js +1 -1
  11. package/dist/conformance/limits.js +15 -2
  12. package/dist/conformance/page.d.ts +6 -0
  13. package/dist/conformance/page.js +8 -0
  14. package/dist/conformance/served.d.ts +4 -4
  15. package/dist/conformance/served.js +26 -16
  16. package/dist/host/types.d.ts +6 -3
  17. package/dist/isolation/served.js +13 -2
  18. package/dist/node/index.d.ts +11 -3
  19. package/dist/node/index.js +70 -10
  20. package/dist/react/frame.d.ts +5 -2
  21. package/dist/server/host.d.ts +42 -8
  22. package/dist/server/host.js +35 -5
  23. package/dist/server/index.d.ts +4 -1
  24. package/dist/server/index.js +2 -0
  25. package/dist/server/pages.js +15 -1
  26. package/dist/server/proxy.js +2 -0
  27. package/dist/server/server.js +9 -2
  28. package/dist/server/types.d.ts +15 -6
  29. package/docs/ARCHITECTURE.md +277 -0
  30. package/docs/DECISIONS.md +1811 -0
  31. package/docs/DESIGN.md +1074 -0
  32. package/docs/OBJECTIVES.md +116 -0
  33. package/docs/PRINCIPLES.md +155 -0
  34. package/examples/app.mjs +234 -0
  35. package/examples/conformance/playwright.config.mjs +28 -0
  36. package/examples/conformance/porthole.spec.mjs +36 -0
  37. package/examples/node/server.mjs +75 -0
  38. package/examples/workers/migrations/0001_porthole_tickets.sql +2 -0
  39. package/examples/workers/worker.mjs +33 -0
  40. package/examples/workers/wrangler.jsonc +19 -0
  41. package/package.json +9 -3
  42. package/src/cli.ts +54 -0
  43. package/src/conformance/entry.ts +70 -19
  44. package/src/conformance/host-kit.ts +194 -45
  45. package/src/conformance/index.ts +4 -0
  46. package/src/conformance/limits.ts +21 -4
  47. package/src/conformance/page.ts +8 -0
  48. package/src/conformance/served.ts +34 -21
  49. package/src/host/types.ts +6 -3
  50. package/src/isolation/served.ts +12 -2
  51. package/src/node/index.ts +73 -10
  52. package/src/react/frame.tsx +5 -2
  53. package/src/server/host.ts +84 -14
  54. package/src/server/index.ts +6 -0
  55. package/src/server/pages.ts +15 -1
  56. package/src/server/proxy.ts +2 -0
  57. package/src/server/server.ts +11 -2
  58. package/src/server/types.ts +18 -7
@@ -1,4 +1,4 @@
1
- "use strict";(()=>{var O={start:"porthole/annotate.start",stop:"porthole/annotate.stop",show:"porthole/annotate.show",focus:"porthole/annotate.focus",clear:"porthole/annotate.clear",selected:"porthole/annotate.selected",unselected:"porthole/annotate.unselected",cancelled:"porthole/annotate.cancelled",anchored:"porthole/annotate.anchored"},N={label:120,cssSelector:1e3,exact:4e3,context:64,marks:500,id:128,position:5e7,coordinate:1e7};var te=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),J=(e,t,n=0)=>typeof e=="string"&&e.length>=n&&e.length<=t,Ue=(e,t)=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=t;function Kt(e){if(!te(e))return null;switch(e.type){case"CssSelector":return J(e.value,N.cssSelector,1)?{type:"CssSelector",value:e.value}:null;case"TextQuoteSelector":{let{exact:t,prefix:n,suffix:o}=e;return!J(t,N.exact,1)||n!==void 0&&!J(n,N.context)||o!==void 0&&!J(o,N.context)?null:{type:"TextQuoteSelector",exact:t,...n===void 0||n===""?{}:{prefix:n},...o===void 0||o===""?{}:{suffix:o}}}case"TextPositionSelector":return Ue(e.start,N.position)&&Ue(e.end,N.position)&&e.start<=e.end?{type:"TextPositionSelector",start:e.start,end:e.end}:null;default:return null}}function Ve(e){if(!te(e)||e.kind!=="element"&&e.kind!=="text"||!Array.isArray(e.selectors)||e.selectors.length===0||e.selectors.length>3||!J(e.label,N.label))return null;let t=[];for(let r of e.selectors){let a=Kt(r);if(a===null||t.some(i=>i.type===a.type))return null;t.push(a)}let n=t.some(r=>r.type==="TextQuoteSelector"),o=t.some(r=>r.type==="CssSelector");return(e.kind==="text"||!o)&&!n?null:{kind:e.kind,selectors:t,label:e.label}}var le=e=>typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=N.coordinate;function Ge(e){if(!te(e))return null;let{x:t,y:n,width:o,height:r}=e;return!le(t)||!le(n)||!le(o)||!le(r)||o<0||r<0?null:{x:t,y:n,width:o,height:r}}var Je=e=>J(e,N.id,1);function Xt(e){if(!Array.isArray(e)||e.length>N.marks)return null;let t=[];for(let n of e){if(!te(n)||!Je(n.id))return null;if(n.state==="orphaned"){t.push({id:n.id,state:"orphaned"});continue}if(n.state!=="attached")return null;let o=n.rect===void 0?void 0:Ge(n.rect);if(o===null)return null;t.push({id:n.id,state:"attached",...o===void 0?{}:{rect:o}})}return t}function de(e){if(!te(e))return null;switch(e.type){case"selected":{let t=Ve(e.anchor),n=Ge(e.rect);return t===null||n===null?null:{type:"selected",anchor:t,rect:n}}case"unselected":return{type:"unselected"};case"cancelled":return{type:"cancelled"};case"anchored":{let t=Xt(e.results);return t===null?null:{type:"anchored",results:t}}default:return null}}function Ke(e){let t=e?.elements??!0,n=e?.text??!0;if(typeof t!="boolean"||typeof n!="boolean"||!t&&!n)throw new TypeError("annotations.start: elements, text, or both");return{elements:t,text:n}}function Xe(e){if(!Array.isArray(e)||e.length>N.marks)throw new TypeError(`annotations.show: at most ${N.marks} marks`);let t=new Set;return e.map((n,o)=>{let r=Ve(n?.anchor);if(!Je(n?.id)||t.has(n.id)||r===null)throw new TypeError(`annotations.show: mark ${o} needs a unique id (1 to ${N.id} characters) and a valid anchor`);return t.add(n.id),{id:n.id,anchor:r}})}var $e=["sendPrompt","openLink","downloadFile","callTool","readData","setModelContext","reportError","resize","copyText","annotate"],ne=e=>({rateLimit:{perMinute:e}});var ce={sendPrompt:{defaultGates:["user-activation","confirm"],served:"handler",global:"sendPrompt",request:{method:"ui/message",sdk:"app.sendMessage"}},openLink:{defaultGates:["user-activation","confirm"],served:"handler",global:"openLink",request:{method:"ui/open-link",sdk:"app.openLink"}},downloadFile:{defaultGates:["user-activation","confirm"],served:"handler",request:{method:"ui/download-file",sdk:"app.downloadFile"}},callTool:{defaultGates:["confirm"],served:"handler",request:{method:"tools/call",sdk:"app.callServerTool"}},readData:{defaultGates:[ne(120)],served:"handler",request:{method:"resources/read",sdk:"app.readServerResource"}},setModelContext:{defaultGates:[ne(30)],served:"handler",request:{method:"ui/update-model-context",sdk:"app.updateModelContext"}},reportError:{defaultGates:[ne(10)],served:"event"},resize:{defaultGates:[],served:"event"},copyText:{defaultGates:["user-activation",ne(30)],served:"handler",global:"copyText",request:{method:"porthole/copy-text"}},annotate:{defaultGates:[ne(120)],served:"event"}};function B(e){return ce[e]}function Ye(e){return typeof e=="string"&&$e.includes(e)}function ue(e,t){return(e.egress.anyHttps??[]).some(n=>n===t)}function D(e){return Object.keys(ce).filter(t=>e.capabilities[t]!==void 0)}function K(e,t){return e.capabilities[t]?.gates??ce[t].defaultGates}var Qe=e=>[...new Set(e)];function F(e,t){let n=D(e).flatMap(o=>{let r=e.capabilities[o];return(t==="connect"?r?.connect:r?.resource)??[]});return Qe([...e.egress[t]??[],...n])}var Yt=e=>e.length===0?["'none'"]:[...e];function Ze(e){if(e.mode==="url")return[];let t=o=>F(e,o),n=o=>ue(e,o)?["https:"]:[];return[["default-src","'none'"],["script-src","'unsafe-inline'","'unsafe-eval'","blob:",...t("script")],["style-src","'unsafe-inline'",...t("style")],["font-src","data:",...n("font"),...t("font")],["img-src","data:","blob:",...n("img"),...t("img")],["media-src","data:","blob:",...n("media"),...t("media")],["connect-src",...Yt(t("connect"))],["worker-src","blob:"],["child-src","blob:"],["frame-src","'none'"],["object-src","'none'"],["base-uri","'none'"],["form-action","'none'"],["webrtc","'block'"]]}function et(e){return e.map(t=>t.join(" ")).join("; ")}function pe(e){switch(e.isolation){case"opaque":return["allow-scripts"];case"domain":return["allow-scripts","allow-same-origin"];case"external":return["allow-scripts","allow-same-origin","allow-forms",...e.sandbox??[]]}}function tt(e){return e.mode==="url"?(e.permissions??[]).join("; "):"clipboard-read 'none'; clipboard-write 'none'"}function nt(e){return Qe([...e.contentOrigins,...e.embedder.frameSrc??[]])}var H=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ot=4096;function Qt(e){if(typeof e!="string"||e.length===0||e.length>ot)return null;let t;try{t=new URL(e.trim())}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"||t.username!==""||t.password!==""?null:t.href}var Zt={sendPrompt:(e,t)=>{let n=H(e)?e.text:void 0;return typeof n=="string"&&n.trim()!==""&&n.length<=t.limits.maxPromptChars?{text:n}:null},openLink:e=>{let t=Qt(H(e)?e.url:void 0);return t===null?null:{url:t}},downloadFile:e=>{let t=H(e)?e.contents:void 0;return Array.isArray(t)&&t.length>0&&t.length<=100?{contents:t}:null},callTool:e=>{if(!H(e)||typeof e.name!="string"||e.name===""||e.name.length>256)return null;let t=e.arguments??{};return H(t)?{name:e.name,arguments:t}:null},readData:e=>{let t=H(e)?e.uri:void 0;return typeof t=="string"&&t!==""&&t.length<=ot?{uri:t}:null},setModelContext:e=>{if(!H(e))return null;let{content:t,structuredContent:n}=e;return t!==void 0&&!Array.isArray(t)||n!==void 0&&!H(n)?null:{...t===void 0?{}:{content:t},...n===void 0?{}:{structuredContent:n}}},reportError:e=>{let t=H(e)?e.message:void 0;return typeof t=="string"&&t!==""?{message:t.slice(0,2e3)}:null},copyText:e=>{let t=H(e)?e.text:void 0;return typeof t=="string"&&t!==""&&t.length<=2e4?{text:t}:null},annotate:e=>de(e),resize:e=>{if(!H(e)||typeof e.height!="number"||!Number.isFinite(e.height)||e.height<0)return null;let t=e.width;return typeof t=="number"&&Number.isFinite(t)&&t>=0?{height:e.height,width:t}:{height:e.height}}};function rt(e){let{config:t,display:n,handlers:o,onEvent:r}=e,a=e.now??(()=>Date.now()),i=new Map,s=0,c=!1,l=(m,v,d)=>(r({type:"refused",capability:m,refusal:v}),{ok:!1,refusal:v,...d===void 0?{}:{message:d}}),f=(m,v)=>{let d=a(),g=(i.get(m)??[]).filter(u=>d-u<6e4);return g.length>=v?(i.set(m,g),!1):(g.push(d),i.set(m,g),!0)};return{declared:m=>t.capabilities[m]!==void 0,async call(m,v,d){if(t.capabilities[m]===void 0)return l(m,"not-declared");let g=Zt[m](v,t);if(g===null)return l(m,"invalid");let u=K(t,m),p=u.includes("confirm");if(p&&c)return l(m,"muted");for(let A of u)if(typeof A=="object"&&!f(m,A.rateLimit.perMinute))return l(m,"rate-limited");if(u.includes("user-activation")&&(d?.userActivated??e.userActivation?.())===!1)return l(m,"no-user-activation");let y=null,C=()=>y??=k(m,g);if(p){if(e.confirm===void 0)return l(m,"no-confirm");let A=!1;try{A=await e.confirm({capability:m,args:g,display:n},()=>{C()})}catch{A=y===null?!1:"accepted"}if(y===null&&A!==!0&&A!=="accepted")return A==="redirected"?l(m,"redirected"):(s+=1,s>=t.limits.declinesBeforeMute&&!c&&(c=!0,r({type:"muted"})),l(m,"declined"));s=0}return C()}};async function k(m,v){{if(B(m).served==="event")return r(m==="resize"?{type:"resize",...v}:m==="annotate"?{type:"annotation",report:v}:{type:"error",message:v.message}),{ok:!0,value:void 0};let d=o[m];if(d===void 0)return l(m,"not-declared");try{return{ok:!0,value:await d(v,{displayId:n.id,title:n.title,capability:m})}}catch(g){return l(m,"failed",g instanceof Error?g.message:String(g))}}}}var Le=["img","media","font"],Ne=["allow-popups","allow-popups-to-escape-sandbox","allow-modals","allow-downloads"],Oe=["clipboard-write","fullscreen"];var Ie=class extends Error{path;constructor(t,n){super(`${t}: ${n}`),this.name="ConfigError",this.path=t}},De=["widget","chart","interactive"],en=/^(localhost|127\.0\.0\.1|\[::1\])$|\.localhost$/u,tn=new Set([...["co","org","ac","gov","me","net","ltd","plc","sch","nhs","police"].map(e=>`${e}.uk`),...["com","net","org","edu","gov","asn","id"].map(e=>`${e}.au`),...["co","org","net","ac","govt","geek","school"].map(e=>`${e}.nz`),...["co","ne","or","ac","go","ad","ed","gr","lg"].map(e=>`${e}.jp`),...["co","or","ne","ac","go","re"].map(e=>`${e}.kr`),...["com","net","org","gov","edu"].flatMap(e=>["br","cn","hk","tw","sg","my","mx","ar","tr","ua","pl","ph","pk","ng","eg","sa","vn","co"].map(t=>`${e}.${t}`)),...["co","net","org","gen","firm","ind","ac","edu","gov","res"].map(e=>`${e}.in`),...["co","org","ac","gov","net","web"].map(e=>`${e}.za`),...["co","org","ac","gov","net","muni"].map(e=>`${e}.il`),"co.id","or.id","ac.id","co.th","or.th","ac.th","co.ke","co.tz","co.ug","com.de","co.at","or.at","ac.at","co.it","com.es","nom.es","com.fr","asso.fr","eu.org","us.com","uk.com","eu.com","uk.net","gb.net","jpn.com","kr.com","github.io","githubusercontent.com","gitlab.io","bitbucket.io","pages.dev","workers.dev","r2.dev","vercel.app","now.sh","netlify.app","netlify.com","herokuapp.com","herokussl.com","appspot.com","web.app","firebaseapp.com","cloudfunctions.net","run.app","googleusercontent.com","blogspot.com","azurewebsites.net","azurestaticapps.net","azureedge.net","blob.core.windows.net","cloudapp.net","trafficmanager.net","cloudfront.net","amazonaws.com","s3.amazonaws.com","elasticbeanstalk.com","awsapprunner.com","amplifyapp.com","fly.dev","onrender.com","railway.app","up.railway.app","glitch.me","repl.co","replit.app","replit.dev","surge.sh","deno.dev","ngrok.io","ngrok-free.app","ngrok.app","loca.lt","trycloudflare.com","codesandbox.io","csb.app","stackblitz.io","webcontainer.io","neocities.org","wordpress.com","tumblr.com","wixsite.com","squarespace.com","myshopify.com","carrd.co","notion.site","framer.app","webflow.io","readthedocs.io","gitbook.io","sourceforge.net","digitaloceanspaces.com","ondigitalocean.app","b-cdn.net","jsdelivr.net"]);function nn(e){return e==="localhost"?null:!e.includes(".")||tn.has(e)?`is a wildcard over a public suffix (*.${e}): anyone can serve a site under it; name a domain of your own (https://*.cdn.example.com)`:null}var on=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/u;function rn(e){let t="is not an origin (scheme://host[:port], lowercase, no path)";if(typeof e!="string"||e.length>269)return`${JSON.stringify(e)} ${t}`;let n=/^(https|http|wss|ws):\/\/([^/:]+|\[::1\])(:(\d{1,5}))?$/u.exec(e);if(n===null)return`${JSON.stringify(e)} ${t}`;let[,o,r="",,a]=n;if(a!==void 0&&(Number(a)<1||Number(a)>65535))return`${JSON.stringify(e)} has no valid port`;if(r!=="[::1]"&&!on.test(r))return`${JSON.stringify(e)} ${t}`;if(r.startsWith("*.")){let i=nn(r.slice(2));if(i!==null)return`${JSON.stringify(e)} ${i}`}return(o==="http"||o==="ws")&&!en.test(r.replace(/^\*\./u,"x."))?`${JSON.stringify(e)} uses ${o} off loopback: ${o} is allowed only for localhost, *.localhost, 127.0.0.1 and [::1] (loopback development); use ${o==="http"?"https":"wss"}`:null}var x=(e,t)=>{throw new Ie(e,t)},re=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function I(e,t){return re(e)?e:x(t,"must be an object")}function _(e,t,n){for(let o of Object.keys(e))t.includes(o)||x(`${n}.${o}`,"is not a known field")}function oe(e,t){if(e!==void 0){if(!Array.isArray(e)){x(t,"must be an array of origins");return}e.forEach((n,o)=>{let r=rn(n);r!==null&&x(`${t}[${o}]`,r)})}}function me(e,t,n=Number.MAX_SAFE_INTEGER){(typeof e!="number"||!Number.isInteger(e)||e<1||e>n)&&x(t,`must be an integer from 1 to ${n}`)}function an(e,t){if(e==="user-activation"||e==="confirm")return;let n=re(e)&&re(e.rateLimit)?e.rateLimit:null;if(n===null||Object.keys(e).length!==1){x(t,'must be "user-activation", "confirm" or { rateLimit: { perMinute } }');return}_(n,["perMinute"],`${t}.rateLimit`),me(n.perMinute,`${t}.rateLimit.perMinute`,1e4)}var at=["inline","artifact","mcp-app","url"],st=["opaque","domain","external"];function it(e){let t=I(e,"config");_(t,["mode","isolation","capabilities","egress","theme","limits","layout","guide","contentOrigins","embedder","sandbox","permissions","storage","errors"],"config"),at.includes(t.mode)||x("config.mode",`must be one of ${at.join(", ")}`),st.includes(t.isolation)||x("config.isolation",`must be one of ${st.join(", ")}`),t.mode==="url"!=(t.isolation==="external")&&x("config.isolation",'url mode, and only url mode, is "external"');let n=I(t.capabilities,"config.capabilities");for(let[d,g]of Object.entries(n)){let u=`config.capabilities.${d}`;Ye(d)||x(u,`is not a capability (${$e.join(", ")})`);let p=I(g,u);_(p,["gates","connect","resource","guide"],u),p.gates!==void 0&&(Array.isArray(p.gates)||x(`${u}.gates`,"must be an array"),p.gates.forEach((y,C)=>an(y,`${u}.gates[${C}]`))),oe(p.connect,`${u}.connect`),oe(p.resource,`${u}.resource`),p.guide!==void 0&&typeof p.guide!="string"&&x(`${u}.guide`,"must be a string")}t.mode==="url"&&Object.keys(n).length>0&&x("config.capabilities","url mode has no shell, so it can declare no capabilities");let o=I(t.egress,"config.egress"),r=["connect","script","style","img","font","media"];_(o,[...r,"anyHttps"],"config.egress");for(let d of r)oe(o[d],`config.egress.${d}`);o.anyHttps!==void 0&&(Array.isArray(o.anyHttps)||x("config.egress.anyHttps",`must be a list of ${Le.join(", ")}`),o.anyHttps.forEach((d,g)=>{Le.includes(d)||x(`config.egress.anyHttps[${g}]`,`${JSON.stringify(d)}: only images, media and fonts may load from any https site (P059), never scripts, styles or data`)}),t.mode==="url"&&x("config.egress.anyHttps","url mode has no egress control"));let a=I(t.theme,"config.theme");_(a,["variables","event","documents"],"config.theme"),a.documents!==void 0&&a.documents!=="declared"&&a.documents!=="always"&&a.documents!=="never"&&x("config.theme.documents",'must be "declared", "always" or "never"'),a.documents==="never"&&t.mode!=="artifact"&&x("config.theme.documents",'"never" is for whole pages: a fragment takes the theme it is drawn in');let i=I(a.variables,"config.theme.variables");for(let[d,g]of Object.entries(i)){let u=`config.theme.variables[${JSON.stringify(d)}]`;/^--[a-z0-9]+(-[a-z0-9]+)*$/u.test(d)||x(u,"must be a CSS custom property name (--lowercase-words)");let p=re(g)?[g.light,g.dark]:[g];re(g)&&_(g,["light","dark"],u);for(let y of p)(typeof y!="string"||y.length===0||y.length>500||/[;{}<>]/u.test(y))&&x(u,"must be a CSS value (1\u2013500 characters, no ; { } < >), or { light, dark } of them")}(typeof a.event!="string"||!/^[a-z][a-z0-9]*([:.-][a-z0-9]+)*$/u.test(a.event))&&x("config.theme.event",'must be an event name such as "porthole:theme"');let s=I(t.limits,"config.limits"),c=["maxHeightPx","minHeightPx","maxBytes","maxLiveFrames","declinesBeforeMute","maxPromptChars","maxErrorReports"];_(s,[...c,"loadTimeoutMs"],"config.limits");for(let d of c)me(s[d],`config.limits.${d}`);s.loadTimeoutMs!==void 0&&me(s.loadTimeoutMs,"config.limits.loadTimeoutMs",6e5),s.minHeightPx>s.maxHeightPx&&x("config.limits.minHeightPx","must not exceed maxHeightPx");let l=I(t.layout,"config.layout");_(l,["minWidthPx","narrowWidthPx","wideWidthPx","kind"],"config.layout"),l.kind!==void 0&&l.kind!=="flow"&&l.kind!=="fill"&&x("config.layout.kind",'must be "flow" or "fill"');for(let d of["minWidthPx","narrowWidthPx","wideWidthPx"])me(l[d],`config.layout.${d}`,1e4);(l.minWidthPx>l.narrowWidthPx||l.narrowWidthPx>l.wideWidthPx)&&x("config.layout","must hold minWidthPx \u2264 narrowWidthPx \u2264 wideWidthPx");let f=I(t.guide,"config.guide");_(f,["toolName","guideToolName","topics"],"config.guide");for(let d of["toolName","guideToolName"]){let g=f[d];g!==void 0&&(typeof g!="string"||!/^[A-Za-z0-9_.-]{1,64}$/u.test(g))&&x(`config.guide.${d}`,"must be a tool name (letters, digits, _ . -)")}if(f.topics!==void 0)for(let[d,g]of Object.entries(I(f.topics,"config.guide.topics"))){let u=`config.guide.topics.${d}`;(!/^[a-z][a-z0-9-]{0,31}$/u.test(d)||De.includes(d))&&x(u,"must be a new topic name (lowercase), not a built-in one"),(typeof g!="string"||g.trim()==="")&&x(u,"must be the topic's text")}oe(t.contentOrigins,"config.contentOrigins");let k=t.isolation==="domain"||t.isolation==="external",m=t.contentOrigins;k!==m.length>0&&x("config.contentOrigins",k?`${String(t.isolation)} isolation needs the origins its content is served from`:"opaque isolation serves nothing: leave it empty");let v=I(t.embedder,"config.embedder");if(_(v,["frameSrc"],"config.embedder"),oe(Array.isArray(v.frameSrc)?v.frameSrc.filter(d=>d!=="'self'"):v.frameSrc,"config.embedder.frameSrc"),t.sandbox!==void 0&&(t.mode!=="url"&&x("config.sandbox","only url mode may add sandbox tokens"),Array.isArray(t.sandbox)||x("config.sandbox","must be an array of sandbox tokens"),t.sandbox.forEach((d,g)=>{Ne.includes(d)||x(`config.sandbox[${g}]`,/top-navigation|same-origin/u.test(String(d))?`${JSON.stringify(d)} is never granted (P037)`:`must be one of ${Ne.join(", ")}`)})),t.storage!==void 0){let d=I(t.storage,"config.storage");_(d,["shared","scope"],"config.storage"),d.shared!==void 0&&d.scope!==void 0&&x("config.storage","shared (several displays at once) or scope (one at a time), not both"),d.scope!==void 0&&(typeof d.scope!="string"||!/^[a-z][a-z ,'-]{0,59}$/u.test(d.scope))&&x("config.storage.scope",'must be short lowercase words ("this artifact, across its versions")'),t.isolation!=="domain"&&x("config.storage","only domain isolation keeps storage across displays"),d.shared!==void 0&&(typeof d.shared!="string"||!/^[a-z][a-z -]{0,39}$/u.test(d.shared))&&x("config.storage.shared",'must be a short lowercase noun ("conversation")')}return t.errors!==void 0&&(t.errors!=="agent"&&t.errors!=="host"&&t.errors!=="none"&&x("config.errors",'must be "agent", "host" or "none"'),t.errors==="none"!=(n.reportError===void 0)&&x("config.errors",t.errors==="none"?'"none" means no reportError: drop the capability':`${JSON.stringify(t.errors)} needs the reportError capability, which carries them`)),t.permissions!==void 0&&(t.mode!=="url"&&x("config.permissions","only url mode may be delegated features"),Array.isArray(t.permissions)||x("config.permissions","must be an array of features"),t.permissions.forEach((d,g)=>{Oe.includes(d)||x(`config.permissions[${g}]`,`must be one of ${Oe.join(", ")}`)})),e}var he="2026-01-26",M={initialize:"ui/initialize",message:"ui/message",openLink:"ui/open-link",downloadFile:"ui/download-file",requestDisplayMode:"ui/request-display-mode",updateModelContext:"ui/update-model-context",callTool:"tools/call",readResource:"resources/read",initialized:"ui/notifications/initialized",sizeChanged:"ui/notifications/size-changed",requestTeardown:"ui/notifications/request-teardown",log:"notifications/message",toolInput:"ui/notifications/tool-input",toolInputPartial:"ui/notifications/tool-input-partial",toolResult:"ui/notifications/tool-result",toolCancelled:"ui/notifications/tool-cancelled",hostContextChanged:"ui/notifications/host-context-changed",resourceTeardown:"ui/resource-teardown",sandboxProxyReady:"ui/notifications/sandbox-proxy-ready",sandboxResourceReady:"ui/notifications/sandbox-resource-ready"},lt=[...["background","text","border","ring"].flatMap(e=>(e==="background"?["primary","secondary","tertiary","inverse","ghost","info","danger","success","warning","disabled"]:e==="text"?["primary","secondary","tertiary","inverse","ghost","info","danger","success","warning","disabled"]:e==="border"?["primary","secondary","tertiary","inverse","ghost","info","danger","success","warning","disabled"]:["primary","secondary","inverse","info","danger","success","warning"]).map(t=>`--color-${e}-${t}`)),"--font-sans","--font-mono",...["normal","medium","semibold","bold"].map(e=>`--font-weight-${e}`),...["xs","sm","md","lg"].map(e=>`--font-text-${e}-size`),...["xs","sm","md","lg","xl","2xl","3xl"].map(e=>`--font-heading-${e}-size`),...["xs","sm","md","lg"].map(e=>`--font-text-${e}-line-height`),...["xs","sm","md","lg","xl","2xl","3xl"].map(e=>`--font-heading-${e}-line-height`),...["xs","sm","md","lg","xl","full"].map(e=>`--border-radius-${e}`),"--border-width-regular",...["hairline","sm","md","lg"].map(e=>`--shadow-${e}`)],dt="porthole/styles",ct="porthole/copy-text";function Y(e){if(e.mode==="url")return null;let t=e.mode==="mcp-app"?"none":"shell",n=D(e),o={};for(let a of n)o[a]={userActivation:K(e,a).includes("user-activation")};let r=t==="shell"?n.flatMap(a=>{let i=B(a);return i.global===void 0?[]:[i.global]}):[];return{protocol:t,content:e.mode==="artifact"?"document":"fragment",capabilities:o,globals:r,themeVariables:Object.keys(e.theme.variables),themeEvent:e.theme.event,themeDocuments:e.theme.documents??"declared",storage:e.isolation==="opaque"?"memory":"native",maxErrorReports:e.limits.maxErrorReports,maxPromptChars:e.limits.maxPromptChars,maxCopyChars:2e4,protocolVersion:he}}var S=e=>e,w=(e,t)=>({light:e,dark:t}),fe={categorical:[{hue:"blue",light:"#2a78d6",dark:"#3987e5"},{hue:"orange",light:"#eb6834",dark:"#d95926"},{hue:"aqua",light:"#1baf7a",dark:"#199e70"},{hue:"yellow",light:"#eda100",dark:"#c98500"},{hue:"magenta",light:"#e87ba4",dark:"#d55181"},{hue:"green",light:"#008300",dark:"#008300"},{hue:"violet",light:"#4a3aa7",dark:"#9085e9"},{hue:"red",light:"#e34948",dark:"#e66767"}],sequential:{light:["#cde2fb","#9ec5f4","#6da7ec","#3987e5","#256abf","#184f95","#0d366b"],dark:["#0d366b","#184f95","#256abf","#3987e5","#6da7ec","#9ec5f4","#cde2fb"]},diverging:{neg:{light:"#e34948",dark:"#e66767"},mid:{light:"#f0efec",dark:"#383835"},pos:{light:"#2a78d6",dark:"#3987e5"}}},ge=(e,t)=>Object.entries(t).map(([n,o])=>[`--color-${e}-${n}`,o]),V=(e,t,n)=>[[`--font-heading-${e}-size`,S(`${t}px`)],[`--font-heading-${e}-line-height`,S(`${n}px`)]],io=Object.fromEntries([["--color-background-primary",w("#f9f9f7","#191918")],["--color-background-secondary",w("#ffffff","#232321")],["--color-background-tertiary",w("#f3f3f1","#2b2b29")],["--color-background-inverse",w("#1a1a19","#f4f4f2")],["--color-background-ghost",w("rgba(11, 11, 11, 0.04)","rgba(255, 255, 255, 0.05)")],["--color-background-disabled",w("#efefec","#2e2e2c")],...ge("background",{info:w("#e8f1fc","#16283d"),success:w("#e7f5ec","#15301f"),warning:w("#fdf3e1","#3a2a10"),danger:w("#fdecec","#3a1a18")}),["--color-text-primary",w("#0b0b0b","#f4f4f2")],["--color-text-secondary",w("#52514e","#b5b4ae")],["--color-text-tertiary",w("#898781","#8f8e88")],["--color-text-inverse",w("#ffffff","#0b0b0b")],["--color-text-ghost",w("#a3a29c","#6e6d68")],["--color-text-disabled",w("#b5b4ae","#5c5b57")],...ge("text",{info:w("#1f5fae","#8cbcf5"),success:w("#1d7a3e","#86d3a2"),warning:w("#8a5a00","#e8b85c"),danger:w("#b42318","#f19a92")}),["--color-border-primary",w("#c3c2b7","#4a4a46")],["--color-border-secondary",w("#e1e0d9","#393936")],["--color-border-tertiary",w("#ebeae5","#2f2f2d")],["--color-border-inverse",w("#3a3a37","#d6d5cf")],["--color-border-ghost",w("rgba(11, 11, 11, 0.06)","rgba(255, 255, 255, 0.08)")],["--color-border-disabled",w("#e6e5e0","#333331")],...ge("border",{info:w("#a9c8f0","#2e5584"),success:w("#a6d9b8","#2c6141"),warning:w("#f0cf8c","#6e5221"),danger:w("#f1b0ab","#7a2f29")}),["--color-ring-primary",w("#2a78d6","#3987e5")],["--color-ring-secondary",w("#898781","#8f8e88")],["--color-ring-inverse",w("#ffffff","#0b0b0b")],...ge("ring",{info:w("#2a78d6","#3987e5"),success:w("#1d7a3e","#86d3a2"),warning:w("#b07400","#e8b85c"),danger:w("#d92d20","#f19a92")}),["--color-accent",w("#2a78d6","#3987e5")],["--color-accent-soft",w("#e8f1fc","#16283d")],...fe.categorical.map((e,t)=>[`--color-chart-${t+1}`,w(e.light,e.dark)]),...fe.sequential.light.map((e,t)=>[`--color-chart-seq-${t+1}`,w(e,fe.sequential.dark[t]??e)]),...["neg","mid","pos"].map(e=>[`--color-chart-${e}`,fe.diverging[e]]),["--font-sans",S('system-ui, -apple-system, "Segoe UI", Roboto, sans-serif')],["--font-mono",S('ui-monospace, "SF Mono", Menlo, Consolas, monospace')],["--font-weight-normal",S("400")],["--font-weight-medium",S("500")],["--font-weight-semibold",S("600")],["--font-weight-bold",S("700")],["--font-text-xs-size",S("12px")],["--font-text-xs-line-height",S("16px")],["--font-text-sm-size",S("13px")],["--font-text-sm-line-height",S("18px")],["--font-text-md-size",S("14px")],["--font-text-md-line-height",S("20px")],["--font-text-lg-size",S("16px")],["--font-text-lg-line-height",S("24px")],...V("xs",14,20),...V("sm",16,24),...V("md",20,28),...V("lg",24,32),...V("xl",28,36),...V("2xl",32,40),...V("3xl",40,48),["--border-radius-xs",S("4px")],["--border-radius-sm",S("6px")],["--border-radius-md",S("8px")],["--border-radius-lg",S("12px")],["--border-radius-xl",S("16px")],["--border-radius-full",S("9999px")],["--border-width-regular",S("1px")],["--shadow-hairline",w("0 0 0 1px rgba(11, 11, 11, 0.06)","0 0 0 1px rgba(255, 255, 255, 0.08)")],["--shadow-sm",w("0 1px 2px rgba(11, 11, 11, 0.06)","0 1px 2px rgba(0, 0, 0, 0.4)")],["--shadow-md",w("0 2px 8px rgba(11, 11, 11, 0.08)","0 2px 8px rgba(0, 0, 0, 0.45)")],["--shadow-lg",w("0 8px 24px rgba(11, 11, 11, 0.12)","0 8px 24px rgba(0, 0, 0, 0.5)")]]);function He(e,t){return typeof e=="string"?e:e[t]}function ut(e,t,n){let o={};for(let[r,a]of Object.entries(e.variables)){let i=n?.[r]?.trim();o[r]=i===void 0||i===""||/[;{}<>]/u.test(i)?He(a,t):i}return o}var q={stats:`<style>
1
+ "use strict";(()=>{var O={start:"porthole/annotate.start",stop:"porthole/annotate.stop",show:"porthole/annotate.show",focus:"porthole/annotate.focus",clear:"porthole/annotate.clear",selected:"porthole/annotate.selected",unselected:"porthole/annotate.unselected",cancelled:"porthole/annotate.cancelled",anchored:"porthole/annotate.anchored"},N={label:120,cssSelector:1e3,exact:4e3,context:64,marks:500,id:128,position:5e7,coordinate:1e7};var te=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),J=(e,t,n=0)=>typeof e=="string"&&e.length>=n&&e.length<=t,Be=(e,t)=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=t;function Kt(e){if(!te(e))return null;switch(e.type){case"CssSelector":return J(e.value,N.cssSelector,1)?{type:"CssSelector",value:e.value}:null;case"TextQuoteSelector":{let{exact:t,prefix:n,suffix:o}=e;return!J(t,N.exact,1)||n!==void 0&&!J(n,N.context)||o!==void 0&&!J(o,N.context)?null:{type:"TextQuoteSelector",exact:t,...n===void 0||n===""?{}:{prefix:n},...o===void 0||o===""?{}:{suffix:o}}}case"TextPositionSelector":return Be(e.start,N.position)&&Be(e.end,N.position)&&e.start<=e.end?{type:"TextPositionSelector",start:e.start,end:e.end}:null;default:return null}}function Ve(e){if(!te(e)||e.kind!=="element"&&e.kind!=="text"||!Array.isArray(e.selectors)||e.selectors.length===0||e.selectors.length>3||!J(e.label,N.label))return null;let t=[];for(let r of e.selectors){let a=Kt(r);if(a===null||t.some(i=>i.type===a.type))return null;t.push(a)}let n=t.some(r=>r.type==="TextQuoteSelector"),o=t.some(r=>r.type==="CssSelector");return(e.kind==="text"||!o)&&!n?null:{kind:e.kind,selectors:t,label:e.label}}var le=e=>typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=N.coordinate;function Ge(e){if(!te(e))return null;let{x:t,y:n,width:o,height:r}=e;return!le(t)||!le(n)||!le(o)||!le(r)||o<0||r<0?null:{x:t,y:n,width:o,height:r}}var Je=e=>J(e,N.id,1);function Xt(e){if(!Array.isArray(e)||e.length>N.marks)return null;let t=[];for(let n of e){if(!te(n)||!Je(n.id))return null;if(n.state==="orphaned"){t.push({id:n.id,state:"orphaned"});continue}if(n.state!=="attached")return null;let o=n.rect===void 0?void 0:Ge(n.rect);if(o===null)return null;t.push({id:n.id,state:"attached",...o===void 0?{}:{rect:o}})}return t}function de(e){if(!te(e))return null;switch(e.type){case"selected":{let t=Ve(e.anchor),n=Ge(e.rect);return t===null||n===null?null:{type:"selected",anchor:t,rect:n}}case"unselected":return{type:"unselected"};case"cancelled":return{type:"cancelled"};case"anchored":{let t=Xt(e.results);return t===null?null:{type:"anchored",results:t}}default:return null}}function Ke(e){let t=e?.elements??!0,n=e?.text??!0;if(typeof t!="boolean"||typeof n!="boolean"||!t&&!n)throw new TypeError("annotations.start: elements, text, or both");return{elements:t,text:n}}function Xe(e){if(!Array.isArray(e)||e.length>N.marks)throw new TypeError(`annotations.show: at most ${N.marks} marks`);let t=new Set;return e.map((n,o)=>{let r=Ve(n?.anchor);if(!Je(n?.id)||t.has(n.id)||r===null)throw new TypeError(`annotations.show: mark ${o} needs a unique id (1 to ${N.id} characters) and a valid anchor`);return t.add(n.id),{id:n.id,anchor:r}})}var $e=["sendPrompt","openLink","downloadFile","callTool","readData","setModelContext","reportError","resize","copyText","annotate"],ne=e=>({rateLimit:{perMinute:e}});var ce={sendPrompt:{defaultGates:["user-activation","confirm"],served:"handler",global:"sendPrompt",request:{method:"ui/message",sdk:"app.sendMessage"}},openLink:{defaultGates:["user-activation","confirm"],served:"handler",global:"openLink",request:{method:"ui/open-link",sdk:"app.openLink"}},downloadFile:{defaultGates:["user-activation","confirm"],served:"handler",request:{method:"ui/download-file",sdk:"app.downloadFile"}},callTool:{defaultGates:["confirm"],served:"handler",request:{method:"tools/call",sdk:"app.callServerTool"}},readData:{defaultGates:[ne(120)],served:"handler",request:{method:"resources/read",sdk:"app.readServerResource"}},setModelContext:{defaultGates:[ne(30)],served:"handler",request:{method:"ui/update-model-context",sdk:"app.updateModelContext"}},reportError:{defaultGates:[ne(10)],served:"event"},resize:{defaultGates:[],served:"event"},copyText:{defaultGates:["user-activation",ne(30)],served:"handler",global:"copyText",request:{method:"porthole/copy-text"}},annotate:{defaultGates:[ne(120)],served:"event"}};function U(e){return ce[e]}function Ye(e){return typeof e=="string"&&$e.includes(e)}function ue(e,t){return(e.egress.anyHttps??[]).some(n=>n===t)}function D(e){return Object.keys(ce).filter(t=>e.capabilities[t]!==void 0)}function K(e,t){return e.capabilities[t]?.gates??ce[t].defaultGates}var Qe=e=>[...new Set(e)];function F(e,t){let n=D(e).flatMap(o=>{let r=e.capabilities[o];return(t==="connect"?r?.connect:r?.resource)??[]});return Qe([...e.egress[t]??[],...n])}var Yt=e=>e.length===0?["'none'"]:[...e];function Ze(e){if(e.mode==="url")return[];let t=o=>F(e,o),n=o=>ue(e,o)?["https:"]:[];return[["default-src","'none'"],["script-src","'unsafe-inline'","'unsafe-eval'","blob:",...t("script")],["style-src","'unsafe-inline'",...t("style")],["font-src","data:",...n("font"),...t("font")],["img-src","data:","blob:",...n("img"),...t("img")],["media-src","data:","blob:",...n("media"),...t("media")],["connect-src",...Yt(t("connect"))],["worker-src","blob:"],["child-src","blob:"],["frame-src","'none'"],["object-src","'none'"],["base-uri","'none'"],["form-action","'none'"],["webrtc","'block'"]]}function et(e){return e.map(t=>t.join(" ")).join("; ")}function pe(e){switch(e.isolation){case"opaque":return["allow-scripts"];case"domain":return["allow-scripts","allow-same-origin"];case"external":return["allow-scripts","allow-same-origin","allow-forms",...e.sandbox??[]]}}function tt(e){return e.mode==="url"?(e.permissions??[]).join("; "):"clipboard-read 'none'; clipboard-write 'none'"}function nt(e){return Qe([...e.contentOrigins,...e.embedder.frameSrc??[]])}var H=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ot=4096;function Qt(e){if(typeof e!="string"||e.length===0||e.length>ot)return null;let t;try{t=new URL(e.trim())}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"||t.username!==""||t.password!==""?null:t.href}var Zt={sendPrompt:(e,t)=>{let n=H(e)?e.text:void 0;return typeof n=="string"&&n.trim()!==""&&n.length<=t.limits.maxPromptChars?{text:n}:null},openLink:e=>{let t=Qt(H(e)?e.url:void 0);return t===null?null:{url:t}},downloadFile:e=>{let t=H(e)?e.contents:void 0;return Array.isArray(t)&&t.length>0&&t.length<=100?{contents:t}:null},callTool:e=>{if(!H(e)||typeof e.name!="string"||e.name===""||e.name.length>256)return null;let t=e.arguments??{};return H(t)?{name:e.name,arguments:t}:null},readData:e=>{let t=H(e)?e.uri:void 0;return typeof t=="string"&&t!==""&&t.length<=ot?{uri:t}:null},setModelContext:e=>{if(!H(e))return null;let{content:t,structuredContent:n}=e;return t!==void 0&&!Array.isArray(t)||n!==void 0&&!H(n)?null:{...t===void 0?{}:{content:t},...n===void 0?{}:{structuredContent:n}}},reportError:e=>{let t=H(e)?e.message:void 0;return typeof t=="string"&&t!==""?{message:t.slice(0,2e3)}:null},copyText:e=>{let t=H(e)?e.text:void 0;return typeof t=="string"&&t!==""&&t.length<=2e4?{text:t}:null},annotate:e=>de(e),resize:e=>{if(!H(e)||typeof e.height!="number"||!Number.isFinite(e.height)||e.height<0)return null;let t=e.width;return typeof t=="number"&&Number.isFinite(t)&&t>=0?{height:e.height,width:t}:{height:e.height}}};function rt(e){let{config:t,display:n,handlers:o,onEvent:r}=e,a=e.now??(()=>Date.now()),i=new Map,s=0,c=!1,l=(m,v,d)=>(r({type:"refused",capability:m,refusal:v}),{ok:!1,refusal:v,...d===void 0?{}:{message:d}}),f=(m,v)=>{let d=a(),g=(i.get(m)??[]).filter(u=>d-u<6e4);return g.length>=v?(i.set(m,g),!1):(g.push(d),i.set(m,g),!0)};return{declared:m=>t.capabilities[m]!==void 0,async call(m,v,d){if(t.capabilities[m]===void 0)return l(m,"not-declared");let g=Zt[m](v,t);if(g===null)return l(m,"invalid");let u=K(t,m),p=u.includes("confirm");if(p&&c)return l(m,"muted");for(let A of u)if(typeof A=="object"&&!f(m,A.rateLimit.perMinute))return l(m,"rate-limited");if(u.includes("user-activation")&&(d?.userActivated??e.userActivation?.())===!1)return l(m,"no-user-activation");let y=null,C=()=>y??=k(m,g);if(p){if(e.confirm===void 0)return l(m,"no-confirm");let A=!1;try{A=await e.confirm({capability:m,args:g,display:n},()=>{C()})}catch{A=y===null?!1:"accepted"}if(y===null&&A!==!0&&A!=="accepted")return A==="redirected"?l(m,"redirected"):(s+=1,s>=t.limits.declinesBeforeMute&&!c&&(c=!0,r({type:"muted"})),l(m,"declined"));s=0}return C()}};async function k(m,v){{if(U(m).served==="event")return r(m==="resize"?{type:"resize",...v}:m==="annotate"?{type:"annotation",report:v}:{type:"error",message:v.message}),{ok:!0,value:void 0};let d=o[m];if(d===void 0)return l(m,"not-declared");try{return{ok:!0,value:await d(v,{displayId:n.id,title:n.title,capability:m})}}catch(g){return l(m,"failed",g instanceof Error?g.message:String(g))}}}}var Le=["img","media","font"],Ne=["allow-popups","allow-popups-to-escape-sandbox","allow-modals","allow-downloads"],Oe=["clipboard-write","fullscreen"];var Ie=class extends Error{path;constructor(t,n){super(`${t}: ${n}`),this.name="ConfigError",this.path=t}},De=["widget","chart","interactive"],en=/^(localhost|127\.0\.0\.1|\[::1\])$|\.localhost$/u,tn=new Set([...["co","org","ac","gov","me","net","ltd","plc","sch","nhs","police"].map(e=>`${e}.uk`),...["com","net","org","edu","gov","asn","id"].map(e=>`${e}.au`),...["co","org","net","ac","govt","geek","school"].map(e=>`${e}.nz`),...["co","ne","or","ac","go","ad","ed","gr","lg"].map(e=>`${e}.jp`),...["co","or","ne","ac","go","re"].map(e=>`${e}.kr`),...["com","net","org","gov","edu"].flatMap(e=>["br","cn","hk","tw","sg","my","mx","ar","tr","ua","pl","ph","pk","ng","eg","sa","vn","co"].map(t=>`${e}.${t}`)),...["co","net","org","gen","firm","ind","ac","edu","gov","res"].map(e=>`${e}.in`),...["co","org","ac","gov","net","web"].map(e=>`${e}.za`),...["co","org","ac","gov","net","muni"].map(e=>`${e}.il`),"co.id","or.id","ac.id","co.th","or.th","ac.th","co.ke","co.tz","co.ug","com.de","co.at","or.at","ac.at","co.it","com.es","nom.es","com.fr","asso.fr","eu.org","us.com","uk.com","eu.com","uk.net","gb.net","jpn.com","kr.com","github.io","githubusercontent.com","gitlab.io","bitbucket.io","pages.dev","workers.dev","r2.dev","vercel.app","now.sh","netlify.app","netlify.com","herokuapp.com","herokussl.com","appspot.com","web.app","firebaseapp.com","cloudfunctions.net","run.app","googleusercontent.com","blogspot.com","azurewebsites.net","azurestaticapps.net","azureedge.net","blob.core.windows.net","cloudapp.net","trafficmanager.net","cloudfront.net","amazonaws.com","s3.amazonaws.com","elasticbeanstalk.com","awsapprunner.com","amplifyapp.com","fly.dev","onrender.com","railway.app","up.railway.app","glitch.me","repl.co","replit.app","replit.dev","surge.sh","deno.dev","ngrok.io","ngrok-free.app","ngrok.app","loca.lt","trycloudflare.com","codesandbox.io","csb.app","stackblitz.io","webcontainer.io","neocities.org","wordpress.com","tumblr.com","wixsite.com","squarespace.com","myshopify.com","carrd.co","notion.site","framer.app","webflow.io","readthedocs.io","gitbook.io","sourceforge.net","digitaloceanspaces.com","ondigitalocean.app","b-cdn.net","jsdelivr.net"]);function nn(e){return e==="localhost"?null:!e.includes(".")||tn.has(e)?`is a wildcard over a public suffix (*.${e}): anyone can serve a site under it; name a domain of your own (https://*.cdn.example.com)`:null}var on=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/u;function rn(e){let t="is not an origin (scheme://host[:port], lowercase, no path)";if(typeof e!="string"||e.length>269)return`${JSON.stringify(e)} ${t}`;let n=/^(https|http|wss|ws):\/\/([^/:]+|\[::1\])(:(\d{1,5}))?$/u.exec(e);if(n===null)return`${JSON.stringify(e)} ${t}`;let[,o,r="",,a]=n;if(a!==void 0&&(Number(a)<1||Number(a)>65535))return`${JSON.stringify(e)} has no valid port`;if(r!=="[::1]"&&!on.test(r))return`${JSON.stringify(e)} ${t}`;if(r.startsWith("*.")){let i=nn(r.slice(2));if(i!==null)return`${JSON.stringify(e)} ${i}`}return(o==="http"||o==="ws")&&!en.test(r.replace(/^\*\./u,"x."))?`${JSON.stringify(e)} uses ${o} off loopback: ${o} is allowed only for localhost, *.localhost, 127.0.0.1 and [::1] (loopback development); use ${o==="http"?"https":"wss"}`:null}var x=(e,t)=>{throw new Ie(e,t)},re=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function I(e,t){return re(e)?e:x(t,"must be an object")}function _(e,t,n){for(let o of Object.keys(e))t.includes(o)||x(`${n}.${o}`,"is not a known field")}function oe(e,t){if(e!==void 0){if(!Array.isArray(e)){x(t,"must be an array of origins");return}e.forEach((n,o)=>{let r=rn(n);r!==null&&x(`${t}[${o}]`,r)})}}function me(e,t,n=Number.MAX_SAFE_INTEGER){(typeof e!="number"||!Number.isInteger(e)||e<1||e>n)&&x(t,`must be an integer from 1 to ${n}`)}function an(e,t){if(e==="user-activation"||e==="confirm")return;let n=re(e)&&re(e.rateLimit)?e.rateLimit:null;if(n===null||Object.keys(e).length!==1){x(t,'must be "user-activation", "confirm" or { rateLimit: { perMinute } }');return}_(n,["perMinute"],`${t}.rateLimit`),me(n.perMinute,`${t}.rateLimit.perMinute`,1e4)}var at=["inline","artifact","mcp-app","url"],st=["opaque","domain","external"];function it(e){let t=I(e,"config");_(t,["mode","isolation","capabilities","egress","theme","limits","layout","guide","contentOrigins","embedder","sandbox","permissions","storage","errors"],"config"),at.includes(t.mode)||x("config.mode",`must be one of ${at.join(", ")}`),st.includes(t.isolation)||x("config.isolation",`must be one of ${st.join(", ")}`),t.mode==="url"!=(t.isolation==="external")&&x("config.isolation",'url mode, and only url mode, is "external"');let n=I(t.capabilities,"config.capabilities");for(let[d,g]of Object.entries(n)){let u=`config.capabilities.${d}`;Ye(d)||x(u,`is not a capability (${$e.join(", ")})`);let p=I(g,u);_(p,["gates","connect","resource","guide"],u),p.gates!==void 0&&(Array.isArray(p.gates)||x(`${u}.gates`,"must be an array"),p.gates.forEach((y,C)=>an(y,`${u}.gates[${C}]`))),oe(p.connect,`${u}.connect`),oe(p.resource,`${u}.resource`),p.guide!==void 0&&typeof p.guide!="string"&&x(`${u}.guide`,"must be a string")}t.mode==="url"&&Object.keys(n).length>0&&x("config.capabilities","url mode has no shell, so it can declare no capabilities");let o=I(t.egress,"config.egress"),r=["connect","script","style","img","font","media"];_(o,[...r,"anyHttps"],"config.egress");for(let d of r)oe(o[d],`config.egress.${d}`);o.anyHttps!==void 0&&(Array.isArray(o.anyHttps)||x("config.egress.anyHttps",`must be a list of ${Le.join(", ")}`),o.anyHttps.forEach((d,g)=>{Le.includes(d)||x(`config.egress.anyHttps[${g}]`,`${JSON.stringify(d)}: only images, media and fonts may load from any https site (P059), never scripts, styles or data`)}),t.mode==="url"&&x("config.egress.anyHttps","url mode has no egress control"));let a=I(t.theme,"config.theme");_(a,["variables","event","documents"],"config.theme"),a.documents!==void 0&&a.documents!=="declared"&&a.documents!=="always"&&a.documents!=="never"&&x("config.theme.documents",'must be "declared", "always" or "never"'),a.documents==="never"&&t.mode!=="artifact"&&x("config.theme.documents",'"never" is for whole pages: a fragment takes the theme it is drawn in');let i=I(a.variables,"config.theme.variables");for(let[d,g]of Object.entries(i)){let u=`config.theme.variables[${JSON.stringify(d)}]`;/^--[a-z0-9]+(-[a-z0-9]+)*$/u.test(d)||x(u,"must be a CSS custom property name (--lowercase-words)");let p=re(g)?[g.light,g.dark]:[g];re(g)&&_(g,["light","dark"],u);for(let y of p)(typeof y!="string"||y.length===0||y.length>500||/[;{}<>]/u.test(y))&&x(u,"must be a CSS value (1\u2013500 characters, no ; { } < >), or { light, dark } of them")}(typeof a.event!="string"||!/^[a-z][a-z0-9]*([:.-][a-z0-9]+)*$/u.test(a.event))&&x("config.theme.event",'must be an event name such as "porthole:theme"');let s=I(t.limits,"config.limits"),c=["maxHeightPx","minHeightPx","maxBytes","maxLiveFrames","declinesBeforeMute","maxPromptChars","maxErrorReports"];_(s,[...c,"loadTimeoutMs"],"config.limits");for(let d of c)me(s[d],`config.limits.${d}`);s.loadTimeoutMs!==void 0&&me(s.loadTimeoutMs,"config.limits.loadTimeoutMs",6e5),s.minHeightPx>s.maxHeightPx&&x("config.limits.minHeightPx","must not exceed maxHeightPx");let l=I(t.layout,"config.layout");_(l,["minWidthPx","narrowWidthPx","wideWidthPx","kind"],"config.layout"),l.kind!==void 0&&l.kind!=="flow"&&l.kind!=="fill"&&x("config.layout.kind",'must be "flow" or "fill"');for(let d of["minWidthPx","narrowWidthPx","wideWidthPx"])me(l[d],`config.layout.${d}`,1e4);(l.minWidthPx>l.narrowWidthPx||l.narrowWidthPx>l.wideWidthPx)&&x("config.layout","must hold minWidthPx \u2264 narrowWidthPx \u2264 wideWidthPx");let f=I(t.guide,"config.guide");_(f,["toolName","guideToolName","topics"],"config.guide");for(let d of["toolName","guideToolName"]){let g=f[d];g!==void 0&&(typeof g!="string"||!/^[A-Za-z0-9_.-]{1,64}$/u.test(g))&&x(`config.guide.${d}`,"must be a tool name (letters, digits, _ . -)")}if(f.topics!==void 0)for(let[d,g]of Object.entries(I(f.topics,"config.guide.topics"))){let u=`config.guide.topics.${d}`;(!/^[a-z][a-z0-9-]{0,31}$/u.test(d)||De.includes(d))&&x(u,"must be a new topic name (lowercase), not a built-in one"),(typeof g!="string"||g.trim()==="")&&x(u,"must be the topic's text")}oe(t.contentOrigins,"config.contentOrigins");let k=t.isolation==="domain"||t.isolation==="external",m=t.contentOrigins;k!==m.length>0&&x("config.contentOrigins",k?`${String(t.isolation)} isolation needs the origins its content is served from`:"opaque isolation serves nothing: leave it empty");let v=I(t.embedder,"config.embedder");if(_(v,["frameSrc"],"config.embedder"),oe(Array.isArray(v.frameSrc)?v.frameSrc.filter(d=>d!=="'self'"):v.frameSrc,"config.embedder.frameSrc"),t.sandbox!==void 0&&(t.mode!=="url"&&x("config.sandbox","only url mode may add sandbox tokens"),Array.isArray(t.sandbox)||x("config.sandbox","must be an array of sandbox tokens"),t.sandbox.forEach((d,g)=>{Ne.includes(d)||x(`config.sandbox[${g}]`,/top-navigation|same-origin/u.test(String(d))?`${JSON.stringify(d)} is never granted (P037)`:`must be one of ${Ne.join(", ")}`)})),t.storage!==void 0){let d=I(t.storage,"config.storage");_(d,["shared","scope"],"config.storage"),d.shared!==void 0&&d.scope!==void 0&&x("config.storage","shared (several displays at once) or scope (one at a time), not both"),d.scope!==void 0&&(typeof d.scope!="string"||!/^[a-z][a-z ,'-]{0,59}$/u.test(d.scope))&&x("config.storage.scope",'must be short lowercase words ("this artifact, across its versions")'),t.isolation!=="domain"&&x("config.storage","only domain isolation keeps storage across displays"),d.shared!==void 0&&(typeof d.shared!="string"||!/^[a-z][a-z -]{0,39}$/u.test(d.shared))&&x("config.storage.shared",'must be a short lowercase noun ("conversation")')}return t.errors!==void 0&&(t.errors!=="agent"&&t.errors!=="host"&&t.errors!=="none"&&x("config.errors",'must be "agent", "host" or "none"'),t.errors==="none"!=(n.reportError===void 0)&&x("config.errors",t.errors==="none"?'"none" means no reportError: drop the capability':`${JSON.stringify(t.errors)} needs the reportError capability, which carries them`)),t.permissions!==void 0&&(t.mode!=="url"&&x("config.permissions","only url mode may be delegated features"),Array.isArray(t.permissions)||x("config.permissions","must be an array of features"),t.permissions.forEach((d,g)=>{Oe.includes(d)||x(`config.permissions[${g}]`,`must be one of ${Oe.join(", ")}`)})),e}var he="2026-01-26",M={initialize:"ui/initialize",message:"ui/message",openLink:"ui/open-link",downloadFile:"ui/download-file",requestDisplayMode:"ui/request-display-mode",updateModelContext:"ui/update-model-context",callTool:"tools/call",readResource:"resources/read",initialized:"ui/notifications/initialized",sizeChanged:"ui/notifications/size-changed",requestTeardown:"ui/notifications/request-teardown",log:"notifications/message",toolInput:"ui/notifications/tool-input",toolInputPartial:"ui/notifications/tool-input-partial",toolResult:"ui/notifications/tool-result",toolCancelled:"ui/notifications/tool-cancelled",hostContextChanged:"ui/notifications/host-context-changed",resourceTeardown:"ui/resource-teardown",sandboxProxyReady:"ui/notifications/sandbox-proxy-ready",sandboxResourceReady:"ui/notifications/sandbox-resource-ready"},lt=[...["background","text","border","ring"].flatMap(e=>(e==="background"?["primary","secondary","tertiary","inverse","ghost","info","danger","success","warning","disabled"]:e==="text"?["primary","secondary","tertiary","inverse","ghost","info","danger","success","warning","disabled"]:e==="border"?["primary","secondary","tertiary","inverse","ghost","info","danger","success","warning","disabled"]:["primary","secondary","inverse","info","danger","success","warning"]).map(t=>`--color-${e}-${t}`)),"--font-sans","--font-mono",...["normal","medium","semibold","bold"].map(e=>`--font-weight-${e}`),...["xs","sm","md","lg"].map(e=>`--font-text-${e}-size`),...["xs","sm","md","lg","xl","2xl","3xl"].map(e=>`--font-heading-${e}-size`),...["xs","sm","md","lg"].map(e=>`--font-text-${e}-line-height`),...["xs","sm","md","lg","xl","2xl","3xl"].map(e=>`--font-heading-${e}-line-height`),...["xs","sm","md","lg","xl","full"].map(e=>`--border-radius-${e}`),"--border-width-regular",...["hairline","sm","md","lg"].map(e=>`--shadow-${e}`)],dt="porthole/styles",ct="porthole/copy-text";function Y(e){if(e.mode==="url")return null;let t=e.mode==="mcp-app"?"none":"shell",n=D(e),o={};for(let a of n)o[a]={userActivation:K(e,a).includes("user-activation")};let r=t==="shell"?n.flatMap(a=>{let i=U(a);return i.global===void 0?[]:[i.global]}):[];return{protocol:t,content:e.mode==="artifact"?"document":"fragment",capabilities:o,globals:r,themeVariables:Object.keys(e.theme.variables),themeEvent:e.theme.event,themeDocuments:e.theme.documents??"declared",storage:e.isolation==="opaque"?"memory":"native",maxErrorReports:e.limits.maxErrorReports,maxPromptChars:e.limits.maxPromptChars,maxCopyChars:2e4,protocolVersion:he}}var S=e=>e,w=(e,t)=>({light:e,dark:t}),fe={categorical:[{hue:"blue",light:"#2a78d6",dark:"#3987e5"},{hue:"orange",light:"#eb6834",dark:"#d95926"},{hue:"aqua",light:"#1baf7a",dark:"#199e70"},{hue:"yellow",light:"#eda100",dark:"#c98500"},{hue:"magenta",light:"#e87ba4",dark:"#d55181"},{hue:"green",light:"#008300",dark:"#008300"},{hue:"violet",light:"#4a3aa7",dark:"#9085e9"},{hue:"red",light:"#e34948",dark:"#e66767"}],sequential:{light:["#cde2fb","#9ec5f4","#6da7ec","#3987e5","#256abf","#184f95","#0d366b"],dark:["#0d366b","#184f95","#256abf","#3987e5","#6da7ec","#9ec5f4","#cde2fb"]},diverging:{neg:{light:"#e34948",dark:"#e66767"},mid:{light:"#f0efec",dark:"#383835"},pos:{light:"#2a78d6",dark:"#3987e5"}}},ge=(e,t)=>Object.entries(t).map(([n,o])=>[`--color-${e}-${n}`,o]),V=(e,t,n)=>[[`--font-heading-${e}-size`,S(`${t}px`)],[`--font-heading-${e}-line-height`,S(`${n}px`)]],lo=Object.fromEntries([["--color-background-primary",w("#f9f9f7","#191918")],["--color-background-secondary",w("#ffffff","#232321")],["--color-background-tertiary",w("#f3f3f1","#2b2b29")],["--color-background-inverse",w("#1a1a19","#f4f4f2")],["--color-background-ghost",w("rgba(11, 11, 11, 0.04)","rgba(255, 255, 255, 0.05)")],["--color-background-disabled",w("#efefec","#2e2e2c")],...ge("background",{info:w("#e8f1fc","#16283d"),success:w("#e7f5ec","#15301f"),warning:w("#fdf3e1","#3a2a10"),danger:w("#fdecec","#3a1a18")}),["--color-text-primary",w("#0b0b0b","#f4f4f2")],["--color-text-secondary",w("#52514e","#b5b4ae")],["--color-text-tertiary",w("#898781","#8f8e88")],["--color-text-inverse",w("#ffffff","#0b0b0b")],["--color-text-ghost",w("#a3a29c","#6e6d68")],["--color-text-disabled",w("#b5b4ae","#5c5b57")],...ge("text",{info:w("#1f5fae","#8cbcf5"),success:w("#1d7a3e","#86d3a2"),warning:w("#8a5a00","#e8b85c"),danger:w("#b42318","#f19a92")}),["--color-border-primary",w("#c3c2b7","#4a4a46")],["--color-border-secondary",w("#e1e0d9","#393936")],["--color-border-tertiary",w("#ebeae5","#2f2f2d")],["--color-border-inverse",w("#3a3a37","#d6d5cf")],["--color-border-ghost",w("rgba(11, 11, 11, 0.06)","rgba(255, 255, 255, 0.08)")],["--color-border-disabled",w("#e6e5e0","#333331")],...ge("border",{info:w("#a9c8f0","#2e5584"),success:w("#a6d9b8","#2c6141"),warning:w("#f0cf8c","#6e5221"),danger:w("#f1b0ab","#7a2f29")}),["--color-ring-primary",w("#2a78d6","#3987e5")],["--color-ring-secondary",w("#898781","#8f8e88")],["--color-ring-inverse",w("#ffffff","#0b0b0b")],...ge("ring",{info:w("#2a78d6","#3987e5"),success:w("#1d7a3e","#86d3a2"),warning:w("#b07400","#e8b85c"),danger:w("#d92d20","#f19a92")}),["--color-accent",w("#2a78d6","#3987e5")],["--color-accent-soft",w("#e8f1fc","#16283d")],...fe.categorical.map((e,t)=>[`--color-chart-${t+1}`,w(e.light,e.dark)]),...fe.sequential.light.map((e,t)=>[`--color-chart-seq-${t+1}`,w(e,fe.sequential.dark[t]??e)]),...["neg","mid","pos"].map(e=>[`--color-chart-${e}`,fe.diverging[e]]),["--font-sans",S('system-ui, -apple-system, "Segoe UI", Roboto, sans-serif')],["--font-mono",S('ui-monospace, "SF Mono", Menlo, Consolas, monospace')],["--font-weight-normal",S("400")],["--font-weight-medium",S("500")],["--font-weight-semibold",S("600")],["--font-weight-bold",S("700")],["--font-text-xs-size",S("12px")],["--font-text-xs-line-height",S("16px")],["--font-text-sm-size",S("13px")],["--font-text-sm-line-height",S("18px")],["--font-text-md-size",S("14px")],["--font-text-md-line-height",S("20px")],["--font-text-lg-size",S("16px")],["--font-text-lg-line-height",S("24px")],...V("xs",14,20),...V("sm",16,24),...V("md",20,28),...V("lg",24,32),...V("xl",28,36),...V("2xl",32,40),...V("3xl",40,48),["--border-radius-xs",S("4px")],["--border-radius-sm",S("6px")],["--border-radius-md",S("8px")],["--border-radius-lg",S("12px")],["--border-radius-xl",S("16px")],["--border-radius-full",S("9999px")],["--border-width-regular",S("1px")],["--shadow-hairline",w("0 0 0 1px rgba(11, 11, 11, 0.06)","0 0 0 1px rgba(255, 255, 255, 0.08)")],["--shadow-sm",w("0 1px 2px rgba(11, 11, 11, 0.06)","0 1px 2px rgba(0, 0, 0, 0.4)")],["--shadow-md",w("0 2px 8px rgba(11, 11, 11, 0.08)","0 2px 8px rgba(0, 0, 0, 0.45)")],["--shadow-lg",w("0 8px 24px rgba(11, 11, 11, 0.12)","0 8px 24px rgba(0, 0, 0, 0.5)")]]);function He(e,t){return typeof e=="string"?e:e[t]}function ut(e,t,n){let o={};for(let[r,a]of Object.entries(e.variables)){let i=n?.[r]?.trim();o[r]=i===void 0||i===""||/[;{}<>]/u.test(i)?He(a,t):i}return o}var q={stats:`<style>
2
2
  .stats { display: flex; flex-wrap: wrap; gap: 8px; }
3
3
  .stat { flex: 1 1 100px; background: var(--color-background-secondary); border: var(--border-width-regular) solid var(--color-border-tertiary); border-radius: var(--border-radius-lg); padding: 12px 16px; }
4
4
  .stat div { font-size: var(--font-text-sm-size); color: var(--color-text-secondary); }
@@ -33,7 +33,7 @@ ${q.line}`:null,be(e,q.bars)?`
33
33
  Bars in HTML, under a title like the line chart's:
34
34
  ${q.bars}`:null)}function j(e,t){let n=[];e.includes("confirm")&&n.push(`The app shows the person ${t} first, and nothing happens unless they confirm.`),e.includes("user-activation")&&n.push("Call it from a click (it needs one).");for(let o of e)typeof o=="object"&&n.push(`At most ${o.rateLimit.perMinute} a minute.`);return n.join(" ")}var hn={sendPrompt:(e,t)=>e.global("sendPrompt")?`- sendPrompt(text): asks to send text to you as the person's message (at most ${e.config.limits.maxPromptChars.toLocaleString("en-US")} characters). Use it for "explain this point", "try these settings". ${j(t,"the whole text")} It returns a promise: true if it was sent.`:`- Messages: the MCP Apps request ui/message (with the App SDK, app.sendMessage) asks to send text to you as the person's message. ${j(t,"the whole text")}`,openLink:(e,t)=>e.global("openLink")?`- openLink(url): asks to open an http(s) link in a new tab; a click on an <a href> does the same for you. ${j(t,"the link")} It returns a promise: true if it opened.`:`- Links: the MCP Apps request ui/open-link (with the App SDK, app.openLink) asks to open an http(s) link in a new tab. ${j(t,"the link")}`,downloadFile:(e,t)=>`- Downloads: the MCP Apps request ui/download-file (with the App SDK, app.downloadFile). ${j(t,"the file")}`,callTool:(e,t)=>`- Tools: the MCP Apps request tools/call (with the App SDK, app.callServerTool). ${j(t,"the call")}`,readData:(e,t)=>`- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${j(t,"the request")}`,setModelContext:(e,t)=>`- Context for the agent: the MCP Apps request ui/update-model-context (with the App SDK, app.updateModelContext). ${j(t,"it")}`,copyText:(e,t)=>e.global("copyText")?`- copyText(text): copies text to the person's clipboard (at most ${2e4.toLocaleString("en-US")} characters), and the app shows them what was copied. Use it for every copy button: nothing else in the ${e.noun} can write the clipboard. ${j(t,"the text")} It returns a promise: true if it was copied.`:`- Copying: the request porthole/copy-text with { text } (at most ${2e4.toLocaleString("en-US")} characters) copies text to the person's clipboard, and the app shows them what was copied; nothing else in the ${e.noun} can write the clipboard. ${j(t,"the text")}`,annotate:e=>`- Comments: the person may point at parts of the ${e.noun} to comment on them. Give headings and the parts that matter stable ids (id="revenue"), so comments stay on them when the ${e.noun} is written again.`,reportError:e=>`- ${we(e.config,"").find(t=>t.id==="errors")?.text??""}`,resize:()=>""};function fn(e){let{config:t,noun:n}=e,o=D(t).map(l=>{let f=t.capabilities[l]?.guide;return f===void 0?hn[l](e,K(t,l)):`- ${f}`}).filter(l=>l!==""),r=we(t,""),a=r.find(l=>l.id==="storage"),i=a===void 0?null:`- ${a.text}`,s=e.declared("reportError")?null:`- ${r.find(l=>l.id==="errors")?.text??""}`,c=o.length===0?"- It can only draw: it has no way to send anything to you or the app.":null;return je(`# Interactive ${n}s`,"",...o,s,c,i)}var ht={widget:pn,chart:mn,interactive:fn};function bt(e,t){let n=gt(e),o=e.guide.topics??{};return(t??De).map(r=>{if(Object.hasOwn(ht,r))return ht[r](n);let a=o[r];if(a===void 0)throw new RangeError(`No guide topic ${JSON.stringify(r)}`);return a}).join(`
35
35
 
36
- `)}function xt(e){let t=gt(e),{layout:n}=e,o=e.mode==="artifact"?"Show a whole HTML page you write: a report, a document, a small app.":e.mode==="mcp-app"?"Show an MCP Apps view.":"Render an SVG or an HTML fragment you write, shown inline: charts, diagrams, explainers, small interactive tools.",r=[...new Set(["script","style","font","img","media","connect"].flatMap(m=>F(e,m)))],a=["img","media","font"].filter(m=>ue(e,m)).map(m=>yt[m]),i=a.length===0?"":`${a.length===1?a[0]:`${a.slice(0,-1).join(", ")} and ${a.at(-1)}`} from ${wt}`,s=r.length===0&&i===""?"with no network (nothing loads from outside)":r.length===0?`loading only ${i}`:`loading only from ${r.join(", ")}${i===""?"":`, and ${i}`}`,c=D(e).flatMap(m=>{let v=B(m);return v.global===void 0||!t.global(v.global)?[]:v.global==="sendPrompt"?["sendPrompt(text) asks the person to send text to you as their message."]:v.global==="openLink"?["openLink(url) asks the person to open a link."]:[]}),l=e.guide.guideToolName===void 0?"":` Call ${e.guide.guideToolName} once before your first ${t.noun}${e.mode==="inline"?" (topic chart before your first chart)":""}.`,f=n.kind==="fill"?`It fills the viewer in a sandbox about ${n.narrowWidthPx} px wide on a phone, from the same code on every screen`:`It runs in a sandbox about ${n.narrowWidthPx} px wide on a phone and ${n.wideWidthPx} on a desktop, from the same code${t.declared("resize")?" (its height follows the content)":""}`,k=e.theme.documents==="never"?"always in light (the app doesn't theme it)":"in the person's light or dark theme through CSS variables";return`${o} ${f}, ${k}, ${s}. ${c.join(" ")}${l} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu," ")}var gn=/^(https?):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(?::(\d{1,5}))?$/u,vt=/^\d{1,3}(\.\d{1,3}){3}$/u,kt={http:"80",https:"443"};function xe(e){let t=gn.exec(e);if(t===null)return null;let[,n="",o="",r]=t;return{scheme:n,host:o,port:r??kt[n]??""}}var yn=/^[a-z][a-z0-9+.-]*:\/\/([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*|\[[0-9a-f:.]+\])(:\d{1,5})?$/u;function wn(e){return typeof e=="string"&&e.length<=300&&yn.test(e)}function St(e){return wn(e)?null:e==="null"?`the host page's origin is opaque ("null"): serve it from a real origin (an Electron custom protocol must be registered as standard, and file: pages have none)`:`${JSON.stringify(e)} is not an exact origin (scheme://host[:port], lowercase, no path)`}function bn(e,t){let n=e.toLowerCase().replace(/\.$/u,""),o=t.toLowerCase().replace(/\.$/u,"");if(n===o)return!0;if(vt.test(n)||vt.test(o)||n.startsWith("[")||o.startsWith("["))return!1;let r=n.split(".").toReversed(),a=o.split(".").toReversed(),i=0;for(;i<r.length&&i<a.length&&r[i]===a[i];)i+=1;return i>=2}function xn(e,t){let n=xe(e),o=/^(https?):\/\/\*\.([a-z0-9.-]+)(?::(\d{1,5}))?$/u.exec(t);if(n===null)return!1;if(o===null){let s=xe(t);return s!==null&&s.scheme===n.scheme&&s.host===n.host&&s.port===n.port}let[,r="",a="",i]=o;return r===n.scheme&&(i??kt[r])===n.port&&n.host.endsWith(`.${a}`)&&n.host.length>a.length+1}function Ct(e,t,n){let o=xe(e.origin),r;try{r=new URL(e.url)}catch{throw new TypeError(`The located URL ${JSON.stringify(e.url)} is not a URL`)}if(o===null||r.origin!==e.origin)throw new TypeError(`The located URL ${JSON.stringify(e.url)} is not on its origin ${JSON.stringify(e.origin)}`);if(!t.some(i=>xn(e.origin,i)))throw new TypeError(`The located origin ${e.origin} is not one of the config's content origins`);let a=xe(n);if(a!==null&&bn(o.host,a.host))throw new TypeError(`The located origin ${e.origin} may be the same site as the host (${n}): content must be served from a registrable domain the host uses for nothing else`)}var Tt=String.raw`if (declared("annotate")) {
36
+ `)}function xt(e){let t=gt(e),{layout:n}=e,o=e.mode==="artifact"?"Show a whole HTML page you write: a report, a document, a small app.":e.mode==="mcp-app"?"Show an MCP Apps view.":"Render an SVG or an HTML fragment you write, shown inline: charts, diagrams, explainers, small interactive tools.",r=[...new Set(["script","style","font","img","media","connect"].flatMap(m=>F(e,m)))],a=["img","media","font"].filter(m=>ue(e,m)).map(m=>yt[m]),i=a.length===0?"":`${a.length===1?a[0]:`${a.slice(0,-1).join(", ")} and ${a.at(-1)}`} from ${wt}`,s=r.length===0&&i===""?"with no network (nothing loads from outside)":r.length===0?`loading only ${i}`:`loading only from ${r.join(", ")}${i===""?"":`, and ${i}`}`,c=D(e).flatMap(m=>{let v=U(m);return v.global===void 0||!t.global(v.global)?[]:v.global==="sendPrompt"?["sendPrompt(text) asks the person to send text to you as their message."]:v.global==="openLink"?["openLink(url) asks the person to open a link."]:[]}),l=e.guide.guideToolName===void 0?"":` Call ${e.guide.guideToolName} once before your first ${t.noun}${e.mode==="inline"?" (topic chart before your first chart)":""}.`,f=n.kind==="fill"?`It fills the viewer in a sandbox about ${n.narrowWidthPx} px wide on a phone, from the same code on every screen`:`It runs in a sandbox about ${n.narrowWidthPx} px wide on a phone and ${n.wideWidthPx} on a desktop, from the same code${t.declared("resize")?" (its height follows the content)":""}`,k=e.theme.documents==="never"?"always in light (the app doesn't theme it)":"in the person's light or dark theme through CSS variables";return`${o} ${f}, ${k}, ${s}. ${c.join(" ")}${l} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu," ")}var gn=/^(https?):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(?::(\d{1,5}))?$/u,vt=/^\d{1,3}(\.\d{1,3}){3}$/u,kt={http:"80",https:"443"};function xe(e){let t=gn.exec(e);if(t===null)return null;let[,n="",o="",r]=t;return{scheme:n,host:o,port:r??kt[n]??""}}var yn=/^[a-z][a-z0-9+.-]*:\/\/([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*|\[[0-9a-f:.]+\])(:\d{1,5})?$/u;function wn(e){return typeof e=="string"&&e.length<=300&&yn.test(e)}function St(e){return wn(e)?null:e==="null"?`the host page's origin is opaque ("null"): serve it from a real origin (an Electron custom protocol must be registered as standard, and file: pages have none)`:`${JSON.stringify(e)} is not an exact origin (scheme://host[:port], lowercase, no path)`}function bn(e,t){let n=e.toLowerCase().replace(/\.$/u,""),o=t.toLowerCase().replace(/\.$/u,"");if(n===o)return!0;if(vt.test(n)||vt.test(o)||n.startsWith("[")||o.startsWith("["))return!1;let r=n.split(".").toReversed(),a=o.split(".").toReversed(),i=0;for(;i<r.length&&i<a.length&&r[i]===a[i];)i+=1;return i>=2}function xn(e,t){let n=xe(e),o=/^(https?):\/\/\*\.([a-z0-9.-]+)(?::(\d{1,5}))?$/u.exec(t);if(n===null)return!1;if(o===null){let s=xe(t);return s!==null&&s.scheme===n.scheme&&s.host===n.host&&s.port===n.port}let[,r="",a="",i]=o;return r===n.scheme&&(i??kt[r])===n.port&&n.host.endsWith(`.${a}`)&&n.host.length>a.length+1}function Ct(e,t,n){let o=xe(e.origin),r;try{r=new URL(e.url)}catch{throw new TypeError("The located URL is not a URL")}if(o===null||r.origin!==e.origin)throw new TypeError(`The located URL is not on its origin ${JSON.stringify(e.origin)} (it is on ${JSON.stringify(vn(e.url))})`);if(!t.some(i=>xn(e.origin,i)))throw new TypeError(`The located origin ${e.origin} is not one of the config's content origins`);let a=xe(n);if(a!==null&&bn(o.host,a.host))throw new TypeError(`The located origin ${e.origin} may be the same site as the host (${n}): content must be served from a registrable domain the host uses for nothing else`)}function vn(e){try{return new URL(e).origin}catch{return"an unparsable address"}}var Tt=String.raw`if (declared("annotate")) {
37
37
  (() => {
38
38
  const LIMIT = { exact: 4000, quote: 300, context: 32, label: 120, css: 1000, marks: 500, boxes: 200 };
39
39
  const M = {
@@ -1611,7 +1611,7 @@ ${q.bars}`:null)}function j(e,t){let n=[];e.includes("confirm")&&n.push(`The app
1611
1611
  setTimeout(initialize, 250);
1612
1612
  };
1613
1613
  initialize();
1614
- })();`;var vn=/^[A-Za-z0-9+/_=-]{8,256}$/u,kn=e=>e.replace(/&/gu,"&amp;").replace(/"/gu,"&quot;").replace(/</gu,"&lt;"),Sn=e=>e.replace(/&/gu,"&amp;").replace(/</gu,"&lt;").replace(/>/gu,"&gt;"),Cn=e=>JSON.stringify(e).replace(/</gu,"\\u003c").replace(/\u2028/gu,"\\u2028").replace(/\u2029/gu,"\\u2029"),Tn=`:root { color-scheme: light dark; }
1614
+ })();`;var kn=/^[A-Za-z0-9+/_=-]{8,256}$/u,Sn=e=>e.replace(/&/gu,"&amp;").replace(/"/gu,"&quot;").replace(/</gu,"&lt;"),Cn=e=>e.replace(/&/gu,"&amp;").replace(/</gu,"&lt;").replace(/>/gu,"&gt;"),Tn=e=>JSON.stringify(e).replace(/</gu,"\\u003c").replace(/\u2028/gu,"\\u2028").replace(/\u2029/gu,"\\u2029"),An=`:root { color-scheme: light dark; }
1615
1615
  html, body { margin: 0; padding: 0; background: transparent; }
1616
1616
  body {
1617
1617
  font-family: var(--font-sans, system-ui, sans-serif);
@@ -1643,15 +1643,15 @@ body {
1643
1643
  :where(textarea) { padding: 8px 10px; }
1644
1644
  :where(input:is([type="checkbox" i], [type="radio" i], [type="range" i])) { accent-color: var(--color-accent, auto); }
1645
1645
  :where(button, input, select, textarea):focus-visible { outline: 2px solid var(--color-ring-primary, Highlight); outline-offset: 1px; }
1646
- :where(button, input, select, textarea):disabled { color: var(--color-text-disabled, GrayText); cursor: default; }`;function Et(e,t,n){for(let i of n.origins){let s=St(i);if(s!==null)throw new TypeError(`shellDocument: ${s}`)}if(n.nonce!==void 0&&!vn.test(n.nonce))throw new TypeError("shellDocument: a nonce is 8 to 256 base64 characters");let o=n.nonce===void 0?"":` nonce="${n.nonce}"`,r=At.replace("__ANNOTATE__",()=>e.capabilities.annotate===void 0?"":Tt).replace("__PLAN__",()=>Cn({...e,origins:n.origins,...n.document===void 0?{}:{document:n.document}}));return`<!doctype html>
1646
+ :where(button, input, select, textarea):disabled { color: var(--color-text-disabled, GrayText); cursor: default; }`;function Et(e,t,n){for(let i of n.origins){let s=St(i);if(s!==null)throw new TypeError(`shellDocument: ${s}`)}if(n.nonce!==void 0&&!kn.test(n.nonce))throw new TypeError("shellDocument: a nonce is 8 to 256 base64 characters");let o=n.nonce===void 0?"":` nonce="${n.nonce}"`,r=At.replace("__ANNOTATE__",()=>e.capabilities.annotate===void 0?"":Tt).replace("__PLAN__",()=>Tn({...e,origins:n.origins,...n.document===void 0?{}:{document:n.document}}));return`<!doctype html>
1647
1647
  <html lang="en">
1648
1648
  <head>
1649
- ${['<meta charset="utf-8">',n.cspMeta===!1?null:`<meta http-equiv="Content-Security-Policy" content="${kn(t)}">`,'<meta name="referrer" content="no-referrer">','<meta http-equiv="x-dns-prefetch-control" content="off">'].filter(i=>i!==null).join(`
1649
+ ${['<meta charset="utf-8">',n.cspMeta===!1?null:`<meta http-equiv="Content-Security-Policy" content="${Sn(t)}">`,'<meta name="referrer" content="no-referrer">','<meta http-equiv="x-dns-prefetch-control" content="off">'].filter(i=>i!==null).join(`
1650
1650
  `)}
1651
1651
  <meta name="viewport" content="width=device-width, initial-scale=1">
1652
- <title>${Sn(n.title??"Content")}</title>
1652
+ <title>${Cn(n.title??"Content")}</title>
1653
1653
  <style${o}>
1654
- ${Tn}
1654
+ ${An}
1655
1655
  </style>
1656
1656
  </head>
1657
1657
  <body>
@@ -1659,4 +1659,4 @@ ${Tn}
1659
1659
  <script${o}>${r}<\/script>
1660
1660
  </body>
1661
1661
  </html>
1662
- `}function Rt(e){it(e);let t=Ze(e),n=et(t),o=Y(e);return{config:e,cspDirectives:t,csp:n,sandbox:pe(e).join(" "),allow:tt(e),referrerPolicy:"no-referrer",embedderFrameSources:nt(e),shell:o,shellDocument:r=>{if(o===null)throw new TypeError("url mode has no shell: the frame loads the app's own document");return Et(o,n,r)},guide:r=>bt(e,r),toolDescription:()=>xt(e)}}async function Mt(e,t,n,o,r){let a=await e.locate(t,r);return Ct(a,n.contentOrigins,o),{kind:"url",url:new URL(a.url).href,origin:a.origin,...a.reports===!0?{reports:!0}:{}}}var ve="porthole/notifications/frame-status";var Pt=400,An=["framing","cookies","sign-in","session","upstream","denied","not-found","error"];function En(e){if(e===null||typeof e!="object")return null;let t=e;if(t.jsonrpc!=="2.0"||t.method!==ve)return null;let n=t.params;return n===null||typeof n!="object"?null:n.state==="entering"?{state:"entering"}:n.state!=="blocked"?null:{state:"blocked",reason:An.includes(n.reason)?n.reason:"error",...typeof n.status=="number"&&Number.isInteger(n.status)?{status:n.status}:{},...typeof n.code=="string"&&/^[a-z0-9-]{1,40}$/u.test(n.code)?{code:n.code}:{}}}function $t(e){let{surface:t,source:n,speaks:o}=e,r=n.kind==="url"&&n.reports===!0,a=null,i=!1,s=!1,c=0,l=new Set,f=(p,y)=>{let C=setTimeout(()=>{l.delete(C),y()},p);l.add(C)},k=()=>{for(let p of l)clearTimeout(p);l.clear()},m=()=>{k(),d(),u()},v=p=>{a===null?(a=p.state,k(),e.onOutcome(p)):a==="loaded"&&p.state==="blocked"&&(a="blocked",e.onOutcome(p))},d=t.transport.listen(p=>{i=!0;let y=En(p);y?.state==="entering"?s=!0:y?.state==="blocked"&&v({state:"blocked",reason:y.reason??"error",...y.status===void 0?{}:{status:y.status},...y.code===void 0?{}:{code:y.code}})}),g=()=>f(Pt,()=>{i||v({state:"blocked",reason:"framing"})}),u=t.onLoad(()=>{if(c+=1,a===null){if(o){n.kind==="url"&&g();return}if(!r){f(Pt,()=>v({state:"loaded"}));return}s&&c>=2?v({state:"loaded"}):s||g()}});return f(e.timeoutMs,()=>v({state:"timeout"})),{initialized:()=>v({state:"loaded"}),stop:m}}function Lt(e,t,n=window,o){let r=new Set,a=!1,i=c=>{let l=e();if(!(a||l===null||c.source!==l)&&!(c.origin!==t&&(o===void 0||c.origin!==o.origin||!o.accept(c.data))))for(let f of r)f(c.data)};n.addEventListener("message",i);let s=t==="null"?"*":t;return{send(c){a||e()?.postMessage(c,s)},listen(c){return r.add(c),()=>r.delete(c)},close(){a=!0,r.clear(),n.removeEventListener("message",i)}}}var Rn=e=>e!==null&&typeof e=="object"&&e.jsonrpc==="2.0"&&e.method===ve,Nt={name:"web",createSurface(e,t){let n=e.ownerDocument.createElement("iframe");n.setAttribute("sandbox",t.sandbox),n.setAttribute("allow",t.allow),n.setAttribute("referrerpolicy",t.referrerPolicy),n.setAttribute("loading","eager"),n.title=t.title,n.dataset.portholeFrame="",Object.assign(n.style,{display:"block",width:"100%",border:"0",background:"transparent",colorScheme:t.colorScheme,...t.fill===!0?{height:"100%",minHeight:`${Math.max(0,Math.round(t.initialHeightPx))}px`}:{height:`${Math.max(0,Math.round(t.initialHeightPx))}px`}});let o=t.source.kind==="srcdoc"?"null":t.source.origin;t.source.kind==="srcdoc"?n.srcdoc=t.source.html:n.src=t.source.url;let r=new Set,a=new Set,i=0;n.addEventListener("load",()=>{i+=1;for(let f of a)f();if(i>1)for(let f of r)f()}),e.append(n);let s=e.ownerDocument.defaultView??window,c=s.origin,l=Lt(()=>n.contentWindow,o,s,o==="null"||c==="null"||c===o?void 0:{origin:c,accept:Rn});return{transport:l,element:n,setHeight(f){t.fill!==!0&&(n.style.height=`${Math.max(0,Math.round(f))}px`)},setColorScheme(f){n.style.colorScheme=f},userActivation(){let f=s.navigator.userActivation;return f===void 0?void 0:f.isActive},onLoad(f){return a.add(f),()=>a.delete(f)},onNavigated(f){return r.add(f),()=>r.delete(f)},destroy(){r.clear(),a.clear(),l.close(),n.remove()}}}};var It={invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},ze=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ot=e=>typeof e=="string"&&e.length<=256||typeof e=="number"&&Number.isSafeInteger(e);function Dt(e){if(!ze(e)||e.jsonrpc!=="2.0"||e.params!==void 0&&!ze(e.params))return null;if(typeof e.method=="string")return e.method.length===0||e.method.length>256?null:e.id===void 0||Ot(e.id)?e:null;if(!Ot(e.id)||e.method!==void 0)return null;let t="result"in e,n="error"in e;if(t===n)return null;if(n){let o=e.error;if(!ze(o)||typeof o.code!="number"||typeof o.message!="string")return null}return e}var Mn=new Set(["error","critical","alert","emergency"]),Pn={[M.message]:{capability:"sendPrompt",args:e=>({text:Array.isArray(e.content)?e.content.map(t=>{let n=t;return n!==null&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string"?n.text:""}).join(""):void 0})},[M.openLink]:{capability:"openLink",args:e=>({url:e.url})},[ct]:{capability:"copyText",args:e=>({text:e.text})},[M.downloadFile]:{capability:"downloadFile",args:e=>({contents:e.contents})},[M.callTool]:{capability:"callTool",args:e=>({name:e.name,arguments:e.arguments})},[M.readResource]:{capability:"readData",args:e=>({uri:e.uri})},[M.updateModelContext]:{capability:"setModelContext",args:e=>({content:e.content,structuredContent:e.structuredContent})}};function $n(e,t){let n=e==="sendPrompt"||e==="openLink"||e==="downloadFile"||e==="copyText";return t.ok?n?{result:t.value===!0?{}:{isError:!0}}:{result:t.value??{}}:n?{result:{isError:!0}}:{error:{code:-32e3,message:`Refused (${t.refusal})`}}}function Ln(e){let t={};return e("openLink")&&(t.openLinks={}),e("sendPrompt")&&(t.message={text:{}}),e("downloadFile")&&(t.downloadFile={}),e("callTool")&&(t.serverTools={}),e("readData")&&(t.serverResources={}),e("setModelContext")&&(t.updateModelContext={text:{}}),e("reportError")&&(t.logging={}),t}var Ht={name:"porthole-shell",connect(e){let{transport:t,bridge:n}=e,o=!1,r=!1,a=null,i=null,s=!1,c=1,l=new Map,f=(u,p)=>t.send({jsonrpc:"2.0",id:u,...p}),k=(u,p)=>t.send({jsonrpc:"2.0",method:u,params:p}),m=()=>{if(!(!o||r||i===null||s)){if(i.partial){a!==i.html&&(a=i.html,k(M.toolInputPartial,{arguments:{html:i.html}}));return}s=!0,k(M.toolInput,{arguments:{html:i.html}})}},v=async u=>{let p=u.params??{};if(u.method===M.initialize){f(u.id,{result:{protocolVersion:he,hostInfo:e.hostInfo,hostCapabilities:Ln(A=>n.declared(A)),hostContext:e.hostContext()}});return}if(u.method==="ping"){f(u.id,{result:{}});return}if(u.method===M.requestDisplayMode){f(u.id,{result:{mode:"inline"}});return}let y=Pn[u.method];if(y===void 0){f(u.id,{error:{code:It.methodNotFound,message:`${u.method} isn't offered here`}});return}let C=await n.call(y.capability,y.args(p));r||f(u.id,$n(y.capability,C))},d=(u,p)=>{switch(u){case M.initialized:o||(o=!0,e.emit({type:"initialized"}),m());return;case M.sizeChanged:n.call("resize",{height:p.height,width:p.width});return;case M.log:if(Mn.has(String(p.level))){let y=p.data;n.call("reportError",{message:typeof y=="string"?y:JSON.stringify(y??null).slice(0,2e3)})}return;case M.requestTeardown:e.emit({type:"teardown-requested"});return;default:return}},g=t.listen(u=>{let p=Dt(u);if(!(p===null||r)){if("method"in p){"id"in p?v(p):d(p.method,p.params??{});return}l.get(p.id)?.(p),l.delete(p.id)}});return{setContent(u,p){s||(i={html:u,partial:p?.partial===!0},m())},hostContextChanged(u){o&&!r&&k(M.hostContextChanged,{...u})},teardown(){if(!o||r)return Promise.resolve();let u=`teardown-${c++}`;return new Promise(p=>{let y=setTimeout(()=>{l.delete(u),p()},500);l.set(u,()=>{clearTimeout(y),p()}),t.send({jsonrpc:"2.0",id:u,method:M.resourceTeardown,params:{}})})},close(){r=!0,g(),l.clear()}}}};var Nn=15e3,On=3,In=new Set(["hostContextChanged","teardown","close"]),Dn={[O.selected]:"selected",[O.unselected]:"unselected",[O.cancelled]:"cancelled",[O.anchored]:"anchored"},_t=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Hn=new Set(lt);function Fe(e,t={}){let n=Rt(e);if((e.isolation==="domain"||e.isolation==="external")&&t.locator===void 0)throw new TypeError(`${e.isolation} isolation needs a locator (HostOptions.locator)`);let o=e.mode!=="url",r=t.adapter??Ht,a=t.platform??Nt,i=t.hostInfo??{name:"porthole",version:"0"};return{compiled:n,mount(s,c){let l={...t.handlers,...c.handlers},f=D(e).filter(h=>B(h).served==="handler"&&l[h]===void 0);if(f.length>0)throw new TypeError(`No handler for the declared capabilities: ${f.join(", ")}`);if(e.isolation!=="opaque"&&c.instance===void 0)throw new TypeError(`${e.isolation} isolation needs MountOptions.instance`);let k=new Map,m=(h,b)=>{for(let E of k.get(h)??[])E(b)},v=h=>{m("contentError",{message:h}),m("error",{message:h,source:"content"})},d=(h,b)=>{m("hostError",{message:h,kind:b}),m("error",{message:h,source:"host"})},g=e.theme.documents==="never",u=g?"light":c.scheme,p=c.initialHeightPx??0,y=null,C=null,A=!1,Te=0,ae=0,Ae=null,Ee=null,Q=null,G=s.ownerDocument.defaultView,Re=new Map,We=e.capabilities.annotate!==void 0,L=null,W=[],z=null,se=!1,U=(h,b)=>{se&&y!==null&&y.transport.send({jsonrpc:"2.0",method:h,params:b})},Bt=()=>{W.length>0&&U(O.show,{marks:W,...z===null?{}:{active:z}}),L!==null&&U(O.start,{...L})},Ut=(h,b)=>{if(!_t(h)||h.jsonrpc!=="2.0"||"id"in h||typeof h.method!="string")return;let E=Dn[h.method];if(E===void 0)return;let R=de({..._t(h.params)?h.params:{},type:E});if(R===null){b.call("annotate",null);return}switch(R.type){case"selected":{let P=R.anchor.kind;if(L===null||!(P==="element"?L.elements:L.text))return;P==="element"&&(L=L.text?{elements:!1,text:!0}:null);break}case"unselected":if(L?.text!==!0)return;break;case"cancelled":if(L?.elements!==!0)return;L=L.text?{elements:!1,text:!0}:null;break;case"anchored":{let P=new Set(W.map(ee=>ee.id)),T=R.results.filter(ee=>P.has(ee.id));if(T.length===0)return;R={type:"anchored",results:T};break}}b.call("annotate",R)},Z=h=>{if(!We)throw new TypeError(`annotations.${h}: the config doesn't declare annotate`)},Vt={start(h){Z("start"),L=Ke(h),U(O.start,{...L})},stop(){Z("stop"),L=null,U(O.stop,{})},show(h){Z("show"),W=Xe(h),z!==null&&!W.some(b=>b.id===z)&&(z=null),U(O.show,{marks:W,...z===null?{}:{active:z}})},focus(h){if(Z("focus"),!W.some(b=>b.id===h))throw new TypeError(`annotations.focus: no mark ${JSON.stringify(h)} is shown`);z=h,U(O.focus,{id:h})},clear(){Z("clear"),W=[],z=null,U(O.clear,{})}},ie=()=>{let h=s.getBoundingClientRect().width,b=ut(e.theme,u,t.theme?.(u)),E={},R={};for(let[P,T]of Object.entries(b))(Hn.has(P)?E:R)[P]=T;return{theme:u,styles:{variables:E},...Object.keys(R).length===0?{}:{[dt]:{variables:R}},displayMode:"inline",availableDisplayModes:["inline"],...h>0?{containerDimensions:{maxWidth:Math.round(h)}}:{},...G===null?{}:{locale:G.navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web"},...t.hostContext?.()}},Gt=h=>{switch(h.type){case"resize":{let b=Math.min(e.limits.maxHeightPx,Math.max(e.limits.minHeightPx,Math.ceil(h.height)));p=b,y?.setHeight(b),m("resize",{height:b,...h.width===void 0?{}:{width:h.width}});return}case"error":v(h.message);return;case"refused":m("refused",{capability:h.capability,refusal:h.refusal});return;case"muted":m("muted",void 0);return;case"annotation":m("annotation",h.report);return}},Me=()=>{se=!1,Ae?.abort(),Ae=null,Ee?.stop(),Ee=null,C?.close(),C=null,y?.destroy(),y=null},Be=h=>{let b=a.createSurface(s,{source:h,title:c.title,sandbox:n.sandbox,allow:n.allow,referrerPolicy:n.referrerPolicy,colorScheme:u,...o&&c.fill!==!0&&e.layout.kind!=="fill"?{initialHeightPx:p}:{fill:!0,initialHeightPx:e.limits.minHeightPx}});y=b;let E=$t({surface:b,source:h,speaks:o,timeoutMs:e.limits.loadTimeoutMs??Nn,onOutcome:T=>m("outcome",T)});if(Ee=E,!o){let T=!1;b.onLoad(()=>{T||(T=!0,m("initialized",void 0))});return}let R=rt({config:e,display:{id:c.displayId,title:c.title},handlers:l,...t.confirm===void 0?{}:{confirm:t.confirm},userActivation:()=>b.userActivation(),onEvent:Gt});We&&b.transport.listen(T=>Ut(T,R));let P=r.connect({display:{id:c.displayId,title:c.title},compiled:n,transport:b.transport,bridge:R,hostInfo:i,hostContext:ie,emit:T=>{T.type==="initialized"&&(E.initialized(),se||(se=!0,Bt()),m("initialized",void 0))},...c.document===void 0?{}:{document:c.document}});C=P;for(let[T,ee]of Re)P[T]?.(...ee);b.onNavigated(()=>{m("navigated",void 0),Te<On?(Te+=1,Pe()):(Me(),v("The content kept navigating its frame away; it was stopped."))})},Pe=()=>{if(Me(),A)return;if(ae+=1,e.isolation==="opaque"){Be({kind:"srcdoc",html:n.shellDocument({origins:[s.ownerDocument.defaultView?.location.origin??""],title:c.title,..._n(t.nonce),...c.document===void 0?{}:{document:c.document}})});return}let h=ae,b=new AbortController;Ae=b;let E=t.locator,R=c.instance;if(E===void 0||R===void 0)return;let P=s.ownerDocument.defaultView?.location.origin??"";Mt(E,R,e,P,b.signal).then(T=>{h===ae&&!A&&Be(T)},T=>{h===ae&&!b.signal.aborted&&(d(T instanceof Error?T.message:String(T),"locate"),m("outcome",{state:"blocked",reason:"locate"}))})};Pe();let Jt={displayId:c.displayId,annotations:Vt,setTheme(h){if(!g){if(u=h,y?.setColorScheme(h),G===null){C?.hostContextChanged(ie());return}Q!==null&&G.cancelAnimationFrame(Q),Q=G.requestAnimationFrame(()=>{Q=G.requestAnimationFrame(()=>{Q=null,C?.hostContextChanged(ie())})})}},refreshTheme(){C?.hostContextChanged(ie())},on(h,b){let E=k.get(h)??new Set;return E.add(b),k.set(h,E),()=>E.delete(b)},reload(){Te=0,Pe()},destroy(){A=!0,Me(),k.clear()}};return new Proxy(Jt,{get(h,b,E){return typeof b=="string"&&!(b in h)&&!In.has(b)?(...R)=>{Re.delete(b),Re.set(b,R);let P=C?.[b];return typeof P=="function"?P.apply(C,R):void 0}:Reflect.get(h,b,E)}})}}}function _n(e){let t=typeof e=="function"?e():e;return t===void 0||t===""?{}:{nonce:t}}var ke=class extends Error{status;code;constructor(t,n,o){super(t),this.name="LocateError",this.status=n,this.code=o}},qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function jt(e,t={}){return{async locate(n,o){let r=typeof t.headers=="function"?t.headers():t.headers,a=new Headers(r);a.set("content-type","application/json"),a.set("accept","application/json");let i=await(t.fetch??fetch)(e,{method:"POST",headers:a,credentials:t.credentials??"same-origin",redirect:"error",body:JSON.stringify({instance:n}),...o===void 0?{}:{signal:o}}),s=await i.json().catch(()=>null);if(!i.ok){let c=qe(s)&&qe(s.error)?s.error:{},l=typeof c.code=="string"?c.code:"failed";throw l==="not-served"&&t.onNotServed?.(),new ke(typeof c.message=="string"?c.message:`The app's issue endpoint answered ${i.status}`,i.status,l)}if(!qe(s)||typeof s.url!="string"||typeof s.origin!="string"||s.reports!==void 0&&typeof s.reports!="boolean")throw new ke("The app's issue endpoint gave no frame location",i.status,"bad-location");return{url:s.url,origin:s.origin,...typeof s.reports=="boolean"?{reports:s.reports}:{}}}}}var jn=["initialized","resize","error","contentError","hostError","navigated","refused","muted","outcome","annotation"],Se=document.currentScript instanceof HTMLScriptElement&&document.currentScript.nonce!==""?document.currentScript.nonce:void 0,$=new Map,Ce=0,zt=e=>new Promise(t=>setTimeout(t,e));function zn(){let e=document.getElementById("porthole-conformance");return e===null&&(e=document.createElement("main"),e.id="porthole-conformance",e.style.cssText="position:fixed;inset:0;overflow:auto;z-index:2147483000;background:#fff;color:#000;padding:8px",document.body.append(e)),e}function Ft(e,t,n){let o=document.createElement("section");return o.id=`porthole-display-${e}`,o.style.width=`${t}px`,n!==void 0&&(o.style.height=`${n}px`),zn().append(o),o}function qt(e){let t=(n,o)=>r=>(e.push({capability:n,args:r}),o);return{sendPrompt:t("sendPrompt",!0),openLink:t("openLink",!0),downloadFile:t("downloadFile",!0),callTool:t("callTool",{content:[]}),readData:t("readData",{contents:[]}),setModelContext:t("setModelContext",void 0),copyText:t("copyText",!0)}}function Wt(e,t){for(let n of jn)t.handle.on(n,o=>t.events.push({type:n,detail:o}));$.set(e,t)}addEventListener("message",e=>{for(let t of $.values())t.frame?.contentWindow===e.source&&e.origin===t.origin&&t.received.push(e.data)});var Fn={async launch(e){let t=Ce;Ce+=1;let n=Ft(t,e.widthPx??600,e.heightPx),o=[],r=[],i=Fe(e.config,{handlers:qt(o),...e.confirms===!1?{}:{confirm:l=>new Promise(f=>r.push({request:l,resolve:f}))},theme:l=>e.hostTheme?.[l]??{},hostInfo:{name:"porthole-conformance",version:"1"},...Se===void 0?{}:{nonce:Se}}).mount(n,{displayId:`display-${t}`,title:e.title??"Probe",scheme:e.scheme??"light",...e.document===void 0?{}:{document:e.document}}),s={handle:i,calls:o,events:[],confirmations:r,received:[],origin:null,failure:null,frame:null},c=new Promise(l=>i.on("initialized",()=>l()));if(Wt(t,s),e.document===void 0){await Promise.race([c,zt(5e3)]);for(let l of e.partials??[])i.setContent(l,{partial:!0}),await zt(150);e.content!==void 0&&i.setContent(e.content)}return t},show(e,t,n,o){let r=Ce;Ce+=1;let a=Ft(r,600,400),i=[],s={handle:null,calls:i,events:[],confirmations:[],received:[],origin:null,failure:null,frame:null},c="issue"in n?jt(n.issue,n.headers===void 0?{}:{headers:n.headers}):{locate:()=>Promise.resolve(n.location)},l={async locate(m,v){try{let d=await c.locate(m,v);return s.origin=d.origin,d}catch(d){throw s.failure=d instanceof Error?`${d.name}: ${d.message}`:String(d),d}}},f=Fe(e,{handlers:qt(i),locator:l,hostInfo:{name:"porthole-conformance",version:"1"},...Se===void 0?{}:{nonce:Se}}).mount(a,{displayId:`display-${r}`,title:"Probe",scheme:"light",instance:t});s.handle=f,Wt(r,s);let k=()=>{s.frame=a.querySelector("iframe"),s.frame===null&&requestAnimationFrame(k)};return k(),o!==void 0&&f.setContent(o),r},origin:e=>$.get(e)?.origin??null,failure:e=>$.get(e)?.failure??null,received:e=>$.get(e)?.received??[],post(e,t){let n=$.get(e);n?.frame?.contentWindow&&n.origin!==null&&n.frame.contentWindow.postMessage(t,n.origin)},setContent(e,t,n){$.get(e)?.handle.setContent(t,{partial:n})},calls:e=>$.get(e)?.calls??[],events:e=>$.get(e)?.events??[],errors:e=>($.get(e)?.events??[]).flatMap(t=>t.type==="error"?[t.detail.message]:[]),pendingConfirmations:e=>$.get(e)?.confirmations.length??0,answer(e,t){let n=$.get(e)?.confirmations.shift();return n===void 0?null:(n.resolve(t),n.request)},setTheme:(e,t)=>$.get(e)?.handle.setTheme(t),destroy(e){$.get(e)?.handle.destroy(),document.getElementById(`porthole-display-${e}`)?.remove(),$.delete(e)}};window.portholeConformance=Fn;document.documentElement.dataset.portholeConformance="ready";})();
1662
+ `}function Rt(e){it(e);let t=Ze(e),n=et(t),o=Y(e);return{config:e,cspDirectives:t,csp:n,sandbox:pe(e).join(" "),allow:tt(e),referrerPolicy:"no-referrer",embedderFrameSources:nt(e),shell:o,shellDocument:r=>{if(o===null)throw new TypeError("url mode has no shell: the frame loads the app's own document");return Et(o,n,r)},guide:r=>bt(e,r),toolDescription:()=>xt(e)}}async function Mt(e,t,n,o,r){let a=await e.locate(t,r);return Ct(a,n.contentOrigins,o),{kind:"url",url:new URL(a.url).href,origin:a.origin,...a.reports===!0?{reports:!0}:{}}}var ve="porthole/notifications/frame-status";var Pt=400,En=["framing","cookies","sign-in","session","upstream","denied","not-found","error"];function Rn(e){if(e===null||typeof e!="object")return null;let t=e;if(t.jsonrpc!=="2.0"||t.method!==ve)return null;let n=t.params;return n===null||typeof n!="object"?null:n.state==="entering"?{state:"entering"}:n.state!=="blocked"?null:{state:"blocked",reason:En.includes(n.reason)?n.reason:"error",...typeof n.status=="number"&&Number.isInteger(n.status)?{status:n.status}:{},...typeof n.code=="string"&&/^[a-z0-9-]{1,40}$/u.test(n.code)?{code:n.code}:{}}}function $t(e){let{surface:t,source:n,speaks:o}=e,r=n.kind==="url"&&n.reports===!0,a=null,i=!1,s=!1,c=0,l=new Set,f=(p,y)=>{let C=setTimeout(()=>{l.delete(C),y()},p);l.add(C)},k=()=>{for(let p of l)clearTimeout(p);l.clear()},m=()=>{k(),d(),u()},v=p=>{a===null?(a=p.state,k(),e.onOutcome(p)):a==="loaded"&&p.state==="blocked"&&(a="blocked",e.onOutcome(p))},d=t.transport.listen(p=>{i=!0;let y=Rn(p);y?.state==="entering"?s=!0:y?.state==="blocked"&&v({state:"blocked",reason:y.reason??"error",...y.status===void 0?{}:{status:y.status},...y.code===void 0?{}:{code:y.code}})}),g=()=>f(Pt,()=>{i||v({state:"blocked",reason:"framing"})}),u=t.onLoad(()=>{if(c+=1,a===null){if(o){n.kind==="url"&&g();return}if(!r){f(Pt,()=>v({state:"loaded"}));return}s&&c>=2?v({state:"loaded"}):s||g()}});return f(e.timeoutMs,()=>v({state:"timeout"})),{initialized:()=>v({state:"loaded"}),stop:m}}function Lt(e,t,n=window,o){let r=new Set,a=!1,i=c=>{let l=e();if(!(a||l===null||c.source!==l)&&!(c.origin!==t&&(o===void 0||c.origin!==o.origin||!o.accept(c.data))))for(let f of r)f(c.data)};n.addEventListener("message",i);let s=t==="null"?"*":t;return{send(c){a||e()?.postMessage(c,s)},listen(c){return r.add(c),()=>r.delete(c)},close(){a=!0,r.clear(),n.removeEventListener("message",i)}}}var Mn=e=>e!==null&&typeof e=="object"&&e.jsonrpc==="2.0"&&e.method===ve,Nt={name:"web",createSurface(e,t){let n=e.ownerDocument.createElement("iframe");n.setAttribute("sandbox",t.sandbox),n.setAttribute("allow",t.allow),n.setAttribute("referrerpolicy",t.referrerPolicy),n.setAttribute("loading","eager"),n.title=t.title,n.dataset.portholeFrame="",Object.assign(n.style,{display:"block",width:"100%",border:"0",background:"transparent",colorScheme:t.colorScheme,...t.fill===!0?{height:"100%",minHeight:`${Math.max(0,Math.round(t.initialHeightPx))}px`}:{height:`${Math.max(0,Math.round(t.initialHeightPx))}px`}});let o=t.source.kind==="srcdoc"?"null":t.source.origin;t.source.kind==="srcdoc"?n.srcdoc=t.source.html:n.src=t.source.url;let r=new Set,a=new Set,i=0;n.addEventListener("load",()=>{i+=1;for(let f of a)f();if(i>1)for(let f of r)f()}),e.append(n);let s=e.ownerDocument.defaultView??window,c=s.origin,l=Lt(()=>n.contentWindow,o,s,o==="null"||c==="null"||c===o?void 0:{origin:c,accept:Mn});return{transport:l,element:n,setHeight(f){t.fill!==!0&&(n.style.height=`${Math.max(0,Math.round(f))}px`)},setColorScheme(f){n.style.colorScheme=f},userActivation(){let f=s.navigator.userActivation;return f===void 0?void 0:f.isActive},onLoad(f){return a.add(f),()=>a.delete(f)},onNavigated(f){return r.add(f),()=>r.delete(f)},destroy(){r.clear(),a.clear(),l.close(),n.remove()}}}};var It={invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},ze=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ot=e=>typeof e=="string"&&e.length<=256||typeof e=="number"&&Number.isSafeInteger(e);function Dt(e){if(!ze(e)||e.jsonrpc!=="2.0"||e.params!==void 0&&!ze(e.params))return null;if(typeof e.method=="string")return e.method.length===0||e.method.length>256?null:e.id===void 0||Ot(e.id)?e:null;if(!Ot(e.id)||e.method!==void 0)return null;let t="result"in e,n="error"in e;if(t===n)return null;if(n){let o=e.error;if(!ze(o)||typeof o.code!="number"||typeof o.message!="string")return null}return e}var Pn=new Set(["error","critical","alert","emergency"]),$n={[M.message]:{capability:"sendPrompt",args:e=>({text:Array.isArray(e.content)?e.content.map(t=>{let n=t;return n!==null&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string"?n.text:""}).join(""):void 0})},[M.openLink]:{capability:"openLink",args:e=>({url:e.url})},[ct]:{capability:"copyText",args:e=>({text:e.text})},[M.downloadFile]:{capability:"downloadFile",args:e=>({contents:e.contents})},[M.callTool]:{capability:"callTool",args:e=>({name:e.name,arguments:e.arguments})},[M.readResource]:{capability:"readData",args:e=>({uri:e.uri})},[M.updateModelContext]:{capability:"setModelContext",args:e=>({content:e.content,structuredContent:e.structuredContent})}};function Ln(e,t){let n=e==="sendPrompt"||e==="openLink"||e==="downloadFile"||e==="copyText";return t.ok?n?{result:t.value===!0?{}:{isError:!0}}:{result:t.value??{}}:n?{result:{isError:!0}}:{error:{code:-32e3,message:`Refused (${t.refusal})`}}}function Nn(e){let t={};return e("openLink")&&(t.openLinks={}),e("sendPrompt")&&(t.message={text:{}}),e("downloadFile")&&(t.downloadFile={}),e("callTool")&&(t.serverTools={}),e("readData")&&(t.serverResources={}),e("setModelContext")&&(t.updateModelContext={text:{}}),e("reportError")&&(t.logging={}),t}var Ht={name:"porthole-shell",connect(e){let{transport:t,bridge:n}=e,o=!1,r=!1,a=null,i=null,s=!1,c=1,l=new Map,f=(u,p)=>t.send({jsonrpc:"2.0",id:u,...p}),k=(u,p)=>t.send({jsonrpc:"2.0",method:u,params:p}),m=()=>{if(!(!o||r||i===null||s)){if(i.partial){a!==i.html&&(a=i.html,k(M.toolInputPartial,{arguments:{html:i.html}}));return}s=!0,k(M.toolInput,{arguments:{html:i.html}})}},v=async u=>{let p=u.params??{};if(u.method===M.initialize){f(u.id,{result:{protocolVersion:he,hostInfo:e.hostInfo,hostCapabilities:Nn(A=>n.declared(A)),hostContext:e.hostContext()}});return}if(u.method==="ping"){f(u.id,{result:{}});return}if(u.method===M.requestDisplayMode){f(u.id,{result:{mode:"inline"}});return}let y=$n[u.method];if(y===void 0){f(u.id,{error:{code:It.methodNotFound,message:`${u.method} isn't offered here`}});return}let C=await n.call(y.capability,y.args(p));r||f(u.id,Ln(y.capability,C))},d=(u,p)=>{switch(u){case M.initialized:o||(o=!0,e.emit({type:"initialized"}),m());return;case M.sizeChanged:n.call("resize",{height:p.height,width:p.width});return;case M.log:if(Pn.has(String(p.level))){let y=p.data;n.call("reportError",{message:typeof y=="string"?y:JSON.stringify(y??null).slice(0,2e3)})}return;case M.requestTeardown:e.emit({type:"teardown-requested"});return;default:return}},g=t.listen(u=>{let p=Dt(u);if(!(p===null||r)){if("method"in p){"id"in p?v(p):d(p.method,p.params??{});return}l.get(p.id)?.(p),l.delete(p.id)}});return{setContent(u,p){s||(i={html:u,partial:p?.partial===!0},m())},hostContextChanged(u){o&&!r&&k(M.hostContextChanged,{...u})},teardown(){if(!o||r)return Promise.resolve();let u=`teardown-${c++}`;return new Promise(p=>{let y=setTimeout(()=>{l.delete(u),p()},500);l.set(u,()=>{clearTimeout(y),p()}),t.send({jsonrpc:"2.0",id:u,method:M.resourceTeardown,params:{}})})},close(){r=!0,g(),l.clear()}}}};var On=15e3,In=3,Dn=new Set(["hostContextChanged","teardown","close"]),Hn={[O.selected]:"selected",[O.unselected]:"unselected",[O.cancelled]:"cancelled",[O.anchored]:"anchored"},_t=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_n=new Set(lt);function Fe(e,t={}){let n=Rt(e);if((e.isolation==="domain"||e.isolation==="external")&&t.locator===void 0)throw new TypeError(`${e.isolation} isolation needs a locator (HostOptions.locator)`);let o=e.mode!=="url",r=t.adapter??Ht,a=t.platform??Nt,i=t.hostInfo??{name:"porthole",version:"0"};return{compiled:n,mount(s,c){let l={...t.handlers,...c.handlers},f=D(e).filter(h=>U(h).served==="handler"&&l[h]===void 0);if(f.length>0)throw new TypeError(`No handler for the declared capabilities: ${f.join(", ")}`);if(e.isolation!=="opaque"&&c.instance===void 0)throw new TypeError(`${e.isolation} isolation needs MountOptions.instance`);let k=new Map,m=(h,b)=>{for(let E of k.get(h)??[])E(b)},v=h=>{m("contentError",{message:h}),m("error",{message:h,source:"content"})},d=(h,b)=>{m("hostError",{message:h,kind:b}),m("error",{message:h,source:"host"})},g=e.theme.documents==="never",u=g?"light":c.scheme,p=c.initialHeightPx??0,y=null,C=null,A=!1,Te=0,ae=0,Ae=null,Ee=null,Q=null,G=s.ownerDocument.defaultView,Re=new Map,We=e.capabilities.annotate!==void 0,L=null,W=[],z=null,se=!1,B=(h,b)=>{se&&y!==null&&y.transport.send({jsonrpc:"2.0",method:h,params:b})},Ut=()=>{W.length>0&&B(O.show,{marks:W,...z===null?{}:{active:z}}),L!==null&&B(O.start,{...L})},Bt=(h,b)=>{if(!_t(h)||h.jsonrpc!=="2.0"||"id"in h||typeof h.method!="string")return;let E=Hn[h.method];if(E===void 0)return;let R=de({..._t(h.params)?h.params:{},type:E});if(R===null){b.call("annotate",null);return}switch(R.type){case"selected":{let P=R.anchor.kind;if(L===null||!(P==="element"?L.elements:L.text))return;P==="element"&&(L=L.text?{elements:!1,text:!0}:null);break}case"unselected":if(L?.text!==!0)return;break;case"cancelled":if(L?.elements!==!0)return;L=L.text?{elements:!1,text:!0}:null;break;case"anchored":{let P=new Set(W.map(ee=>ee.id)),T=R.results.filter(ee=>P.has(ee.id));if(T.length===0)return;R={type:"anchored",results:T};break}}b.call("annotate",R)},Z=h=>{if(!We)throw new TypeError(`annotations.${h}: the config doesn't declare annotate`)},Vt={start(h){Z("start"),L=Ke(h),B(O.start,{...L})},stop(){Z("stop"),L=null,B(O.stop,{})},show(h){Z("show"),W=Xe(h),z!==null&&!W.some(b=>b.id===z)&&(z=null),B(O.show,{marks:W,...z===null?{}:{active:z}})},focus(h){if(Z("focus"),!W.some(b=>b.id===h))throw new TypeError(`annotations.focus: no mark ${JSON.stringify(h)} is shown`);z=h,B(O.focus,{id:h})},clear(){Z("clear"),W=[],z=null,B(O.clear,{})}},ie=()=>{let h=s.getBoundingClientRect().width,b=ut(e.theme,u,t.theme?.(u)),E={},R={};for(let[P,T]of Object.entries(b))(_n.has(P)?E:R)[P]=T;return{theme:u,styles:{variables:E},...Object.keys(R).length===0?{}:{[dt]:{variables:R}},displayMode:"inline",availableDisplayModes:["inline"],...h>0?{containerDimensions:{maxWidth:Math.round(h)}}:{},...G===null?{}:{locale:G.navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:"web"},...t.hostContext?.()}},Gt=h=>{switch(h.type){case"resize":{let b=Math.min(e.limits.maxHeightPx,Math.max(e.limits.minHeightPx,Math.ceil(h.height)));p=b,y?.setHeight(b),m("resize",{height:b,...h.width===void 0?{}:{width:h.width}});return}case"error":v(h.message);return;case"refused":m("refused",{capability:h.capability,refusal:h.refusal});return;case"muted":m("muted",void 0);return;case"annotation":m("annotation",h.report);return}},Me=()=>{se=!1,Ae?.abort(),Ae=null,Ee?.stop(),Ee=null,C?.close(),C=null,y?.destroy(),y=null},Ue=h=>{let b=a.createSurface(s,{source:h,title:c.title,sandbox:n.sandbox,allow:n.allow,referrerPolicy:n.referrerPolicy,colorScheme:u,...o&&c.fill!==!0&&e.layout.kind!=="fill"?{initialHeightPx:p}:{fill:!0,initialHeightPx:e.limits.minHeightPx}});y=b;let E=$t({surface:b,source:h,speaks:o,timeoutMs:e.limits.loadTimeoutMs??On,onOutcome:T=>m("outcome",T)});if(Ee=E,!o){let T=!1;b.onLoad(()=>{T||(T=!0,m("initialized",void 0))});return}let R=rt({config:e,display:{id:c.displayId,title:c.title},handlers:l,...t.confirm===void 0?{}:{confirm:t.confirm},userActivation:()=>b.userActivation(),onEvent:Gt});We&&b.transport.listen(T=>Bt(T,R));let P=r.connect({display:{id:c.displayId,title:c.title},compiled:n,transport:b.transport,bridge:R,hostInfo:i,hostContext:ie,emit:T=>{T.type==="initialized"&&(E.initialized(),se||(se=!0,Ut()),m("initialized",void 0))},...c.document===void 0?{}:{document:c.document}});C=P;for(let[T,ee]of Re)P[T]?.(...ee);b.onNavigated(()=>{m("navigated",void 0),Te<In?(Te+=1,Pe()):(Me(),v("The content kept navigating its frame away; it was stopped."))})},Pe=()=>{if(Me(),A)return;if(ae+=1,e.isolation==="opaque"){Ue({kind:"srcdoc",html:n.shellDocument({origins:[s.ownerDocument.defaultView?.location.origin??""],title:c.title,...jn(t.nonce),...c.document===void 0?{}:{document:c.document}})});return}let h=ae,b=new AbortController;Ae=b;let E=t.locator,R=c.instance;if(E===void 0||R===void 0)return;let P=s.ownerDocument.defaultView?.location.origin??"";Mt(E,R,e,P,b.signal).then(T=>{h===ae&&!A&&Ue(T)},T=>{h===ae&&!b.signal.aborted&&(d(T instanceof Error?T.message:String(T),"locate"),m("outcome",{state:"blocked",reason:"locate"}))})};Pe();let Jt={displayId:c.displayId,annotations:Vt,setTheme(h){if(!g){if(u=h,y?.setColorScheme(h),G===null){C?.hostContextChanged(ie());return}Q!==null&&G.cancelAnimationFrame(Q),Q=G.requestAnimationFrame(()=>{Q=G.requestAnimationFrame(()=>{Q=null,C?.hostContextChanged(ie())})})}},refreshTheme(){C?.hostContextChanged(ie())},on(h,b){let E=k.get(h)??new Set;return E.add(b),k.set(h,E),()=>E.delete(b)},reload(){Te=0,Pe()},destroy(){A=!0,Me(),k.clear()}};return new Proxy(Jt,{get(h,b,E){return typeof b=="string"&&!(b in h)&&!Dn.has(b)?(...R)=>{Re.delete(b),Re.set(b,R);let P=C?.[b];return typeof P=="function"?P.apply(C,R):void 0}:Reflect.get(h,b,E)}})}}}function jn(e){let t=typeof e=="function"?e():e;return t===void 0||t===""?{}:{nonce:t}}var ke=class extends Error{status;code;constructor(t,n,o){super(t),this.name="LocateError",this.status=n,this.code=o}},qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function jt(e,t={}){return{async locate(n,o){let r=typeof t.headers=="function"?t.headers():t.headers,a=new Headers(r);a.set("content-type","application/json"),a.set("accept","application/json");let i=await(t.fetch??fetch)(e,{method:"POST",headers:a,credentials:t.credentials??"same-origin",redirect:"error",body:JSON.stringify({instance:n}),...o===void 0?{}:{signal:o}}),s=await i.json().catch(()=>null);if(!i.ok){let c=qe(s)&&qe(s.error)?s.error:{},l=typeof c.code=="string"?c.code:"failed";throw l==="not-served"&&t.onNotServed?.(),new ke(typeof c.message=="string"?c.message:`The app's issue endpoint answered ${i.status}`,i.status,l)}if(!qe(s)||typeof s.url!="string"||typeof s.origin!="string"||s.reports!==void 0&&typeof s.reports!="boolean")throw new ke("The app's issue endpoint gave no frame location",i.status,"bad-location");return{url:s.url,origin:s.origin,...typeof s.reports=="boolean"?{reports:s.reports}:{}}}}}var zn=["initialized","resize","error","contentError","hostError","navigated","refused","muted","outcome","annotation"],Se=document.currentScript instanceof HTMLScriptElement&&document.currentScript.nonce!==""?document.currentScript.nonce:void 0,$=new Map,Ce=0,zt=e=>new Promise(t=>setTimeout(t,e));function Fn(){let e=document.getElementById("porthole-conformance");return e===null&&(e=document.createElement("main"),e.id="porthole-conformance",e.style.cssText="position:fixed;inset:0;overflow:auto;z-index:2147483000;background:#fff;color:#000;padding:8px",document.body.append(e)),e}function Ft(e,t,n){let o=document.createElement("section");return o.id=`porthole-display-${e}`,o.style.width=`${t}px`,n!==void 0&&(o.style.height=`${n}px`),Fn().append(o),o}function qt(e){let t=(n,o)=>r=>(e.push({capability:n,args:r}),o);return{sendPrompt:t("sendPrompt",!0),openLink:t("openLink",!0),downloadFile:t("downloadFile",!0),callTool:t("callTool",{content:[]}),readData:t("readData",{contents:[]}),setModelContext:t("setModelContext",void 0),copyText:t("copyText",!0)}}function Wt(e,t){for(let n of zn)t.handle.on(n,o=>t.events.push({type:n,detail:o}));$.set(e,t)}addEventListener("message",e=>{for(let t of $.values())t.frame?.contentWindow===e.source&&e.origin===t.origin&&t.received.push(e.data)});var qn={async launch(e){let t=Ce;Ce+=1;let n=Ft(t,e.widthPx??600,e.heightPx),o=[],r=[],i=Fe(e.config,{handlers:qt(o),...e.confirms===!1?{}:{confirm:l=>new Promise(f=>r.push({request:l,resolve:f}))},theme:l=>e.hostTheme?.[l]??{},hostInfo:{name:"porthole-conformance",version:"1"},...Se===void 0?{}:{nonce:Se}}).mount(n,{displayId:`display-${t}`,title:e.title??"Probe",scheme:e.scheme??"light",...e.document===void 0?{}:{document:e.document}}),s={handle:i,calls:o,events:[],confirmations:r,received:[],origin:null,failure:null,frame:null},c=new Promise(l=>i.on("initialized",()=>l()));if(Wt(t,s),e.document===void 0){await Promise.race([c,zt(5e3)]);for(let l of e.partials??[])i.setContent(l,{partial:!0}),await zt(150);e.content!==void 0&&i.setContent(e.content)}return t},show(e,t,n,o){let r=Ce;Ce+=1;let a=Ft(r,600,400),i=[],s={handle:null,calls:i,events:[],confirmations:[],received:[],origin:null,failure:null,frame:null},c="issue"in n?jt(n.issue,n.headers===void 0?{}:{headers:n.headers}):{locate:()=>Promise.resolve(n.location)},l={async locate(m,v){try{let d=await c.locate(m,v);return s.origin=d.origin,d}catch(d){throw s.failure=d instanceof Error?`${d.name}: ${d.message}`:String(d),d}}},f=Fe(e,{handlers:qt(i),locator:l,hostInfo:{name:"porthole-conformance",version:"1"},...Se===void 0?{}:{nonce:Se}}).mount(a,{displayId:`display-${r}`,title:"Probe",scheme:"light",instance:t});s.handle=f,Wt(r,s);let k=()=>{s.frame=a.querySelector("iframe"),s.frame===null&&requestAnimationFrame(k)};return k(),o!==void 0&&f.setContent(o),r},origin:e=>$.get(e)?.origin??null,failure:e=>$.get(e)?.failure??null,received:e=>$.get(e)?.received??[],post(e,t){let n=$.get(e);n?.frame?.contentWindow&&n.origin!==null&&n.frame.contentWindow.postMessage(t,n.origin)},setContent(e,t,n){$.get(e)?.handle.setContent(t,{partial:n})},calls:e=>$.get(e)?.calls??[],events:e=>$.get(e)?.events??[],errors:e=>($.get(e)?.events??[]).flatMap(t=>t.type==="error"?[t.detail.message]:[]),pendingConfirmations:e=>$.get(e)?.confirmations.length??0,answer(e,t){let n=$.get(e)?.confirmations.shift();return n===void 0?null:(n.resolve(t),n.request)},setTheme:(e,t)=>$.get(e)?.handle.setTheme(t),destroy(e){$.get(e)?.handle.destroy(),document.getElementById(`porthole-display-${e}`)?.remove(),$.delete(e)}};window.portholeConformance=qn;document.documentElement.dataset.portholeConformance="ready";})();
@@ -2,6 +2,7 @@ import { type Page, type TestType } from "@playwright/test";
2
2
  import type { PortholeConfig } from "../config/schema.ts";
3
3
  import type { FrameLocation, InstanceRef } from "../isolation/types.ts";
4
4
  import { type EntryConformanceHost } from "./entry.ts";
5
+ export { conformancePage } from "./page.ts";
5
6
  import type { ConformanceHost } from "./index.ts";
6
7
  import { type ServedConformanceHost } from "./served.ts";
7
8
  /**
@@ -40,24 +41,40 @@ export interface HostConformanceOptions {
40
41
  /** The config a served instance is framed under (the app's served config for its preset). */
41
42
  readonly config: (instance: InstanceRef) => PortholeConfig;
42
43
  /**
43
- * The instances the served cases ask for, each for the scope a case names. `shell` runs the
44
- * domain-mode cases; `artifact` (versions of one stored page), `app` (url mode) and `proxy` (the
45
- * MCP Apps sandbox proxy) run theirs where given, and are skipped (with the reason) where not.
44
+ * The instances the served cases ask for, each for the scope a case names (may be async: a
45
+ * page published on demand, `onDemand`). Give what the app serves; the cases for the rest are
46
+ * skipped, each with its reason:
47
+ * - `shell`: a served shell (domain mode). An app that serves only stored pages leaves it out:
48
+ * the domain-mode cases then run on `artifact(scope, "1")`;
49
+ * - `artifact(scope, version)`: versions "1" and "2" of one stored page on `scope`'s origin,
50
+ * each exactly `conformancePage(version)`;
51
+ * - `app`: a url-mode app; `proxy`: the MCP Apps sandbox proxy.
46
52
  */
47
- readonly instances: Pick<ServedConformanceHost, "shell"> & Partial<Pick<ServedConformanceHost, "artifact" | "app" | "proxy">>;
53
+ readonly instances: Partial<Pick<ServedConformanceHost, "shell" | "artifact" | "app" | "proxy">>;
48
54
  /**
49
55
  * Redirect entry (P068), where the app serves clean addresses: the cases open them directly,
50
56
  * signed in and out, and in a frame.
51
57
  */
52
58
  readonly entry?: {
53
- /** The clean address of `instances.artifact(scope, "1")` (`ContentHost.urlOf`). */
54
- readonly url: (scope: string) => string;
55
- /** A clean address the signed-in viewer may not open. */
56
- readonly denied: (scope: string) => string;
57
- /** Whether `page` shows the app's own sign-in. */
58
- readonly atSignIn: (page: Page) => Promise<boolean>;
59
- /** On the app's sign-in page: signs in, as a person does. */
60
- readonly completeSignIn: (page: Page) => Promise<void>;
59
+ /**
60
+ * The clean address of `instances.artifact(scope, "1")` (`ContentHost.urlOf`); may publish it
61
+ * on demand.
62
+ */
63
+ readonly url: (scope: string) => string | Promise<string>;
64
+ /** A clean address the signed-in viewer may not open. Absent: that case is skipped. */
65
+ readonly denied?: (scope: string) => string | Promise<string>;
66
+ /**
67
+ * Whether `page` shows the app's own sign-in. Absent: the browser left the content origin and
68
+ * shows no content.
69
+ */
70
+ readonly atSignIn?: (page: Page) => Promise<boolean>;
71
+ /** On the app's sign-in page: signs in, as a person does. Absent: the case stops there. */
72
+ readonly completeSignIn?: (page: Page) => Promise<void>;
73
+ /**
74
+ * Addresses on the content domain that name nothing: each a 404 there (P070). `"derive"`:
75
+ * `www`, the bare domain and a label no naming makes, under the domain of `url`'s address.
76
+ */
77
+ readonly unknown?: "derive" | (() => readonly string[] | Promise<readonly string[]>);
61
78
  };
62
79
  /** Case ids to skip, each with its reason (shown in the report). */
63
80
  readonly skip?: Readonly<Record<string, string>>;
@@ -77,9 +94,27 @@ export interface HostConformance {
77
94
  }
78
95
  /** The leak and served hosts on an app's real page, for an app that registers the cases itself. */
79
96
  export declare function hostConformance(options: HostConformanceOptions): HostConformance;
97
+ /**
98
+ * A memo for fixtures made on demand (a page published the first time a case asks for it): one
99
+ * promise per key, per worker (P071).
100
+ */
101
+ export declare function onDemand<V>(make: (key: string) => Promise<V>): (key: string) => Promise<V>;
102
+ /** One Playwright project per engine Porthole supports, as Porthole's own suites run them. */
103
+ export interface ConformanceProject {
104
+ readonly name: "chromium" | "webkit" | "firefox";
105
+ readonly use: Record<string, unknown>;
106
+ }
107
+ /**
108
+ * The Playwright projects to run the suite on: Chromium, WebKit and Firefox, Firefox with the
109
+ * preferences its WebRTC probe needs (loopback ICE). Pass `devices` from `@playwright/test`
110
+ * (P071).
111
+ */
112
+ export declare function conformanceProjects(devices: Readonly<Record<string, Record<string, unknown>>>, options?: {
113
+ readonly engines?: readonly ("chromium" | "webkit" | "firefox")[];
114
+ }): ConformanceProject[];
80
115
  /**
81
116
  * Registers the leak and served suites against an app's real page, in a spec file of the app's
82
117
  * (so `-g "\[1\.connect\]"` selects one). The served cases for instances the app didn't give are
83
118
  * skipped, each with its reason.
84
119
  */
85
- export declare function defineHostConformance(test: TestType<object, object>, options: HostConformanceOptions): void;
120
+ export declare function defineHostConformance<T extends object, W extends object>(test: TestType<T, W>, options: HostConformanceOptions): void;