@punica/editor 1.4.10 → 1.4.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.bundle.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var e;!function(e){e.CREATED="created",e.BOOTSTRAPPING="bootstrapping",e.BOOTSTRAPPED="bootstrapped",e.BOOTSTRAP_FAILED="bootstrap_failed",e.STARTING="starting",e.STARTED="started",e.START_FAILED="start_failed",e.READY="ready"}(e||(e={}));async function t(){try{const e=punica.runtime?.workspace;if(!e)return;const t=await e.getCurrent();return t?.id}catch(e){return void console.warn("[hostAccess] Failed to get current workspace id:",e)}}function n(){return punica.runtime?.fs}const r={manager:new class{#e=new Map;#t=new Map;registerCommand(e,t){const n={dispose:()=>{this.#e.delete(e),this.#t.delete(e)}};t.disposable=n,this.#t.set(e,n),this.#e.set(e,t)}executeCommand(e,...t){const n=this.#e.get(e);if(!n){const n=punica.extensions?.manager;if(!n)return void console.error(`[Commands] Command ${e} not found (extension manager unavailable)`);const r=n.getExtensionsForCommand(e);if(0===r.length)return void console.error(`[Commands] Command ${e} not found`);const i=r[0];return n.activate(i,{reason:"command",trigger:e}).then(()=>{const n=this.#e.get(e);return n?(console.log("[Commands] execute after activate",e,"via extension",i),n.execute(...t)):void console.error(`Command ${e} not found after activating extension "${i}"`)}).catch(t=>{console.error(`Error activating extension "${i}" for command ${e}:`,t)})}console.log("[Commands] execute",e,"with args",t);try{const r=n.execute(...t);return r&&"function"==typeof r.then&&r.catch(t=>{console.error(`[Commands] Command ${e} rejected:`,t)}),r}catch(t){throw console.error(`[Commands] Command ${e} threw:`,t),t}}disposeCommand(e){const t=this.#t.get(e);t?t.dispose():console.error(`Command ${e} not found or already disposed`)}getAllCommands(){return Array.from(this.#e.entries()).map(([e,t])=>({id:e,command:t}))}}};const i=new class{async write(e){try{const t=n();if(!t)return;const r=".punica/audit";await t.createFolder(r).catch(()=>{});const i=new Date(e.timestamp).toISOString().split("T")[0],s=`${r}/${`${i}_${e.invocationId}.json`}`;await t.createFileWithContent(s,JSON.stringify(e,null,2))}catch(e){console.warn("[AuditWriter] Failed to write audit record:",e)}}async read(e){try{const t=n();if(!t)return[];const r=".punica/audit",i=await t.getFileTree(),s=(e,t)=>{const n=[];for(const r of e)(r.path.startsWith(t+"/")||r.path===t)&&(r.isDirectory||n.push(r),r.isDirectory&&r.children&&n.push(...s(r.children,t)));return n},o=s(i,r),a=[];for(const n of o)if(n.name.endsWith(".json"))try{const r=await t.readFile(n.path),i=JSON.parse(r);if(e?.since&&i.timestamp<e.since)continue;if(e?.until&&i.timestamp>e.until)continue;if(e?.capability&&i.capability!==e.capability)continue;if(e?.workspaceId&&i.workspace!==e.workspaceId)continue;a.push(i)}catch(e){console.warn(`[AuditWriter] Failed to read audit file ${n.name}:`,e)}return a.sort((e,t)=>t.timestamp-e.timestamp),a}catch(e){return console.warn("[AuditWriter] Failed to read audit records:",e),[]}}};const s={manager:new class{#n=new Map;#r=[];#i=[];registerCommand(e){this.#n.set(e.id,e)}executeCommand(e){const t=this.#n.get(e);t?(t.execute(),this.#r.push(t),this.#i=[]):console.error(`Command with ID ${e} not found.`)}undo(){const e=this.#r.pop();e?(e.undo(),this.#i.push(e)):console.error("No command to undo.")}redo(){const e=this.#i.pop();e?(e.execute(),this.#r.push(e)):console.error("No command to redo.")}},auditWriter:i};const o={manager:new class{#s=[];#o=null;#a(){null===this.#o&&(this.#o=window.setInterval(()=>{const e=new Date;this.#s.forEach(t=>t.update(e))},1e3))}#c(){null!==this.#o&&(window.clearInterval(this.#o),this.#o=null)}subscribe(e){this.#s.push(e),1==this.#s.length&&this.#a()}unsubscribe(e){this.#s=this.#s.filter(t=>t!==e),0==this.#s.length&&this.#c()}}};function a(){return(new Date).toISOString()}function c(e,t){const n=new Map,r=new Map,i=new Set;function s(e){for(const t of i)try{t(e)}catch{}try{const t=window,n=t.punica?.Commands?.manager,r=t.punica?.runtime,i="failed"===e.status?"error":"cancelled"===e.status?"warning":"info";let s=`[${e.label}] ${e.status}`;null!=e.exitCode&&(s+=` (exitCode=${e.exitCode})`),n&&n.executeCommand("output.append",{channel:"Tasks",text:s,level:i}),r?.events?.publish("tasks.runChanged",{run:e}),!r?.notifications||"failed"!==e.status&&"success"!==e.status||r.notifications.push({id:"",level:"failed"===e.status?"error":"success",title:e.label,message:s,timestamp:"",source:"tasks",actionCommandId:"tasks.open"})}catch{}}const o={listDefinitions:async()=>Array.from(n.values()),registerDefinition(e){n.set(e.id,e)},unregisterDefinition(e){n.delete(e)},async run(i,c){const l=n.get(i);if(!l)throw new Error(`[Runtime.tasks] Task definition not found: ${i}`);const u=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`task_${Date.now()}_${Math.floor(1e6*Math.random())}`}(),d=a(),{env:p,workspaceId:h,resolvedEnvironmentId:f}=await async function(e,n){if(!t)return{env:e};try{const r=await t.getCurrent();if(!r)return{env:e};const i=n??r.currentEnvironmentId,s=r.environments.find(e=>e.id===i),o={...s?.variables??{},...e??{}};return{env:Object.keys(o).length?o:void 0,workspaceId:r.id,resolvedEnvironmentId:s?.id}}catch{return{env:e}}}(l.env,c?.environmentId),m=await e.create({cwd:l.cwd,env:p,title:l.label}),g={runId:u,definitionId:l.id,label:l.label,status:"running",startedAt:d,terminalId:m.id,workspaceId:h,environmentId:f};r.set(u,g),s(g);const y=[l.command,...l.args??[]].join(" ").trim();try{const e=window,t=e.punica?.Commands?.manager;t&&"function"==typeof t.executeCommand&&(y?t.executeCommand("terminal.openForTaskSession",{sessionId:m.id,commandLine:y}):t.executeCommand("terminal.openForSession",m.id))}catch{}return e.onExit(m.id,e=>{const t=r.get(u);if(!t)return;const n={...t,status:0===e||null==e?"success":"failed",finishedAt:a(),exitCode:e??null};r.set(u,n),s(n),l.autoRerun&&setTimeout(()=>{o.run(l.id,{environmentId:f}).catch(()=>{})},300)}),g},getRun:async e=>r.get(e)??null,async listRuns(e){let t=Array.from(r.values());return e?.status&&e.status.length&&(t=t.filter(t=>e.status.includes(t.status))),e?.definitionId&&(t=t.filter(t=>t.definitionId===e.definitionId)),e?.workspaceId&&(t=t.filter(t=>t.workspaceId===e.workspaceId)),t},async cancel(t){const n=r.get(t);if(!n)return;if("running"!==n.status||!n.terminalId)return;try{e.close(n.terminalId)}catch{}const i={...n,status:"cancelled",finishedAt:a()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const l=new class{#l=null;#u(){if(this.#l)return this.#l;const e=globalThis.punica;if(!e)throw new Error("[Tasks.manager] Punica not initialized. Call punica.initialize() first.");const t=e.runtime?.terminals;if(!t)throw new Error("[Tasks.manager] Runtime terminals not available. Host must provide punica.runtime.terminals");const n=e.runtime?.workspace;return this.#l=c(t,n),this.#l}async listDefinitions(){return this.#u().listDefinitions()}registerDefinition(e){this.#u().registerDefinition(e)}unregisterDefinition(e){this.#u().unregisterDefinition(e)}async run(e,t){return this.#u().run(e,t)}async getRun(e){return this.#u().getRun(e)}async listRuns(e){return this.#u().listRuns(e)}async cancel(e){return this.#u().cancel(e)}onDidChangeRun(e){return this.#u().onDidChangeRun(e)}};var u={manager:l},d=Object.freeze({__proto__:null,createTasksApi:c,default:u,manager:l});function p(e){let t=String(e??"");try{const e=punica.runtime?.secrets;if(e){const n=e.list();for(const r of n){const n=e.get(r.name);n&&"string"==typeof n&&n.length>=4&&(t=t.split(n).join("[REDACTED]"))}}}catch{}return t}function h(e){return p(function(e){let t=String(e??"");const n=[/\bsk-[A-Za-z0-9]{20,}\b/g,/\bghp_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*\b/g,/(\b(password|passwd|pwd|secret|token|api[_-]?key)\b\s*[:=]\s*)([^\s'"]+)/gi];for(const e of n)t=t.replace(e,(e,t)=>"string"==typeof t?`${t}[REDACTED]`:"[REDACTED]");return t}(e))}const f=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function m(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||f.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function g(e,t=2){const n=function(e){const t=new WeakSet;return function e(n){if(null===n||"object"!=typeof n)return n;if(t.has(n))return"[Circular]";if(t.add(n),Array.isArray(n))return n.map(e);const r={};for(const[t,i]of Object.entries(n))m(t)?r[t]=null==i?i:"[REDACTED]":r[t]=e(i);return r}(e)}(e);return h(JSON.stringify(n,null,t))}function y(e){const t=[];return function e(n,r){if(!n||"object"!=typeof n)return;const i=n,s=i.properties;if(s&&"object"==typeof s)for(const[n,i]of Object.entries(s)){if(!i||"object"!=typeof i)continue;const s=i,o=[...r,n];!0===s.sensitive&&t.push(o),e(s,o)}const o=i.items;if(o&&"object"==typeof o)if(Array.isArray(o))for(const t of o)e(t,[...r,"*"]);else e(o,[...r,"*"]);for(const t of["anyOf","oneOf","allOf"]){const n=i[t];if(Array.isArray(n))for(const t of n)e(t,r)}}(e,[]),t}function b(e,t){if(0===t.length)return e;return function e(t,n){if(null===t||"object"!=typeof t)return t;if(0===n.length)return t;if(Array.isArray(t)){const r=[];let i=!1;for(const e of n)"*"===e[0]&&(1===e.length?i=!0:r.push(e.slice(1)));return i&&0===r.length?t.map(e=>null==e?e:"[REDACTED]"):t.map(t=>e(t,r))}const r={};for(const[i,s]of Object.entries(t)){const t=[];let o=!1;for(const e of n)e[0]===i&&(1===e.length?o=!0:t.push(e.slice(1)));o?r[i]=null==s?s:"[REDACTED]":t.length>0?r[i]=e(s,t):r[i]=s}return r}(e,t)}const w=6048e5,v={rules:[],defaultTtlMs:w};function k(e,t){if(t===e)return!0;if("*"===t)return!0;if(t.endsWith(".*")){const n=t.slice(0,-1);return e.startsWith(n)}return!1}function I(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(k(e,i.pattern)){const e=i.pattern.length;e>r&&(n=i,r=e)}return n}(e,t.rules??[]);return n-(r?.ttlMs??t.defaultTtlMs??w)}const E=".punica/events";let A={};function S(e){const t=[],n=[...e];for(;n.length>0;){const e=n.pop();if(e){if(Array.isArray(e.children))for(const t of e.children)n.push(t);!0!==e.isDirectory&&"string"==typeof e.path&&e.path.startsWith(E)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function _(e,t){if(!t)return!0;const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId&&n?.id!==t.correlationId)return!1;if(void 0!==t.name){if(!(Array.isArray(t.name)?t.name:[t.name]).includes(e.name))return!1}return!(void 0!==t.since&&(n?.timestampMs??0)<t.since)&&!(void 0!==t.until&&(n?.timestampMs??0)>t.until)}const x=new class{#d;#p=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const r=n();if(!r)return;if(punica.runtime?.workspace&&!await t())return;const i=Date.now();try{await r.createFolder(E)}catch{}if(!this.#p){this.#p=!0;try{await r.createFileWithContent(`${E}/.gitignore`,"*\n!.gitignore\n")}catch{}}for(const t of e)try{const e=t.envelope?.timestampMs??Date.now(),n=new Date(e).toISOString().split("T")[0],i=t.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,s=`${E}/${n}_${i}.json`,o=g(t);await r.createFileWithContent(s,o)}catch{}try{A.onWrite?.(Date.now()-i,e.length)}catch{}}async query(e){const t=n();if(!t)return[];let r;try{r=await t.getFileTree()}catch{return[]}if(!Array.isArray(r))return[];const i=S(r),s=[];for(const n of i)try{const r=await t.readFile(n),i=JSON.parse(r);_(i,e)&&s.push(i)}catch{}return s.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),e?.limit&&e.limit>0?s.slice(-e.limit):s}async delete(e){const t=n();if(!t)return 0;let r;try{r=await t.getFileTree()}catch{return 0}if(!Array.isArray(r))return 0;const i=S(r);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(_(JSON.parse(r),e))await t.deleteFile(n),s++;else{const e=n.split("/").pop()??"",t=e.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]??"";o.push({path:n,dateKey:t})}}catch{}if(o.length>this.#d){o.sort((e,t)=>e.dateKey.localeCompare(t.dateKey));const e=o.length-this.#d;for(const n of o.slice(0,e))try{await t.deleteFile(n.path),s++}catch{}}return s}async applyRetention(e,t=Date.now()){const r=n();if(!r)return 0;let i;try{i=await r.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=S(i);let o=0;for(const n of s)try{const i=await r.readFile(n),s=JSON.parse(i),a=s.envelope?.timestampMs??0;a<I(s.name,e,t)&&(await r.deleteFile(n),o++)}catch{}return o}};let C=x;function T(){return C}const N=new class{#h=void 0;get(){return this.#h}runWith(e,t){const n=this.#h;let r;this.#h=e;try{r=t()}catch(e){throw this.#h=n,e}return r&&"function"==typeof r.then?r.then(e=>(this.#h=n,e),e=>{throw this.#h=n,e}):(this.#h=n,r)}};let M=N;function D(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=M.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function P(e,t){const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId)return!1;if(void 0!==t.traceId&&n?.traceId!==t.traceId)return!1;if(void 0!==t.kind){const e=Array.isArray(t.kind)?t.kind:[t.kind];if(0===e.length)return!1;if(!e.includes(n?.kind))return!1}if(void 0!==t.source){const e=Array.isArray(t.source)?t.source:[t.source];if(0===e.length)return!1;if(!n?.source||!e.includes(n.source))return!1}if(void 0!==t.name){const n=Array.isArray(t.name)?t.name:[t.name];if(0===n.length)return!1;let r=!1;for(const t of n)if(k(e.name,t)){r=!0;break}if(!r)return!1}return!0}class O extends Error{constructor(e){super(e),this.name="EventReplayError"}}let R={exportSpan:()=>{}};function L(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function $(){return Date.now()}function j(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;function o(){try{A.onQueueDepthChange?.(i.length)}catch{}}async function a(){if(0===i.length)return;const e=[...i];i=[],o(),s&&(clearTimeout(s),s=null);try{await T().write(e),U()}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function c(e){(function(e){const t=e.name;return r.some(e=>e.test(t))})(e)&&(i.push(e),o(),i.length>=10?a():s||(s=setTimeout(()=>{a()},5e3)))}function l(n,r){if("string"==typeof n){const t=n;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(r),()=>{i?.delete(r),i&&0===i.size&&e.delete(t)}}const i={filter:n,listener:r};return t.push(i),()=>{const e=t.indexOf(i);e>=0&&t.splice(e,1)}}function u(r,i){const s=i,o=s&&"object"==typeof s&&s.name===r?s:{name:r,envelope:{id:L(),timestampMs:$()},payload:i};try{n.push(o),n.length>200&&n.splice(0,n.length-200),c(o)}catch{}const a=e.get(r);if(a&&a.size>0)for(const e of a)try{e(i)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(P(o,t.filter))try{t.listener(o)}catch{}}}async function d(e){try{return await T().query(e)}catch{return[]}}function p(e){let t=[...n];if(e?.correlationId){const n=e.correlationId;t=t.filter(e=>e.envelope?.correlationId===n||e.envelope?.id===n)}if(e?.name){const n=Array.isArray(e.name)?e.name:[e.name];t=t.filter(e=>n.includes(e.name))}if(e?.kind){const n=Array.isArray(e.kind)?e.kind:[e.kind];t=t.filter(e=>n.includes(e.envelope?.kind))}if(e?.source){const n=Array.isArray(e.source)?e.source:[e.source];t=t.filter(e=>e.envelope?.source&&n.includes(e.envelope.source))}return"number"==typeof e?.since&&(t=t.filter(t=>(t.envelope?.timestampMs??0)>=e.since)),"number"==typeof e?.until&&(t=t.filter(t=>(t.envelope?.timestampMs??0)<=e.until)),t.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),"number"==typeof e?.limit&&e.limit>0&&(t=t.slice(-e.limit)),t}const h={publish:u,subscribe:l,subscribeMany(e,t){const n=e.map(e=>l(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:L,publishEvent:function(e){const t=D({id:e.envelope?.id??L(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??$(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{R.exportSpan(function(e){const t=e.envelope,n={};if(void 0!==t.source&&(n.source=t.source),void 0!==e.payload&&null!==e.payload){const t=g(e.payload);try{n.payload=JSON.parse(t)}catch{n.payload=t}}return{traceId:t.traceId,spanId:t.spanId??t.id,parentSpanId:t.parentSpanId,correlationId:t.correlationId,name:e.name,timestampMs:t.timestampMs,kind:t.kind,source:t.source,attributes:n}}(n))}catch{}return u(n.name,n),t},getRecent(e){const t="number"==typeof e&&e>0?e:n.length;return n.slice(Math.max(0,n.length-t))},filterEvents:p,getTrace:function(e){return p({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?p(e.filter):[...n].sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0));if("csv"===t){const e=["timestamp","name","kind","source","correlationId","id","payload"],t=r.map(e=>[e.envelope?.timestampMs?new Date(e.envelope.timestampMs).toISOString():"",e.name,e.envelope?.kind??"",e.envelope?.source??"",e.envelope?.correlationId??"",e.envelope?.id??"",g(e.payload??{},0)]);return[e.join(","),...t.map(e=>e.map(e=>{const t=String(e);return t.includes(",")||t.includes('"')||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}).join(","))].join("\n")}return g({exportedAt:$(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:d,replay:async function(e){"dispatch"===e.mode&&function(){throw new O('events.replay({ mode: "dispatch" }) is disabled. Host must call setReplayDispatchAllowed(true) during bootstrap (test/dev only — side-effectful listeners will fire again).')}();const t=!1!==e.includePersisted,r=[...n];let i=[];if(t)try{i=await d({name:e.name,since:e.since,until:e.until})}catch{i=[]}const s=function(e,t,n){const r=new Set,i=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}i.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}i.push(e)}const s={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=i.filter(e=>{if(!P(e,s))return!1;const t=e.envelope?.timestampMs??0;return!(void 0!==n.since&&t<n.since||void 0!==n.until&&t>n.until)});return o.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),void 0!==n.limit&&n.limit>0&&(o=o.slice(-n.limit)),o}(r,i,{name:e.name,correlationId:e.correlationId,traceId:e.traceId,kind:e.kind,source:e.source,since:e.since,until:e.until,limit:e.limit});if("log"===e.mode)for(const e of s)console.log("[Punica Replay]",e.name,e);else for(const e of s)u(e.name,e);return{count:s.length,events:s}}};return h}const F=j();var B={manager:F};let q=v;function z(){return q}async function U(){try{const e=T(),t=z();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??w;return await e.delete({until:$()-n})??0}catch{return 0}}var V=Object.freeze({__proto__:null,createCorrelationId:L,createEventsApi:j,default:B,getRetentionConfig:z,manager:F,runEventRetentionCleanup:U,setRetentionConfig:function(e){q=e??v}});function W(){let e=[];const t=new Set;function n(){for(const e of t)try{e()}catch{}}const r={list:async()=>e.slice(),push(t){const r=t.id||`notif_${Date.now()}_${Math.random().toString(36).slice(2)}`,i=t.timestamp||(new Date).toISOString(),s={...t,id:r,timestamp:i};e=[s,...e],n()},markRead(t){e=e.map(e=>e.id===t?{...e,read:!0}:e),n()},clear(t){e=t?e.filter(e=>e.source!==t):[],n()},onDidChange:e=>(t.add(e),()=>{t.delete(e)})};return r}const K=W();var G={manager:K},H=Object.freeze({__proto__:null,createNotificationsApi:W,default:G,manager:K});const Y="punica.kernel.policy.v2";function J(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function Z(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class Q{#f=new Map;constructor(){this.#m()}set(e,t,n){let r=this.#f.get(e);r||(r=new Map,this.#f.set(e,r)),r.set(t,n),this.#g()}get(e,t){return this.#f.get(e)?.get(t)}has(e,t){return this.#f.get(e)?.has(t)??!1}delete(e,t){const n=this.#f.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#f.delete(e),r&&this.#g(),r}list(){const e=[];for(const t of this.#f.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#f.size&&(this.#f.clear(),this.#g())}restoreAll(e){this.#f.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=Z(n);if(!e)continue;let r=this.#f.get(n.key);r||(r=new Map,this.#f.set(n.key,r)),r.set(e,n),t++}return this.#g(),t}#m(){const e=J();if(e)try{const t=e.getItem(Y);if(!t)return;const n=JSON.parse(t);if(!Array.isArray(n?.approvals))return;for(const e of n.approvals){if(!e||"string"!=typeof e.key)continue;const t=Z(e);if(!t)continue;let n=this.#f.get(e.key);n||(n=new Map,this.#f.set(e.key,n)),n.set(t,e)}}catch{}}#g(){const e=J();if(e)try{let t={};try{const n=e.getItem(Y);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,approvals:this.list(),exportedAt:Date.now()};e.setItem(Y,JSON.stringify(n))}catch{}}}let X=new Q;function ee(){return Date.now()}function te(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function ne(e){return`${e.kind}:${e.id}`}function re(e,t){return"workspace"===e?`workspace:${t??""}`:e}function ie(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const se="punica.kernel.policy.v1",oe="punica.kernel.policy.v2";class ae{#y="execute";#b;#w=new Set;#v=new Map;#k=[];#I=1e3;constructor(e){this.#b=e??new Q,this.#E()}#E(){const e=ie();if(e)try{const t=e.getItem(oe);if(t){const e=JSON.parse(t);if(e&&2===e.v)return void("suggest"!==e.mode&&"execute"!==e.mode||(this.#y=e.mode))}const n=e.getItem(se);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#y=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#b.restoreAll(n),this.#g();try{e.removeItem(se)}catch{}return}}}catch{}}#g(){const e=ie();if(e)try{let t={};try{const n=e.getItem(oe);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#y,exportedAt:ee()};e.setItem(oe,JSON.stringify(n))}catch{}}setMode(e){this.#y=e,this.#g()}getMode(){return this.#y}clearApprovals(){this.#b.clear(),this.#w.clear()}#A(e,t,n="info"){try{F.publishEvent({name:e,envelope:{id:F.createCorrelationId(),timestampMs:ee(),source:"kernel:policy",kind:n},payload:t})}catch{}}#S(e,t){return`${e}|${t}`}revokeApproval(e){const t=ne({kind:e.kind,id:e.id}),n="workspace"===e.scope?re("workspace",e.workspaceId):re(e.scope),r=this.#b.delete(t,n);return r&&(this.#_("revocation",{kind:e.kind,id:e.id,risk:"low",approval:"none"},void 0,e.scope,e.workspaceId),this.#A("approval.revoked",{kind:e.kind,id:e.id,scope:e.scope,workspaceId:e.workspaceId}),this.#w.delete(this.#S(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#b.list();if(t)return n;const r=ee();return n.filter(e=>!te(e,r))}hasApproval(e,t,n){const r=ne(e),i="workspace"===t?n?.workspaceId?re("workspace",n.workspaceId):null:re(t);if(null===i)return!1;const s=this.#b.get(r,i);if(!s)return!1;if(te(s,ee())){const e=this.#S(r,i);return this.#w.has(e)||(this.#w.add(e),this.#A("approval.expired",{kind:s.kind,id:s.id,scope:s.scope,workspaceId:s.workspaceId,expiresAt:s.expiresAt,decidedBy:s.decidedBy},"warn")),!1}return!0}recordApproval(e,t,n){if("workspace"===t&&!n?.workspaceId)throw new Error("[Policy] Workspace scope requires workspaceId in context");const r=ne(e),i="workspace"===t?re("workspace",n?.workspaceId):re(t),s={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:ee(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,chainRef:n?.chainRef};return this.#b.set(r,i,s),this.#_("approval",e,void 0,t,n?.workspaceId),this.#w.delete(this.#S(r,i)),this.#A("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:n?.decidedBy,expiresAt:n?.expiresAt}),s}#_(e,t,n,r,i){this.#k.push({timestampMs:ee(),type:e,request:t,decision:n,scope:r,workspaceId:i}),this.#k.length>this.#I&&this.#k.splice(0,this.#k.length-this.#I)}evaluate(e,t){const n=n=>{const r=t,i=r?.correlationId,s=r?.traceId??i;F.publishEvent({name:"policy.evaluated",envelope:{id:F.createCorrelationId(),correlationId:i,traceId:s,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})};if("suggest"===this.#y){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===e.approval){const r={allowed:!0,mode:"execute",requiresApproval:!1};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}if("plan"===e.approval){const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (plan)."};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (step)."};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}requestApproval(e,t){F.publishEvent({name:"policy.approvalRequested",envelope:{id:F.createCorrelationId(),correlationId:t?.correlationId,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,context:{workspaceId:t?.workspaceId,traceId:t?.traceId}}})}exportState(){return{version:2,exportedAt:ee(),mode:this.#y,approvals:this.listApprovals({includeExpired:!0})}}importState(e,t){if(!e||"object"!=typeof e)throw new Error("[Policy] Invalid export data");if(2!==e.version)throw new Error(`[Policy] Unsupported export version: ${e.version}. Expected 2.`);const n=t?.merge??!1,r=Array.isArray(e.approvals)?e.approvals:[];"suggest"!==e.mode&&"execute"!==e.mode||(this.#y=e.mode);let i=0;if(n)for(const e of r){if(!e||"string"!=typeof e.key)continue;const t=e.key,n=e.scope,r=e.workspaceId;if("workspace"===n&&!r)continue;const s="workspace"===n?re("workspace",r):re(n);"string"==typeof s&&s&&(this.#b.has(t,s)||(this.#b.set(t,s,e),i++))}else i=this.#b.restoreAll(r),this.#w.clear();return this.#g(),F.publishEvent({name:"policy.stateImported",envelope:{id:F.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:i,merged:n}}),i}saveTemplate(e,t,n){const r=n??"global";let i=this.#v.get(r);i||(i=new Map,this.#v.set(r,i));const s={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??ee(),updatedAtMs:ee()};i.set(e,s),this.#g()}getTemplate(e,t){const n=t??"global",r=this.#v.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#v.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#v.get(n);if(!r)return!1;const i=r.delete(e);return i&&this.#g(),i}exportAuditLog(e){const t=e?.format??"json";let n=[...this.#k];if(e?.since&&(n=n.filter(t=>t.timestampMs>=e.since)),e?.until&&(n=n.filter(t=>t.timestampMs<=e.until)),e?.workspaceId&&(n=n.filter(t=>t.workspaceId===e.workspaceId)),"csv"===t){const e=["timestamp","type","kind","id","risk","approval","allowed","requiresApproval","scope","workspaceId","reason"],t=n.map(e=>[new Date(e.timestampMs).toISOString(),e.type,e.request.kind,e.request.id,e.request.risk,e.request.approval,e.decision?.allowed?"true":"false",e.decision?.requiresApproval?"true":"false",e.scope??"",e.workspaceId??"",e.decision?.reason??e.request.reason??""]);return[e.join(","),...t.map(e=>e.map(e=>{const t=String(e);return t.includes(",")||t.includes('"')||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}).join(","))].join("\n")}return JSON.stringify({exportedAt:ee(),version:1,count:n.length,entries:n},null,2)}}const ce=new ae(X);var le={manager:ce},ue=Object.freeze({__proto__:null,PolicyManager:ae,default:le,manager:ce});async function de(e,n,r){if(r())e.status="cancelled";else if("success"!==e.status&&"cancelled"!==e.status){e.status="running",e.startedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runStepStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=n,s=await t(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:n,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:n},trace:{traceId:i,parentSpanId:void 0},policy:{mode:"execute"}});e.status="success",e.finishedAtMs=Date.now(),e.correlationId=r,e.resultPayload=o,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:n,step:e}})}catch(t){const r=String(t?.message??t);if(r.includes("Approval required")||r.includes("CAPABILITY_APPROVAL_REQUIRED"))throw e.status="blocked",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}}),new Error("blocked");throw e.status="failed",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:n,step:e}}),t}}}async function pe(e,t,n,r){let i=e;if(i||(i=function(){try{const e=punica.kernel.Events.manager.getRecent(200);for(let t=e.length-1;t>=0;t--){const n=e[t],r=n?.name??n?.event?.name,i=n?.payload??n?.event?.payload;if("ai.planGenerated"===r&&i?.plan?.planId)return i.plan}}catch{}return null}(),i&&r(i)),!i)throw new Error("[AI] No plan to run");return await async function(e,t,n){const r=t&&t.planId===e.planId&&!t.finishedAtMs?t:{runId:punica.kernel.Events.manager.createCorrelationId(),planId:e.planId,startedAtMs:Date.now(),steps:e.steps.map(e=>({...e,status:"pending"}))};punica.kernel.Events.manager.publishEvent({name:"ai.runStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}});for(const e of r.steps)try{await de(e,r.runId,n)}catch(e){if("blocked"===e?.message)break;break}return r.finishedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}}),r}(i,t,n)}const he={estimate:e=>Math.ceil(e.length/4)};function fe(){return he}function me(e){const t=fe();let n=0;for(const r of e)if(n+=4+t.estimate(r.content??""),r.toolCalls&&r.toolCalls.length>0)try{n+=t.estimate(JSON.stringify(r.toolCalls))}catch{}return n}const ge={fast:{maxContextTokens:12e3,keepLastTurnsVerbatim:2,toolResultMaxChars:1500,summarizeWhenOver:!1},balanced:{maxContextTokens:32e3,keepLastTurnsVerbatim:4,toolResultMaxChars:4e3,summarizeWhenOver:!0},accurate:{maxContextTokens:96e3,keepLastTurnsVerbatim:6,toolResultMaxChars:8e3,summarizeWhenOver:!0}};const ye="[elided tool result:";function be(e){const t=(e.content??"").length;return`${ye} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function we(e,t){let n=0;for(let r=e.length-1;r>0;r--){const i=e[r].role;if(("assistant"===i||"user"===i)&&(n++,n>=t))return r}return 1}async function ve(e,t,n,r){const i=me(e);if(i<=t.maxContextTokens)return{messages:[...e],compacted:!1,strategy:"none",preTokens:i,postTokens:i,estSavedTokens:0};const s=Math.floor(.6*t.maxContextTokens),o=we(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(ye)?{...e,content:be(e)}:e);let c=me(a);if(c<=s||!t.summarizeWhenOver||!n){const e=c<i;return{messages:a,compacted:e,strategy:e?"elide":"none",preTokens:i,postTokens:c,estSavedTokens:i-c}}const l=a.slice(1,o),u=a.slice(o);try{const e="Summarize this agent conversation segment so a follow-up model call can continue the task without the originals. Keep: the user goal, decisions made, tool outcomes (names + key results), and open questions. Be dense and factual; no preamble.\n\n"+l.map(e=>`${e.role}: ${e.content??""}`).join("\n"),t=await n("llm.chat",{messages:[{role:"user",content:e}],profile:"fast"},r??{}),s=(t?.text??"").trim();if(s){const e=[a[0],{role:"assistant",content:`[conversation summary]\n${s}`},...u];return c=me(e),{messages:e,compacted:!0,strategy:"summarize",preTokens:i,postTokens:c,estSavedTokens:i-c}}}catch{}return{messages:a,compacted:c<i,strategy:"elide",preTokens:i,postTokens:c,estSavedTokens:i-c}}const ke=["capability.search","capability.describe"];function Ie(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function Ee(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Ae(e,t,n,r){const i=punica.kernel?.Events?.manager;i&&i.publishEvent({name:e,envelope:{id:i.createCorrelationId(),correlationId:t,timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}async function Se(e,t,n,r){try{const i=await e("capability.recommend",{intent:n,limit:200},r),s=i?.recommendations??[],o=new Map;let a=!1,c=0;s.forEach((e,t)=>{null!=e?.id&&o.set(String(e.id),t),"number"==typeof e?.score&&(a=!0,e.score>c&&(c=e.score))});const l=new Map;for(const e of t){const t=Ie(String(e.id)),n=l.get(t);n?n.push(e):l.set(t,[e])}if(0===o.size||a&&c<=1e-9)return function(e,t){const n=[],r=[...e.values()],i=new Array(r.length).fill(0);let s=!0;for(;s&&n.length<t;){s=!1;for(let e=0;e<r.length&&n.length<t;e++){const t=i[e];t<r[e].length&&(n.push(r[e][t]),i[e]=t+1,s=!0)}}return n}(l,100);const u=e=>o.has(String(e.id))?o.get(String(e.id)):Number.POSITIVE_INFINITY,d=[...l.keys()],p=new Map(d.map(e=>[e,Math.min(...l.get(e).map(u))])),h=new Map(d.map((e,t)=>[e,t]));d.sort((e,t)=>{const n=p.get(e)-p.get(t);return 0!==n?n:h.get(e)-h.get(t)});const f=[];for(const e of d.slice(0,64)){const t=l.get(e),n=t.filter(e=>o.has(String(e.id))).sort((e,t)=>u(e)-u(t)),r=t.filter(e=>!o.has(String(e.id)));f.push(...n,...r)}return f.slice(0,100)}catch{return t}}function _e(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function xe(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function Ce(e){const t=String(e.description??e.title??e.id).replace(/\s+/g," ").trim();return t.length>100?t.slice(0,99).trimEnd()+"…":t}async function Te(e,t,n){const r=await e("capability.schemaExport",{filter:t.toolFilter,mode:"ai-tools"},n);let i=r?.capabilities??[];if(console.log("[AgentLoop] schemaExport raw catalog",{total:i.length,byCategory:i.reduce((e,t)=>{const n=Ie(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(_e).sort(xe),deferredIndex:[]};const s=i.filter(e=>ke.includes(String(e.id)));if(i=i.filter(e=>{return!ke.includes(String(e.id))&&(!((n=String(e.id)).startsWith("ai.")||(n.startsWith("capability.")?!ke.includes(n):n.startsWith("llm.")))&&(!(!t.includeIvyNodes&&"ivy-node"===String(e.origin))&&!("mcp"===String(e.origin)&&!function(e,t){if(t.includeMcp)return!0;const n=function(e){const t=e.split(".");return"mcp"===t[0]&&t.length>=3?t[1]:void 0}(e);return!!n&&(t.allowedMcpServers??[]).includes(n)}(String(e.id),t))));var n}),console.log("[AgentLoop] after default-exclude filter",{remaining:i.length,includeIvyNodes:!!t.includeIvyNodes,includeMcp:!!t.includeMcp,allowedMcpServers:t.allowedMcpServers??[],willTier:!1!==t.deferToolLoading&&i.length>24,narrowThreshold:24}),i.length<=24)return{hot:i.map(_e).sort(xe),deferredIndex:[]};if(!1===t.deferToolLoading){return{hot:(await Se(e,i,t.query,n)).map(_e).sort(xe),deferredIndex:[]}}const o="number"==typeof t.hotSetSize&&t.hotSetSize>0?Math.floor(t.hotSetSize):16,a=(await Se(e,i,t.query,n)).slice(0,o),c=new Set(a.map(e=>String(e.id))),l=s.length===ke.length?s.map(_e):[{name:"capability.search",description:"Search the deferred tool index by natural-language need; returns candidate tool ids with one-line descriptions.",parameters:{type:"object",required:["query"],properties:{query:{type:"string"},limit:{type:"number"}}}},{name:"capability.describe",description:"Load full definitions (input schema) for up to 16 tool ids from the deferred index; described tools become directly callable.",parameters:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},maxItems:16}}}}],u=i.filter(e=>!c.has(String(e.id))).map(e=>({id:String(e.id),line:Ce(e),category:Ie(String(e.id))})).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0);return console.log("[AgentLoop] tiered catalog",{hot:a.length,deferred:u.length,hotIds:[...c]}),{hot:[...l,...a.map(_e)].sort(xe),deferredIndex:u}}async function Ne(e,t,n,r){const i={id:t.id,name:t.name,arguments:t.arguments,status:"success"};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){if(!function(e){const t=String(e?.message??e);return t.includes("Approval required")||t.includes("CAPABILITY_APPROVAL_REQUIRED")}(e))return{...i,status:"failed",error:String(e?.message??e)}}const s=String(n.trace?.traceId??n.sessionId??""),o=await function(e,t,n){return new Promise(r=>{const i=punica.kernel.Events.manager;let s=!1;const o=e=>{if(!s){s=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=i.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed"],n=>{const r=n?.payload?.payload??n?.payload,i=r?.pending;i?.id===e&&(i?.traceId&&i.traceId!==t||o("ai.approvalRecorded"===n?.name?"approved":"dismissed"))})??void 0,c=setInterval(()=>{n()&&o("cancelled")},250),l=setTimeout(()=>o("timeout"),18e4)})}(t.name,s,r);if("approved"!==o)return{...i,status:"blocked",error:`tool "${t.name}" not approved (${o})`};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){return{...i,status:"failed",error:String(e?.message??e)}}}async function Me(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Oe(n)}\nRejected arguments:\n${Oe(r)}\nValidation errors: ${i}\nReturn ONLY a JSON object with the corrected arguments — no prose, no code fence.`;try{const t=await e("llm.chat",{messages:[{role:"user",content:o}],correlationId:s.sessionId},s);return function(e){let t=(e??"").trim();if(!t)return;const n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");e>=0&&n>e&&(t=t.slice(e,n+1))}try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch{}}(t?.text??"")}catch{return}}async function De(e,t,n,r,i){let s=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Ne(e,{...t,arguments:s},r,i);if("failed"!==l.status||!Ee(l.error))return o?{...l,arguments:s,repaired:!0}:l;if(a=l.error??"",2===c||i())break;const u=await Me(e,t.name,n,s,a,r);if(!u)break;s=u,o=!0}const c={id:t.id,name:t.name,arguments:s,status:"failed",error:a||"input validation failed"};return o&&(c.repaired=!0),c}function Pe(e){return fe().estimate(e)}function Oe(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Re(e,n,r,i){const s=punica.kernel.Events.manager,o=i??s.createCorrelationId(),a="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,c=(l=e.profile,ge[l??"balanced"]);var l;const u=[],d=e.sessionId?punica.kernel?.AI?.sessions:void 0,p=[];let h=0;const f=[],m=Date.now();let g=0,y=0,b=0,w=0,v=!1,k=0,I=!1,E=0;const A=(t,n)=>{const r={inputTokens:g,outputTokens:y,totalTokens:b,latencyMs:Date.now()-m,steps:u.length,toolCalls:E};I&&(r.totalCost=k),v&&(r.cacheReadTokens=w);const i={runId:o,finishReason:t,steps:u,usage:r};if(void 0!==n&&(i.finalText=n),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:u.length}),(t=>{if(d&&e.sessionId&&0!==h)try{const n=[{role:"user",content:e.query},...f];t&&n.push({role:"assistant",content:t});const r=n.map(e=>({id:"",createdAtMs:0,role:e.role,content:e.content??"",...e.name?{name:e.name}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolCalls&&e.toolCalls.length>0?{toolCalls:e.toolCalls}:{}}));d.appendMessages(e.sessionId,r,{runId:o})}catch(e){console.warn("[AgentLoop] session persist failed:",e)}})(n),d&&e.sessionId&&h>0)try{d.recordUsage?.(e.sessionId,r)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Ae("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),i};Ae("ai.agentStarted",o,"info",{runId:o,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{}});const S=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!S)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),A("error");const _=await t(),x=function(e,t,n){return{sessionId:e,workspaceId:t,actor:{type:"ai",id:"ai:agent"},origin:{kind:"ai",id:e},trace:{traceId:e,parentSpanId:void 0},policy:{mode:"execute"},...n?{signal:n}:{}}}(o,_,r);let C;e.sessionId&&(x.conversationId=e.sessionId);try{C=await Te(S,e,x)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),A("error")}const T=[...C.hot];console.log("[AgentLoop] tool catalog built",{hot:T.length,deferred:C.deferredIndex.length,toolFilter:e.toolFilter??null,names:T.map(e=>e.name)});const N=new Map(T.map(e=>[e.name,e.parameters])),M=new Map(C.deferredIndex.map(e=>[e.id,e])),D=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!N.has(String(e.id))).map(_e).sort(xe);for(const e of n)T.push(e),N.set(e.name,e.parameters),M.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:T.length}),n.length};if(p.push({role:"system",content:"You are an autonomous agent operating inside an IDE. You are given a set of tools (capabilities). To accomplish the user request, call the tools you need one or more times; after each tool result, decide whether to call another tool or to answer. When you have enough information, reply with a concise final answer and no further tool calls."}),C.deferredIndex.length>0&&p.push(function(e){const t=new Map;for(const n of e){const e=t.get(n.category);e?e.push(n):t.set(n.category,[n])}const n=[];for(const e of[...t.keys()].sort())for(const r of t.get(e))n.push(`[${e}] ${r.id} — ${r.line}`);return{role:"system",content:"Additional tools exist but are not loaded yet. Index (id — purpose):\n"+n.join("\n")+"\nTo use one: call capability.search to find candidates, then capability.describe to load full schemas. You may also call an indexed tool directly by its id if its arguments are obvious."}}(C.deferredIndex)),d&&e.sessionId)try{p.push(...d.getContextMessages(e.sessionId))}catch(e){console.warn("[AgentLoop] session seed failed; running cold:",e)}p.push({role:"user",content:e.query}),h=p.length;let P=0;for(let t=0;t<a;t++){if(n())return A("cancelled");let r,i=!1;if(me(p)>c.maxContextTokens){const e=await ve(p,c,S,x);e.compacted&&(p.splice(0,p.length,...e.messages),P=0,i=!0,Ae("ai.agentContextCompacted",o,"info",{runId:o,step:t,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const s=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:t,messageCount:p.length,toolsSent:T.length,toolChoice:"auto",toolNames:T.map(e=>e.name)});const n={stableToolsAndSystem:!0,stableMessagePrefix:P,cacheKey:o};r=await S("llm.chatStream",{messages:p,tools:T,toolChoice:"auto",correlationId:o,cacheHints:n,...e.profile?{profile:e.profile}:{}},x),P=p.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:t,textLen:(r?.text??"").length,toolCalls:r?.toolCalls?.length??0})}catch(e){return console.error("[AgentLoop] llm.chatStream call failed; aborting run:",e),A("error")}if(n())return A("cancelled");const a=Date.now()-s,l=(r.text??"").trim(),d="string"==typeof r.thinking?r.thinking:void 0,h=r.toolCalls??[],m={index:t,assistantText:l||void 0,thinking:d,toolCalls:[],latencyMs:a},_=r.usage,C=r.meta;_?(m.usage=_,g+=_.inputTokens??0,y+=_.outputTokens??0,b+=_.totalTokens??(_.inputTokens??0)+(_.outputTokens??0),"number"==typeof _.cacheReadInputTokens&&(w+=_.cacheReadInputTokens,v=!0)):C&&(m.usage={inputTokens:C.promptTokens,outputTokens:C.completionTokens,totalTokens:C.promptTokens+C.completionTokens},g+=C.promptTokens,y+=C.completionTokens,b+=C.promptTokens+C.completionTokens),C&&"number"==typeof C.totalCost&&(k+=C.totalCost,I=!0);const O={runId:o,step:t,estToolDefTokens:Pe(JSON.stringify(T)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+Pe(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+Pe(t.content??""),0),toolCount:T.length,deferredToolCount:M.size,compactionApplied:i};if(m.usage&&(O.reportedInputTokens=m.usage.inputTokens,O.reportedOutputTokens=m.usage.outputTokens,"number"==typeof m.usage.cacheReadInputTokens&&(O.cacheReadTokens=m.usage.cacheReadInputTokens)),Ae("ai.agentTurnUsage",o,"info",{...O}),0===h.length)return u.push(m),Ae("ai.agentStep",o,"info",{runId:o,turn:m}),A("final",l);u.push(m),Ae("ai.agentStep",o,"info",{runId:o,turn:m});const R=h.map(e=>`${e.name}(${Oe(e.arguments)})`).join(", "),L={role:"assistant",content:l?`${l}\n[calling tools: ${R}]`:`[calling tools: ${R}]`,toolCalls:h.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};p.push(L),f.push(L);let $=!1;for(const e of h){if(n())return A("cancelled");if(Ae("ai.agentToolCall",o,"info",{runId:o,toolCall:{id:e.id,name:e.name,arguments:e.arguments},status:"running"}),!N.has(e.name)&&M.has(e.name))try{D(await S("capability.describe",{ids:[e.name]},x))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const r=await De(S,e,N.get(e.name),x,n);m.toolCalls.push(r),E++,"success"===r.status&&"capability.describe"===r.name&&D(r.resultPayload),console.log("[AgentLoop] tool dispatched",{step:t,name:r.name,arguments:r.arguments,status:r.status,repaired:r.repaired??!1,error:r.error,resultPreview:"success"===r.status?Oe(r.resultPayload).slice(0,300):void 0}),Ae("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const i={role:"tool",content:"success"===r.status?Oe(r.resultPayload,c.toolResultMaxChars):`ERROR: ${r.error??"tool failed"}`,name:r.name,toolCallId:r.id};p.push(i),f.push(i),"blocked"===r.status&&($=!0)}if($)return A("blocked")}return A("maxSteps")}function Le(e,t=2){const n=new WeakSet;return JSON.stringify(e,(e,t)=>{if("object"==typeof t&&null!==t){if(n.has(t))return"[Circular]";n.add(t)}return"bigint"==typeof t?t.toString():t},t)}const $e={EVENTS:"kernel.events",COMMANDS:"kernel.commands",HISTORY:"kernel.history",TIME_SERVER:"kernel.timeServer",NOTIFICATIONS:"kernel.notifications",AI:"kernel.ai",LLM:"kernel.llm",POLICY:"kernel.policy",TASKS:"kernel.tasks"},je={FS:"runtime.fs",SEARCH:"runtime.search",VCS:"runtime.vcs",WORKSPACE:"runtime.workspace",LLM:"runtime.llm",SECRETS:"runtime.secrets",TASKS:"runtime.tasks",TERMINALS:"runtime.terminals",MCP:"runtime.mcp"},Fe={ACTIVITY_BAR:"shell.activityBar",STATUSBAR:"shell.statusbar",VIEW:"shell.view",VIEWS:"shell.views",KEYBOARD_SHORTCUTS:"shell.keyboardShortcuts",LAYOUT:"shell.layout",CONTENT_TABS:"shell.contentTabs",PANEL_TABS:"shell.panelTabs"},Be={SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},qe={MANAGER:"extensions.manager"},ze={TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},Ue={AGENT_RUN:"ai.agent.run",APPROVE_PENDING:"ai.approvePending",ASK:"ai.ask",CANCEL_RUN:"ai.cancelRun",DISMISS_PENDING:"ai.dismissPending",DO:"ai.do",RUN_PLAN:"ai.runPlan",SESSION_ARCHIVE:"ai.session.archive",SESSION_CREATE:"ai.session.create",SESSION_DELETE:"ai.session.delete",SESSION_LIST:"ai.session.list",SESSION_RENAME:"ai.session.rename",SHOW_LAST_TRACE:"ai.showLastTrace",SUMMARIZE:"ai.summarize"},Ve={EXPORT:"policy.export",IMPORT:"policy.import",LIST_APPROVALS:"policy.listApprovals",SET_MODE:"policy.setMode",SHOW_MODE:"policy.showMode"},We={APPROVAL_APPROVE:"workflow.approval.approve",APPROVAL_REJECT:"workflow.approval.reject",RUN_CANCEL:"workflow.run.cancel",RUN_GET:"workflow.run.get",RUN_LIST:"workflow.run.list",RUN_PAUSE:"workflow.run.pause",RUN_RESUME:"workflow.run.resume",RUN_START:"workflow.run.start",RUN_SUBFLOW:"workflow.run.subflow"};function Ke(e,t=220){let n=String(e??"");const r=[/\bsk-[A-Za-z0-9]{20,}\b/g,/\bghp_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*\b/g,/(\b(password|passwd|pwd|secret|token|api[_-]?key)\b\s*[:=]\s*)([^\s'"]+)/gi];for(const e of r)n=n.replace(e,(e,t)=>"string"==typeof t?`${t}[REDACTED]`:"[REDACTED]");return n=n.replace(/\s+/g," ").trim(),n.length>t?n.slice(0,t)+"…":n}function Ge(e,t,n,r,i,s,o,a){punica.kernel?.Events?.manager&&punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:r,spanId:i,parentSpanId:s,timestampMs:Date.now(),source:o,kind:t},payload:a})}const He="punica.kernel.ai.sessions.index.v1";function Ye(e){return`punica.kernel.ai.session.${e}.v1`}function Je(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const Ze=new class{readIndex(){const e=Je();if(!e)return[];try{const t=e.getItem(He);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=Je();if(t)try{t.setItem(He,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=Je();if(t)try{const n=t.getItem(Ye(e));if(!n)return;const r=JSON.parse(n);if(!r||1!==r.version||!r.meta?.sessionId)return;return r}catch{return}}writeSession(e){const t=Je();if(t)try{t.setItem(Ye(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=Je();if(t)try{t.removeItem(Ye(e))}catch{}}};let Qe=Ze;function Xe(){return Qe}const et="New chat";function tt(){return Date.now()}function nt(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${tt().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function rt(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:tt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function it(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function st(e){const t={role:e.role,content:e.content};return e.name&&(t.name=e.name),e.toolCallId&&(t.toolCallId=e.toolCallId),e.toolCalls&&e.toolCalls.length>0&&(t.toolCalls=e.toolCalls),t}const ot=new class{#x=null;#C=null;#T=new Map;#N=!1;#M=new Map;initialize(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{!function(e,t){const n=e?.payload??e,r=n?.request;if(!r?.id)return;const i=e?.envelope?.correlationId,s=n?.context?.workspaceId,o=n?.context?.traceId,a=punica.kernel.Events.manager.createCorrelationId(),c={pendingId:a,kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason,correlationId:i,...o?{traceId:o}:{},workspaceId:s,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#T)}),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#x=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(Ve.SET_MODE,{title:"Policy: Set Mode…",description:"Switch policy mode: suggest (plan only) or execute (allow running capabilities).",execute:e=>{const t="execute"===("string"==typeof e?e:e?.mode??"suggest")?"execute":"suggest";punica.kernel?.Policy?.manager&&punica.kernel?.Events?.manager&&(punica.kernel.Policy.manager.setMode(t),punica.kernel.Events.manager.publishEvent({name:"policy.modeChanged",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{mode:t}}))}}),t.registerCommand(Ve.SHOW_MODE,{title:"Policy: Show Mode",description:"Print current policy mode to console.",execute:()=>{punica.kernel?.Policy?.manager&&console.log("[Policy] mode",punica.kernel.Policy.manager.getMode())}}),t.registerCommand(Ve.EXPORT,{title:"Policy: Export State…",description:"Export policy state (mode + approvals) as JSON.",execute:e=>{const t="boolean"==typeof e?e:e?.download??!1;if(!punica.kernel?.Policy?.manager)return;const n=Le(punica.kernel.Policy.manager.exportState(),2);if(t){const e=globalThis;if(void 0===e.document||void 0===e.Blob||void 0===e.URL)return console.warn("[Policy] Download not available in this environment. Exporting to console:"),void console.log("[Policy] Export:\n"+n);const t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),i=e.document.createElement("a");i.href=r,i.download=`punica-policy-export-${Date.now()}.json`,e.document.body.appendChild(i),i.click(),e.document.body.removeChild(i),URL.revokeObjectURL(r)}else console.log("[Policy] Export:\n"+n)}}),t.registerCommand(Ve.IMPORT,{title:"Policy: Import State…",description:"Import policy state from JSON (file or clipboard).",execute:async e=>{let t;const n=e?.merge??!1;if(e&&"object"==typeof e&&e.data){const n=e.data;if("string"==typeof n)try{t=JSON.parse(n)}catch(e){throw new Error(`[Policy] Failed to parse import data: ${String(e)}`)}else"object"==typeof n&&(t=n)}if(!t){const e=globalThis;if(!e.navigator?.clipboard?.readText)throw new Error("[Policy] No import data provided. Pass data in arg or copy JSON to clipboard.");try{const n=await e.navigator.clipboard.readText();t=JSON.parse(n)}catch{throw new Error("[Policy] No import data provided. Pass data in arg or copy valid JSON to clipboard.")}}if(!punica.kernel?.Policy?.manager)return;const r=punica.kernel.Policy.manager.importState(t,{merge:n});console.log(`[Policy] Imported ${r} approval(s) (merge: ${n})`)}}),t.registerCommand(Ve.LIST_APPROVALS,{title:"Policy: List Approvals",description:"List all recorded approvals.",execute:()=>{if(!punica.kernel?.Policy?.manager)return;const e=punica.kernel.Policy.manager.listApprovals();console.log(`[Policy] ${e.length} approval(s):\n`+Le(e,2))}}),t.registerCommand(Ue.ASK,{title:"AI: Ask…",description:"Ask the AI to suggest a plan (no execution).",execute:e=>{const t="string"==typeof e?e:e?.query;if(!t||!String(t).trim())return;if(!punica.kernel?.Events?.manager)return;const n="object"==typeof e&&null!==e?e:{},r={query:String(t).trim(),mode:"suggest"};n.productId&&(r.productId=n.productId),n.targetArtifact&&(r.targetArtifact=n.targetArtifact),n.profile&&(r.profile=n.profile),n.originExtension&&(r.originExtension=n.originExtension),punica.kernel.Events.manager.publishEvent({name:"ai.planRequested",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:r})}}),t.registerCommand(Ue.DO,{title:"AI: Do…",description:"Single-shot: ask the AI, generate a plan, and execute it (when policy mode allows).",execute:e=>{const t="string"==typeof e?e:e?.query;if(!t||!String(t).trim())return;if(!punica.kernel?.Events?.manager)return;const n="object"==typeof e&&null!==e?e:{},r={query:String(t).trim(),mode:"execute"};n.productId&&(r.productId=n.productId),n.targetArtifact&&(r.targetArtifact=n.targetArtifact),n.profile&&(r.profile=n.profile),n.originExtension&&(r.originExtension=n.originExtension),punica.kernel.Events.manager.publishEvent({name:"ai.planRequested",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:r})}}),t.registerCommand(Ue.RUN_PLAN,{title:"AI: Run Plan",description:"Execute the last suggested plan (optionally a user-edited copy).",execute:t=>{const n=t&&"object"==typeof t&&"string"==typeof t.planId&&Array.isArray(t.steps)?t:void 0;e.runLastPlan(n).catch(e=>{console.error("[AI] run failed",e)})}}),t.registerCommand(Ue.AGENT_RUN,{title:"AI: Run Agent",description:"Run the agentic tool-use loop: the model calls capabilities as tools, sees results, and iterates until it answers.",execute:t=>{const n="string"==typeof t?{query:t}:t&&"object"==typeof t&&"string"==typeof t.query?t:void 0;n&&n.query.trim()&&e.runAgent(n).catch(e=>{console.error("[AI] agent run failed",e)})}}),t.registerCommand(Ue.APPROVE_PENDING,{title:"AI: Approve Pending Action…",description:"Approve a pending policy-gated action by ID.",execute:t=>{let n,r;if("string"==typeof t?n=t:t&&"object"==typeof t&&(n=t.pendingId,r=t.scope),!n){const t=e.getPendingApprovals();if(0===t.length)return;n=t[0].pendingId}const i="always"===r?"always":"workspace"===r?"workspace":"once";e.approvePending(n,i)||console.warn("[AI] Failed to approve pending",n)}}),t.registerCommand(Ue.DISMISS_PENDING,{title:"AI: Dismiss Pending Action…",description:"Dismiss a pending policy-gated action by ID.",execute:t=>{let n;"string"==typeof t?n=t:t&&"object"==typeof t&&(n=t.pendingId),n&&(e.dismissPending(n)||console.warn("[AI] Failed to dismiss pending",n))}}),t.registerCommand(Ue.CANCEL_RUN,{title:"AI: Cancel Run",description:"Cancel AI runs. Bare: everything (legacy Stop). Pass { runId } or { sessionId } to cancel one run / one conversation only.",execute:t=>{const n=t&&"object"==typeof t&&(t.runId||t.sessionId)?{runId:t.runId,sessionId:t.sessionId}:void 0;e.setCancelRequested(!0,n)}}),t.registerCommand(Ue.SESSION_CREATE,{title:"AI: New Session…",description:"Create a new AI conversation session.",execute:e=>{const t=punica.kernel?.AI?.sessions;if(t)return t.create(e&&"object"==typeof e?e:void 0)}}),t.registerCommand(Ue.SESSION_LIST,{title:"AI: List Sessions",description:"List AI conversation sessions (most recent first).",execute:e=>{const t=punica.kernel?.AI?.sessions;return t?t.list(e?.workspaceId):[]}}),t.registerCommand(Ue.SESSION_RENAME,{title:"AI: Rename Session…",description:"Rename an AI conversation session.",execute:e=>{const t=punica.kernel?.AI?.sessions,n=e?.sessionId,r=e?.title;return!(!t||!n||"string"!=typeof r)&&t.rename(String(n),r)}}),t.registerCommand(Ue.SESSION_ARCHIVE,{title:"AI: Archive Session…",description:"Archive (or unarchive) an AI conversation session.",execute:e=>{const t=punica.kernel?.AI?.sessions,n=e?.sessionId;return!(!t||!n)&&t.archive(String(n),e?.archived)}}),t.registerCommand(Ue.SESSION_DELETE,{title:"AI: Delete Session…",description:"Delete an AI conversation session and its history.",execute:e=>{const t=punica.kernel?.AI?.sessions,n="string"==typeof e?e:e?.sessionId;return!(!t||!n)&&t.delete(String(n))}}),t.registerCommand(Ue.SHOW_LAST_TRACE,{title:"AI: Show Last Run Trace",description:"Print last run trace to console (temporary).",execute:()=>{const t=e.getLastRun();console.log("[AI] lastRun\n"+Le(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+Le(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Ue.SUMMARIZE,{title:"AI: Summarize…",description:"Summarize a given text snippet (no capability invocation).",execute:async(e,t)=>{const n=String(e?.text??"").trim();if(!n)return;if(!punica.kernel?.Events?.manager)return;const r=t?.__punica?.correlationId??punica.kernel.Events.manager.createCorrelationId(),i=t?.__punica?.traceId??r,s=t?.__punica?.spanId??punica.kernel.Events.manager.createCorrelationId(),o=t?.__punica?.source??"kernel:ai",a=e?.source;Ge("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:Ke(n),source:a}});try{const e={correlationId:r,messages:[{role:"system",content:"You are a helpful assistant. Summarize the provided text concisely. Prefer bullet points when appropriate. Keep it clear and accurate."},{role:"user",content:n}]},t=punica.runtime.capabilities?.gateway;if(!t&&!punica.runtime?.llm)return;const c=t?await t.call("llm.chat",e,{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"ai:commands"},origin:{kind:"ai",id:"command-summary"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat(e),l=String(c?.text??"").trim(),u=punica.kernel.Events.manager.createCorrelationId();Ge("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:Ke(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),Ge("ai.summaryGenerated","result",r,i,punica.kernel.Events.manager.createCorrelationId(),u,o,{summary:l,usage:c?.usage,modelId:c?.modelId,provider:c?.provider,source:a})}catch(e){Ge("ai.response","error",r,i,punica.kernel.Events.manager.createCorrelationId(),s,o,{kind:"summarize",error:String(e?.message??e)})}}})}({runLastPlan:e=>this.runLastPlan(e),runAgent:e=>this.runAgent(e),getLastPlan:()=>this.getLastPlan(),approvePending:(e,t)=>this.approvePending(e,t),dismissPending:e=>this.dismissPending(e),getPendingApprovals:()=>this.getPendingApprovals(),getLastRun:()=>this.#C,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#M){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#N=e;for(const t of this.#M.values())t.cancelRequested=e,e&&t.controller.abort()}}})}getLastPlan(){return this.#x}getPendingApprovals(){return e=this.#T,Array.from(e.values()).sort((e,t)=>e.timestampMs-t.timestampMs);var e}approvePending(e,t){return function(e,t,n){const r=n.get(e);return!!r&&(punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason},t,{decidedBy:"user",workspaceId:r.workspaceId}),n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.approvalRecorded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r,scope:t}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"approved"}}),!0)}(e,t,this.#T)}dismissPending(e){return function(e,t){const n=t.get(e);return!!n&&(t.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalDismissed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:n}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"dismissed"}}),!0)}(e,this.#T)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#x=e);const t=await pe(this.#x,this.#C,()=>this.#N,e=>{this.#x=e});return this.#C=t,this.#N=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#M.set(t,n);try{return await Re(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#M.delete(t)}}},at=new class{#D;create(e){const t=Xe(),n={sessionId:nt("sess"),title:e?.title?.trim()||et,createdAtMs:tt(),updatedAtMs:tt(),messageCount:0,tokenEstimate:0};e?.workspaceId&&(n.workspaceId=e.workspaceId);const r={version:1,meta:n,transcript:[]};t.writeSession(r);const i=t.readIndex();return i.push(n),this.#P(i,n),t.writeIndex(i),rt("ai.sessionCreated",n),{...n}}list(e){const t=Xe().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return Xe().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#O(e,e=>{e.title=n});return!!r&&(rt("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#O(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(rt("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=Xe(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[i]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),rt("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=Xe(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||nt("msg"),createdAtMs:e.createdAtMs||tt(),content:e.content.length>16e3?e.content.slice(0,16e3)+"…":e.content};return n?.runId&&!t.runId&&(t.runId=n.runId),t});i.transcript.push(...s),i.transcript.length>200&&i.transcript.splice(0,i.transcript.length-200);const o=i.meta;if(o.messageCount=i.transcript.length,o.updatedAtMs=tt(),n?.runId&&(o.lastRunId=n.runId),o.tokenEstimate=i.transcript.reduce((e,t)=>e+function(e){return Math.ceil(e.length/4)}(t.content),0),o.title===et){const e=i.transcript.find(e=>"user"===e.role);e&&(o.title=function(e){const t=e.replace(/\s+/g," ").trim();return t?t.length>48?t.slice(0,47)+"…":t:et}(e.content))}r.writeSession(i),this.#R(o),rt("ai.sessionUpdated",o,{appendedCount:s.length,runId:n?.runId});const a=this.#D;a?.shouldCompact(i)&&Promise.resolve().then(()=>a.compact(i)).then(t=>{const n=Xe().readSession(e);n&&(n.contextView=t,Xe().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=Xe().readSession(e);if(!t)return[];const n=t.contextView;if(n){const e=[];return n.summaryText&&e.push({role:"system",content:`[conversation summary]\n${n.summaryText}`}),e.push(...it(n.messages).map(st)),e}return it(t.transcript.slice(-40)).map(st)}setCompactor(e){this.#D=e}recordUsage(e,t){const n=this.#O(e,e=>{const n=e.usage??{inputTokens:0,outputTokens:0,totalTokens:0,cacheReadTokens:0,runCount:0};n.inputTokens+=t.inputTokens,n.outputTokens+=t.outputTokens,n.totalTokens+=t.totalTokens,n.cacheReadTokens+=t.cacheReadTokens??0,"number"==typeof t.totalCost&&(n.totalCostUsd=(n.totalCostUsd??0)+t.totalCost),n.runCount+=1,n.lastRunAtMs=tt(),e.usage=n});return!!n&&(rt("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#O(e,t){const n=Xe(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=tt(),n.writeSession(r),this.#R(r.meta),{...r.meta}}#R(e){const t=Xe(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#P(e,t){const n=Xe(),r=e=>e.workspaceId===t.workspaceId;let i=e.filter(r);for(;i.length>50;){const s=i.filter(e=>e.sessionId!==t.sessionId).sort((e,t)=>{const n=e.archived?0:1,r=t.archived?0:1;return n!==r?n-r:e.updatedAtMs-t.updatedAtMs})[0];if(!s)break;const o=e.findIndex(e=>e.sessionId===s.sessionId);o>=0&&e.splice(o,1),n.deleteSession(s.sessionId),rt("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};at.setCompactor(function(){const e=ge.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=we([{role:"system",content:""},...n.map(e=>({role:e.role,content:e.content,...e.name?{name:e.name}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolCalls?{toolCalls:e.toolCalls}:{}}))],e.keepLastTurnsVerbatim);return{messages:n.map((e,t)=>t+1<r&&"tool"===e.role&&!e.content.startsWith(ye)?{...e,content:be(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());var ct={manager:ot,sessions:at},lt=Object.freeze({__proto__:null,default:ct,manager:ot,sessions:at});const ut=new class{#L=new Map;#$=new Map;#j=new Map;#F;registerProductOriginResolver(e){this.#F=e}#B(e){try{const t=punica.extensions?.manager;if(t){if(t.getExtension(e))return!0;const n=t.getAllExtensions();if(Array.isArray(n))return n.some(t=>t.name===e||t.id===e)}return!0}catch{return!0}}register(e,t){if(!e.id)throw new Error("Instruction class must have an id");if(!e.role)throw new Error("Instruction class must have a role");if(!e.systemPrompt)throw new Error("Instruction class must have a systemPrompt");if(this.#L.has(e.id)){const n=this.#L.get(e.id),r=n?.originExtension||this.#j.get(e.id),i=t||e.originExtension;if(!r||!i||r!==i)throw new Error(`Instruction class ID collision: "${e.id}" is already registered by a different extension. Each product extension must use namespaced IDs (e.g., "ivy.node.generator", "ivy.agent.generator").`)}!t&&e.productId&&this.#F&&(t=this.#F(e.productId)),t&&(e.originExtension=t,this.#j.set(e.id,t)),e.capability||(e.capability=function(e){if(e.capability)return e.capability;const t={id:e.id,title:e.role.charAt(0).toUpperCase()+e.role.slice(1),description:`LLM instruction class: ${e.role}`,version:"1.0.0",tags:["llm","instruction-class",e.role]};return t.inputs={schema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",enum:[e.id],description:"Instruction class identifier"},userPrompt:{type:"string",description:"User prompt/query"},context:{type:"object",properties:{workspaceId:{type:"string"},filePath:{type:"string"},previousOutputs:{type:"object"},capabilities:{type:"array"}}},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"}}}}}},e.outputSchema?t.outputs={schema:e.outputSchema,kind:"direct"}:t.outputs={schema:{type:"object",properties:{text:{type:"string"},structured:{type:"object"}}},kind:"direct"},e.riskLevel?t.policy={risk:e.riskLevel,approval:"high"===e.riskLevel?"step":"plan"}:t.policy={risk:"medium",approval:"step"},t.sideEffects=["llm-invocation"],"json_object"===e.responseFormat&&t.sideEffects.push("structured-output"),t}(e)),this.#L.set(e.id,e),this.#$.set(e.id,e.capability)}unregister(e){this.#L.delete(e),this.#$.delete(e),this.#j.delete(e)}unregisterByOrigin(e){const t=[];this.#j.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>this.unregister(e))}get(e){return this.#L.get(e)}list(e=!1){const t=Array.from(this.#L.values());return e?t.filter(e=>{const t=e.originExtension||this.#j.get(e.id);return!t||this.#B(t)}):t}listSummaries(e=!1){return this.list(e).map(e=>({id:e.id,role:e.role,originExtension:e.originExtension||this.#j.get(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0}))}has(e){return this.#L.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#j.get(e);return!n||this.#B(n)}getCapability(e){return this.#$.get(e)}listCapabilities(){return Array.from(this.#$.values())}};async function dt(e){const{primaryModelId:t,count:n,exclude:r}=e,i=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{return await e.listInstalled()}catch{return null}}();if(!i||!Array.isArray(i.installed)||0===i.installed.length)return t?[t]:[];const s=new Set(i.installed.map(e=>e.id)),o=[],a=e=>{e&&s.has(e)&&(function(e,t){return!(!t||0===t.length)&&t.includes(e)}(e,r)||o.includes(e)||o.push(e))};if(a(t),o.length<n)for(const e of i.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function pt(e,t){let n=e.riskLevel;if(!n){const r=await async function(e,t){if("risk-assessor"===e.id)return{riskLevel:"medium"};const n=ut.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,i=[];i.push("Assess the risk level for this task:"),i.push(""),i.push(`Instruction Class: ${e.id}`),i.push(`Role: ${e.role}`),i.push(""),i.push("User Prompt:"),i.push(t.userPrompt),i.push(""),i.push("Context:"),i.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),i.push(`- File Path: ${r?.filePath??"N/A"}`),i.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),i.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),i.push(""),i.push("Consider:"),i.push("- Is this production code?"),i.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),i.push("- Is it a critical business function?"),i.push("- Does it handle sensitive data?"),i.push("- Is it a simple utility or a complex system?"),i.push(""),i.push('Respond with ONLY one word: "low", "medium", or "high".');const s=i.join("\n");try{const e=punica.runtime.capabilities?.gateway,t=e?await e.call("llm.chat",{messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20},{sessionId:"internal",workspaceId:void 0,actor:{type:"extension",extensionName:"kernel:policy"},origin:{kind:"command",id:"risk-assessment"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat({messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20}),r=String(t.text??"").toLowerCase();return/\bhigh\b/.test(r)?{riskLevel:"high"}:/\bmedium\b/.test(r)?{riskLevel:"medium"}:/\blow\b/.test(r)?{riskLevel:"low"}:{riskLevel:"medium"}}catch{return{riskLevel:"medium"}}}(e,t);n=r.riskLevel}if(n||(n="medium"),"high"===n){const t=e.expertModelId,r=e.expertModelIds;let i=[];return i=r&&r.length>0?r.slice():await dt({primaryModelId:t,count:3}),{strategy:i.length>1?"multi":"single",modelIds:i.length?i:[t].filter(Boolean),riskLevel:n,reason:"High risk detected via LLM-based assessment"}}let r=e.expertModelId??null;return r||(r=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{const t=await e.listInstalled();if(t.activeModelId)return t.activeModelId;const n=t.installed[0];return n?n.id:null}catch{return null}}()),{strategy:"single",modelIds:r?[r]:[],riskLevel:n,reason:"Low/medium risk, single expert sufficient"}}function ht(e){const t=[];return e.capabilities&&e.capabilities.length>0&&t.push(`Available capabilities:\n${JSON.stringify(e.capabilities,null,2)}`),e.previousOutputs&&t.push(`Previous outputs:\n${JSON.stringify(e.previousOutputs,null,2)}`),e.filePath&&t.push(`Current file: ${e.filePath}`),e.workspaceId&&t.push(`Workspace ID: ${e.workspaceId}`),t.length>0?t.join("\n\n"):void 0}function ft(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function mt(){const e=globalThis;return e.punica?.runtime?.fs}function gt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const yt={type:"ai",id:"llm:context"},bt={kind:"ai",id:"context-builder"};async function wt(e){if(e.filePath)try{const t=ft(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:yt,origin:bt,trace:{traceId:gt()},policy:{mode:"execute"}}):await(mt()?.readFile?.(e.filePath));if(!n)return;const r=5e3,i=n.length>r?n.slice(0,r)+"\n... (truncated)":n;return`File content (${e.filePath}):\n\`\`\`\n${i}\n\`\`\``}catch{return}}async function vt(e){try{const t=ft(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:yt,origin:bt,trace:{traceId:gt()},policy:{mode:"execute"}}):await(mt()?.getFileTree?.());if(!n||!Array.isArray(n)||0===n.length)return;const r=n.filter(e=>!e.isDirectory).length,i=n.filter(e=>e.isDirectory).length;return`Workspace structure: ${r} files, ${i} directories\nTop-level items: ${n.filter(e=>{const t=String(e.path??"");return!t.includes("/")||2===t.split("/").length}).slice(0,20).map(e=>{const t=String(e.name??"");if(t)return t;return String(e.path??"").split("/").pop()??""}).join(", ")}`}catch{return}}function kt(){const e=globalThis;return e.punica?.shell?.ContentTabs}function It(){return"undefined"==typeof document?void 0:document}function Et(){const e=It();if(!e)return;const t=e.getElementById("content-tabs-panels");if(!t)return;const n=Array.from(t.children);for(const e of n){const t=e.__codeEditorInstance;if(t)return t}}function At(e){try{const t=kt();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Et();if(!n)return;const r=n.getSelection?.(),i=n.getModel?.();if(!r||!i||r.isEmpty())return;const s=i.getValueInRange(r),o=String(s??"").trim();if(!o)return;const a=2e3,c=o.length>a?o.slice(0,a)+"\n... (truncated)":o,l=r.startLineNumber;return`Selected code (lines ${l}-${r.endLineNumber}):\n\`\`\`\n${c}\n\`\`\``}catch{return}}function St(){try{const e=kt();if(!e)return;const t=[],n=e.getActivePath?.()??null,r=e.getActiveViewType?.()??null;if(n&&(t.push(`Active file: ${n}`),r&&t.push(`View type: ${r}`)),n)try{const e=Et();if(e){const n=e.getPosition?.(),r=e.getModel?.();if(n&&r){const e=n.lineNumber,i=n.column,s=r.getOffsetAt(n);t.push(`Cursor position: Line ${e}, Column ${i} (offset: ${s})`)}}}catch{}try{const e=It();if(e){const n=e.querySelector('[id*="content-tabs"]');if(n){const e=n.querySelectorAll('[role="tab"]');e.length>1&&t.push(`Open files: ${e.length} tabs`)}}}catch{}return t.length>0?`Editor State:\n${t.join("\n")}`:void 0}catch{return}}function _t(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const xt={type:"ai",id:"llm:context"},Ct={kind:"ai",id:"context-builder"};async function Tt(e){const t=function(){const e=globalThis;return e.punica?.runtime?.vcs}();if(!t)return;const n=[];if(t.status)try{const r=function(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}(),i=r?await r.call("vcs.status",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:xt,origin:Ct,trace:{traceId:_t()},policy:{mode:"execute"}}):await t.status();if(i){const e=[];i.current&&(e.push(`Branch: ${i.current}`),i.tracking&&e.push(`Tracking: ${i.tracking}`),i.ahead&&i.ahead>0&&e.push(`Ahead: ${i.ahead}`),i.behind&&i.behind>0&&e.push(`Behind: ${i.behind}`));const t=i.modified??[],r=i.staged??[],s=i.created??[],o=i.deleted??[],a=i.renamed??[],c=(t,n,r)=>{if(0===n.length)return;const i=n.slice(0,r).join(", "),s=n.length>r?"...":"";e.push(`${t} (${n.length}): ${i}${s}`)};c("Staged",r,5),c("Modified",t,5),c("Created",s,3),c("Deleted",o,3),c("Renamed",a,3),e.length>0&&n.push(`Git Status:\n${e.join("\n")}`)}}catch{}if(t.logs&&e.filePath)try{const e=await t.logs({limit:5});if(e&&Array.isArray(e)&&e.length>0){const t=e.slice(0,5).map(e=>{const t=e.hash?e.hash.substring(0,7):"unknown",n=e.date?new Date(e.date).toLocaleDateString():"",r=e.authorName??"",i=(e.message??"").split("\n")[0].substring(0,60);return` ${t} ${n} ${r?`(${r})`:""}: ${i}${i.length>=60?"...":""}`}).join("\n");n.push(`Recent Commits:\n${t}`)}}catch{}if(t.branches)try{const e=await t.branches();if(e&&Array.isArray(e)&&e.length>0){const t=e.find(e=>e.current),r=e.filter(e=>!e.current).slice(0,5),i=[];t?.name&&i.push(`Current: ${t.name}`),r.length>0&&i.push(`Other branches: ${r.map(e=>e.name).filter(Boolean).join(", ")}`),i.length>0&&n.push(`Branches:\n${i.join("\n")}`)}}catch{}return n.length>0?n.join("\n\n"):void 0}async function Nt(){const e=function(){const e=globalThis;return e.punica?.kernel?.Tasks?.manager}();if(!e)return;const t=[];try{const n=await(e.listRuns?.({status:["running","pending"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown";return` ${e.label??e.definitionId??"Unknown"} (${t})`}).join("\n");t.push(`Active Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listDefinitions?.());if(n&&n.length>0){const e=n.slice(0,10).map(e=>{const t=e.kind??"unknown",n=e.group?` [${e.group}]`:"";return` ${e.label??e.id??"Unknown"} (${t})${n}`}).join("\n");t.push(`Available Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listRuns?.({status:["success","failed","cancelled"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown",n=e.label??e.definitionId??"Unknown",r=null!=e.exitCode?` (exit: ${e.exitCode})`:"",i=e.startedAt?new Date(e.startedAt).toLocaleDateString():"";return` ${n}: ${t}${r}${i?` (${i})`:""}`}).join("\n");t.push(`Recent Task History:\n${e}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}async function Mt(e){if(!e.workspaceId)return;if(!function(){const e=globalThis;return e.punica?.runtime?.resources}())return;const t=[];try{const e=await(function(){const e=globalThis;return e.punica?.runtime?.datasets}()?.list?.());if(e&&e.length>0){const n=e.slice(0,10).map(e=>{const t=e.name??e.ref.id??"Unnamed",n=e.ref.provider??"";var r;return` ${t}${n?` [${n}]`:""}${"number"==typeof e.stats?.bytes?` (${r=e.stats.bytes,r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(2)} KB`:r<1073741824?`${(r/1048576).toFixed(2)} MB`:`${(r/1073741824).toFixed(2)} GB`})`:""}`}).join("\n");t.push(`Datasets (${e.length}):\n${n}`)}}catch{}try{const e=function(){const e=globalThis;return e.punica?.runtime?.compute?.registry?.listProviders?.()??[]}();if(e.length>0){const n=e.slice(0,10).map(e=>{const t=e.label??e.id??"Unnamed",n=e.kind??"",r=e.description??"";return` ${t}${n?` [${n}]`:""}${r?` - ${r}`:""}`}).join("\n");t.push(`Compute Providers (${e.length}):\n${n}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}const Dt="problems.getDiagnostics";function Pt(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Commands?.manager}();if(!t)return;const n=t.getAllCommands?.()??[];if(!n.some(e=>e.id===Dt))return;let r;try{r=t.executeCommand?.(Dt)}catch{return}if(!r||!Array.isArray(r)||0===r.length)return;const i=e.filePath?r.filter(t=>t.file===e.filePath):r;if(0===i.length)return;const s=i.slice(0,10).map(e=>{const t=e.file?`${e.file}:${e.line??0}:${e.column??0}`:`${e.line??0}:${e.column??0}`;return` ${(e.severity??"error").toUpperCase()} ${t}${e.source?`[${e.source}]`:""}${e.code?`(${e.code})`:""}: ${e.message??""}`}).join("\n"),o=i.length;return`Diagnostics (${o} ${1===o?"issue":"issues"}):\n${s}${o>10?`\n ... and ${o-10} more`:""}`}catch{return}}function Ot(e,t){switch(e){case"tenant":return t.workspaceId??"(unknown)";case"user":return t.userId??"(unknown)";case"capability":return t.capabilityId??"(unknown)";case"provider":return t.provider}}const Rt=new class{#q;#z=[];constructor(e){this.#q=Math.max(1,e?.maxRecords??1e4)}record(e){this.#z.push(e),this.#z.length>this.#q&&this.#z.splice(0,this.#z.length-this.#q)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,i=new Map;let s=0,o=0,a=0,c=0,l=0;for(const e of this.#z){if(e.timestamp<n||e.timestamp>r)continue;const u=Ot(t,e),d=i.get(u)??{cost:0,calls:0,promptTokens:0,completionTokens:0,cachedPromptTokens:0};d.cost+=e.totalCost,d.calls+=1,d.promptTokens+=e.promptTokens,d.completionTokens+=e.completionTokens,d.cachedPromptTokens+=e.cachedPromptTokens??0,i.set(u,d),s+=e.totalCost,o+=1,a+=e.promptTokens,c+=e.completionTokens,l+=e.cachedPromptTokens??0}const u=Array.from(i.entries()).map(([e,t])=>({key:e,cost:t.cost,calls:t.calls,promptTokens:t.promptTokens,completionTokens:t.completionTokens,cachedPromptTokens:t.cachedPromptTokens})).sort((e,t)=>t.cost-e.cost);return{scope:t,totalCost:s,totalCalls:o,totalPromptTokens:a,totalCompletionTokens:c,totalCachedPromptTokens:l,byKey:u}}clear(){this.#z.length=0}};async function Lt(e,n){const r=ut;if(!r)return{ok:!1,error:"Instruction class registry not available",metadata:{instructionClass:e.instructionClass,role:"unknown"}};if(!(r.isAvailable?r.isAvailable(e.instructionClass):r.has(e.instructionClass))){const t=r.get(e.instructionClass);return t?{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_ORIGIN_EXTENSION_INACTIVE",error:`Instruction class "${e.instructionClass}" is registered but its origin extension is not active`,metadata:{instructionClass:e.instructionClass,role:t.role,originExtension:t.originExtension,productId:t.productId}}:{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}}}const i=r.get(e.instructionClass);if(!i)return{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}};try{const r=await async function(e){return e?(await Promise.all([Promise.resolve(ht(e)),wt(e),Promise.resolve(At(e)),vt(e),Tt(e),Nt(),Promise.resolve(St()),Mt(e),Promise.resolve(Pt(e))])).filter(e=>void 0!==e&&e.length>0).join("\n\n"):""}(e.context),s=r?`${r}\n\n${e.userPrompt}`:e.userPrompt,o=await pt(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,correlationId:n?.correlationId??punica.kernel.Events.manager.createCorrelationId()},c=!0===e.options?.stream?"llm.chatStream":"llm.chat";let l,u,d=0;const p=await t();if("single"===o.strategy||o.modelIds.length<=1){const t=o.modelIds[0],n=Date.now();try{const r=punica.kernel.Events.manager;l=await punica.runtime.capabilities.gateway.call(c,{...a,modelId:t},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-n}catch(t){if(!(o.modelIds.length>1)||e.options?.skipFallback)throw t;{let n=t;for(const t of o.modelIds.slice(1))try{const r=Date.now(),s=punica.kernel.Events.manager;try{s.publishEvent({name:"llm.fallback",envelope:{id:s.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,fromModelId:o.modelIds[0],toModelId:t,reason:n?.message??"unknown"}})}catch{}l=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??s.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??s.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-r;break}catch(e){n=e;continue}if(!l)throw n}}}else{const t=Date.now(),n=punica.kernel.Events.manager,r=o.modelIds.map(async t=>{const r=Date.now(),s=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??n.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??n.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),o=Date.now()-r;let c;if(i.outputSchema&&"json_object"===i.responseFormat)try{c=JSON.parse(s.text)}catch{}return{res:s,expert:{modelId:s.modelId??t,text:s.text,structured:c,usage:s.usage,latencyMs:o}}}),s=await Promise.all(r);u=s.map(e=>e.expert);const c=function(e,t){if(!e.length)throw new Error("aggregateBestOfN called with no results");if("json_object"===t.responseFormat){const t=e.filter(e=>void 0!==e.structured);if(t.length>0)return t.reduce((e,t)=>t.latencyMs<e.latencyMs?t:e)}return e.reduce((e,t)=>{const n=e.text.length-e.latencyMs/1e3+.1*(e.usage?.outputTokens??0);return t.text.length-t.latencyMs/1e3+.1*(t.usage?.outputTokens??0)>n?t:e})}(u,i);l={text:c.text,modelId:c.modelId,provider:s.find(e=>e.expert.modelId===c.modelId)?.res.provider,usage:c.usage},d=Date.now()-t}let h;if(i.outputSchema&&"json_object"===i.responseFormat)try{h=JSON.parse(l.text)}catch(e){return{ok:!1,error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}const f={ok:!0,text:l.text,structured:h,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId,tokensUsed:l.usage?.totalTokens,inputTokens:l.usage?.inputTokens,outputTokens:l.usage?.outputTokens,latencyMs:d,modelId:l.modelId,provider:l.provider}};try{const e=l.usage?.inputTokens??0,t=l.usage?.outputTokens??0,n=l.usage?.cacheReadInputTokens??0,r=String(l.provider??"unknown"),s=String(l.modelId??"unknown"),o=0,c={provider:r,model:s,promptTokens:e,completionTokens:t,totalCost:o,latencyMs:d};Rt.record({capabilityId:i.id,provider:r,model:s,promptTokens:e,completionTokens:t,...n>0?{cachedPromptTokens:n}:{},totalCost:o,latencyMs:d,timestamp:Date.now(),workspaceId:p}),punica.kernel.Events.manager.publishEvent({name:"llm.call",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,workspaceId:p,meta:c}})}catch{}return f}catch(e){return{ok:!1,error:`LLM invocation failed: ${e?.message??String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}}async function $t(e){return Lt({instructionClass:"planner",userPrompt:`Generate a Workflow (ivy.workflow/v0.1) workflow from this query:\n${e.query}\n\nThe Workflow should have:\n- apiVersion: "ivy.workflow/v0.1"\n- kind: "Workflow"\n- capability: { id, version, title, description, inputs, outputs }\n- graph: { entryNodeId, nodes[], edges[] }\n- Nodes should use ref: { kind: "ivyNode" | "workflow" | "flowInput" | "flowOutput", id?, version? }\n- Edges should use fromPath/toPath for property mapping\n`,context:{capabilities:e.capabilities}})}async function jt(e){return Lt({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function Ft(e){return Lt({instructionClass:"validator",userPrompt:e.language?`Validate this ${e.language} code:\n\n${e.code}`:`Validate this code:\n\n${e.code}`,context:e.context})}async function Bt(e){return Lt({instructionClass:"reviewer",userPrompt:e.language?`Review this ${e.language} code:\n\n${e.code}`:`Review this code:\n\n${e.code}`,context:e.context})}async function qt(e){let t="";e.requirements?t+=`Requirements:\n${e.requirements}\n\n`:t+="Optimize and improve this Workflow:\n\n",t+=`Current Workflow:\n${JSON.stringify(e.workflow,null,2)}\n\n`,e.requirements?(t+="Please edit this Workflow according to the requirements above. ",t+="Maintain DAG structure, preserve all node.ref and node.data, ",t+='ensure all IDs remain valid, and maintain apiVersion="ivy.workflow/v0.1" and kind="Workflow".\n'):(t+="Please optimize this Workflow: ",t+="- Improve parallelization opportunities\n",t+="- Remove redundant nodes/edges\n",t+="- Improve node labels\n",t+="- Maintain DAG structure (no cycles)\n",t+="- Preserve all functionality\n",t+='- Maintain apiVersion="ivy.workflow/v0.1" and kind="Workflow"\n');return await Lt({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function zt(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function Ut(e,t){const n=zt(e).split("/").filter(Boolean),r=zt(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function Vt(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function Wt(e,t){const n=zt(e).split("/").filter(Boolean),r=zt(t).split("/").filter(Boolean);let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;const s=n.length-i,o=r.slice(i);return[...Array(s).fill(".."),...o].join("/")}async function Kt(e,t){const n=[];let r=0;const i=1048576;if("0.1"!==e.specVersion)throw new Error(`Unsupported CodegenBundle version: ${e.specVersion}`);if(!e.files||!Array.isArray(e.files))throw new Error("CodegenBundle must have a files array");if(0===e.files.length)throw new Error("CodegenBundle files array cannot be empty");if(e.files.length>50)throw new Error(`CodegenBundle exceeds max files limit: ${e.files.length} > 50`);let s=0;const o=/^(?!\/)(?!.*\.\.)([a-zA-Z0-9._-]+\/)*[a-zA-Z0-9._-]+$/;for(const r of e.files){if(!o.test(r.path)){n.push({path:r.path,error:"Invalid path: must be relative, no absolute paths, no .."});continue}if("delete"===r.action){if(void 0!==r.content){n.push({path:r.path,error:"Delete action cannot have content"});continue}}else if("create"===r.action||"update"===r.action){if(!r.content){n.push({path:r.path,error:`${r.action} action requires content`});continue}s+=r.content.length}const e=Wt(t,Ut(t,zt(r.path)));(e.startsWith("..")||Vt(e))&&n.push({path:r.path,error:"Path traversal detected"})}if(s>i)throw new Error(`CodegenBundle exceeds max total size: ${s} > 1048576 bytes`);for(const t of e.files)if(!n.some(e=>e.path===t.path))try{const e=zt(t.path);if("create"===t.action){const n=e.split("/");if(n.length>1){const e=n.slice(0,-1).join("/");try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFolder(e)}catch{}}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFileWithContent(e,t.content),r++}else if("update"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{n.push({path:t.path,error:"File does not exist for update"});continue}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.updateFileContent(e,t.content),r++}else if("delete"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{continue}await punica.runtime.fs.deleteFile(e),r++}}catch(e){n.push({path:t.path,error:e?.message??String(e)})}return{applied:r,errors:n}}const Gt={type:"object",additionalProperties:!1,required:["specVersion","files"],properties:{specVersion:{type:"string",const:"0.1"},summary:{type:"string",maxLength:500},files:{type:"array",minItems:1,maxItems:50,items:{type:"object",additionalProperties:!1,required:["path","action"],properties:{path:{type:"string",minLength:1,maxLength:500,pattern:"^(?!/)(?!.*\\.\\.)([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+$"},action:{type:"string",enum:["create","update","delete"]},content:{type:"string",maxLength:1e6},encoding:{type:"string",enum:["utf-8"],default:"utf-8"}}}}}};const Ht=new class{api;constructor(){this.api={instructionClassRegistry:ut,invoke:Lt,plan:$t,generateCode:jt,validator:Ft,reviewer:Bt,editWorkflow:qt,listInstructionClasses:e=>ut.listSummaries(e)}}};var Yt={manager:Ht};const Jt={Commands:r,History:s,TimeServer:o,Tasks:d,Events:V,Notifications:H,Policy:ue,AI:lt,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:Gt,applyCodegenBundle:Kt,default:Yt,manager:Ht})};const Zt={manager:new class{#U=new Map;#V=new Map;#W=null;#K;#G;#H;#Y(){const e=punica.shell.Layout.manager,t=e.getSlot("activityBar")??e.getSlot("primarySidebar"),n=t?.content;this.#K=document.createElement("punica-row"),this.#G=document.createElement("punica-col"),this.#H=document.createElement("punica-col"),this.#K.setAttribute("direction","column"),this.#K.setAttribute("alignitems","stretch"),this.#K.setAttribute("justifycontent","space-between"),this.#K.style.height="100%",this.#K.appendChild(this.#G),this.#K.appendChild(this.#H),n?.appendChild(this.#K)}constructor(){}setActiveByViewId(e){if(e){for(const t of this.#U.values())if(t.viewId===e)return void this.#J(t.id);for(const t of this.#V.values())if(t.viewId===e)return void this.#J(t.id)}else this.#J(null)}#Z(e,t){const n=globalThis,r=()=>{const r=n.punica?.shell?.Views?.manager;return r?.reveal?.(e,{kind:"user-gesture",id:`activity-bar:${t}`})},i=n.punica?.runtime?.capabilities?.gateway;if(!i?.call)return void Promise.resolve(r()).catch(t=>{console.error("[ActivityBar] Failed to reveal view",e,t)});const s=n.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`activity-bar-${Date.now()}`;i.call("shell.revealView",{viewId:e},{sessionId:"default",actor:{type:"user"},origin:{kind:"command",id:`activity-bar:${t}`},trace:{traceId:o},policy:{mode:"execute"}}).catch(e=>(console.warn("[ActivityBar] shell.revealView failed, falling back to direct reveal:",e),Promise.resolve(r()))).catch(t=>{console.error("[ActivityBar] Failed to reveal view",e,t)})}#J(e){if(!this.#K)return;const t="extension-is-active";if(this.#K.querySelectorAll(".extension").forEach(e=>e.classList.remove(t)),!e){this.#W=null;const e=punica.shell.Layout.manager,t=e.getSlot("primarySidebar")?.content;return void(t&&t.classList.add("primarySidebar-hidden"))}const n=this.#K.querySelector("#"+e);n&&(n.classList.add(t),this.#W=e);const r=punica.shell.Layout.manager,i=r.getSlot("primarySidebar")?.content;i&&i.classList.remove("primarySidebar-hidden")}addItem(e){this.#K||this.#Y();const t=punica.shell.Layout.manager,n=document.createElement("punica-button");n.setAttribute("id",e.id),n.setAttribute("rounded",""),n.setAttribute("color","primary"),n.setAttribute("variant","text"),n.setAttribute("size","medium"),n.setAttribute("style","margin-bottom: 4px;"),n.setAttribute("title",e.title),n.onclick=()=>{const n=globalThis.punica?.shell?.Views?.manager,r=!!e.viewId&&!!n?.getPlacement?.(e.viewId),i=()=>{if(e.command)try{punica.kernel.Commands.manager.executeCommand(e.command)}catch(t){console.error("[ActivityBar] Failed to execute command for item",e.id,e.command,t)}};if(r||!!e.viewId){if(this.#W===e.id)return r&&n.hide(e.viewId,{kind:"user-gesture",id:`activity-bar:${e.id}`}),void this.#J(null);if(this.#J(e.id),r)this.#Z(e.viewId,e.id);else{try{t.ensureViewHost("primarySidebar",e.viewId)}catch(t){console.error("[ActivityBar] Failed to show primary view for item",e.id,e.viewId,t)}i()}}else i()},n.innerHTML=`<punica-icon size="xlarge">${e.icon}</punica-icon>`,n.className="extension";const r="primary"===e.alignment,i=r?this.#G:this.#H;(r?this.#U:this.#V).set(e.id,e);const s=i.querySelector("#"+e.id);s?i.replaceChild(n,s):i.appendChild(n),this.#W===e.id&&n.classList.add("extension-is-active")}removeItem(e){if(this.#U.has(e)){const t=this.#G.querySelector("#"+e);t&&(this.#G.removeChild(t),this.#U.delete(e))}else if(this.#V.has(e)){const t=this.#H.querySelector("#"+e);t&&(this.#H.removeChild(t),this.#V.delete(e))}}}};const Qt={manager:new class{#U=new Map;#V=new Map;#K;#G;#H;#Y(){const e=window.punica?.shell?.Layout.manager,t=e.getSlot("statusbar"),n=t?.content;this.#K=document.createElement("div"),this.#K.className="status-bar-inner",this.#G=document.createElement("div"),this.#G.className="status-bar-group status-bar-group-primary",this.#H=document.createElement("div"),this.#H.className="status-bar-group status-bar-group-secondary",this.#K.appendChild(this.#G),this.#K.appendChild(this.#H),n?.appendChild(this.#K)}constructor(){}addItem(e){this.#K||this.#Y();const t=document.createElement("button");t.type="button",t.id=e.id,t.title=e.title,t.className="status-bar-action";const n=e.command??e.capability;t.onclick=()=>{if(n)try{punica.kernel.Commands.manager.executeCommand(n)}catch(t){console.error("[Statusbar] Failed to execute command for item",e.id,n,t)}};const r=[];e.icon&&r.push(`<punica-icon size="small">${e.icon}</punica-icon>`),e.label&&r.push(`<span class="status-bar-label">${e.label}</span>`),t.innerHTML=r.join(""),"primary"===e.alignment?(this.#U.set(e.id,e),this.#G.appendChild(t)):(this.#V.set(e.id,e),this.#H.appendChild(t))}removeItem(e){if(this.#U.has(e)){const t=this.#G.querySelector("#"+e);t&&(this.#G.removeChild(t),this.#U.delete(e))}else if(this.#V.has(e)){const t=this.#H.querySelector("#"+e);t&&(this.#H.removeChild(t),this.#V.delete(e))}}}};function Xt(e,t){const n=document.createElement("punica-typography");if(n.textContent=e,t?.variant&&n.setAttribute("variant",t.variant),t?.color&&n.setAttribute("color",t.color),"bold"===t?.fontWeight&&n.setAttribute("fontweight","bold"),t?.attrs)for(const[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);return t?.style&&("string"==typeof t.style?n.setAttribute("style",t.style):Object.assign(n.style,t.style)),t?.className&&(n.className=t.className),n}const en={createElement:function(e,t){const n=document.createElement(e);if(t?.attrs)for(const[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);return t?.text&&(n.textContent=t.text),t?.children&&t.children.forEach(e=>n.appendChild(e)),t?.style&&("string"==typeof t.style?n.setAttribute("style",t.style):Object.assign(n.style,t.style)),t?.className&&(n.className=t.className),n},createButton:function(e,t,n){const r=document.createElement("punica-button");if(e.includes("<")||e.includes("<")?r.innerHTML=e:r.textContent=e,!1!==n?.rounded&&r.setAttribute("rounded",""),r.setAttribute("size",n?.size??"small"),r.setAttribute("variant",n?.variant??"outlined"),n?.color&&r.setAttribute("color",n.color),n?.disabled&&r.setAttribute("disabled",""),n?.fullwidth&&r.setAttribute("fullwidth",""),n?.icon){const e=document.createElement("punica-icon");e.setAttribute("slot","startIcon");const t=document.createElement("i");t.className=n.icon,e.appendChild(t),r.appendChild(e)}return n?.disabled||r.addEventListener("click",t),r},createIconButton:function(e,t,n){const r=document.createElement("punica-icon-button");if(r.setAttribute("size",n?.size??"x-small"),n?.variant&&r.setAttribute("variant",n.variant),n?.title&&r.setAttribute("title",n.title),n?.disabled&&r.setAttribute("disabled",""),n?.attrs)for(const[e,t]of Object.entries(n.attrs))r.setAttribute(e,t);return r.innerHTML=`<i class="${e}"></i>`,n?.disabled||r.addEventListener("click",t),r},createTypography:Xt,createChip:function(e,t){const n=document.createElement("punica-chip");return n.textContent=e,n.setAttribute("size",t?.size??"small"),n.setAttribute("variant",t?.variant??"filled"),t?.color&&n.setAttribute("color",t.color),n},createBox:function(e){const t=document.createElement("punica-box");if(e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createRow:function(e){const t=document.createElement("punica-row");if(e?.spacing&&t.setAttribute("spacing",e.spacing),e?.alignItems&&t.setAttribute("alignitems",e.alignItems),e?.wrap&&t.setAttribute("wrap",e.wrap),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createCol:function(e){const t=document.createElement("punica-col");if(void 0!==e?.xs&&t.setAttribute("xs",String(e.xs)),void 0!==e?.sm&&t.setAttribute("sm",String(e.sm)),void 0!==e?.md&&t.setAttribute("md",String(e.md)),void 0!==e?.lg&&t.setAttribute("lg",String(e.lg)),void 0!==e?.xl&&t.setAttribute("xl",String(e.xl)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createInput:function(e){const t=document.createElement("punica-input");if(void 0!==e?.value&&(t.value=e.value),e?.placeholder&&t.setAttribute("placeholder",e.placeholder),e?.type&&t.setAttribute("type",e.type),e?.size&&t.setAttribute("size",e.size),e?.fullwidth&&t.setAttribute("fullwidth",""),e?.rounded&&t.setAttribute("rounded",""),e?.disabled&&t.setAttribute("disabled",""),e?.id&&t.setAttribute("id",e.id),void 0!==e?.min&&t.setAttribute("min",String(e.min)),void 0!==e?.max&&t.setAttribute("max",String(e.max)),void 0!==e?.step&&t.setAttribute("step",String(e.step)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onInput&&t.addEventListener("input",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onInput(n)}),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onChange(n)}),t},createSelect:function(e){const t=document.createElement("punica-select");if(void 0!==e?.value&&(t.value=e.value),e?.size&&t.setAttribute("size",e.size),e?.fullwidth&&t.setAttribute("fullwidth",""),e?.rounded&&t.setAttribute("rounded",""),e?.disabled&&t.setAttribute("disabled",""),e?.minimumTargetWidth&&t.setAttribute("minimumtargetwidth",""),e?.id&&t.setAttribute("id",e.id),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onChange(n)}),t},createSelectItem:function(e){const t=document.createElement("punica-select-item");if(t.setAttribute("value",e.value),e.text&&(t.textContent=e.text),e.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t},createCheckbox:function(e){const t=document.createElement("punica-checkbox");if(void 0!==e?.checked&&(t.checked=e.checked),e?.disabled&&t.setAttribute("disabled",""),e?.id&&t.setAttribute("id",e.id),e?.label&&t.setAttribute("label",e.label),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.checked??t?.target?.checked??!1;e.onChange(n)}),t},createIcon:function(e){const t=document.createElement("punica-icon");if(e?.iconClass){const n=document.createElement("i");n.className=e.iconClass,t.appendChild(n)}else e?.innerHTML&&(t.innerHTML=e.innerHTML);if(e?.slot&&t.setAttribute("slot",e.slot),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createTextarea:function(e){const t=document.createElement("punica-textarea");if(void 0!==e?.value&&(t.value=e.value),e?.placeholder&&t.setAttribute("placeholder",e.placeholder),e?.rows&&t.setAttribute("rows",String(e.rows)),e?.cols&&t.setAttribute("cols",String(e.cols)),e?.size&&t.setAttribute("size",e.size),e?.fullwidth&&t.setAttribute("fullwidth",""),e?.rounded&&t.setAttribute("rounded",""),e?.disabled&&t.setAttribute("disabled",""),e?.id&&t.setAttribute("id",e.id),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onInput&&t.addEventListener("input",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onInput(n)}),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onChange(n)}),t},createDivider:function(e){const t=document.createElement("punica-divider");if(e?.orientation&&t.setAttribute("orientation",e.orientation),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createListView:function(e){const t=document.createElement("punica-list-view");if(e?.enableDivider&&t.setAttribute("enabledivider",""),e?.spacing&&t.setAttribute("spacing",e.spacing),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createListViewItem:function(e){const t=document.createElement("punica-list-view-item");if(e?.label)if("string"==typeof e.label){const n=document.createElement("punica-typography");n.setAttribute("slot","label"),n.textContent=e.label,t.appendChild(n)}else e.label.getAttribute("slot")||e.label.setAttribute("slot","label"),t.appendChild(e.label);if(e?.content)if("string"==typeof e.content){const n=document.createElement("div");n.setAttribute("slot","content"),n.textContent=e.content,t.appendChild(n)}else e.content.getAttribute("slot")||e.content.setAttribute("slot","content"),t.appendChild(e.content);if(e?.endAdornment&&(e.endAdornment.getAttribute("slot")||e.endAdornment.setAttribute("slot","endAdornment"),t.appendChild(e.endAdornment)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),t},createPaper:function(e){const t=document.createElement("punica-paper");if(void 0!==e?.elevation&&t.setAttribute("elevation",String(e.elevation)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createTab:function(e){const t=document.createElement("punica-tab");if(e?.value&&t.setAttribute("value",e.value),e?.orientation&&t.setAttribute("orientation",e.orientation),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.getAttribute("value")??"";e.onChange(n)}),t},createTabItem:function(e){const t=document.createElement("punica-tab-item");if(t.setAttribute("value",e.value),e.text&&(t.textContent=e.text),e.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t},createTabPanel:function(e){const t=document.createElement("punica-tab-panel");if(t.setAttribute("value",e.value),e.selectedValue&&t.setAttribute("selectedvalue",e.selectedValue),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createBadge:function(e){const t=document.createElement("punica-badge");if(e?.text&&(t.textContent=e.text),e?.variant&&t.setAttribute("variant",e.variant),e?.color&&t.setAttribute("color",e.color),e?.size&&t.setAttribute("size",e.size),e?.title&&t.setAttribute("title",e.title),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t},createMenu:function(e){const t=document.createElement("punica-menu");if(e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createMenuItem:function(e){const t=document.createElement("punica-menu-item");if(e?.text){const n=Xt(e.text);t.appendChild(n)}if(e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.onClick&&t.addEventListener("click",e.onClick),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.children&&e.children.forEach(e=>t.appendChild(e)),t},createLink:function(e,t){const n=document.createElement("a");if(n.href=t.href,n.textContent=e,t.target&&(n.target=t.target),t.rel&&(n.rel=t.rel),t.download&&(n.download=t.download),t.attrs)for(const[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);return t.children&&t.children.forEach(e=>n.appendChild(e)),t.style&&("string"==typeof t.style?n.setAttribute("style",t.style):Object.assign(n.style,t.style)),t.className&&(n.className=t.className),n},createToolbar:function(e){const t=document.createElement("punica-toolbar");if(e?.variant&&t.setAttribute("variant",e.variant),e?.disableGutters&&t.setAttribute("disablegutters",""),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t}};const tn={light:{id:"light",name:"Light",variables:{"--background-main":"#ffffff","--background-paper":"#f0f0f0","--background-navbar":"#0969da","--background-tabbar":"#e1e4e8","--background-backdrop":"rgba(0, 0, 0, 0.25)","--text-primary":"#24292f","--text-secondary":"#57606a","--text-placeholder":"#8c959f","--text-navbar":"#ffffff","--text-tabbar":"#0969da","--icon-navbar":"#ffffff","--icon-tabbar-active":"#0969da","--icon-tabbar-inactive":"#656d76","--primary-light":"#58a6ff","--primary-main":"#0969da","--primary-dark":"#0550ae","--error-light":"#ffebe9","--error-main":"#cf222e","--error-dark":"#a40e26","--warning-light":"#fff8c5","--warning-main":"#9a6700","--warning-dark":"#7d4e00","--success-light":"#dafbe1","--success-main":"#1a7f37","--success-dark":"#116329","--info-light":"#ddf4ff","--info-main":"#0969da","--info-dark":"#0550ae","--neutral-light":"#d1d9e0","--neutral-main":"#e9e9e9","--neutral-dark":"#8c959f","--disabled":"#33353a","--highlight":"#ddf4ff","--white":"#ffffff","--black":"#000000","--divider":"#d1d9e0","--focus-ring":"#0969da","--root-border-radius":"8px","--root-padding":"16px"}},dark:{id:"dark",name:"Dark",variables:{"--background-main":"#131416","--background-paper":"#2a2d33","--background-navbar":"#0969da","--background-tabbar":"#232529","--background-backdrop":"rgba(0, 0, 0, 0.5)","--text-primary":"#f5f7fa","--text-secondary":"#c0c4cc","--text-placeholder":"#9aa0a6","--text-navbar":"#ffffff","--text-tabbar":"#0a84ff","--icon-navbar":"#ffffff","--icon-tabbar-active":"#0a84ff","--icon-tabbar-inactive":"#6b6e76","--primary-light":"#66b3ff","--primary-main":"#0a84ff","--primary-dark":"#0056b3","--error-light":"#f8d7da","--error-main":"#ff453a","--error-dark":"#c41c12","--warning-light":"#ffe28a","--warning-main":"#ffd60a","--warning-dark":"#c9a400","--success-light":"#48e09e","--success-main":"#30d158","--success-dark":"#228c3f","--info-light":"#4ac8ff","--info-main":"#64d2ff","--info-dark":"#0a84ff","--neutral-light":"#45484e","--neutral-main":"#35383f","--neutral-dark":"#25272b","--disabled":"#33353a","--highlight":"#52a8ff","--white":"#ffffff","--black":"#000000","--divider":"#3a3d44","--focus-ring":"#52a8ff","--root-border-radius":"8px","--root-padding":"16px"}}};const nn=new class{currentProfileId=null;listeners=new Set;async loadProfile(e){const t=tn[e];if(!t)return void console.warn(`[Theme] Profile not found: ${e}`);const n=document.documentElement;if(Object.entries(t.variables).forEach(([e,t])=>{n.style.setProperty(e,t)}),this.currentProfileId=e,this.listeners.forEach(t=>t(e)),"undefined"!=typeof punica&&punica.extensions?.settings?.manager)try{await punica.extensions.settings.manager.set("system","theme.profile",e,"global")}catch(e){console.error("[Theme] Failed to save profile to settings:",e)}}getCurrentProfile(){return this.currentProfileId}getProfiles(){return{...tn}}getProfile(e){return tn[e]}registerProfile(e){tn[e.id]=e}onDidChangeProfile(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDefaultImmediate(){const e=tn.dark;if(!e)return void console.warn("[Theme] Default dark profile not found");const t=document.documentElement;Object.entries(e.variables).forEach(([e,n])=>{t.style.setProperty(e,n)}),this.currentProfileId="dark"}async initialize(){if("undefined"!=typeof punica&&punica.extensions?.settings?.manager)try{await punica.extensions.settings.manager.load();const e=punica.extensions.settings.manager.get("system","theme.profile");e&&"string"==typeof e&&tn[e]?await this.loadProfile(e):await this.loadProfile("dark")}catch(e){console.error("[Theme] Failed to initialize from settings:",e),await this.loadProfile("dark")}else await this.loadProfile("dark")}};async function rn(e){return new Promise(t=>{const{title:n,message:r,html:i,buttons:s=[{label:"OK",variant:"filled",action:"ok"}],footerHtml:o,modal:a=!0,width:c,height:l,icon:u,tone:d,onMount:p}=e,h=`punica-dialog-${Date.now()}`,f=document.querySelector(`#${h}`);f?.remove();const m=document.createElement("punica-dialog");m.id=h,m.setAttribute("rounded",""),a&&m.setAttribute("modal","");const g=[`width: ${c||"440px"}`];l&&g.push(`height: ${l}`);const y=` style="${g.join("; ")}"`,b=d?`var(--${d}-main)`:"",w=u||(d?{info:"fa-circle-info",warning:"fa-triangle-exclamation",error:"fa-circle-exclamation",success:"fa-circle-check"}[d]:""),v=w&&b?`<span style="flex:0 0 auto; width:34px; height:34px; display:inline-flex; align-items:center; justify-content:center; border-radius:50%; background: color-mix(in srgb, ${b} 16%, transparent); color:${b}; font-size:16px;"><i class="fa-duotone fa-solid ${w}"></i></span>`:"",k=i||(r?`<punica-typography style="color: var(--text-secondary); line-height: 1.6;">${r}</punica-typography>`:"");m.innerHTML=`\n <punica-dialog-header>\n <punica-box style="display:flex; align-items:center; gap:12px;">\n ${v}\n <punica-typography fontweight="bold" style="color: var(--text-primary); font-size: 16px;">${n}</punica-typography>\n </punica-box>\n </punica-dialog-header>\n <punica-dialog-content${y}>\n <punica-box style="display:flex; flex-direction: column; gap: 10px; padding: 4px 2px 8px;">\n ${k}\n </punica-box>\n </punica-dialog-content>\n <punica-dialog-footer>\n ${o||`\n <punica-box style="display:flex; width:100%; box-sizing:border-box; gap: 8px; justify-content: flex-end; padding-top: 14px; border-top: 1px solid var(--divider);">\n ${s.map((e,t)=>`<punica-button id="${`${h}-btn-${t}`}" variant="${e.variant||"outlined"}" color="${e.color||"primary"}" size="small" rounded>${e.label}</punica-button>`).join("")}\n </punica-box>\n `}\n </punica-dialog-footer>\n `,document.body.appendChild(m),queueMicrotask(()=>{try{m.setAttribute("open","true"),m.open=!0,p?.(m)}catch{}});const I=e=>{try{m.remove()}catch{}t(e)};s.forEach((e,t)=>{const n=`${h}-btn-${t}`,r=m.querySelector(`#${n}`);r?.addEventListener("click",()=>{I(e.action||e.label.toLowerCase())})}),m.addEventListener?.("close",()=>{I(void 0)})})}async function sn(e){const{title:t,message:n,variant:r="info",buttonLabel:i="OK"}=e,s=t||("success"===r?"Success":"warning"===r?"Warning":"error"===r?"Error":"Information");await rn({title:s,message:n,tone:r,buttons:[{label:i,variant:"filled",color:"error"===r?"error":"primary",action:"ok"}]})}const on={showInformationMessage:async function(e,...t){return 0===t.length?void await sn({message:e,variant:"info",title:"Information"}):await rn({title:"Information",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showWarningMessage:async function(e,...t){return 0===t.length?void await sn({message:e,variant:"warning",title:"Warning"}):await rn({title:"Warning",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showErrorMessage:async function(e,...t){return 0===t.length?void await sn({message:e,variant:"error",title:"Error"}):await rn({title:"Error",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showDialog:rn,showConfirm:async function(e){const{title:t="Confirm",message:n,confirmLabel:r="OK",cancelLabel:i="Cancel",variant:s="info"}=e;return"confirm"===await rn({title:t,message:n,tone:s,buttons:[{label:i,variant:"text",action:"cancel"},{label:r,variant:"filled",color:"error"===s?"error":"primary",action:"confirm"}]})},showAlert:sn,showPrompt:async function(e){return new Promise(t=>{const{title:n="Prompt",message:r,placeholder:i="",defaultValue:s="",confirmLabel:o="OK",cancelLabel:a="Cancel",type:c="text"}=e,l=`${`punica-prompt-${Date.now()}`}-input`;rn({title:n,html:`\n <punica-box style="display:flex; flex-direction: column; gap: 10px;">\n <punica-typography>${r}</punica-typography>\n <punica-input \n id="${l}" \n type="${c}" \n placeholder="${i}" \n value="${s}"\n rounded>\n </punica-input>\n </punica-box>\n `,buttons:[{label:a,variant:"outlined",action:"cancel"},{label:o,variant:"filled",action:"confirm"}]}).then(e=>{if("confirm"===e){const e=document.querySelector(`#${l}`),n=e?.value??e?.getAttribute?.("value")??"";t(n||void 0)}else t(void 0)})})},showToast:function(e){const{title:t="",message:n="",variant:r="neutral",duration:i=1e3,dismissible:s=!0,placement:o="top-right"}=e,a=function(){let e=document.querySelector("punica-toaster");return e||(e=document.createElement("punica-toaster"),document.body.appendChild(e)),e}().shadowRoot;if(!a){if(window.Toast?.show)return window.Toast.show(e);throw new Error("punica-toaster shadow root not available")}const c=a.querySelector(`.region.${o}`)||a.querySelector(".region.top-right");if(!c)throw new Error(`Toast region not found: ${o}`);const l=document.createElement("punica-toast");return l.setAttribute("variant",r),t&&l.setAttribute("title",t),n&&l.setAttribute("message",n),i>0&&l.setAttribute("duration",String(i)),l.setAttribute("dismissible",String(s)),l.setAttribute("enter-from",o.startsWith("top")?"top":"bottom"),c.prepend(l),l},showChangesPreview:async function(e){const{title:t,summary:n,files:r,onConfirm:i,onCancel:s}=e,o=`changes-preview-files-${Date.now()}`,a=`changes-preview-content-${Date.now()}`,c=`changes-preview-selected-${Date.now()}`;let l=0;const u=()=>{const e=document.querySelector(`#${c}`);e&&r[l]&&(e.textContent=r[l].path)},d=e=>{e.innerHTML="",r.forEach((t,n)=>{const r=en.createBadge({text:t.action,variant:"filled",color:"delete"===t.action?"error":"create"===t.action?"success":"primary",size:"small"}),i=en.createListViewItem({label:t.path,content:t.action,endAdornment:r});n===l&&(i.style.backgroundColor="rgba(255, 255, 255, 0.1)"),i.style.cursor="pointer",i.addEventListener("click",()=>{l=n,d(e),p(document.getElementById(a)),u()}),e.appendChild(i)})},p=e=>{const t=r[l];if(e.innerHTML="","delete"===t.action){const n=en.createTypography(`This file will be deleted: ${t.path}`,{variant:"body"});return void e.appendChild(n)}if(!t.content){const t=en.createTypography("No content preview available",{variant:"body"});return void e.appendChild(t)}const n=en.createBox({style:{width:"100%",height:"400px",border:"1px solid rgba(255, 255, 255, 0.1)",borderRadius:"4px",overflow:"hidden"}});e.appendChild(n);const i=window.monaco||globalThis.monaco;if(i?.editor)try{const r=f(t.path),s=i.editor.create(n,{value:t.content||"",language:r,theme:"vs-dark",readOnly:!0,minimap:{enabled:!1},fontSize:13,fontLigatures:!0,automaticLayout:!0,scrollBeyondLastLine:!1});e.__monacoEditor=s}catch(e){h(n,t.content||"")}else h(n,t.content||"")},h=(e,t)=>{const n=document.createElement("pre");n.style.cssText="margin: 0; padding: 10px; overflow: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap; word-wrap: break-word;",n.textContent=t,e.innerHTML="",e.appendChild(n)},f=e=>{const t=e.split(".").pop()?.toLowerCase();return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",json:"json",md:"markdown",html:"html",css:"css",yaml:"yaml",yml:"yaml"}[t||""]||"plaintext"},m=`\n <punica-box style="display: flex; flex-direction: column; gap: 12px; min-width: 800px; max-width: 1200px; max-height: 80vh;">\n ${n?`<punica-typography>${n}</punica-typography>`:""}\n <punica-box style="display: flex; gap: 12px; flex: 1; min-height: 0;">\n <punica-box style="flex: 0 0 300px; display: flex; flex-direction: column; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 4px; overflow: hidden;">\n <punica-box style="padding: 8px; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">\n <punica-typography fontweight="bold">Files (${r.length})</punica-typography>\n </punica-box>\n <punica-box id="${o}" style="flex: 1; overflow-y: auto; padding: 4px;"></punica-box>\n </punica-box>\n <punica-box style="flex: 1; display: flex; flex-direction: column; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 4px; overflow: hidden; min-width: 0;">\n <punica-box style="padding: 8px; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">\n <punica-typography fontweight="bold" id="${c}">${r[0]?.path||""}</punica-typography>\n </punica-box>\n <punica-box id="${a}" style="flex: 1; overflow: auto; padding: 0;"></punica-box>\n </punica-box>\n </punica-box>\n </punica-box>\n `;return new Promise(e=>{punica.shell.View.showDialog({title:t,html:m,buttons:[{label:"Cancel",variant:"outlined",action:"cancel"},{label:"Apply Changes",variant:"filled",color:"primary",action:"confirm"}],width:"90vw",onMount:e=>{const t=e.querySelector(`#${o}`),n=e.querySelector(`#${a}`);e.querySelector(`#${c}`),t&&d(t),n&&p(n),u()}}).then(async t=>{const n=document.querySelector('[id^="punica-dialog-"]');if(n){const e=n.querySelector(`#${a}`);if(e&&e.__monacoEditor)try{e.__monacoEditor.dispose()}catch{}}if("confirm"===t)try{await i(),e("confirm")}catch(t){await punica.shell.View.showAlert({title:"Error",message:`Failed to apply changes: ${t instanceof Error?t.message:String(t)}`,variant:"error"}),e(void 0)}else s?.(),e("cancel"===t?"cancel":void 0)})})},Helpers:en,Theme:{manager:nn,profiles:tn}};function an(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!t?.publishEvent||!t?.createCorrelationId)&&(t.publishEvent({name:e.name,envelope:{id:t.createCorrelationId(),correlationId:e.correlationId,traceId:e.traceId,timestampMs:Date.now(),source:e.source??"shell:profile",kind:e.kind??"info"},payload:e.payload}),!0)}catch{return!1}}function cn(){return globalThis.punica?.shell?.Layout?.manager}function ln(){return globalThis.punica?.shell?.ActivityBar?.manager}const un={manager:new class{#Q=new Map;#X=new Map;#ee=new Map;#te=new Map;registerPlacement(e){if(!e?.viewId||!e.slot)return;const t=this.#Q.get(e.viewId);t&&t.extensionName!==e.extensionName&&console.warn(`[Views] Placement collision for view "${e.viewId}" between "${t.extensionName}" and "${e.extensionName}". Keeping the last registered.`),this.#Q.set(e.viewId,e),an({name:"shell.view.registered",source:"shell:views",payload:{viewId:e.viewId,slot:e.slot,extensionName:e.extensionName}})}registerProvider(e,t,n){return this.#Q.has(e)||console.warn(`[Views] Provider registered for "${e}" but no placement is declared in any manifest.`+(n?` (extension: ${n})`:"")),this.#X.set(e,t),{dispose:()=>{this.#X.get(e)===t&&this.#X.delete(e)}}}getPlacement(e){return this.#Q.get(e)}hasProvider(e){return this.#X.has(e)}getState(e){if(!this.#Q.has(e)&&!this.#X.has(e))return;const t=this.#Q.get(e);return t&&this.#te.get(t.slot)===e?"visible":this.#ee.has(e)?"materialized":"registered"}getVisibleView(e){return this.#te.get(e)}listViews(){return Array.from(this.#Q.values()).map(e=>({viewId:e.viewId,slot:e.slot,extensionName:e.extensionName,title:e.title,state:this.getState(e.viewId)??"registered"}))}async reveal(e,t,n){const r=this.#Q.get(e);if(!r)throw new Error(`[Views] Cannot reveal "${e}": no placement is registered for this view.`);if(!this.#X.has(e)){const t=globalThis.punica?.extensions?.manager;t?.activate&&await t.activate(r.extensionName,{reason:"view",trigger:e,presentation:"interactive"})}const i=cn();if(!i)throw new Error("[Views] Layout manager unavailable — cannot reveal.");const s=i.materializeViewHost(r.slot,e),o=this.#X.get(e),a="contentSidebar"===r.slot;if(o&&(a||!this.#ee.has(e))){if(a){const t=this.#ee.get(e);try{t?.dispose()}catch(t){console.warn(`[Views] provider dispose failed for "${e}":`,t)}}const t=await o.render(s);this.#ee.set(e,t&&"function"==typeof t.dispose?t:null)}if(i.showView(r.slot,e),i.setSlotCollapsed?.(r.slot,!1),this.#te.set(r.slot,e),"panel"===r.slot&&(globalThis.punica?.shell?.PanelTabs)?.activateTabVisual?.(e),"primarySidebar"===r.slot)try{ln()?.setActiveByViewId?.(e)}catch{}if(!o&&r.fallbackCommand)try{(globalThis.punica?.kernel?.Commands?.manager)?.executeCommand?.(r.fallbackCommand)}catch(t){console.warn(`[Views] fallback command "${r.fallbackCommand}" for view "${e}" failed:`,t)}an({name:"shell.view.revealed",source:"shell:views",payload:{viewId:e,slot:r.slot,extensionName:r.extensionName,source:t?.kind??"host",sourceId:t?.id,focus:n?.focus??!1}})}hide(e,t){const n=this.#Q.get(e);if(!n)return;if(this.#te.get(n.slot)!==e)return;const r=cn();if("contentSidebar"===n.slot?this.#ne(n.slot):(r?.hideSlotViews(n.slot),r?.setSlotCollapsed?.(n.slot,!0)),this.#te.delete(n.slot),"primarySidebar"===n.slot)try{ln()?.setActiveByViewId?.(null)}catch{}an({name:"shell.view.hidden",source:"shell:views",payload:{viewId:e,slot:n.slot,source:t?.kind??"host",sourceId:t?.id}})}notifySlotReset(e){this.#ne(e);const t=this.#te.get(e);void 0!==t&&(this.#te.delete(e),an({name:"shell.view.hidden",source:"shell:views",payload:{viewId:t,slot:e,source:"host",sourceId:"slot-reset"}}))}#ne(e){const t=cn();for(const n of this.#Q.values()){if(n.slot!==e)continue;const r=this.#ee.get(n.viewId);try{r?.dispose()}catch(e){console.warn(`[Views] provider dispose failed for "${n.viewId}":`,e)}this.#ee.delete(n.viewId),t?.removeViewHost?.(e,n.viewId)}}unmountByExtension(e){for(const t of this.#Q.values()){if(t.extensionName!==e)continue;const n=t.viewId;this.#te.get(t.slot)===n&&this.hide(n,{kind:"host",id:"deactivate"});const r=this.#ee.get(n);try{r?.dispose()}catch(e){console.warn(`[Views] provider dispose failed for "${n}":`,e)}this.#ee.delete(n),this.#X.delete(n);const i=cn();i?.removeViewHost?.(t.slot,n)}}}};const dn={manager:new class{#re=[];#ie(e,t){return e.length===t.length&&e.every((e,n)=>e.key.toLowerCase()===t[n].key.toLowerCase()&&!!e.ctrlKey==!!t[n].ctrlKey&&!!e.shiftKey==!!t[n].shiftKey&&!!e.altKey==!!t[n].altKey&&!!e.metaKey==!!t[n].metaKey)}#se(e,t){return t.every(t=>!!t.ctrlKey===e.ctrlKey&&!!t.shiftKey===e.shiftKey&&!!t.altKey===e.altKey&&!!t.metaKey===e.metaKey&&e.key.toLowerCase()===t.key.toLowerCase())}constructor(){document.addEventListener("keydown",this.handleKeyEvent.bind(this))}#oe(e){switch(e){case"editorTextFocus":return this.#ae();case"fileExplorerFocus":return this.#ce("primarySidebar","file-explorer-sidebar");default:return}}#ae(){const e="undefined"!=typeof document?document.activeElement:null;if(!e)return!1;const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||(!!e.isContentEditable||!!e.closest?.(".monaco-editor, .cm-editor"))}#ce(e,t){if("undefined"==typeof document)return!1;if((punica.shell.Views?.manager?.getVisibleView?.(e)??null)!==t)return!1;const n=document.getElementById(e),r=document.activeElement;return!!(n&&r&&n.contains(r))}#le(e){const t=e.when;return!t||t.split("&&").map(e=>e.trim()).filter(e=>e.length>0).every(e=>this.#ue(e))}#ue(e){const t=e.indexOf("==");if(-1!==t){const n=e.slice(0,t).trim(),r=e.slice(t+2).trim().replace(/^['"]|['"]$/g,"");if("view"===n){return(punica.shell.ContentTabs?.getActiveViewType?.()??null)===r}return!1}if(e.startsWith("!")){const t=this.#oe(e.slice(1).trim());return void 0!==t&&!t}return!0===this.#oe(e)}registerShortcut(e){const t=this.#re.find(t=>this.#ie(t.keys,e.keys)&&(t.when??"")===(e.when??""));t?console.warn(`[KeyboardShortcuts] Ignoring duplicate binding for command "${e.command}"; "${t.command}" already owns this chord${e.when?` (when: ${e.when})`:""}.`):this.#re.push(e)}unregisterShortcut(e){this.#re=this.#re.filter(t=>!this.#ie(t.keys,e))}handleKeyEvent(e){if(e.repeat)return;const t=this.#re.find(t=>this.#se(e,t.keys)&&this.#le(t));t&&(e.preventDefault(),punica.kernel.Commands.manager.executeCommand(t.command))}}};let pn=0;function hn(){return pn>0}async function fn(e){pn++;try{return await e()}finally{pn>0&&pn--}}const mn={id:"classic-editor",title:"Classic Editor",root:{type:"row",sizes:[70,30],children:[{type:"column",sizes:[80,20],children:[{type:"slot",id:"content",role:"content"},{type:"slot",id:"panel",role:"panel"}]},{type:"slot",id:"secondarySidebar",role:"secondarySidebar"}]}},gn={id:"welcome",title:"Welcome",root:{type:"row",sizes:[100],children:[{type:"column",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]}]}},yn={type:"row",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]};const bn={manager:new class{#de;#pe=new Map;#he=new Map;#fe;#me=new Map;constructor(){this.#de=document.createElement("div"),this.#de.id="punica-editor",this.#fe=mn}applyProfile(e){if(this.#fe=e,this.#pe.clear(),this.#he.clear(),this.#me.clear(),this.#de.innerHTML="",this.#de.classList.remove("layout-welcome","layout-classic"),this.#de.classList.add("welcome"===e.id?"layout-welcome":"layout-classic"),"welcome"!==e.id){const e=document.createElement("div");e.id="activityBar",this.#de.appendChild(e),this.#pe.set("activityBar",{id:"activityBar",role:"activityBar",content:e})}const t=document.createElement("div");if(t.id="mainContent",t.style.height="100%",t.style.width="100%",t.style.display="flex",this.#de.appendChild(t),"welcome"!==e.id){const e=document.createElement("div");e.id="primarySidebar",this.#de.appendChild(e),this.#pe.set("primarySidebar",{id:"primarySidebar",role:"primarySidebar",content:e});const t=document.createElement("div");t.id="contentSidebar",this.#de.appendChild(t),this.#pe.set("contentSidebar",{id:"contentSidebar",role:"overlay",content:t})}const n=document.createElement("div");n.id="statusbar",this.#de.appendChild(n),this.#pe.set("statusbar",{id:"statusbar",role:"statusbar",content:n}),this.#ge(e.root,t,!0)}getActiveProfile(){return this.#fe}getSlot(e){return this.#pe.get(e)}materializeViewHost(e,t){const n=this.#pe.get(e);if(!n)throw new Error(`Layout slot "${e}" not found in active profile`);let r=this.#he.get(e);r||(r=new Map,this.#he.set(e,r));let i=n.content;if("panel"===e){const e=n.content.querySelector("#panel-views-root");e&&(i=e)}let s=r.get(t);return s?s.parentElement||i.appendChild(s):(s=document.createElement("div"),s.dataset.viewId=t,s.style.height="100%",s.style.width="100%",s.style.display="none",i.appendChild(s),r.set(t,s)),s}showView(e,t){if("primarySidebar"===e){const e=this.#pe.get("contentSidebar");if(e){const t=this.#he.get("contentSidebar");t&&(t.forEach(e=>{e.parentElement&&e.parentElement.removeChild(e)}),t.clear()),e.content.innerHTML="";try{punica.shell?.Views?.manager?.notifySlotReset?.("contentSidebar")}catch{}}}const n=this.#pe.get(e);if(!n)throw new Error(`Layout slot "${e}" not found in active profile`);const r=this.#he.get(e);if(r?.forEach((e,n)=>{e.style.display=n===t?"block":"none"}),n.content.style.display="block","primarySidebar"===e)try{punica.shell.ActivityBar.manager.setActiveByViewId?.(t)}catch(e){console.warn("[Layout] Failed to sync ActivityBar selection:",e)}}hideSlotViews(e){const t=this.#he.get(e);t?.forEach(e=>{e.style.display="none"})}#ye(e){const t=this.#pe.get(e);if(!t)return;const n=t.content.closest("punica-split");if(!n)return;let r=t.content;for(;r&&r.parentElement!==n;)r=r.parentElement;if(!r)return;const i=Array.from(n.children).filter(e=>1===e.nodeType),s=i.indexOf(r);return s<0?void 0:{split:n,index:s,count:i.length}}isSlotCollapsed(e){return this.#me.has(e)}setSlotCollapsed(e,t){const n=this.#ye(e);if(!n)return;const{split:r,index:i,count:s}=n;if("function"==typeof r.setSizes)if(t){if(this.#me.has(e))return;const t=(r.getSizes?.()??[]).slice();if(t.length!==s||s<2)return;this.#me.set(e,t);const n=t.reduce((e,t,n)=>n===i?e:e+t,0),o=t.map((e,t)=>t===i?0:n>0?e/n*100:100/(s-1));r.setSizes(o)}else{const t=this.#me.get(e);this.#me.delete(e),t&&t.length===s&&r.setSizes(t)}}removeViewHost(e,t){const n=this.#he.get(e),r=n?.get(t);r&&(r.parentElement&&r.parentElement.removeChild(r),n?.delete(t))}ensureViewHost(e,t){const n=this.materializeViewHost(e,t);return hn()?(an({name:"shell.view.revealBlocked",source:"shell:views",kind:"warn",payload:{viewId:t,slot:e,api:"Layout.ensureViewHost"}}),console.warn(`[Shell] UI mutation during headless activation blocked: ensureViewHost("${e}", "${t}"). Register a ViewProvider (context.ui.registerViewProvider) and reveal via the shell.revealView capability instead.`),n):(this.showView(e,t),n)}#ge(e,t,n){if("slot"===e.type){const n=document.createElement("div");n.style.height="100%",n.style.width="100%",n.style.overflow="hidden",t.appendChild(n);const r={id:e.id,role:e.role,content:n};return void this.#pe.set(e.id,r)}const r="row"===e.type,i=document.createElement("punica-split");i.style.height="100%",i.style.width="100%",i.setAttribute("orientation",r?"horizontal":"vertical"),e.sizes&&e.sizes.length&&i.setAttribute("sizes",e.sizes.join(",")),t.appendChild(i);const s=e.children.length;for(let t=0;t<s;t++){const n=document.createElement("div");n.style.height="100%",n.style.width="100%",i.appendChild(n),this.#ge(e.children[t],n,!1)}}applyApplicationProfile(e){const t=new Set(e.shell.activeModules),n=t.has("shell.activityBar"),r=t.has("shell.view"),i=t.has("shell.statusbar"),s=e.shell.layout,o=s?.id??e.identity.id,a=s?.root??yn;if(this.#fe={id:o,title:e.identity.name,root:a},this.#pe.clear(),this.#he.clear(),this.#me.clear(),this.#de.innerHTML="",this.#de.classList.remove("layout-welcome","layout-classic"),this.#de.classList.add(n?"layout-classic":"layout-welcome"),this.#de.dataset.profileId=e.identity.id,n){const e=document.createElement("div");e.id="activityBar",this.#de.appendChild(e),this.#pe.set("activityBar",{id:"activityBar",role:"activityBar",content:e})}const c=document.createElement("div");if(c.id="mainContent",c.style.height="100%",c.style.width="100%",c.style.display="flex",this.#de.appendChild(c),r){const e=document.createElement("div");e.id="primarySidebar",this.#de.appendChild(e),this.#pe.set("primarySidebar",{id:"primarySidebar",role:"primarySidebar",content:e});const t=document.createElement("div");t.id="contentSidebar",this.#de.appendChild(t),this.#pe.set("contentSidebar",{id:"contentSidebar",role:"overlay",content:t})}if(i){const e=document.createElement("div");e.id="statusbar",this.#de.appendChild(e),this.#pe.set("statusbar",{id:"statusbar",role:"statusbar",content:e})}this.#ge(a,c,!0)}render(e){try{const e=window,t=e.punica?.Runtime?.runtime??e.punica?.runtime,n=t?.lifecyclePhase,r="noWorkspace"===n?gn:mn;this.#de.childElementCount&&this.#fe.id===r.id||this.applyProfile(r)}catch{this.#de.childElementCount||this.applyProfile(this.#fe)}e.appendChild(this.#de)}}};const wn=new class{#be=!1;#we=null;#ve=null;#ke=new Map;#Ie=null;#Ee(){if(this.#be)return;const e=punica.shell.Layout.manager.getSlot("content"),t=e?.content;if(!t)return void console.warn("[ContentTabs] content host not found");t.innerHTML="";const n=document.createElement("punica-box");n.id="content-tabs-root",n.style.height="100%",n.style.display="flex",n.style.flexDirection="column";const r=document.createElement("punica-box");r.style.height="40px",r.style.display="flex",r.style.alignItems="center";const i=document.createElement("punica-tab");i.setAttribute("orientation","horizontal"),i.style.width="100%",i.style.height="100%",i.style.backgroundColor="var(--background-paper)",i.addEventListener("change",e=>{const t=e?.detail?.value;t&&this.#Ae(t)}),r.appendChild(i);const s=document.createElement("punica-box");s.id="content-tabs-panels",s.style.flex="1",s.style.height="calc(100% - 40px)",n.appendChild(r),n.appendChild(s);const o=document.createElement("punica-context-menu");o.id="content-tabs-menu",o.setAttribute("target","#content-tabs-root");const a=document.createElement("punica-context-menu-item");a.setAttribute("label","Close"),a.setAttribute("value","close"),o.appendChild(a);const c=document.createElement("punica-context-menu-item");c.setAttribute("label","Close Others"),c.setAttribute("value","closeOthers"),o.appendChild(c);const l=document.createElement("punica-context-menu-item");l.setAttribute("label","Close All"),l.setAttribute("value","closeAll"),o.appendChild(l),o.addEventListener("punica-context-menu-select",e=>{const t=e?.detail?.value;if(!t)return;const n=this.#Ie||this.#we&&this.#we.getAttribute("value")||"";switch(t){case"close":n&&this.closeById(n);break;case"closeOthers":n&&this.closeOthersById(n);break;case"closeAll":this.closeAll()}this.#Ie=null}),n.appendChild(o),t.appendChild(n),this.#we=i,this.#ve=s,this.#be=!0}#Ae(e){if(!this.#we||!this.#ve)return;this.#we.setAttribute("value",e);this.#we.querySelectorAll("punica-tab-item").forEach(t=>{const n=t.getAttribute("value");t.style.backgroundColor=n===e?"var(--background-main)":""});this.#ve.querySelectorAll("punica-tab-panel").forEach(t=>{t.setAttribute("selectedvalue",e)});try{const t=window,n=t?.punica?.kernel?.Commands?.manager;n&&"function"==typeof n.executeCommand&&n.executeCommand("file-explorer.revealFile",e)}catch(e){console.warn("[ContentTabs] Failed to notify file-explorer",e)}}open(e){if(this.#Ee(),!this.#we||!this.#ve)return null;const t=this.#ke.get(e.path);if(t)return this.#Ae(t.id),t.container;const n=e.path,r=e.title??e.path.split("/").pop()??e.path,i=document.createElement("punica-tab-item");i.setAttribute("value",n),i.className="content-file-type",i.style.maxWidth="200px",i.style.flex="0 0 auto",i.style.padding="var(--spacing-8) var(--spacing-4) var(--spacing-8) var(--spacing-12)";const s=document.createElement("punica-row");s.setAttribute("alignitems","center"),s.setAttribute("wrap","nowrap"),s.setAttribute("spacing","0.5"),s.style.maxWidth="200px";const o=document.createElement("punica-col"),a=document.createElement("punica-typography");a.setAttribute("truncate","1"),a.style.maxWidth="150px",a.setAttribute("title",e.path),a.textContent=r,o.appendChild(a);const c=document.createElement("punica-col"),l=document.createElement("punica-icon-button");l.setAttribute("size","small"),l.setAttribute("title","Close"),l.innerHTML="<i class='fa-duotone fa-solid fa-xmark'></i>",l.addEventListener("click",t=>{t.stopPropagation(),this.close(e.path)}),c.appendChild(l),s.appendChild(o),s.appendChild(c),i.appendChild(s),i.addEventListener("contextmenu",()=>{this.#Ie=n,this.#Ae(n)}),this.#we.appendChild(i);const u=document.createElement("punica-tab-panel");u.setAttribute("value",n),u.setAttribute("selectedvalue",n),u.style.height="100%",u.style.width="100%",u.style.boxSizing="border-box";const d=document.createElement("div");d.style.height="100%",d.style.width="100%",d.style.boxSizing="border-box",u.appendChild(d),this.#ve.appendChild(u);const p={id:n,path:e.path,title:r,viewType:e.viewType,tabElement:i,labelElement:a,container:d,panel:u,dirty:!1};return this.#ke.set(e.path,p),this.#Ae(n),d}async close(e){const t=this.#ke.get(e);t&&await this.#Se(t)&&this.#_e(t)}async closeById(e){const t=Array.from(this.#ke.values()).find(t=>t.id===e);t&&await this.#Se(t)&&this.#_e(t)}async closeOthers(e){const t=this.#ke.get(e);t&&await this.closeOthersById(t.id)}async closeOthersById(e){const t=Array.from(this.#ke.values()).filter(t=>t.id!==e);for(const e of t){if(!await this.#Se(e))return;this.#_e(e)}this.#Ae(e)}async closeAll(){const e=Array.from(this.#ke.values());for(const t of e){if(!await this.#Se(t))return;this.#_e(t)}}#_e(e){if(!this.#we||!this.#ve)return;e.tabElement.parentElement===this.#we&&this.#we.removeChild(e.tabElement),e.panel.parentElement===this.#ve&&this.#ve.removeChild(e.panel),this.#ke.delete(e.path);const t=Array.from(this.#ke.values());if(t.length>0){const e=t[t.length-1];this.#Ae(e.id)}else this.#we.removeAttribute("value")}async#Se(e){if(!e.dirty)return!0;this.#Ae(e.id);const t=e.title||e.path.split("/").pop()||e.path,n=await punica.shell.View.showDialog({title:"Unsaved changes",message:`"${t}" has unsaved changes. Do you want to save before closing?`,tone:"warning",buttons:[{label:"Cancel",variant:"text",action:"cancel"},{label:"Don't Save",variant:"outlined",action:"discard"},{label:"Save",variant:"filled",color:"primary",action:"save"}]});if("save"===n)try{const e=punica?.kernel?.Commands?.manager;return e&&"function"==typeof e.executeCommand&&await e.executeCommand("editor.saveActiveFile"),!0}catch(e){return await punica.shell.View.showAlert({title:"Save failed",message:`Could not save "${t}". The tab was left open.`,variant:"error"}),console.warn("[ContentTabs] save before close failed",e),!1}return"discard"===n}setDirty(e,t){const n=this.#ke.get(e);if(!n)return;n.dirty=t;const r=n.title||n.path.split("/").pop()||n.path;n.labelElement.textContent=t?`${r} •`:r}getActivePath(){if(!this.#we)return null;const e=this.#we.getAttribute("value");if(!e)return null;const t=Array.from(this.#ke.values()).find(t=>t.id===e);return t?.path??null}getActiveViewType(){if(!this.#we)return null;const e=this.#we.getAttribute("value");if(!e)return null;const t=Array.from(this.#ke.values()).find(t=>t.id===e);return t?.viewType??null}};const vn=new class{#be=!1;#xe=null;#we=null;#Ce=null;#Te=null;#Ne=null;#Me=null;#De=!1;#Pe=new Set;#Oe=new Map;#W=null;#Ee(){if(this.#be)return;const e=punica.shell.Layout.manager.getSlot("panel"),t=e?.content;if(!t)return void console.warn("[PanelTabs] panel host not found");t.innerHTML="";const n=document.createElement("punica-box");n.id="panel-tabs-root",n.style.height="100%",n.style.display="flex",n.style.flexDirection="column";const r=document.createElement("punica-box");r.style.height="32px",r.style.display="flex",r.style.alignItems="center",r.style.backgroundColor="var(--background-paper)";const i=document.createElement("punica-tab");i.setAttribute("orientation","horizontal"),i.style.flex="1 1 auto",i.style.minWidth="0",i.style.overflow="hidden",i.style.height="100%",i.style.backgroundColor="var(--background-paper)",i.addEventListener("change",e=>{const t=e?.detail?.value;t&&this.#Re(t,"panel-tab")});const s=document.createElement("punica-icon-button");s.id="panel-tab-overflow-btn",s.setAttribute("size","x-small"),s.setAttribute("title","More tabs"),s.setAttribute("aria-label","More tabs"),s.style.flex="0 0 auto",s.style.display="none",s.innerHTML='<i class="fa-solid fa-ellipsis"></i>',s.addEventListener("click",()=>{this.#Le()});const o=document.createElement("punica-box");o.id="panel-toolbar-area",o.style.flex="0 0 auto",o.style.display="flex",o.style.alignItems="center",o.style.padding="0 var(--spacing-8)",r.appendChild(i),r.appendChild(s),r.appendChild(o);const a=document.createElement("punica-menu");a.id="panel-tab-overflow-menu",a.addEventListener("close",()=>{a.removeAttribute("open")}),a.addEventListener("menu-item-click",e=>{const t=e?.detail?.data;t&&(e.stopPropagation?.(),a.removeAttribute("open"),this.#Re(t,"panel-tab-overflow"))});const c=document.createElement("div");if(c.id="panel-views-root",c.style.flex="1",c.style.height="calc(100% - 32px)",n.appendChild(r),n.appendChild(c),n.appendChild(a),t.appendChild(n),"undefined"!=typeof ResizeObserver){new ResizeObserver(()=>{this.#$e()}).observe(r)}this.#xe=n,this.#we=i,this.#Ce=o,this.#Te=s,this.#Ne=a,this.#be=!0}#Re(e,t){const n=globalThis.punica?.shell?.Views?.manager;if(n?.getPlacement?.(e))return n.reveal(e,{kind:"user-gesture",id:`${t}:${e}`}).catch(t=>{console.warn("[PanelTabs] reveal failed for tab",e,t)}),void this.activateTabVisual(e);this.setActive(e)}open(e){if(this.#Ee(),!this.#we)return;if(this.#Oe.get(e.id))return void(!1===e.autoActivate||this.#W===e.id||this.#je(e.id,"PanelTabs.open")||this.setActive(e.id));const t=document.createElement("punica-tab-item");t.setAttribute("value",e.id),t.style.maxWidth="160px",t.style.flex="0 0 auto",t.style.padding="var(--spacing-6) var(--spacing-8)";const n=document.createElement("punica-row");if(n.setAttribute("alignitems","center"),n.setAttribute("wrap","nowrap"),n.setAttribute("spacing","0.5"),e.iconClass){const t=document.createElement("punica-col"),r=document.createElement("punica-icon"),i=document.createElement("i");i.className=e.iconClass,r.appendChild(i),t.appendChild(r),n.appendChild(t)}const r=document.createElement("punica-col"),i=document.createElement("punica-typography");i.setAttribute("truncate","1"),i.textContent=e.title,r.appendChild(i),n.appendChild(r),t.appendChild(n);const s=e.order??1e3,o=Array.from(this.#Oe.values()).sort((e,t)=>e.order-t.order).find(e=>e.order>s);o?this.#we.insertBefore(t,o.tabElement):this.#we.appendChild(t);const a={id:e.id,title:e.title,commandId:e.commandId,iconClass:e.iconClass,order:s,tabElement:t,toolbar:e.toolbar,toolbarEl:null};e.toolbar?.length&&this.#Ce&&(a.toolbarEl=this.#Fe(e.id,e.toolbar),this.#Ce.appendChild(a.toolbarEl)),this.#Oe.set(e.id,a),this.#$e();const c=e.autoActivate;this.#W||!1===c||this.#je(e.id,"PanelTabs.open")||this.setActive(e.id)}#Fe(e,t){const n=document.createElement("div");n.dataset.viewId=e,n.style.display="none",n.style.alignItems="center",n.style.gap="var(--spacing-4)";for(const e of t){if(!e?.command)continue;const t=document.createElement("punica-icon-button");t.setAttribute("size","x-small"),t.setAttribute("title",e.title??e.command),t.setAttribute("aria-label",e.title??e.command),t.dataset.actionId=e.id,t.style.flex="0 0 auto",t.innerHTML=e.icon??"",t.addEventListener("click",()=>{try{const t=window,n=t?.punica?.kernel?.Commands?.manager;n&&"function"==typeof n.executeCommand&&n.executeCommand(e.command)}catch(t){console.warn("[PanelTabs] Failed to execute toolbar command",e.command,t)}}),n.appendChild(t)}return n}#je(e,t){return!!hn()&&(an({name:"shell.view.revealBlocked",source:"shell:views",kind:"warn",payload:{viewId:e,slot:"panel",api:t}}),console.warn(`[Shell] UI mutation during headless activation blocked: ${t}("${e}"). Declare the tab without autoActivate and reveal via the shell.revealView capability instead.`),!0)}activateTabVisual(e){if(!this.#we)return;if(!this.#Oe.get(e))return;this.#W=e,this.#we.setAttribute("value",e);this.#we.querySelectorAll("punica-tab-item").forEach(t=>{const n=t.getAttribute("value");t.style.backgroundColor=n===e?"var(--background-main)":""}),this.#Oe.forEach(t=>{t.toolbarEl&&(t.toolbarEl.style.display=t.id===e?"flex":"none")}),this.recomputeOverflow()}close(e){if(!this.#we)return;const t=this.#Oe.get(e);if(t&&(t.tabElement.parentElement===this.#we&&this.#we.removeChild(t.tabElement),t.toolbarEl&&(t.toolbarEl.remove(),t.toolbarEl=null),this.#Pe.delete(e),this.#Oe.delete(e),this.#$e(),this.#W===e)){const e=Array.from(this.#Oe.values()).sort((e,t)=>e.order-t.order);this.#W=null,e.length>0?this.setActive(e[0].id):this.#we.removeAttribute("value")}}closeAll(){this.#we&&Array.from(this.#Oe.keys()).forEach(e=>this.close(e))}setActive(e){if(!this.#we)return;const t=this.#Oe.get(e);if(t&&!this.#je(e,"PanelTabs.setActive")&&(this.activateTabVisual(e),t.commandId))try{const e=window,n=e?.punica?.kernel?.Commands?.manager;n&&"function"==typeof n.executeCommand&&n.executeCommand(t.commandId)}catch(e){console.warn("[PanelTabs] Failed to execute command",t.commandId,e)}}getActiveId(){return this.#W}#$e(){if(this.#De)return;this.#De=!0;const e=()=>{this.#De=!1,this.recomputeOverflow()};"function"==typeof requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,0)}recomputeOverflow(){const e=this.#we;if(!e)return;const t=Array.from(e.querySelectorAll("punica-tab-item"));if(t.forEach(e=>{e.style.display=""}),0===t.length)return this.#Pe.clear(),void this.#Be(!1);const n=e.clientWidth;if(n<=0)return this.#Pe.clear(),void this.#Be(!1);const r=t.map(e=>e.offsetWidth);if(r.reduce((e,t)=>e+t,0)<=n)return this.#Pe.clear(),void this.#Be(!1);const i=n-this.#qe(),s=t.findIndex(e=>e.getAttribute("value")===this.#W);let o=s>=0?r[s]:0;const a=new Set;let c=!0;t.forEach((e,t)=>{if(t===s)return;if(c&&o+r[t]<=i)return void(o+=r[t]);c=!1,e.style.display="none";const n=e.getAttribute("value");n&&a.add(n)}),this.#Pe=a,this.#Be(a.size>0)}#Be(e){const t=this.#Te;t&&(t.style.display=e?"inline-flex":"none",e||this.#Ne?.removeAttribute("open"))}#qe(){if(null!=this.#Me)return this.#Me;const e=this.#Te;if(!e)return 28;const t=e.style.display;e.style.display="inline-flex";const n=e.offsetWidth||28;return e.style.display=t,this.#Me=n,n}#Le(){const e=this.#Ne,t=this.#Te,n=this.#we;if(!e||!t||!n||0===this.#Pe.size)return;e.innerHTML="",n.querySelectorAll("punica-tab-item").forEach(t=>{const n=t.getAttribute("value");if(!n||!this.#Pe.has(n))return;const r=this.#Oe.get(n);if(!r)return;const i=document.createElement("punica-menu-item");i.setAttribute("data-item",n),i.setAttribute("aria-label",r.title);const s=document.createElement("punica-typography");s.textContent=r.title,i.appendChild(s),e.appendChild(i)});const r=t.getBoundingClientRect();e.setAttribute("top",String(r.top)),e.setAttribute("left",String(r.left)),e.setAttribute("width",String(r.width)),e.setAttribute("height",String(r.height)),e.setAttribute("bottom",String(r.bottom)),e.setAttribute("placement","bottom"),e.setAttribute("open","true")}};function kn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function In(e){return"string"==typeof e}function En(e){return"string"==typeof e&&e.trim().length>0}function An(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const Sn=new Set(["shell.activityBar","shell.statusbar","shell.view","shell.views","shell.keyboardShortcuts","shell.layout","shell.contentTabs","shell.panelTabs","flow.shell"]),_n=new Set(["light","dark","auto"]),xn=new Set(["compact","comfortable"]),Cn=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const Tn=new class{validate(e){const t=[];if(!kn(e))return{valid:!1,errors:["ApplicationProfile must be an object"]};if("1"!==e.schemaVersion&&t.push(`schemaVersion must be '1', got: ${JSON.stringify(e.schemaVersion)}`),kn(e.identity)?(En(e.identity.id)||t.push("identity.id must be a non-empty string"),En(e.identity.name)||t.push("identity.name must be a non-empty string"),En(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),kn(e.shell)?(Array.isArray(e.shell.activeModules)?e.shell.activeModules.forEach((e,n)=>{In(e)&&Sn.has(e)||t.push(`shell.activeModules[${n}] is not a valid ShellModuleId: ${JSON.stringify(e)}`)}):t.push("shell.activeModules must be an array"),void 0!==e.shell.layout&&(kn(e.shell.layout)?(En(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),kn(e.shell.layout.root)||t.push("shell.layout.root must be an object")):t.push("shell.layout must be an object when provided"))):t.push("shell must be an object"),kn(e.theme)?(_n.has(e.theme.mode)||t.push(`theme.mode must be one of 'light'|'dark'|'auto', got: ${JSON.stringify(e.theme.mode)}`),void 0===e.theme.density||xn.has(e.theme.density)||t.push(`theme.density must be 'compact' or 'comfortable', got: ${JSON.stringify(e.theme.density)}`)):t.push("theme must be an object"),kn(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||An(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||An(e.capabilities.deniedIds)||t.push("capabilities.deniedIds must be string[] when provided"),void 0!==e.capabilities.allowedOrigins&&(Array.isArray(e.capabilities.allowedOrigins)?e.capabilities.allowedOrigins.forEach((e,n)=>{In(e)&&Cn.has(e)||t.push(`capabilities.allowedOrigins[${n}] must be a valid CapabilityOrigin, got: ${JSON.stringify(e)}`)}):t.push("capabilities.allowedOrigins must be an array when provided"))}else t.push("capabilities must be an object");return t.length>0?{valid:!1,errors:t}:{valid:!0,profile:e}}};class Nn{#ze=new Map;#W;register(e){if(this.#ze.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#ze.set(e.identity.id,e),void 0===this.#W&&(this.#W=e.identity.id)}get(e){return this.#ze.get(e)}getActive(){if(void 0===this.#W||!this.#ze.has(this.#W))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#ze.get(this.#W)}setActive(e){if(!this.#ze.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#W=e}switchProfile(e){if(!this.#ze.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#W=e,an({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#ze.has(e)}list(){return Array.from(this.#ze.values())}}const Mn={manager:new class{registry=new Nn;get validator(){return Tn}loadProfile(e){if("string"==typeof e){if(this.registry.has(e))return void this.registry.setActive(e);let t;try{t=JSON.parse(e)}catch{throw new Error(`loadProfile: '${e}' is not a registered profile id and could not be parsed as JSON`)}return void this.#Ue(t)}this.#Ue(e)}#Ue(e){const t=this.validator.validate(e);if(!t.valid)throw an({name:"shell.profile.load_failed",payload:{errors:t.errors}}),new Error(`ApplicationProfile validation failed:\n ${t.errors.join("\n ")}`);this.registry.has(t.profile.identity.id)||this.registry.register(t.profile),this.registry.setActive(t.profile.identity.id),an({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}},Dn={};function Pn(e,t){"string"!=typeof t&&(t=Pn.defaultChars);const n=function(e){let t=Dn[e];if(t)return t;t=Dn[e]=[];for(let e=0;e<128;e++){const n=String.fromCharCode(e);t.push(n)}for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t[r]="%"+("0"+r.toString(16).toUpperCase()).slice(-2)}return t}(t);return e.replace(/(%[a-f0-9]{2})+/gi,function(e){let t="";for(let r=0,i=e.length;r<i;r+=3){const s=parseInt(e.slice(r+1,r+3),16);if(s<128)t+=n[s];else{if(192==(224&s)&&r+3<i){const n=parseInt(e.slice(r+4,r+6),16);if(128==(192&n)){const e=s<<6&1984|63&n;t+=e<128?"��":String.fromCharCode(e),r+=3;continue}}if(224==(240&s)&&r+6<i){const n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16);if(128==(192&n)&&128==(192&i)){const e=s<<12&61440|n<<6&4032|63&i;t+=e<2048||e>=55296&&e<=57343?"���":String.fromCharCode(e),r+=6;continue}}if(240==(248&s)&&r+9<i){const n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16),o=parseInt(e.slice(r+10,r+12),16);if(128==(192&n)&&128==(192&i)&&128==(192&o)){let e=s<<18&1835008|n<<12&258048|i<<6&4032|63&o;e<65536||e>1114111?t+="����":(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(1023&e))),r+=9;continue}}t+="�"}}return t})}Pn.defaultChars=";/?:@&=+$,#",Pn.componentChars="";const On={};function Rn(e,t,n){"string"!=typeof t&&(n=t,t=Rn.defaultChars),void 0===n&&(n=!0);const r=function(e){let t=On[e];if(t)return t;t=On[e]=[];for(let e=0;e<128;e++){const n=String.fromCharCode(e);/^[0-9a-z]$/i.test(n)?t.push(n):t.push("%"+("0"+e.toString(16).toUpperCase()).slice(-2))}for(let n=0;n<e.length;n++)t[e.charCodeAt(n)]=e[n];return t}(t);let i="";for(let t=0,s=e.length;t<s;t++){const o=e.charCodeAt(t);if(n&&37===o&&t+2<s&&/^[0-9a-f]{2}$/i.test(e.slice(t+1,t+3)))i+=e.slice(t,t+3),t+=2;else if(o<128)i+=r[o];else if(o>=55296&&o<=57343){if(o>=55296&&o<=56319&&t+1<s){const n=e.charCodeAt(t+1);if(n>=56320&&n<=57343){i+=encodeURIComponent(e[t]+e[t+1]),t++;continue}}i+="%EF%BF%BD"}else i+=encodeURIComponent(e[t])}return i}function Ln(e){let t="";return t+=e.protocol||"",t+=e.slashes?"//":"",t+=e.auth?e.auth+"@":"",e.hostname&&-1!==e.hostname.indexOf(":")?t+="["+e.hostname+"]":t+=e.hostname||"",t+=e.port?":"+e.port:"",t+=e.pathname||"",t+=e.search||"",t+=e.hash||"",t}function $n(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}Rn.defaultChars=";/?:@&=+$,-_.!~*'()#",Rn.componentChars="-_.!~*'()";const jn=/^([a-z0-9.+-]+:)/i,Fn=/:[0-9]*$/,Bn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,qn=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),zn=["'"].concat(qn),Un=["%","/","?",";","#"].concat(zn),Vn=["/","?","#"],Wn=/^[+a-z0-9A-Z_-]{0,63}$/,Kn=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,Gn={javascript:!0,"javascript:":!0},Hn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function Yn(e,t){if(e&&e instanceof $n)return e;const n=new $n;return n.parse(e,t),n}$n.prototype.parse=function(e,t){let n,r,i,s=e;if(s=s.trim(),!t&&1===e.split("#").length){const e=Bn.exec(s);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=jn.exec(s);if(o&&(o=o[0],n=o.toLowerCase(),this.protocol=o,s=s.substr(o.length)),(t||o||s.match(/^\/\/[^@\/]+@[^@\/]+/))&&(i="//"===s.substr(0,2),!i||o&&Gn[o]||(s=s.substr(2),this.slashes=!0)),!Gn[o]&&(i||o&&!Hn[o])){let e,t,n=-1;for(let e=0;e<Vn.length;e++)r=s.indexOf(Vn[e]),-1!==r&&(-1===n||r<n)&&(n=r);t=-1===n?s.lastIndexOf("@"):s.lastIndexOf("@",n),-1!==t&&(e=s.slice(0,t),s=s.slice(t+1),this.auth=e),n=-1;for(let e=0;e<Un.length;e++)r=s.indexOf(Un[e]),-1!==r&&(-1===n||r<n)&&(n=r);-1===n&&(n=s.length),":"===s[n-1]&&n--;const i=s.slice(0,n);s=s.slice(n),this.parseHost(i),this.hostname=this.hostname||"";const o="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!o){const e=this.hostname.split(/\./);for(let t=0,n=e.length;t<n;t++){const n=e[t];if(n&&!n.match(Wn)){let r="";for(let e=0,t=n.length;e<t;e++)n.charCodeAt(e)>127?r+="x":r+=n[e];if(!r.match(Wn)){const r=e.slice(0,t),i=e.slice(t+1),o=n.match(Kn);o&&(r.push(o[1]),i.unshift(o[2])),i.length&&(s=i.join(".")+s),this.hostname=r.join(".");break}}}}this.hostname.length>255&&(this.hostname=""),o&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}const a=s.indexOf("#");-1!==a&&(this.hash=s.substr(a),s=s.slice(0,a));const c=s.indexOf("?");return-1!==c&&(this.search=s.substr(c),s=s.slice(0,c)),s&&(this.pathname=s),Hn[n]&&this.hostname&&!this.pathname&&(this.pathname=""),this},$n.prototype.parseHost=function(e){let t=Fn.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var Jn,Zn=Object.freeze({__proto__:null,decode:Pn,encode:Rn,format:Ln,parse:Yn}),Qn=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,Xn=/[\0-\x1F\x7F-\x9F]/,er=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,tr=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,nr=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,rr=Object.freeze({__proto__:null,Any:Qn,Cc:Xn,Cf:/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,P:er,S:tr,Z:nr}),ir=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏઑඡ༉༦ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲϏϢϸontourIntegraìȹoɴ\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲy;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱còJTabcdfgorstרׯؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ߂ߐĀiyޱrc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣসে্ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४ĀnrࢃgleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpwਖਛgȀLRlr৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼અઋp;椅y;䐜Ādl੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑඞcy;䐊cute;䅃ƀaeyહાron;䅇dil;䅅;䐝ƀgswે૰ativeƀMTV૨ediumSpace;怋hiĀcn૦ëeryThiîtedĀGLଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷreak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪௫ఄ಄ದൡඅ櫬Āoungruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater;EFGLSTஶஷ扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨setĀ;Eೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂෛ෧ขภยา฿ไlig;䅒cute耻Ó䃓Āiyීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲcr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬืde耻Õ䃕es;樷ml耻Ö䃖erĀBP๋Āar๐๓r;怾acĀek๚;揞et;掴arenthesis;揜ҀacfhilorsງຊຏຒດຝະrtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ檻cedesȀ;EST່້扺qual;檯lantEqual;扼ilde;找me;怳Ādpuct;戏ortionĀ;aȥl;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL憒ar;懥eftArrow;懄eiling;按oǵ\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄቕቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHcቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗ĀeiቻDzኀ\0ኇefore;戴a;䎘ĀcnኘkSpace;쀀 Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtèa;䎖r;愨pf;愤cr;쀀𝒵ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒;Eaeiopᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;eᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;eᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰᝃᝈ០៦ᠹᡐᜍ᥈ᥰot;櫭ĀcrᛶkȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;tbrk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯᝳ;䎲;愶een;扬r;쀀𝔟gcostuvwឍឝឳេ៕៛ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀakoᠦᠵĀcn៲ᠣkƀlst֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ;敛;敘;攘;攔;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģbar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;elƀ;bhᥨᥩᥫ䁜;槅sub;柈ŬᥴlĀ;e怢t»pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭒\0᯽\0ᰌƀcprᦲute;䄇̀;abcdsᦿᧀᧄ᧕᧙戩nd;橄rcup;橉Āau᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r;Ecefms᩠ᩢᩫ᪤᪪旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ\0\0aĀ;t䀬;䁀ƀ;fl戁îᅠeĀmxent»eóɍǧ\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯delprvw᭠᭬᭷ᮂᮬᯔarrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;pᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰻᰿ᱝᱩᱵᲞᲬᲷᴍᵻᶑᶫᶻ᷆᷍ròar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂᳖᳜᳠mƀ;oș᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄĀDoḆᴴoôĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»ṺƀaeiἒἚls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧\0耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₥₰₴⃰℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽ƀ;qsؾٌlanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqrⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0proør;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼ròòΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonóquigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roøurĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨íistĀ;sடr;쀀𝔫ȀEest⩦⩹⩼ƀ;qs⩭ƀ;qs⩴lanôií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast⭕⭚⭟lleìl;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖchimpqu⮽⯍⯙⬄⯤⯯Ȁ;cerല⯆ഷ⯉uå;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭ååഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñĀ;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;cⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācrir;榿;쀀𝔬ͯ\0\0\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕⶥⶨrò᪀Āirⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔǒr;榷rp;榹;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ\0\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ脀¶;l䂶leìЃɩ\0\0m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳ᤈ⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t⾴ïrel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⋢⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔ABHabcdefhilmnoprstuxけさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstwガクシスゼゾダッデナp;極Ā;fゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ìâヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘rrowĀ;tㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowóarpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓ròaòՑ;怏oustĀ;a㈞掱che»mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì耻䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;qኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫwar;椪lig耻ß䃟㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rëƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproøim»ኬsðኞĀas㚺㚮ðrn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈadempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xôheadĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roðtré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜtré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),sr=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));const or=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),ar=null!==(Jn=String.fromCodePoint)&&void 0!==Jn?Jn:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t};var cr;!function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"}(cr||(cr={}));var lr,ur,dr;function pr(e){return e>=cr.ZERO&&e<=cr.NINE}function hr(e){return e>=cr.UPPER_A&&e<=cr.UPPER_F||e>=cr.LOWER_A&&e<=cr.LOWER_F}function fr(e){return e===cr.EQUALS||function(e){return e>=cr.UPPER_A&&e<=cr.UPPER_Z||e>=cr.LOWER_A&&e<=cr.LOWER_Z||pr(e)}(e)}!function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"}(lr||(lr={})),function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"}(ur||(ur={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(dr||(dr={}));class mr{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=ur.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=dr.Strict}startEntity(e){this.decodeMode=e,this.state=ur.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case ur.EntityStart:return e.charCodeAt(t)===cr.NUM?(this.state=ur.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=ur.NamedEntity,this.stateNamedEntity(e,t));case ur.NumericStart:return this.stateNumericStart(e,t);case ur.NumericDecimal:return this.stateNumericDecimal(e,t);case ur.NumericHex:return this.stateNumericHex(e,t);case ur.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===cr.LOWER_X?(this.state=ur.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=ur.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const i=n-t;this.result=this.result*Math.pow(r,i)+parseInt(e.substr(t,i),r),this.consumed+=i}}stateNumericHex(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!pr(r)&&!hr(r))return this.addToNumericResult(e,n,t,16),this.emitNumericEntity(r,3);t+=1}return this.addToNumericResult(e,n,t,16),-1}stateNumericDecimal(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!pr(r))return this.addToNumericResult(e,n,t,10),this.emitNumericEntity(r,2);t+=1}return this.addToNumericResult(e,n,t,10),-1}emitNumericEntity(e,t){var n;if(this.consumed<=t)return null===(n=this.errors)||void 0===n||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===cr.SEMI)this.consumed+=1;else if(this.decodeMode===dr.Strict)return 0;return this.emitCodePoint(function(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=or.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==cr.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],i=(r&lr.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const s=e.charCodeAt(t);if(this.treeIndex=yr(n,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return 0===this.result||this.decodeMode===dr.Attribute&&(0===i||fr(s))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],i=(r&lr.VALUE_LENGTH)>>14,0!==i){if(s===cr.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==dr.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&lr.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~lr.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case ur.NamedEntity:return 0===this.result||this.decodeMode===dr.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case ur.NumericDecimal:return this.emitNumericEntity(0,2);case ur.NumericHex:return this.emitNumericEntity(0,3);case ur.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case ur.EntityStart:return 0}}}function gr(e){let t="";const n=new mr(e,e=>t+=ar(e));return function(e,r){let i=0,s=0;for(;(s=e.indexOf("&",s))>=0;){t+=e.slice(i,s),n.startEntity(r);const o=n.write(e,s+1);if(o<0){i=s+n.end();break}i=s+o,s=0===o?i+1:i}const o=t+e.slice(i);return t="",o}}function yr(e,t,n,r){const i=(t&lr.BRANCH_LENGTH)>>7,s=t&lr.JUMP_TABLE;if(0===i)return 0!==s&&r===s?n:-1;if(s){const t=r-s;return t<0||t>=i?-1:e[n+t]-1}let o=n,a=o+i-1;for(;o<=a;){const t=o+a>>>1,n=e[t];if(n<r)o=t+1;else{if(!(n>r))return e[t+i];a=t-1}}return-1}const br=gr(ir);function wr(e){return"[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}gr(sr);const vr=Object.prototype.hasOwnProperty;function kr(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach(function(n){e[n]=t[n]})}}),e}function Ir(e,t,n){return[].concat(e.slice(0,t),n,e.slice(t+1))}function Er(e){return!(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(!!(65535&~e&&65534!=(65535&e))&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function Ar(e){if(e>65535){const t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}const Sr=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,_r=new RegExp(Sr.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),xr=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function Cr(e,t){if(35===t.charCodeAt(0)&&xr.test(t)){const n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Er(n)?Ar(n):e}const n=function(e,t=dr.Legacy){return br(e,t)}(e);return n!==e?n:e}function Tr(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(_r,function(e,t,n){return t||Cr(e,n)})}const Nr=/[&<>"]/,Mr=/[&<>"]/g,Dr={"&":"&","<":"<",">":">",'"':"""};function Pr(e){return Dr[e]}function Or(e){return Nr.test(e)?e.replace(Mr,Pr):e}const Rr=/[.?*+^$[\]\\(){}|-]/g;function Lr(e){switch(e){case 9:case 32:return!0}return!1}function $r(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1}function jr(e){return er.test(e)||tr.test(e)}function Fr(e){return jr(Ar(e))}function Br(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function qr(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}function zr(e){return 32===e||9===e||10===e||13===e}function Ur(e){let t=0;for(;t<e.length&&zr(e.charCodeAt(t));t++);let n=e.length-1;for(;n>=t&&zr(e.charCodeAt(n));n--);return e.slice(t,n+1)}const Vr={mdurl:Zn,ucmicro:rr};var Wr=Object.freeze({__proto__:null,arrayReplaceAt:Ir,asciiTrim:Ur,assign:kr,escapeHtml:Or,escapeRE:function(e){return e.replace(Rr,"\\$&")},fromCodePoint:Ar,has:function(e,t){return vr.call(e,t)},isMdAsciiPunct:Br,isPunctChar:jr,isPunctCharCode:Fr,isSpace:Lr,isString:wr,isValidEntityCode:Er,isWhiteSpace:$r,lib:Vr,normalizeReference:qr,unescapeAll:Tr,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(Sr,"$1")}});var Kr=Object.freeze({__proto__:null,parseLinkDestination:function(e,t,n){let r,i=t;const s={ok:!1,pos:0,str:""};if(60===e.charCodeAt(i)){for(i++;i<n;){if(r=e.charCodeAt(i),10===r)return s;if(60===r)return s;if(62===r)return s.pos=i+1,s.str=Tr(e.slice(t+1,i)),s.ok=!0,s;92===r&&i+1<n?i+=2:i++}return s}let o=0;for(;i<n&&(r=e.charCodeAt(i),32!==r)&&!(r<32||127===r);)if(92===r&&i+1<n){if(32===e.charCodeAt(i+1))break;i+=2}else{if(40===r&&(o++,o>32))return s;if(41===r){if(0===o)break;o--}i++}return t===i||0!==o||(s.str=Tr(e.slice(t,i)),s.pos=i,s.ok=!0),s},parseLinkLabel:function(e,t,n){let r,i,s,o;const a=e.posMax,c=e.pos;for(e.pos=t+1,r=1;e.pos<a;){if(s=e.src.charCodeAt(e.pos),93===s&&(r--,0===r)){i=!0;break}if(o=e.pos,e.md.inline.skipToken(e),91===s)if(o===e.pos-1)r++;else if(n)return e.pos=c,-1}let l=-1;return i&&(l=e.pos),e.pos=c,l},parseLinkTitle:function(e,t,n,r){let i,s=t;const o={ok:!1,can_continue:!1,pos:0,str:"",marker:0};if(r)o.str=r.str,o.marker=r.marker;else{if(s>=n)return o;let r=e.charCodeAt(s);if(34!==r&&39!==r&&40!==r)return o;t++,s++,40===r&&(r=41),o.marker=r}for(;s<n;){if(i=e.charCodeAt(s),i===o.marker)return o.pos=s+1,o.str+=Tr(e.slice(t,s)),o.ok=!0,o;if(40===i&&41===o.marker)return o;92===i&&s+1<n&&s++,s++}return o.can_continue=!0,o.str+=Tr(e.slice(t,s)),o}});const Gr={};function Hr(){this.rules=kr({},Gr)}function Yr(){this.__rules__=[],this.__cache__=null}function Jr(e,t,n){this.type=e,this.tag=t,this.attrs=null,this.map=null,this.nesting=n,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}function Zr(e,t,n){this.src=e,this.env=n,this.tokens=[],this.inlineMode=!1,this.md=t}Gr.code_inline=function(e,t,n,r,i){const s=e[t];return"<code"+i.renderAttrs(s)+">"+Or(s.content)+"</code>"},Gr.code_block=function(e,t,n,r,i){const s=e[t];return"<pre"+i.renderAttrs(s)+"><code>"+Or(e[t].content)+"</code></pre>\n"},Gr.fence=function(e,t,n,r,i){const s=e[t],o=s.info?Tr(s.info).trim():"";let a,c="",l="";if(o){const e=o.split(/(\s+)/g);c=e[0],l=e.slice(2).join("")}if(a=n.highlight&&n.highlight(s.content,c,l)||Or(s.content),0===a.indexOf("<pre"))return a+"\n";if(o){const e=s.attrIndex("class"),t=s.attrs?s.attrs.slice():[];e<0?t.push(["class",n.langPrefix+c]):(t[e]=t[e].slice(),t[e][1]+=" "+n.langPrefix+c);const r={attrs:t};return`<pre><code${i.renderAttrs(r)}>${a}</code></pre>\n`}return`<pre><code${i.renderAttrs(s)}>${a}</code></pre>\n`},Gr.image=function(e,t,n,r,i){const s=e[t];return s.attrs[s.attrIndex("alt")][1]=i.renderInlineAsText(s.children,n,r),i.renderToken(e,t,n)},Gr.hardbreak=function(e,t,n){return n.xhtmlOut?"<br />\n":"<br>\n"},Gr.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"<br />\n":"<br>\n":"\n"},Gr.text=function(e,t){return Or(e[t].content)},Gr.html_block=function(e,t){return e[t].content},Gr.html_inline=function(e,t){return e[t].content},Hr.prototype.renderAttrs=function(e){let t,n,r;if(!e.attrs)return"";for(r="",t=0,n=e.attrs.length;t<n;t++)r+=" "+Or(e.attrs[t][0])+'="'+Or(e.attrs[t][1])+'"';return r},Hr.prototype.renderToken=function(e,t,n){const r=e[t];let i="";if(r.hidden)return"";r.block&&-1!==r.nesting&&t&&e[t-1].hidden&&(i+="\n"),i+=(-1===r.nesting?"</":"<")+r.tag,i+=this.renderAttrs(r),0===r.nesting&&n.xhtmlOut&&(i+=" /");let s=!1;if(r.block&&(s=!0,1===r.nesting&&t+1<e.length)){const n=e[t+1];("inline"===n.type||n.hidden||-1===n.nesting&&n.tag===r.tag)&&(s=!1)}return i+=s?">\n":">",i},Hr.prototype.renderInline=function(e,t,n){let r="";const i=this.rules;for(let s=0,o=e.length;s<o;s++){const o=e[s].type;void 0!==i[o]?r+=i[o](e,s,t,n,this):r+=this.renderToken(e,s,t)}return r},Hr.prototype.renderInlineAsText=function(e,t,n){let r="";for(let i=0,s=e.length;i<s;i++)switch(e[i].type){case"text":case"html_inline":case"html_block":r+=e[i].content;break;case"image":r+=this.renderInlineAsText(e[i].children,t,n);break;case"softbreak":case"hardbreak":r+="\n"}return r},Hr.prototype.render=function(e,t,n){let r="";const i=this.rules;for(let s=0,o=e.length;s<o;s++){const o=e[s].type;"inline"===o?r+=this.renderInline(e[s].children,t,n):void 0!==i[o]?r+=i[o](e,s,t,n,this):r+=this.renderToken(e,s,t,n)}return r},Yr.prototype.__find__=function(e){for(let t=0;t<this.__rules__.length;t++)if(this.__rules__[t].name===e)return t;return-1},Yr.prototype.__compile__=function(){const e=this,t=[""];e.__rules__.forEach(function(e){e.enabled&&e.alt.forEach(function(e){t.indexOf(e)<0&&t.push(e)})}),e.__cache__={},t.forEach(function(t){e.__cache__[t]=[],e.__rules__.forEach(function(n){n.enabled&&(t&&n.alt.indexOf(t)<0||e.__cache__[t].push(n.fn))})})},Yr.prototype.at=function(e,t,n){const r=this.__find__(e),i=n||{};if(-1===r)throw new Error("Parser rule not found: "+e);this.__rules__[r].fn=t,this.__rules__[r].alt=i.alt||[],this.__cache__=null},Yr.prototype.before=function(e,t,n,r){const i=this.__find__(e),s=r||{};if(-1===i)throw new Error("Parser rule not found: "+e);this.__rules__.splice(i,0,{name:t,enabled:!0,fn:n,alt:s.alt||[]}),this.__cache__=null},Yr.prototype.after=function(e,t,n,r){const i=this.__find__(e),s=r||{};if(-1===i)throw new Error("Parser rule not found: "+e);this.__rules__.splice(i+1,0,{name:t,enabled:!0,fn:n,alt:s.alt||[]}),this.__cache__=null},Yr.prototype.push=function(e,t,n){const r=n||{};this.__rules__.push({name:e,enabled:!0,fn:t,alt:r.alt||[]}),this.__cache__=null},Yr.prototype.enable=function(e,t){Array.isArray(e)||(e=[e]);const n=[];return e.forEach(function(e){const r=this.__find__(e);if(r<0){if(t)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[r].enabled=!0,n.push(e)},this),this.__cache__=null,n},Yr.prototype.enableOnly=function(e,t){Array.isArray(e)||(e=[e]),this.__rules__.forEach(function(e){e.enabled=!1}),this.enable(e,t)},Yr.prototype.disable=function(e,t){Array.isArray(e)||(e=[e]);const n=[];return e.forEach(function(e){const r=this.__find__(e);if(r<0){if(t)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[r].enabled=!1,n.push(e)},this),this.__cache__=null,n},Yr.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},Jr.prototype.attrIndex=function(e){if(!this.attrs)return-1;const t=this.attrs;for(let n=0,r=t.length;n<r;n++)if(t[n][0]===e)return n;return-1},Jr.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]},Jr.prototype.attrSet=function(e,t){const n=this.attrIndex(e),r=[e,t];n<0?this.attrPush(r):this.attrs[n]=r},Jr.prototype.attrGet=function(e){const t=this.attrIndex(e);let n=null;return t>=0&&(n=this.attrs[t][1]),n},Jr.prototype.attrJoin=function(e,t){const n=this.attrIndex(e);n<0?this.attrPush([e,t]):this.attrs[n][1]=this.attrs[n][1]+" "+t},Zr.prototype.Token=Jr;const Qr=/\r\n?|\n/g,Xr=/\0/g;function ei(e){return/^<a[>\s]/i.test(e)}function ti(e){return/^<\/a\s*>/i.test(e)}const ni=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,ri=/\((c|tm|r)\)/i,ii=/\((c|tm|r)\)/gi,si={c:"©",r:"®",tm:"™"};function oi(e,t){return si[t.toLowerCase()]}function ai(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||(r.content=r.content.replace(ii,oi)),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++}}function ci(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||ni.test(r.content)&&(r.content=r.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/gm,"$1—").replace(/(^|\s)--(?=\s|$)/gm,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,"$1–")),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++}}const li=/['"]/,ui=/['"]/g;function di(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function pi(e,t){let n;const r=[],i={};for(let s=0;s<e.length;s++){const o=e[s],a=e[s].level;for(n=r.length-1;n>=0&&!(r[n].level<=a);n--);if(r.length=n+1,"text"!==o.type)continue;const c=o.content;let l=0;const u=c.length;e:for(;l<u;){ui.lastIndex=l;const o=ui.exec(c);if(!o)break;let d=!0,p=!0;l=o.index+1;const h="'"===o[0];let f=32;if(o.index-1>=0)f=c.charCodeAt(o.index-1);else for(n=s-1;n>=0&&("softbreak"!==e[n].type&&"hardbreak"!==e[n].type);n--)if(e[n].content){f=e[n].content.charCodeAt(e[n].content.length-1);break}let m=32;if(l<u)m=c.charCodeAt(l);else for(n=s+1;n<e.length&&("softbreak"!==e[n].type&&"hardbreak"!==e[n].type);n++)if(e[n].content){m=e[n].content.charCodeAt(0);break}const g=Br(f)||Fr(f),y=Br(m)||Fr(m),b=$r(f),w=$r(m);if(w?d=!1:y&&(b||g||(d=!1)),b?p=!1:g&&(w||y||(p=!1)),34===m&&'"'===o[0]&&f>=48&&f<=57&&(p=d=!1),d&&p&&(d=g,p=y),d||p){if(p)for(n=r.length-1;n>=0;n--){let e=r[n];if(r[n].level<a)break;if(e.single===h&&r[n].level===a){let a,c;e=r[n],h?(a=t.md.options.quotes[2],c=t.md.options.quotes[3]):(a=t.md.options.quotes[0],c=t.md.options.quotes[1]),di(i,s,o.index,c),di(i,e.token,e.pos,a),r.length=n;continue e}}d?r.push({token:s,pos:o.index,single:h,level:a}):p&&h&&di(i,s,o.index,"’")}else h&&di(i,s,o.index,"’")}}Object.keys(i).forEach(function(t){e[t].content=function(e,t){let n="",r=0;t.sort((e,t)=>e.pos-t.pos);for(let i=0;i<t.length;i++){const s=t[i];n+=e.slice(r,s.pos)+s.ch,r=s.pos+1}return n+e.slice(r)}(e[t].content,i[t])})}const hi=[["normalize",function(e){let t;t=e.src.replace(Qr,"\n"),t=t.replace(Xr,"�"),e.src=t}],["block",function(e){let t;e.inlineMode?(t=new e.Token("inline","",0),t.content=e.src,t.map=[0,1],t.children=[],e.tokens.push(t)):e.md.block.parse(e.src,e.md,e.env,e.tokens)}],["inline",function(e){const t=e.tokens;for(let n=0,r=t.length;n<r;n++){const r=t[n];"inline"===r.type&&e.md.inline.parse(r.content,e.md,e.env,r.children)}}],["linkify",function(e){const t=e.tokens;if(e.md.options.linkify)for(let n=0,r=t.length;n<r;n++){if("inline"!==t[n].type||!e.md.linkify.pretest(t[n].content))continue;let r=t[n].children,i=0;for(let s=r.length-1;s>=0;s--){const o=r[s];if("link_close"!==o.type){if("html_inline"===o.type&&(ei(o.content)&&i>0&&i--,ti(o.content)&&i++),!(i>0)&&"text"===o.type&&e.md.linkify.test(o.content)){const i=o.content;let a=e.md.linkify.match(i);const c=[];let l=o.level,u=0;a.length>0&&0===a[0].index&&s>0&&"text_special"===r[s-1].type&&(a=a.slice(1));for(let t=0;t<a.length;t++){const n=a[t].url,r=e.md.normalizeLink(n);if(!e.md.validateLink(r))continue;let s=a[t].text;s=a[t].schema?"mailto:"!==a[t].schema||/^mailto:/i.test(s)?e.md.normalizeLinkText(s):e.md.normalizeLinkText("mailto:"+s).replace(/^mailto:/,""):e.md.normalizeLinkText("http://"+s).replace(/^http:\/\//,"");const o=a[t].index;if(o>u){const t=new e.Token("text","",0);t.content=i.slice(u,o),t.level=l,c.push(t)}const d=new e.Token("link_open","a",1);d.attrs=[["href",r]],d.level=l++,d.markup="linkify",d.info="auto",c.push(d);const p=new e.Token("text","",0);p.content=s,p.level=l,c.push(p);const h=new e.Token("link_close","a",-1);h.level=--l,h.markup="linkify",h.info="auto",c.push(h),u=a[t].lastIndex}if(u<i.length){const t=new e.Token("text","",0);t.content=i.slice(u),t.level=l,c.push(t)}t[n].children=r=Ir(r,s,c)}}else for(s--;r[s].level!==o.level&&"link_open"!==r[s].type;)s--}}}],["replacements",function(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&(ri.test(e.tokens[t].content)&&ai(e.tokens[t].children),ni.test(e.tokens[t].content)&&ci(e.tokens[t].children))}],["smartquotes",function(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&li.test(e.tokens[t].content)&&pi(e.tokens[t].children,e)}],["text_join",function(e){let t,n;const r=e.tokens,i=r.length;for(let e=0;e<i;e++){if("inline"!==r[e].type)continue;const i=r[e].children,s=i.length;for(t=0;t<s;t++)"text_special"===i[t].type&&(i[t].type="text");for(t=n=0;t<s;t++)"text"===i[t].type&&t+1<s&&"text"===i[t+1].type?i[t+1].content=i[t].content+i[t+1].content:(t!==n&&(i[n]=i[t]),n++);t!==n&&(i.length=n)}}]];function fi(){this.ruler=new Yr;for(let e=0;e<hi.length;e++)this.ruler.push(hi[e][0],hi[e][1])}function mi(e,t,n,r){this.src=e,this.md=t,this.env=n,this.tokens=r,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0;const i=this.src;for(let e=0,t=0,n=0,r=0,s=i.length,o=!1;t<s;t++){const a=i.charCodeAt(t);if(!o){if(Lr(a)){n++,9===a?r+=4-r%4:r++;continue}o=!0}10!==a&&t!==s-1||(10!==a&&t++,this.bMarks.push(e),this.eMarks.push(t),this.tShift.push(n),this.sCount.push(r),this.bsCount.push(0),o=!1,n=0,r=0,e=t+1)}this.bMarks.push(i.length),this.eMarks.push(i.length),this.tShift.push(0),this.sCount.push(0),this.bsCount.push(0),this.lineMax=this.bMarks.length-1}fi.prototype.process=function(e){const t=this.ruler.getRules("");for(let n=0,r=t.length;n<r;n++)t[n](e)},fi.prototype.State=Zr,mi.prototype.push=function(e,t,n){const r=new Jr(e,t,n);return r.block=!0,n<0&&this.level--,r.level=this.level,n>0&&this.level++,this.tokens.push(r),r},mi.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},mi.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},mi.prototype.skipSpaces=function(e){for(let t=this.src.length;e<t;e++){if(!Lr(this.src.charCodeAt(e)))break}return e},mi.prototype.skipSpacesBack=function(e,t){if(e<=t)return e;for(;e>t;)if(!Lr(this.src.charCodeAt(--e)))return e+1;return e},mi.prototype.skipChars=function(e,t){for(let n=this.src.length;e<n&&this.src.charCodeAt(e)===t;e++);return e},mi.prototype.skipCharsBack=function(e,t,n){if(e<=n)return e;for(;e>n;)if(t!==this.src.charCodeAt(--e))return e+1;return e},mi.prototype.getLines=function(e,t,n,r){if(e>=t)return"";const i=new Array(t-e);for(let s=0,o=e;o<t;o++,s++){let e=0;const a=this.bMarks[o];let c,l=a;for(c=o+1<t||r?this.eMarks[o]+1:this.eMarks[o];l<c&&e<n;){const t=this.src.charCodeAt(l);if(Lr(t))9===t?e+=4-(e+this.bsCount[o])%4:e++;else{if(!(l-a<this.tShift[o]))break;e++}l++}i[s]=e>n?new Array(e-n+1).join(" ")+this.src.slice(l,c):this.src.slice(l,c)}return i.join("")},mi.prototype.Token=Jr;function gi(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function yi(e){const t=[],n=e.length;let r=0,i=e.charCodeAt(r),s=!1,o=0,a="";for(;r<n;)124===i&&(s?(a+=e.substring(o,r-1),o=r):(t.push(a+e.substring(o,r)),a="",o=r+1)),s=92===i,r++,i=e.charCodeAt(r);return t.push(a+e.substring(o)),t}function bi(e,t){const n=e.eMarks[t];let r=e.bMarks[t]+e.tShift[t];const i=e.src.charCodeAt(r++);if(42!==i&&45!==i&&43!==i)return-1;if(r<n){if(!Lr(e.src.charCodeAt(r)))return-1}return r}function wi(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];let i=n;if(i+1>=r)return-1;let s=e.src.charCodeAt(i++);if(s<48||s>57)return-1;for(;;){if(i>=r)return-1;if(s=e.src.charCodeAt(i++),!(s>=48&&s<=57)){if(41===s||46===s)break;return-1}if(i-n>=10)return-1}return i<r&&(s=e.src.charCodeAt(i),!Lr(s))?-1:i}const vi="<[A-Za-z][A-Za-z0-9\\-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^\"'=<>`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",ki="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",Ii=new RegExp("^(?:"+vi+"|"+ki+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|<![A-Za-z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)"),Ei=new RegExp("^(?:"+vi+"|"+ki+")"),Ai=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^<!--/,/-->/,!0],[/^<\?/,/\?>/,!0],[/^<![A-Z]/,/>/,!0],[/^<!\[CDATA\[/,/\]\]>/,!0],[new RegExp("^</?("+["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"].join("|")+")(?=(\\s|/?>|$))","i"),/^$/,!0],[new RegExp(Ei.source+"\\s*$"),/^$/,!1]];const Si=[["table",function(e,t,n,r){if(t+2>n)return!1;let i=t+1;if(e.sCount[i]<e.blkIndent)return!1;if(e.sCount[i]-e.blkIndent>=4)return!1;let s=e.bMarks[i]+e.tShift[i];if(s>=e.eMarks[i])return!1;const o=e.src.charCodeAt(s++);if(124!==o&&45!==o&&58!==o)return!1;if(s>=e.eMarks[i])return!1;const a=e.src.charCodeAt(s++);if(124!==a&&45!==a&&58!==a&&!Lr(a))return!1;if(45===o&&Lr(a))return!1;for(;s<e.eMarks[i];){const t=e.src.charCodeAt(s);if(124!==t&&45!==t&&58!==t&&!Lr(t))return!1;s++}let c=gi(e,t+1),l=c.split("|");const u=[];for(let e=0;e<l.length;e++){const t=l[e].trim();if(!t){if(0===e||e===l.length-1)continue;return!1}if(!/^:?-+:?$/.test(t))return!1;58===t.charCodeAt(t.length-1)?u.push(58===t.charCodeAt(0)?"center":"right"):58===t.charCodeAt(0)?u.push("left"):u.push("")}if(c=gi(e,t).trim(),-1===c.indexOf("|"))return!1;if(e.sCount[t]-e.blkIndent>=4)return!1;l=yi(c),l.length&&""===l[0]&&l.shift(),l.length&&""===l[l.length-1]&&l.pop();const d=l.length;if(0===d||d!==u.length)return!1;if(r)return!0;const p=e.parentType;e.parentType="table";const h=e.md.block.ruler.getRules("blockquote"),f=[t,0];e.push("table_open","table",1).map=f,e.push("thead_open","thead",1).map=[t,t+1],e.push("tr_open","tr",1).map=[t,t+1];for(let t=0;t<l.length;t++){const n=e.push("th_open","th",1);u[t]&&(n.attrs=[["style","text-align:"+u[t]]]);const r=e.push("inline","",0);r.content=l[t].trim(),r.children=[],e.push("th_close","th",-1)}let m;e.push("tr_close","tr",-1),e.push("thead_close","thead",-1);let g=0;for(i=t+2;i<n&&!(e.sCount[i]<e.blkIndent);i++){let r=!1;for(let t=0,s=h.length;t<s;t++)if(h[t](e,i,n,!0)){r=!0;break}if(r)break;if(c=gi(e,i).trim(),!c)break;if(e.sCount[i]-e.blkIndent>=4)break;if(l=yi(c),l.length&&""===l[0]&&l.shift(),l.length&&""===l[l.length-1]&&l.pop(),g+=d-l.length,g>65536)break;if(i===t+2){e.push("tbody_open","tbody",1).map=m=[t+2,0]}e.push("tr_open","tr",1).map=[i,i+1];for(let t=0;t<d;t++){const n=e.push("td_open","td",1);u[t]&&(n.attrs=[["style","text-align:"+u[t]]]);const r=e.push("inline","",0);r.content=l[t]?l[t].trim():"",r.children=[],e.push("td_close","td",-1)}e.push("tr_close","tr",-1)}return m&&(e.push("tbody_close","tbody",-1),m[1]=i),e.push("table_close","table",-1),f[1]=i,e.parentType=p,e.line=i,!0},["paragraph","reference"]],["code",function(e,t,n){if(e.sCount[t]-e.blkIndent<4)return!1;let r=t+1,i=r;for(;r<n;)if(e.isEmpty(r))r++;else{if(!(e.sCount[r]-e.blkIndent>=4))break;r++,i=r}e.line=i;const s=e.push("code_block","code",0);return s.content=e.getLines(t,i,4+e.blkIndent,!1)+"\n",s.map=[t,e.line],!0}],["fence",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;if(i+3>s)return!1;const o=e.src.charCodeAt(i);if(126!==o&&96!==o)return!1;let a=i;i=e.skipChars(i,o);let c=i-a;if(c<3)return!1;const l=e.src.slice(a,i),u=e.src.slice(i,s);if(96===o&&u.indexOf(String.fromCharCode(o))>=0)return!1;if(r)return!0;let d=t,p=!1;for(;(d++,!(d>=n))&&(i=a=e.bMarks[d]+e.tShift[d],s=e.eMarks[d],!(i<s&&e.sCount[d]<e.blkIndent));)if(e.src.charCodeAt(i)===o&&!(e.sCount[d]-e.blkIndent>=4||(i=e.skipChars(i,o),i-a<c||(i=e.skipSpaces(i),i<s)))){p=!0;break}c=e.sCount[t],e.line=d+(p?1:0);const h=e.push("fence","code",0);return h.info=u,h.content=e.getLines(t+1,d,c,!0),h.markup=l,h.map=[t,e.line],!0},["paragraph","reference","blockquote","list"]],["blockquote",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];const o=e.lineMax;if(e.sCount[t]-e.blkIndent>=4)return!1;if(62!==e.src.charCodeAt(i))return!1;if(r)return!0;const a=[],c=[],l=[],u=[],d=e.md.block.ruler.getRules("blockquote"),p=e.parentType;e.parentType="blockquote";let h,f=!1;for(h=t;h<n;h++){const t=e.sCount[h]<e.blkIndent;if(i=e.bMarks[h]+e.tShift[h],s=e.eMarks[h],i>=s)break;if(62===e.src.charCodeAt(i++)&&!t){let t,n,r=e.sCount[h]+1;32===e.src.charCodeAt(i)?(i++,r++,n=!1,t=!0):9===e.src.charCodeAt(i)?(t=!0,(e.bsCount[h]+r)%4==3?(i++,r++,n=!1):n=!0):t=!1;let o=r;for(a.push(e.bMarks[h]),e.bMarks[h]=i;i<s;){const t=e.src.charCodeAt(i);if(!Lr(t))break;9===t?o+=4-(o+e.bsCount[h]+(n?1:0))%4:o++,i++}f=i>=s,c.push(e.bsCount[h]),e.bsCount[h]=e.sCount[h]+1+(t?1:0),l.push(e.sCount[h]),e.sCount[h]=o-r,u.push(e.tShift[h]),e.tShift[h]=i-e.bMarks[h];continue}if(f)break;let r=!1;for(let t=0,i=d.length;t<i;t++)if(d[t](e,h,n,!0)){r=!0;break}if(r){e.lineMax=h,0!==e.blkIndent&&(a.push(e.bMarks[h]),c.push(e.bsCount[h]),u.push(e.tShift[h]),l.push(e.sCount[h]),e.sCount[h]-=e.blkIndent);break}a.push(e.bMarks[h]),c.push(e.bsCount[h]),u.push(e.tShift[h]),l.push(e.sCount[h]),e.sCount[h]=-1}const m=e.blkIndent;e.blkIndent=0;const g=e.push("blockquote_open","blockquote",1);g.markup=">";const y=[t,0];g.map=y,e.md.block.tokenize(e,t,h),e.push("blockquote_close","blockquote",-1).markup=">",e.lineMax=o,e.parentType=p,y[1]=e.line;for(let n=0;n<u.length;n++)e.bMarks[n+t]=a[n],e.tShift[n+t]=u[n],e.sCount[n+t]=l[n],e.bsCount[n+t]=c[n];return e.blkIndent=m,!0},["paragraph","reference","blockquote","list"]],["hr",function(e,t,n,r){const i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let s=e.bMarks[t]+e.tShift[t];const o=e.src.charCodeAt(s++);if(42!==o&&45!==o&&95!==o)return!1;let a=1;for(;s<i;){const t=e.src.charCodeAt(s++);if(t!==o&&!Lr(t))return!1;t===o&&a++}if(a<3)return!1;if(r)return!0;e.line=t+1;const c=e.push("hr","hr",0);return c.map=[t,e.line],c.markup=Array(a+1).join(String.fromCharCode(o)),!0},["paragraph","reference","blockquote","list"]],["list",function(e,t,n,r){let i,s,o,a,c=t,l=!0;if(e.sCount[c]-e.blkIndent>=4)return!1;if(e.listIndent>=0&&e.sCount[c]-e.listIndent>=4&&e.sCount[c]<e.blkIndent)return!1;let u,d,p,h=!1;if(r&&"paragraph"===e.parentType&&e.sCount[c]>=e.blkIndent&&(h=!0),(p=wi(e,c))>=0){if(u=!0,o=e.bMarks[c]+e.tShift[c],d=Number(e.src.slice(o,p-1)),h&&1!==d)return!1}else{if(!((p=bi(e,c))>=0))return!1;u=!1}if(h&&e.skipSpaces(p)>=e.eMarks[c])return!1;if(r)return!0;const f=e.src.charCodeAt(p-1),m=e.tokens.length;u?(a=e.push("ordered_list_open","ol",1),1!==d&&(a.attrs=[["start",d]])):a=e.push("bullet_list_open","ul",1);const g=[c,0];a.map=g,a.markup=String.fromCharCode(f);let y=!1;const b=e.md.block.ruler.getRules("list"),w=e.parentType;for(e.parentType="list";c<n;){s=p,i=e.eMarks[c];const t=e.sCount[c]+p-(e.bMarks[c]+e.tShift[c]);let r=t;for(;s<i;){const t=e.src.charCodeAt(s);if(9===t)r+=4-(r+e.bsCount[c])%4;else{if(32!==t)break;r++}s++}const d=s;let h;h=d>=i?1:r-t,h>4&&(h=1);const m=t+h;a=e.push("list_item_open","li",1),a.markup=String.fromCharCode(f);const g=[c,0];a.map=g,u&&(a.info=e.src.slice(o,p-1));const w=e.tight,v=e.tShift[c],k=e.sCount[c],I=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=m,e.tight=!0,e.tShift[c]=d-e.bMarks[c],e.sCount[c]=r,d>=i&&e.isEmpty(c+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,c,n,!0),e.tight&&!y||(l=!1),y=e.line-c>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=I,e.tShift[c]=v,e.sCount[c]=k,e.tight=w,a=e.push("list_item_close","li",-1),a.markup=String.fromCharCode(f),c=e.line,g[1]=c,c>=n)break;if(e.sCount[c]<e.blkIndent)break;if(e.sCount[c]-e.blkIndent>=4)break;let E=!1;for(let t=0,r=b.length;t<r;t++)if(b[t](e,c,n,!0)){E=!0;break}if(E)break;if(u){if(p=wi(e,c),p<0)break;o=e.bMarks[c]+e.tShift[c]}else if(p=bi(e,c),p<0)break;if(f!==e.src.charCodeAt(p-1))break}return a=u?e.push("ordered_list_close","ol",-1):e.push("bullet_list_close","ul",-1),a.markup=String.fromCharCode(f),g[1]=c,e.line=c,e.parentType=w,l&&function(e,t){const n=e.level+2;for(let r=t+2,i=e.tokens.length-2;r<i;r++)e.tokens[r].level===n&&"paragraph_open"===e.tokens[r].type&&(e.tokens[r+2].hidden=!0,e.tokens[r].hidden=!0,r+=2)}(e,m),!0},["paragraph","reference","blockquote"]],["reference",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t],o=t+1;if(e.sCount[t]-e.blkIndent>=4)return!1;if(91!==e.src.charCodeAt(i))return!1;function a(t){const n=e.lineMax;if(t>=n||e.isEmpty(t))return null;let r=!1;if(e.sCount[t]-e.blkIndent>3&&(r=!0),e.sCount[t]<0&&(r=!0),!r){const r=e.md.block.ruler.getRules("reference"),i=e.parentType;e.parentType="reference";let s=!1;for(let i=0,o=r.length;i<o;i++)if(r[i](e,t,n,!0)){s=!0;break}if(e.parentType=i,s)return null}const i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];return e.src.slice(i,s+1)}let c=e.src.slice(i,s+1);s=c.length;let l=-1;for(i=1;i<s;i++){const e=c.charCodeAt(i);if(91===e)return!1;if(93===e){l=i;break}if(10===e){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}else if(92===e&&(i++,i<s&&10===c.charCodeAt(i))){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}}if(l<0||58!==c.charCodeAt(l+1))return!1;for(i=l+2;i<s;i++){const e=c.charCodeAt(i);if(10===e){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}else if(!Lr(e))break}const u=e.md.helpers.parseLinkDestination(c,i,s);if(!u.ok)return!1;const d=e.md.normalizeLink(u.str);if(!e.md.validateLink(d))return!1;i=u.pos;const p=i,h=o,f=i;for(;i<s;i++){const e=c.charCodeAt(i);if(10===e){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}else if(!Lr(e))break}let m,g=e.md.helpers.parseLinkTitle(c,i,s);for(;g.can_continue;){const t=a(o);if(null===t)break;c+=t,i=s,s=c.length,o++,g=e.md.helpers.parseLinkTitle(c,i,s,g)}for(i<s&&f!==i&&g.ok?(m=g.str,i=g.pos):(m="",i=p,o=h);i<s;){if(!Lr(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i)&&m)for(m="",i=p,o=h;i<s;){if(!Lr(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i))return!1;const y=qr(c.slice(1,l));return!!y&&(r||(void 0===e.env.references&&(e.env.references={}),void 0===e.env.references[y]&&(e.env.references[y]={title:m,href:d}),e.line=o),!0)}],["html_block",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;if(!e.md.options.html)return!1;if(60!==e.src.charCodeAt(i))return!1;let o=e.src.slice(i,s),a=0;for(;a<Ai.length&&!Ai[a][0].test(o);a++);if(a===Ai.length)return!1;if(r)return Ai[a][2];let c=t+1;const l=Ai[a][1].test("");if(!Ai[a][1].test(o))for(;c<n&&(!(e.sCount[c]<e.blkIndent)||!l&&e.isEmpty(c));c++)if(i=e.bMarks[c]+e.tShift[c],s=e.eMarks[c],o=e.src.slice(i,s),Ai[a][1].test(o)){0!==o.length&&c++;break}e.line=c;const u=e.push("html_block","",0);return u.map=[t,c],u.content=e.getLines(t,c,e.blkIndent,!0),!0},["paragraph","reference","blockquote"]],["heading",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let o=e.src.charCodeAt(i);if(35!==o||i>=s)return!1;let a=1;for(o=e.src.charCodeAt(++i);35===o&&i<s&&a<=6;)a++,o=e.src.charCodeAt(++i);if(a>6||i<s&&!Lr(o))return!1;if(r)return!0;s=e.skipSpacesBack(s,i);const c=e.skipCharsBack(s,35,i);c>i&&Lr(e.src.charCodeAt(c-1))&&(s=c),e.line=t+1;const l=e.push("heading_open","h"+String(a),1);l.markup="########".slice(0,a),l.map=[t,e.line];const u=e.push("inline","",0);return u.content=Ur(e.src.slice(i,s)),u.map=[t,e.line],u.children=[],e.push("heading_close","h"+String(a),-1).markup="########".slice(0,a),!0},["paragraph","reference","blockquote"]],["lheading",function(e,t,n){const r=e.md.block.ruler.getRules("paragraph");if(e.sCount[t]-e.blkIndent>=4)return!1;const i=e.parentType;e.parentType="paragraph";let s,o=0,a=t+1;for(;a<n&&!e.isEmpty(a);a++){if(e.sCount[a]-e.blkIndent>3)continue;if(e.sCount[a]>=e.blkIndent){let t=e.bMarks[a]+e.tShift[a];const n=e.eMarks[a];if(t<n&&(s=e.src.charCodeAt(t),(45===s||61===s)&&(t=e.skipChars(t,s),t=e.skipSpaces(t),t>=n))){o=61===s?1:2;break}}if(e.sCount[a]<0)continue;let t=!1;for(let i=0,s=r.length;i<s;i++)if(r[i](e,a,n,!0)){t=!0;break}if(t)break}if(!o)return e.parentType=i,!1;const c=Ur(e.getLines(t,a,e.blkIndent,!1));e.line=a+1;const l=e.push("heading_open","h"+String(o),1);l.markup=String.fromCharCode(s),l.map=[t,e.line];const u=e.push("inline","",0);return u.content=c,u.map=[t,e.line-1],u.children=[],e.push("heading_close","h"+String(o),-1).markup=String.fromCharCode(s),e.parentType=i,!0}],["paragraph",function(e,t,n){const r=e.md.block.ruler.getRules("paragraph"),i=e.parentType;let s=t+1;for(e.parentType="paragraph";s<n&&!e.isEmpty(s);s++){if(e.sCount[s]-e.blkIndent>3)continue;if(e.sCount[s]<0)continue;let t=!1;for(let i=0,o=r.length;i<o;i++)if(r[i](e,s,n,!0)){t=!0;break}if(t)break}const o=Ur(e.getLines(t,s,e.blkIndent,!1));e.line=s,e.push("paragraph_open","p",1).map=[t,e.line];const a=e.push("inline","",0);return a.content=o,a.map=[t,e.line],a.children=[],e.push("paragraph_close","p",-1),e.parentType=i,!0}]];function _i(){this.ruler=new Yr;for(let e=0;e<Si.length;e++)this.ruler.push(Si[e][0],Si[e][1],{alt:(Si[e][2]||[]).slice()})}function xi(e,t,n,r){this.src=e,this.env=n,this.md=t,this.tokens=r,this.tokens_meta=Array(r.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}function Ci(e){switch(e){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}_i.prototype.tokenize=function(e,t,n){const r=this.ruler.getRules(""),i=r.length,s=e.md.options.maxNesting;let o=t,a=!1;for(;o<n&&(e.line=o=e.skipEmptyLines(o),!(o>=n))&&!(e.sCount[o]<e.blkIndent);){if(e.level>=s){e.line=n;break}const t=e.line;let c=!1;for(let s=0;s<i;s++)if(c=r[s](e,o,n,!1),c){if(t>=e.line)throw new Error("block rule didn't increment state.line");break}if(!c)throw new Error("none of the block rules matched");e.tight=!a,e.isEmpty(e.line-1)&&(a=!0),o=e.line,o<n&&e.isEmpty(o)&&(a=!0,o++,e.line=o)}},_i.prototype.parse=function(e,t,n,r){if(!e)return;const i=new this.State(e,t,n,r);this.tokenize(i,i.line,i.lineMax)},_i.prototype.State=mi,xi.prototype.pushPending=function(){const e=new Jr("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},xi.prototype.push=function(e,t,n){this.pending&&this.pushPending();const r=new Jr(e,t,n);let i=null;return n<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),r.level=this.level,n>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],i={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(r),this.tokens_meta.push(i),r},xi.prototype.scanDelims=function(e,t){const n=this.posMax,r=this.src.charCodeAt(e);let i;if(0===e)i=32;else if(1===e)i=this.src.charCodeAt(0),55296==(63488&i)&&(i=65533);else if(i=this.src.charCodeAt(e-1),56320==(64512&i)){const t=this.src.charCodeAt(e-2);i=55296==(64512&t)?65536+(t-55296<<10)+(i-56320):65533}else 55296==(64512&i)&&(i=65533);let s=e;for(;s<n&&this.src.charCodeAt(s)===r;)s++;const o=s-e;let a=s<n?this.src.charCodeAt(s):32;if(55296==(64512&a)){const e=this.src.charCodeAt(s+1);a=56320==(64512&e)?65536+(a-55296<<10)+(e-56320):65533}else 56320==(64512&a)&&(a=65533);const c=Br(i)||Fr(i),l=Br(a)||Fr(a),u=$r(i),d=$r(a),p=!d&&(!l||u||c),h=!u&&(!c||d||l);return{can_open:p&&(t||!h||c),can_close:h&&(t||!p||l),length:o}},xi.prototype.Token=Jr;const Ti=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;const Ni=[];for(let e=0;e<256;e++)Ni.push(0);function Mi(e,t){let n;const r=[],i=t.length;for(let s=0;s<i;s++){const i=t[s];if(126!==i.marker)continue;if(-1===i.end)continue;const o=t[i.end];n=e.tokens[i.token],n.type="s_open",n.tag="s",n.nesting=1,n.markup="~~",n.content="",n=e.tokens[o.token],n.type="s_close",n.tag="s",n.nesting=-1,n.markup="~~",n.content="","text"===e.tokens[o.token-1].type&&"~"===e.tokens[o.token-1].content&&r.push(o.token-1)}for(;r.length;){const t=r.pop();let i=t+1;for(;i<e.tokens.length&&"s_close"===e.tokens[i].type;)i++;i--,t!==i&&(n=e.tokens[i],e.tokens[i]=e.tokens[t],e.tokens[t]=n)}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(e){Ni[e.charCodeAt(0)]=1});var Di={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return!1;if(126!==r)return!1;const i=e.scanDelims(e.pos,!0);let s=i.length;const o=String.fromCharCode(r);if(s<2)return!1;let a;s%2&&(a=e.push("text","",0),a.content=o,s--);for(let t=0;t<s;t+=2)a=e.push("text","",0),a.content=o+o,e.delimiters.push({marker:r,length:0,token:e.tokens.length-1,end:-1,open:i.can_open,close:i.can_close});return e.pos+=i.length,!0},postProcess:function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Mi(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Mi(e,t[r].delimiters)}};function Pi(e,t){for(let n=t.length-1;n>=0;n--){const r=t[n];if(95!==r.marker&&42!==r.marker)continue;if(-1===r.end)continue;const i=t[r.end],s=n>0&&t[n-1].end===r.end+1&&t[n-1].marker===r.marker&&t[n-1].token===r.token-1&&t[r.end+1].token===i.token+1,o=String.fromCharCode(r.marker),a=e.tokens[r.token];a.type=s?"strong_open":"em_open",a.tag=s?"strong":"em",a.nesting=1,a.markup=s?o+o:o,a.content="";const c=e.tokens[i.token];c.type=s?"strong_close":"em_close",c.tag=s?"strong":"em",c.nesting=-1,c.markup=s?o+o:o,c.content="",s&&(e.tokens[t[n-1].token].content="",e.tokens[t[r.end+1].token].content="",n--)}}var Oi={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return!1;if(95!==r&&42!==r)return!1;const i=e.scanDelims(e.pos,42===r);for(let t=0;t<i.length;t++){e.push("text","",0).content=String.fromCharCode(r),e.delimiters.push({marker:r,length:i.length,token:e.tokens.length-1,end:-1,open:i.can_open,close:i.can_close})}return e.pos+=i.length,!0},postProcess:function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Pi(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Pi(e,t[r].delimiters)}};const Ri=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,Li=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;const $i=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,ji=/^&([a-z][a-z0-9]{1,31});/i;function Fi(e){const t={},n=e.length;if(!n)return;let r=0,i=-2;const s=[];for(let o=0;o<n;o++){const n=e[o];if(s.push(0),e[r].marker===n.marker&&i===n.token-1||(r=o),i=n.token,n.length=n.length||0,!n.close)continue;t.hasOwnProperty(n.marker)||(t[n.marker]=[-1,-1,-1,-1,-1,-1]);const a=t[n.marker][(n.open?3:0)+n.length%3];let c=r-s[r]-1,l=c;for(;c>a;c-=s[c]+1){const t=e[c];if(t.marker===n.marker&&(t.open&&t.end<0)){let r=!1;if((t.close||n.open)&&(t.length+n.length)%3==0&&(t.length%3==0&&n.length%3==0||(r=!0)),!r){const r=c>0&&!e[c-1].open?s[c-1]+1:0;s[o]=o-c+r,s[c]=r,n.open=!1,t.end=o,t.close=!1,l=-1,i=-2;break}}}-1!==l&&(t[n.marker][(n.open?3:0)+(n.length||0)%3]=l)}}const Bi=[["text",function(e,t){let n=e.pos;for(;n<e.posMax&&!Ci(e.src.charCodeAt(n));)n++;return n!==e.pos&&(t||(e.pending+=e.src.slice(e.pos,n)),e.pos=n,!0)}],["linkify",function(e,t){if(!e.md.options.linkify)return!1;if(e.linkLevel>0)return!1;const n=e.pos;if(n+3>e.posMax)return!1;if(58!==e.src.charCodeAt(n))return!1;if(47!==e.src.charCodeAt(n+1))return!1;if(47!==e.src.charCodeAt(n+2))return!1;const r=e.pending.match(Ti);if(!r)return!1;const i=r[1],s=e.md.linkify.matchAtStart(e.src.slice(n-i.length));if(!s)return!1;let o=s.url;if(o.length<=i.length)return!1;let a=o.length;for(;a>0&&42===o.charCodeAt(a-1);)a--;a!==o.length&&(o=o.slice(0,a));const c=e.md.normalizeLink(o);if(!e.md.validateLink(c))return!1;if(!t){e.pending=e.pending.slice(0,-i.length);const t=e.push("link_open","a",1);t.attrs=[["href",c]],t.markup="linkify",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(o);const n=e.push("link_close","a",-1);n.markup="linkify",n.info="auto"}return e.pos+=o.length-i.length,!0}],["newline",function(e,t){let n=e.pos;if(10!==e.src.charCodeAt(n))return!1;const r=e.pending.length-1,i=e.posMax;if(!t)if(r>=0&&32===e.pending.charCodeAt(r))if(r>=1&&32===e.pending.charCodeAt(r-1)){let t=r-1;for(;t>=1&&32===e.pending.charCodeAt(t-1);)t--;e.pending=e.pending.slice(0,t),e.push("hardbreak","br",0)}else e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0);else e.push("softbreak","br",0);for(n++;n<i&&Lr(e.src.charCodeAt(n));)n++;return e.pos=n,!0}],["escape",function(e,t){let n=e.pos;const r=e.posMax;if(92!==e.src.charCodeAt(n))return!1;if(n++,n>=r)return!1;let i=e.src.charCodeAt(n);if(10===i){for(t||e.push("hardbreak","br",0),n++;n<r&&(i=e.src.charCodeAt(n),Lr(i));)n++;return e.pos=n,!0}if(32===i){if(!t){const t=e.push("text_special","",0);t.content="\\",t.markup="\\",t.info="escape"}return e.pos=n,!0}let s=e.src[n];if(i>=55296&&i<=56319&&n+1<r){const t=e.src.charCodeAt(n+1);t>=56320&&t<=57343&&(s+=e.src[n+1],n++)}const o="\\"+s;if(!t){const t=e.push("text_special","",0);i<256&&0!==Ni[i]?t.content=s:t.content=o,t.markup=o,t.info="escape"}return e.pos=n+1,!0}],["backticks",function(e,t){let n=e.pos;if(96!==e.src.charCodeAt(n))return!1;const r=n;n++;const i=e.posMax;for(;n<i&&96===e.src.charCodeAt(n);)n++;const s=e.src.slice(r,n),o=s.length;if(e.backticksScanned&&(e.backticks[o]||0)<=r)return t||(e.pending+=s),e.pos+=o,!0;let a,c=n;for(;-1!==(a=e.src.indexOf("`",c));){for(c=a+1;c<i&&96===e.src.charCodeAt(c);)c++;const r=c-a;if(r===o){if(!t){const t=e.push("code_inline","code",0);t.markup=s,t.content=e.src.slice(n,a).replace(/\n/g," ").replace(/^ (.+) $/,"$1")}return e.pos=c,!0}e.backticks[r]=a}return e.backticksScanned=!0,t||(e.pending+=s),e.pos+=o,!0}],["strikethrough",Di.tokenize],["emphasis",Oi.tokenize],["link",function(e,t){let n,r,i,s,o="",a="",c=e.pos,l=!0;if(91!==e.src.charCodeAt(e.pos))return!1;const u=e.pos,d=e.posMax,p=e.pos+1,h=e.md.helpers.parseLinkLabel(e,e.pos,!0);if(h<0)return!1;let f=h+1;if(f<d&&40===e.src.charCodeAt(f)){for(l=!1,f++;f<d&&(n=e.src.charCodeAt(f),Lr(n)||10===n);f++);if(f>=d)return!1;if(c=f,i=e.md.helpers.parseLinkDestination(e.src,f,e.posMax),i.ok){for(o=e.md.normalizeLink(i.str),e.md.validateLink(o)?f=i.pos:o="",c=f;f<d&&(n=e.src.charCodeAt(f),Lr(n)||10===n);f++);if(i=e.md.helpers.parseLinkTitle(e.src,f,e.posMax),f<d&&c!==f&&i.ok)for(a=i.str,f=i.pos;f<d&&(n=e.src.charCodeAt(f),Lr(n)||10===n);f++);}(f>=d||41!==e.src.charCodeAt(f))&&(l=!0),f++}if(l){if(void 0===e.env.references)return!1;if(f<d&&91===e.src.charCodeAt(f)?(c=f+1,f=e.md.helpers.parseLinkLabel(e,f),f>=0?r=e.src.slice(c,f++):f=h+1):f=h+1,r||(r=e.src.slice(p,h)),s=e.env.references[qr(r)],!s)return e.pos=u,!1;o=s.href,a=s.title}if(!t){e.pos=p,e.posMax=h;const t=[["href",o]];e.push("link_open","a",1).attrs=t,a&&t.push(["title",a]),e.linkLevel++,e.md.inline.tokenize(e),e.linkLevel--,e.push("link_close","a",-1)}return e.pos=f,e.posMax=d,!0}],["image",function(e,t){let n,r,i,s,o,a,c,l,u="";const d=e.pos,p=e.posMax;if(33!==e.src.charCodeAt(e.pos))return!1;if(91!==e.src.charCodeAt(e.pos+1))return!1;const h=e.pos+2,f=e.md.helpers.parseLinkLabel(e,e.pos+1,!1);if(f<0)return!1;if(s=f+1,s<p&&40===e.src.charCodeAt(s)){for(s++;s<p&&(n=e.src.charCodeAt(s),Lr(n)||10===n);s++);if(s>=p)return!1;for(l=s,a=e.md.helpers.parseLinkDestination(e.src,s,e.posMax),a.ok&&(u=e.md.normalizeLink(a.str),e.md.validateLink(u)?s=a.pos:u=""),l=s;s<p&&(n=e.src.charCodeAt(s),Lr(n)||10===n);s++);if(a=e.md.helpers.parseLinkTitle(e.src,s,e.posMax),s<p&&l!==s&&a.ok)for(c=a.str,s=a.pos;s<p&&(n=e.src.charCodeAt(s),Lr(n)||10===n);s++);else c="";if(s>=p||41!==e.src.charCodeAt(s))return e.pos=d,!1;s++}else{if(void 0===e.env.references)return!1;if(s<p&&91===e.src.charCodeAt(s)?(l=s+1,s=e.md.helpers.parseLinkLabel(e,s),s>=0?i=e.src.slice(l,s++):s=f+1):s=f+1,i||(i=e.src.slice(h,f)),o=e.env.references[qr(i)],!o)return e.pos=d,!1;u=o.href,c=o.title}if(!t){r=e.src.slice(h,f);const t=[];e.md.inline.parse(r,e.md,e.env,t);const n=e.push("image","img",0),i=[["src",u],["alt",""]];n.attrs=i,n.children=t,n.content=r,c&&i.push(["title",c])}return e.pos=s,e.posMax=p,!0}],["autolink",function(e,t){let n=e.pos;if(60!==e.src.charCodeAt(n))return!1;const r=e.pos,i=e.posMax;for(;;){if(++n>=i)return!1;const t=e.src.charCodeAt(n);if(60===t)return!1;if(62===t)break}const s=e.src.slice(r+1,n);if(Li.test(s)){const n=e.md.normalizeLink(s);if(!e.md.validateLink(n))return!1;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(s);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto"}return e.pos+=s.length+2,!0}if(Ri.test(s)){const n=e.md.normalizeLink("mailto:"+s);if(!e.md.validateLink(n))return!1;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(s);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto"}return e.pos+=s.length+2,!0}return!1}],["html_inline",function(e,t){if(!e.md.options.html)return!1;const n=e.posMax,r=e.pos;if(60!==e.src.charCodeAt(r)||r+2>=n)return!1;const i=e.src.charCodeAt(r+1);if(33!==i&&63!==i&&47!==i&&!function(e){const t=32|e;return t>=97&&t<=122}(i))return!1;const s=e.src.slice(r).match(Ii);if(!s)return!1;if(!t){const t=e.push("html_inline","",0);t.content=s[0],o=t.content,/^<a[>\s]/i.test(o)&&e.linkLevel++,function(e){return/^<\/a\s*>/i.test(e)}(t.content)&&e.linkLevel--}var o;return e.pos+=s[0].length,!0}],["entity",function(e,t){const n=e.pos,r=e.posMax;if(38!==e.src.charCodeAt(n))return!1;if(n+1>=r)return!1;if(35===e.src.charCodeAt(n+1)){const r=e.src.slice(n).match($i);if(r){if(!t){const t="x"===r[1][0].toLowerCase()?parseInt(r[1].slice(1),16):parseInt(r[1],10),n=e.push("text_special","",0);n.content=Er(t)?Ar(t):Ar(65533),n.markup=r[0],n.info="entity"}return e.pos+=r[0].length,!0}}else{const r=e.src.slice(n).match(ji);if(r){const n=(i=r[0],br(i,dr.Strict));if(n!==r[0]){if(!t){const t=e.push("text_special","",0);t.content=n,t.markup=r[0],t.info="entity"}return e.pos+=r[0].length,!0}}}var i;return!1}]],qi=[["balance_pairs",function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Fi(e.delimiters);for(let e=0;e<n;e++)t[e]&&t[e].delimiters&&Fi(t[e].delimiters)}],["strikethrough",Di.postProcess],["emphasis",Oi.postProcess],["fragments_join",function(e){let t,n,r=0;const i=e.tokens,s=e.tokens.length;for(t=n=0;t<s;t++)i[t].nesting<0&&r--,i[t].level=r,i[t].nesting>0&&r++,"text"===i[t].type&&t+1<s&&"text"===i[t+1].type?i[t+1].content=i[t].content+i[t+1].content:(t!==n&&(i[n]=i[t]),n++);t!==n&&(i.length=n)}]];function zi(){this.ruler=new Yr;for(let e=0;e<Bi.length;e++)this.ruler.push(Bi[e][0],Bi[e][1]);this.ruler2=new Yr;for(let e=0;e<qi.length;e++)this.ruler2.push(qi[e][0],qi[e][1])}function Ui(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(n){e[n]=t[n]})}),e}function Vi(e){return Object.prototype.toString.call(e)}function Wi(e){return"[object Function]"===Vi(e)}function Ki(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}zi.prototype.skipToken=function(e){const t=e.pos,n=this.ruler.getRules(""),r=n.length,i=e.md.options.maxNesting,s=e.cache;if(void 0!==s[t])return void(e.pos=s[t]);let o=!1;if(e.level<i){for(let i=0;i<r;i++)if(e.level++,o=n[i](e,!0),e.level--,o){if(t>=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;o||e.pos++,s[t]=e.pos},zi.prototype.tokenize=function(e){const t=this.ruler.getRules(""),n=t.length,r=e.posMax,i=e.md.options.maxNesting;for(;e.pos<r;){const s=e.pos;let o=!1;if(e.level<i)for(let r=0;r<n;r++)if(o=t[r](e,!1),o){if(s>=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(o){if(e.pos>=r)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},zi.prototype.parse=function(e,t,n,r){const i=new this.State(e,t,n,r);this.tokenize(i);const s=this.ruler2.getRules(""),o=s.length;for(let e=0;e<o;e++)s[e](i)},zi.prototype.State=xi;const Gi={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};const Hi={"http:":{validate:function(e,t,n){const r=e.slice(t);return n.re.http||(n.re.http=new RegExp(`^\\/\\/${n.re.src_auth}${n.re.src_host_port_strict}${n.re.src_path}`,"i")),n.re.http.test(r)?r.match(n.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(e,t,n){const r=e.slice(t);return n.re.no_http||(n.re.no_http=new RegExp("^"+n.re.src_auth+`(?:localhost|(?:(?:${n.re.src_domain})\\.)+${n.re.src_domain_root})`+n.re.src_port+n.re.src_host_terminator+n.re.src_path,"i")),n.re.no_http.test(r)?t>=3&&":"===e[t-3]||t>=3&&"/"===e[t-3]?0:r.match(n.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,n){const r=e.slice(t);return n.re.mailto||(n.re.mailto=new RegExp(`^${n.re.src_email_name}@${n.re.src_host_strict}`,"i")),n.re.mailto.test(r)?r.match(n.re.mailto)[0].length:0}}},Yi="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function Ji(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=Qn.source,t.src_Cc=Xn.source,t.src_Z=nr.source,t.src_P=er.source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|");const n="[><|]";return t.src_pseudo_letter=`(?:(?!${n}|${t.src_ZPCc})${t.src_Any})`,t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth=`(?:(?:(?!${t.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`,t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator=`(?=$|${n}|${t.src_ZPCc})(?!${e["---"]?"-(?!--)|":"-|"}_|:\\d|\\.-|\\.(?!$|${t.src_ZPCc}))`,t.src_path=`(?:[/?#](?:(?!${t.src_ZCc}|${n}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${t.src_ZCc}|\\]).)*\\]|\\((?:(?!${t.src_ZCc}|[)]).)*\\)|\\{(?:(?!${t.src_ZCc}|[}]).)*\\}|\\"(?:(?!${t.src_ZCc}|["]).)+\\"|\\'(?:(?!${t.src_ZCc}|[']).)+\\'|\\'(?=${t.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${t.src_ZCc}|[.]|$)|`+(e["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+`,(?!${t.src_ZCc}|$)|`+`;(?!${t.src_ZCc}|$)|`+`\\!+(?!${t.src_ZCc}|[!]|$)|`+`\\?(?!${t.src_ZCc}|[?]|$))+|\\/)?`,t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+`${t.src_pseudo_letter}{1,63})`,t.src_domain="(?:"+t.src_xn+"|"+`(?:${t.src_pseudo_letter})|`+`(?:${t.src_pseudo_letter}(?:-|${t.src_pseudo_letter}){0,61}${t.src_pseudo_letter}))`,t.src_host=`(?:(?:(?:(?:${t.src_domain})\\.)*${t.src_domain}))`,t.tpl_host_fuzzy="(?:"+t.src_ip4+"|"+`(?:(?:(?:${t.src_domain})\\.)+(?:%TLDS%)))`,t.tpl_host_no_ip_fuzzy=`(?:(?:(?:${t.src_domain})\\.)+(?:%TLDS%))`,t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test=`localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${t.src_ZPCc}|>|$))`,t.tpl_email_fuzzy=`(^|${n}|"|\\(|${t.src_ZCc})(${t.src_email_name}@${t.tpl_host_fuzzy_strict})`,t.tpl_link_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${t.src_ZPCc}))((?![$+<=>^\`||])${t.tpl_host_port_fuzzy_strict}${t.src_path})`,t.tpl_link_no_ip_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${t.src_ZPCc}))((?![$+<=>^\`||])${t.tpl_host_port_no_ip_fuzzy_strict}${t.src_path})`,t}(e.__opts__),n=e.__tlds__.slice();function r(e){return e.replace("%TLDS%",t.src_tlds)}e.onCompile(),e.__tlds_replaced__||n.push("a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"),n.push(t.src_xn),t.src_tlds=n.join("|"),t.email_fuzzy=RegExp(r(t.tpl_email_fuzzy),"i"),t.email_fuzzy_global=RegExp(r(t.tpl_email_fuzzy),"ig"),t.link_fuzzy=RegExp(r(t.tpl_link_fuzzy),"i"),t.link_fuzzy_global=RegExp(r(t.tpl_link_fuzzy),"ig"),t.link_no_ip_fuzzy=RegExp(r(t.tpl_link_no_ip_fuzzy),"i"),t.link_no_ip_fuzzy_global=RegExp(r(t.tpl_link_no_ip_fuzzy),"ig"),t.host_fuzzy_test=RegExp(r(t.tpl_host_fuzzy_test),"i");const i=[];function s(e,t){throw new Error(`(LinkifyIt) Invalid schema "${e}": ${t}`)}e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){const n=e.__schemas__[t];if(null===n)return;const r={validate:null,link:null};if(e.__compiled__[t]=r,"[object Object]"===Vi(n))return!function(e){return"[object RegExp]"===Vi(e)}(n.validate)?Wi(n.validate)?r.validate=n.validate:s(t,n):r.validate=function(e){return function(t,n){const r=t.slice(n);return e.test(r)?r.match(e)[0].length:0}}(n.validate),void(Wi(n.normalize)?r.normalize=n.normalize:n.normalize?s(t,n):r.normalize=function(e,t){t.normalize(e)});!function(e){return"[object String]"===Vi(e)}(n)?s(t,n):i.push(t)}),i.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize)}),e.__compiled__[""]={validate:null,normalize:function(e,t){t.normalize(e)}};const o=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(Ki).join("|");e.re.schema_test=RegExp(`(^|(?!_)(?:[><|]|${t.src_ZPCc}))(${o})`,"i"),e.re.schema_search=RegExp(`(^|(?!_)(?:[><|]|${t.src_ZPCc}))(${o})`,"ig"),e.re.schema_at_start=RegExp(`^${e.re.schema_search.source}`,"i"),e.re.pretest=RegExp(`(${e.re.schema_test.source})|(${e.re.host_fuzzy_test.source})|@`,"i")}function Zi(e,t,n,r){const i=e.slice(n,r);this.schema=t.toLowerCase(),this.index=n,this.lastIndex=r,this.raw=i,this.text=i,this.url=i}function Qi(e,t){if(!(this instanceof Qi))return new Qi(e,t);var n;t||(n=e,Object.keys(n||{}).reduce(function(e,t){return e||Gi.hasOwnProperty(t)},!1)&&(t=e,e={})),this.__opts__=Ui({},Gi,t),this.__schemas__=Ui({},Hi,e),this.__compiled__={},this.__tlds__=Yi,this.__tlds_replaced__=!1,this.re={},Ji(this)}Qi.prototype.add=function(e,t){return this.__schemas__[e]=t,Ji(this),this},Qi.prototype.set=function(e){return this.__opts__=Ui(this.__opts__,e),this},Qi.prototype.test=function(e){if(!e.length)return!1;let t,n;if(this.re.schema_test.test(e))for(n=this.re.schema_search,n.lastIndex=0;null!==(t=n.exec(e));)if(this.testSchemaAt(e,t[2],n.lastIndex))return!0;return!!(this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&e.search(this.re.host_fuzzy_test)>=0&&null!==e.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy))||!!(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&e.indexOf("@")>=0&&null!==e.match(this.re.email_fuzzy))},Qi.prototype.pretest=function(e){return this.re.pretest.test(e)},Qi.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},Qi.prototype.match=function(e){const t=[],n=[],r=[],i=[];let s,o,a;function c(e,t){return e?t?e.index!==t.index?e.index<t.index?e:t:e.lastIndex>=t.lastIndex?e:t:e:t}if(!e.length)return null;if(this.re.schema_test.test(e))for(a=this.re.schema_search,a.lastIndex=0;null!==(s=a.exec(e));)o=this.testSchemaAt(e,s[2],a.lastIndex),o&&n.push({schema:s[2],index:s.index+s[1].length,lastIndex:s.index+s[0].length+o});if(this.__opts__.fuzzyLink&&this.__compiled__["http:"])for(a=this.__opts__.fuzzyIP?this.re.link_fuzzy_global:this.re.link_no_ip_fuzzy_global,a.lastIndex=0;null!==(s=a.exec(e));)r.push({schema:"",index:s.index+s[1].length,lastIndex:s.index+s[0].length});if(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"])for(a=this.re.email_fuzzy_global,a.lastIndex=0;null!==(s=a.exec(e));)i.push({schema:"mailto:",index:s.index+s[1].length,lastIndex:s.index+s[0].length});const l=[0,0,0];let u=0;for(;;){const s=[n[l[0]],i[l[1]],r[l[2]]],o=c(c(s[0],s[1]),s[2]);if(!o)break;if(o===s[0]?l[0]++:o===s[1]?l[1]++:l[2]++,o.index<u)continue;const a=new Zi(e,o.schema,o.index,o.lastIndex);this.__compiled__[a.schema].normalize(a,this),t.push(a),u=o.lastIndex}return t.length?t:null},Qi.prototype.matchAtStart=function(e){if(!e.length)return null;const t=this.re.schema_at_start.exec(e);if(!t)return null;const n=this.testSchemaAt(e,t[2],t[0].length);if(!n)return null;const r=new Zi(e,t[2],t.index+t[1].length,t.index+t[0].length+n);return this.__compiled__[r.schema].normalize(r,this),r},Qi.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,n){return e!==n[t-1]}).reverse(),Ji(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,Ji(this),this)},Qi.prototype.normalize=function(e){e.schema||(e.url=`http://${e.url}`),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url=`mailto:${e.url}`)},Qi.prototype.onCompile=function(){};const Xi=2147483647,es=36,ts=/^xn--/,ns=/[^\0-\x7F]/,rs=/[\x2E\u3002\uFF0E\uFF61]/g,is={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},ss=Math.floor,os=String.fromCharCode;function as(e){throw new RangeError(is[e])}function cs(e,t){const n=e.split("@");let r="";n.length>1&&(r=n[0]+"@",e=n[1]);const i=function(e,t){const n=[];let r=e.length;for(;r--;)n[r]=t(e[r]);return n}((e=e.replace(rs,".")).split("."),t).join(".");return r+i}function ls(e){const t=[];let n=0;const r=e.length;for(;n<r;){const i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<r){const r=e.charCodeAt(n++);56320==(64512&r)?t.push(((1023&i)<<10)+(1023&r)+65536):(t.push(i),n--)}else t.push(i)}return t}const us=function(e){return e>=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:es},ds=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},ps=function(e,t,n){let r=0;for(e=n?ss(e/700):e>>1,e+=ss(e/t);e>455;r+=es)e=ss(e/35);return ss(r+36*e/(e+38))},hs=function(e){const t=[],n=e.length;let r=0,i=128,s=72,o=e.lastIndexOf("-");o<0&&(o=0);for(let n=0;n<o;++n)e.charCodeAt(n)>=128&&as("not-basic"),t.push(e.charCodeAt(n));for(let a=o>0?o+1:0;a<n;){const o=r;for(let t=1,i=es;;i+=es){a>=n&&as("invalid-input");const o=us(e.charCodeAt(a++));o>=es&&as("invalid-input"),o>ss((Xi-r)/t)&&as("overflow"),r+=o*t;const c=i<=s?1:i>=s+26?26:i-s;if(o<c)break;const l=es-c;t>ss(Xi/l)&&as("overflow"),t*=l}const c=t.length+1;s=ps(r-o,c,0==o),ss(r/c)>Xi-i&&as("overflow"),i+=ss(r/c),r%=c,t.splice(r++,0,i)}return String.fromCodePoint(...t)},fs=function(e){const t=[],n=(e=ls(e)).length;let r=128,i=0,s=72;for(const n of e)n<128&&t.push(os(n));const o=t.length;let a=o;for(o&&t.push("-");a<n;){let n=Xi;for(const t of e)t>=r&&t<n&&(n=t);const c=a+1;n-r>ss((Xi-i)/c)&&as("overflow"),i+=(n-r)*c,r=n;for(const n of e)if(n<r&&++i>Xi&&as("overflow"),n===r){let e=i;for(let n=es;;n+=es){const r=n<=s?1:n>=s+26?26:n-s;if(e<r)break;const i=e-r,o=es-r;t.push(os(ds(r+i%o,0))),e=ss(i/o)}t.push(os(ds(e,0))),s=ps(i,c,a===o),i=0,++a}++i,++r}return t.join("")},ms=function(e){return cs(e,function(e){return ns.test(e)?"xn--"+fs(e):e})},gs=function(e){return cs(e,function(e){return ts.test(e)?hs(e.slice(4).toLowerCase()):e})};const ys={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}},zero:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","fragments_join"]}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","fragments_join"]}}}},bs=/^(vbscript|javascript|file|data):/,ws=/^data:image\/(gif|png|jpeg|webp);/;function vs(e){const t=e.trim().toLowerCase();return!bs.test(t)||ws.test(t)}const ks=["http:","https:","mailto:"];function Is(e){const t=Yn(e,!0);if(t.hostname&&(!t.protocol||ks.indexOf(t.protocol)>=0))try{t.hostname=ms(t.hostname)}catch(e){}return Rn(Ln(t))}function Es(e){const t=Yn(e,!0);if(t.hostname&&(!t.protocol||ks.indexOf(t.protocol)>=0))try{t.hostname=gs(t.hostname)}catch(e){}return Pn(Ln(t),Pn.defaultChars+"%")}function As(e,t){if(!(this instanceof As))return new As(e,t);t||wr(e)||(t=e||{},e="default"),this.inline=new zi,this.block=new _i,this.core=new fi,this.renderer=new Hr,this.linkify=new Qi,this.validateLink=vs,this.normalizeLink=Is,this.normalizeLinkText=Es,this.utils=Wr,this.helpers=kr({},Kr),this.options={},this.configure(e),t&&this.set(t)}function Ss(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _s,xs;function Cs(){if(xs)return _s;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],i=typeof r;"object"!==i&&"function"!==i||Object.isFrozen(r)||e(r)}),t}xs=1;class t{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...t){const n=Object.create(null);for(const t in e)n[t]=e[t];return t.forEach(function(e){for(const t in e)n[t]=e[t]}),n}const i=e=>!!e.scope;class s{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=n(e)}openNode(e){if(!i(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){i(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const o=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class a{constructor(){this.rootNode=o(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=o({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{a._collapse(e)}))}}class c extends a{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new s(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function l(e){return e?"string"==typeof e?e:e.source:null}function u(e){return h("(?=",e,")")}function d(e){return h("(?:",e,")*")}function p(e){return h("(?:",e,")?")}function h(...e){return e.map(e=>l(e)).join("")}function f(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>l(e)).join("|")+")"}function m(e){return new RegExp(e.toString()+"|").exec("").length-1}const g=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function y(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=l(e),i="";for(;r.length>0;){const e=g.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+String(Number(e[1])+t):(i+=e[0],"("===e[0]&&n++)}return i}).map(e=>`(${e})`).join(t)}const b="[a-zA-Z]\\w*",w="[a-zA-Z_]\\w*",v="\\b\\d+(\\.\\d+)?",k="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",I="\\b(0b[01]+)",E={begin:"\\\\[\\s\\S]",relevance:0},A={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[E]},S={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[E]},_=function(e,t,n={}){const i=r({scope:"comment",begin:e,end:t,contains:[]},n);i.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const s=f("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return i.contains.push({begin:h(/[ ]+/,"(",s,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i},x=_("//","$"),C=_("/\\*","\\*/"),T=_("#","$"),N={scope:"number",begin:v,relevance:0},M={scope:"number",begin:k,relevance:0},D={scope:"number",begin:I,relevance:0},P={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[E,{begin:/\[/,end:/\]/,relevance:0,contains:[E]}]},O={scope:"title",begin:b,relevance:0},R={scope:"title",begin:w,relevance:0},L={begin:"\\.\\s*"+w,relevance:0};var $=Object.freeze({__proto__:null,APOS_STRING_MODE:A,BACKSLASH_ESCAPE:E,BINARY_NUMBER_MODE:D,BINARY_NUMBER_RE:I,COMMENT:_,C_BLOCK_COMMENT_MODE:C,C_LINE_COMMENT_MODE:x,C_NUMBER_MODE:M,C_NUMBER_RE:k,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:T,IDENT_RE:b,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:L,NUMBER_MODE:N,NUMBER_RE:v,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:S,REGEXP_MODE:P,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=h(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:O,UNDERSCORE_IDENT_RE:w,UNDERSCORE_TITLE_MODE:R});function j(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function F(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function B(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=j,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function q(e,t){Array.isArray(e.illegal)&&(e.illegal=f(...e.illegal))}function z(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function U(e,t){void 0===e.relevance&&(e.relevance=1)}const V=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=h(n.beforeMatch,u(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},W=["of","and","for","in","not","or","if","then","parent","list","value"];function K(e,t,n="keyword"){const r=Object.create(null);return"string"==typeof e?i(n,e.split(" ")):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,K(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,G(n[0],n[1])]})}}function G(e,t){return t?Number(t):function(e){return W.includes(e.toLowerCase())}(e)?0:1}const H={},Y=e=>{console.error(e)},J=(e,...t)=>{console.log(`WARN: ${e}`,...t)},Z=(e,t)=>{H[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),H[`${e}/${t}`]=!0)},Q=new Error;function X(e,t,{key:n}){let r=0;const i=e[n],s={},o={};for(let e=1;e<=t.length;e++)o[e+r]=i[e],s[e+r]=!0,r+=m(t[e-1]);e[n]=o,e[n]._emit=s,e[n]._multi=!0}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw Y("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),Q;if("object"!=typeof e.beginScope||null===e.beginScope)throw Y("beginScope must be object"),Q;X(e,e.begin,{key:"beginScope"}),e.begin=y(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw Y("skip, excludeEnd, returnEnd not compatible with endScope: {}"),Q;if("object"!=typeof e.endScope||null===e.endScope)throw Y("endScope must be object"),Q;X(e,e.end,{key:"endScope"}),e.end=y(e.end,{joinWith:""})}}(e)}function te(e){function t(t,n){return new RegExp(l(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=m(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(y(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class i{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(s,o){const a=s;if(s.isCompiled)return a;[F,z,ee,V].forEach(e=>e(s,o)),e.compilerExtensions.forEach(e=>e(s,o)),s.__beforeBegin=null,[B,q,U].forEach(e=>e(s,o)),s.isCompiled=!0;let c=null;return"object"==typeof s.keywords&&s.keywords.$pattern&&(s.keywords=Object.assign({},s.keywords),c=s.keywords.$pattern,delete s.keywords.$pattern),c=c||/\w+/,s.keywords&&(s.keywords=K(s.keywords,e.case_insensitive)),a.keywordPatternRe=t(c,!0),o&&(s.begin||(s.begin=/\B|\b/),a.beginRe=t(a.begin),s.end||s.endsWithParent||(s.end=/\B|\b/),s.end&&(a.endRe=t(a.end)),a.terminatorEnd=l(a.end)||"",s.endsWithParent&&o.terminatorEnd&&(a.terminatorEnd+=(s.end?"|":"")+o.terminatorEnd)),s.illegal&&(a.illegalRe=t(s.illegal)),s.contains||(s.contains=[]),s.contains=[].concat(...s.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?s:e)})),s.contains.forEach(function(e){n(e,a)}),s.starts&&n(s.starts,o),a.matcher=function(e){const t=new i;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(a),a}(e)}function ne(e){return!!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const ie=n,se=r,oe=Symbol("nomatch"),ae=function(n){const r=Object.create(null),i=Object.create(null),s=[];let o=!0;const a="Could not find the language '{}', did you forget to load/include a language module?",l={disableAutodetect:!0,name:"Plain text",contains:[]};let m={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:c};function g(e){return m.noHighlightRe.test(e)}function y(e,t,n){let r="",i="";"object"==typeof t?(r=e,n=t.ignoreIllegals,i=t.language):(Z("10.7.0","highlight(lang, code, ...args) has been deprecated."),Z("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),i=e,r=t),void 0===n&&(n=!0);const s={code:r,language:i};_("before:highlight",s);const o=s.result?s.result:b(s.language,s.code,n);return o.code=s.code,_("after:highlight",o),o}function b(e,n,i,s){const c=Object.create(null);function l(e,t){return e.keywords[t]}function u(){if(!x.keywords)return void T.addText(N);let e=0;x.keywordPatternRe.lastIndex=0;let t=x.keywordPatternRe.exec(N),n="";for(;t;){n+=N.substring(e,t.index);const r=A.case_insensitive?t[0].toLowerCase():t[0],i=l(x,r);if(i){const[e,s]=i;if(T.addText(n),n="",c[r]=(c[r]||0)+1,c[r]<=7&&(M+=s),e.startsWith("_"))n+=t[0];else{const n=A.classNameAliases[e]||e;p(t[0],n)}}else n+=t[0];e=x.keywordPatternRe.lastIndex,t=x.keywordPatternRe.exec(N)}n+=N.substring(e),T.addText(n)}function d(){null!=x.subLanguage?function(){if(""===N)return;let e=null;if("string"==typeof x.subLanguage){if(!r[x.subLanguage])return void T.addText(N);e=b(x.subLanguage,N,!0,C[x.subLanguage]),C[x.subLanguage]=e._top}else e=w(N,x.subLanguage.length?x.subLanguage:null);x.relevance>0&&(M+=e.relevance),T.__addSublanguage(e._emitter,e.language)}():u(),N=""}function p(e,t){""!==e&&(T.startScope(t),T.addText(e),T.endScope())}function h(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=A.classNameAliases[e[n]]||e[n],i=t[n];r?p(i,r):(N=i,u(),N=""),n++}}function f(e,t){return e.scope&&"string"==typeof e.scope&&T.openNode(A.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(p(N,A.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),N=""):e.beginScope._multi&&(h(e.beginScope,t),N="")),x=Object.create(e,{parent:{value:x}}),x}function g(e,n,r){let i=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(i){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return g(e.parent,n,r)}function y(e){return 0===x.matcher.regexIndex?(N+=e[0],1):(O=!0,0)}function v(e){const t=e[0],r=n.substring(e.index),i=g(x,e,r);if(!i)return oe;const s=x;x.endScope&&x.endScope._wrap?(d(),p(t,x.endScope._wrap)):x.endScope&&x.endScope._multi?(d(),h(x.endScope,e)):s.skip?N+=t:(s.returnEnd||s.excludeEnd||(N+=t),d(),s.excludeEnd&&(N=t));do{x.scope&&T.closeNode(),x.skip||x.subLanguage||(M+=x.relevance),x=x.parent}while(x!==i.parent);return i.starts&&f(i.starts,e),s.returnEnd?0:t.length}let k={};function I(r,s){const a=s&&s[0];if(N+=r,null==a)return d(),0;if("begin"===k.type&&"end"===s.type&&k.index===s.index&&""===a){if(N+=n.slice(s.index,s.index+1),!o){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=k.rule,t}return 1}if(k=s,"begin"===s.type)return function(e){const n=e[0],r=e.rule,i=new t(r),s=[r.__beforeBegin,r["on:begin"]];for(const t of s)if(t&&(t(e,i),i.isMatchIgnored))return y(n);return r.skip?N+=n:(r.excludeBegin&&(N+=n),d(),r.returnBegin||r.excludeBegin||(N=n)),f(r,e),r.returnBegin?0:n.length}(s);if("illegal"===s.type&&!i){const e=new Error('Illegal lexeme "'+a+'" for mode "'+(x.scope||"<unnamed>")+'"');throw e.mode=x,e}if("end"===s.type){const e=v(s);if(e!==oe)return e}if("illegal"===s.type&&""===a)return N+="\n",1;if(P>1e5&&P>3*s.index){throw new Error("potential infinite loop, way more iterations than matches")}return N+=a,a.length}const A=E(e);if(!A)throw Y(a.replace("{}",e)),new Error('Unknown language: "'+e+'"');const S=te(A);let _="",x=s||S;const C={},T=new m.__emitter(m);!function(){const e=[];for(let t=x;t!==A;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>T.openNode(e))}();let N="",M=0,D=0,P=0,O=!1;try{if(A.__emitTokens)A.__emitTokens(n,T);else{for(x.matcher.considerAll();;){P++,O?O=!1:x.matcher.considerAll(),x.matcher.lastIndex=D;const e=x.matcher.exec(n);if(!e)break;const t=I(n.substring(D,e.index),e);D=e.index+t}I(n.substring(D))}return T.finalize(),_=T.toHTML(),{language:e,value:_,relevance:M,illegal:!1,_emitter:T,_top:x}}catch(t){if(t.message&&t.message.includes("Illegal"))return{language:e,value:ie(n),illegal:!0,relevance:0,_illegalBy:{message:t.message,index:D,context:n.slice(D-100,D+100),mode:t.mode,resultSoFar:_},_emitter:T};if(o)return{language:e,value:ie(n),illegal:!1,relevance:0,errorRaised:t,_emitter:T,_top:x};throw t}}function w(e,t){t=t||m.languages||Object.keys(r);const n=function(e){const t={value:ie(e),illegal:!1,relevance:0,_top:l,_emitter:new m.__emitter(m)};return t._emitter.addText(e),t}(e),i=t.filter(E).filter(S).map(t=>b(t,e,!1));i.unshift(n);const s=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(E(e.language).supersetOf===t.language)return 1;if(E(t.language).supersetOf===e.language)return-1}return 0}),[o,a]=s,c=o;return c.secondBest=a,c}function v(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=m.languageDetectRe.exec(t);if(n){const t=E(n[1]);return t||(J(a.replace("{}",n[1])),J("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>g(e)||E(e))}(e);if(g(n))return;if(_("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(m.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),m.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,s=n?y(r,{language:n,ignoreIllegals:!0}):w(r);e.innerHTML=s.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&i[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`)}(e,n,s.language),e.result={language:s.language,re:s.relevance,relevance:s.relevance},s.secondBest&&(e.secondBest={language:s.secondBest.language,relevance:s.secondBest.relevance}),_("after:highlightElement",{el:e,result:s,text:r})}let k=!1;function I(){if("loading"===document.readyState)return k||window.addEventListener("DOMContentLoaded",function(){I()},!1),void(k=!0);document.querySelectorAll(m.cssSelector).forEach(v)}function E(e){return e=(e||"").toLowerCase(),r[e]||r[i[e]]}function A(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function S(e){const t=E(e);return t&&!t.disableAutodetect}function _(e,t){const n=e;s.forEach(function(e){e[n]&&e[n](t)})}Object.assign(n,{highlight:y,highlightAuto:w,highlightAll:I,highlightElement:v,highlightBlock:function(e){return Z("10.7.0","highlightBlock will be removed entirely in v12.0"),Z("10.7.0","Please use highlightElement now."),v(e)},configure:function(e){m=se(m,e)},initHighlighting:()=>{I(),Z("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){I(),Z("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(e,t){let i=null;try{i=t(n)}catch(t){if(Y("Language definition for '{}' could not be registered.".replace("{}",e)),!o)throw t;Y(t),i=l}i.name||(i.name=e),r[e]=i,i.rawDefinition=t.bind(null,n),i.aliases&&A(i.aliases,{languageName:e})},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(i))i[t]===e&&delete i[t]},listLanguages:function(){return Object.keys(r)},getLanguage:E,registerAliases:A,autoDetection:S,inherit:se,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),s.push(e)},removePlugin:function(e){const t=s.indexOf(e);-1!==t&&s.splice(t,1)}}),n.debugMode=function(){o=!1},n.safeMode=function(){o=!0},n.versionString="11.11.1",n.regex={concat:h,lookahead:u,either:f,optional:p,anyNumberOfTimes:d};for(const t in $)"object"==typeof $[t]&&e($[t]);return Object.assign(n,$),n},ce=ae({});return ce.newInstance=()=>ae({}),_s=ce,ce.HighlightJS=ce,ce.default=ce,_s}As.prototype.set=function(e){return kr(this.options,e),this},As.prototype.configure=function(e){const t=this;if(wr(e)){const t=e;if(!(e=ys[t]))throw new Error('Wrong `markdown-it` preset "'+t+'", check name')}if(!e)throw new Error("Wrong `markdown-it` preset, can't be empty");return e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach(function(n){e.components[n].rules&&t[n].ruler.enableOnly(e.components[n].rules),e.components[n].rules2&&t[n].ruler2.enableOnly(e.components[n].rules2)}),this},As.prototype.enable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.enable(e,!0))},this),n=n.concat(this.inline.ruler2.enable(e,!0));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+r);return this},As.prototype.disable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.disable(e,!0))},this),n=n.concat(this.inline.ruler2.disable(e,!0));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+r);return this},As.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},As.prototype.parse=function(e,t){if("string"!=typeof e)throw new Error("Input data should be a String");const n=new this.core.State(e,this,t);return this.core.process(n),n.tokens},As.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},As.prototype.parseInline=function(e,t){const n=new this.core.State(e,this,t);return n.inlineMode=!0,this.core.process(n),n.tokens},As.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var Ts=Ss(Cs());const Ns="[A-Za-z$_][0-9A-Za-z$_]*",Ms=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Ds=["true","false","null","undefined","NaN","Infinity"],Ps=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Os=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Rs=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ls=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],$s=[].concat(Rs,Ps,Os);const js="[A-Za-z$_][0-9A-Za-z$_]*",Fs=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Bs=["true","false","null","undefined","NaN","Infinity"],qs=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],zs=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Us=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Vs=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Ws=[].concat(Us,qs,zs);function Ks(e){const t=e.regex,n=js,r="<>",i="</>",s={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const s=e.input.substring(n);((i=s.match(/^\s*=/))||(i=s.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},o={$pattern:js,keyword:Fs,literal:Bs,built_in:Ws,"variable.language":Vs},a="[0-9](_?[0-9])*",c=`\\.(${a})`,l="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",u={className:"number",variants:[{begin:`(\\b(${l})((${c})|\\.)?|(${c}))[eE][+-]?(${a})\\b`},{begin:`\\b(${l})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},h={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},f={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},m={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},g={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},y=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,{match:/\$\d+/},u];d.contains=y.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(y)});const b=[].concat(g,d.contains),w=b.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(b)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w},k={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...qs,...zs]}},E={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/};const A={match:t.concat(/\b/,function(e){return t.concat("(?!",e.join("|"),")")}([...Us,"super","import"].map(e=>`${e}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},S={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},_={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},x="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",C={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(x)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:w,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,g,{match:/\$\d+/},u,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},C,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[g,e.REGEXP_MODE,{className:"function",begin:x,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:s.begin,"on:begin":s.isTrulyOpeningTag,end:s.end}],subLanguage:"xml",contains:[{begin:s.begin,end:s.end,skip:!0,contains:["self"]}]}]},E,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},S,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},A,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},k,_,{match:/\$[(.]/}]}}const Gs=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Hs=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),Ys=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Js=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Zs=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();Ts.registerLanguage("javascript",function(e){const t=e.regex,n=Ns,r="<>",i="</>",s={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const s=e.input.substring(n);((i=s.match(/^\s*=/))||(i=s.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},o={$pattern:Ns,keyword:Ms,literal:Ds,built_in:$s,"variable.language":Ls},a="[0-9](_?[0-9])*",c=`\\.(${a})`,l="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",u={className:"number",variants:[{begin:`(\\b(${l})((${c})|\\.)?|(${c}))[eE][+-]?(${a})\\b`},{begin:`\\b(${l})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},h={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},f={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},m={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},g={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},y=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,{match:/\$\d+/},u];d.contains=y.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(y)});const b=[].concat(g,d.contains),w=b.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(b)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w},k={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...Ps,...Os]}},E={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/},A={match:t.concat(/\b/,function(e){return t.concat("(?!",e.join("|"),")")}([...Rs,"super","import"].map(e=>`${e}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},S={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},_={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},x="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",C={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(x)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:w,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,g,{match:/\$\d+/},u,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},C,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[g,e.REGEXP_MODE,{className:"function",begin:x,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:s.begin,"on:begin":s.isTrulyOpeningTag,end:s.end}],subLanguage:"xml",contains:[{begin:s.begin,end:s.end,skip:!0,contains:["self"]}]}]},E,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},S,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},A,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},k,_,{match:/\$[(.]/}]}}),Ts.registerLanguage("typescript",function(e){const t=e.regex,n=Ks(e),r=js,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],s={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[n.exports.CLASS_REFERENCE]},a={$pattern:js,keyword:Fs.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:Bs,built_in:Ws.concat(i),"variable.language":Vs},c={className:"meta",begin:"@"+r},l=(e,t,n)=>{const r=e.contains.findIndex(e=>e.label===t);if(-1===r)throw new Error("can not find mode to replace");e.contains.splice(r,1,n)};Object.assign(n.keywords,a),n.exports.PARAMS_CONTAINS.push(c);const u=n.contains.find(e=>"attr"===e.scope),d=Object.assign({},u,{match:t.concat(r,t.lookahead(/\s*\?:/))});return n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,u,d]),n.contains=n.contains.concat([c,s,o,d]),l(n,"shebang",e.SHEBANG()),l(n,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/}),n.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}),Ts.registerLanguage("python",function(e){const t=e.regex,n=/[\p{XID_Start}_]\p{XID_Continue}*/u,r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},s={className:"meta",begin:/^(>>>|\.\.\.) /},o={className:"subst",begin:/\{/,end:/\}/,keywords:i,illegal:/#/},a={begin:/\{\{/,relevance:0},c={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,s],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,s],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,s,a,o]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,s,a,o]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,a,o]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,a,o]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l="[0-9](_?[0-9])*",u=`(\\b(${l}))?\\.(${l})|\\b(${l})\\.`,d=`\\b|${r.join("|")}`,p={className:"number",relevance:0,variants:[{begin:`(\\b(${l})|(${u}))[eE][+-]?(${l})[jJ]?(?=${d})`},{begin:`(${u})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${l})[jJ](?=${d})`}]},h={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},f={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:["self",s,p,c,e.HASH_COMMENT_MODE]}]};return o.contains=[c,p,s],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[s,p,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},c,h,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[f]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[p,f,c]}]}}),Ts.registerLanguage("json",function(e){const t=["true","false","null"],n={scope:"literal",beginKeywords:t.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,n,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}),Ts.registerLanguage("yaml",function(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(r,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),s={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},o={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},a={begin:/\{/,end:/\}/,contains:[o],illegal:"\\n",relevance:0},c={begin:"\\[",end:"\\]",contains:[o],illegal:"\\n",relevance:0},l=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},s,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},a,c,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},r],u=[...l];return u.pop(),u.push(i),o.contains=u,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:l}}),Ts.registerLanguage("bash",function(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const i={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},s=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},a={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(a);const c={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},l=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),u={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[l,e.SHEBANG(),u,c,s,o,{match:/(\/[a-z._-]+)+/},a,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},n]}}),Ts.registerLanguage("xml",function(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},s=e.inherit(i,{begin:/\(/,end:/\)/}),o=e.inherit(e.APOS_STRING_MODE,{className:"string"}),a=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[r]},{begin:/'/,end:/'/,contains:[r]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[i,a,o,s,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,s,a,o]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[a]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:c}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}),Ts.registerLanguage("css",function(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+Ys.join("|")+")"},{begin:":(:)?("+Js.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Zs.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:Hs.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Gs.join("|")+")\\b"}]}}),Ts.registerLanguage("sql",function(e){const t=e.regex,n=e.COMMENT("--","$"),r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],i=r,s=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!r.includes(e)),o={match:t.concat(/\b/,t.either(...i),/\s*\(/),relevance:0,keywords:{built_in:i}};function a(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const c={scope:"keyword",match:a(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:n}={}){const r=n;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}(s,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:a(["double precision","large object","with timezone","without timezone"])},c,o,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}),Ts.registerLanguage("markdown",function(e){const t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},n={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},r={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},s=e.inherit(r,{contains:[]}),o=e.inherit(i,{contains:[]});r.contains.push(o),i.contains.push(s);let a=[t,n];return[r,i,s,o].forEach(e=>{e.contains=e.contains.concat(a)}),a=a.concat(r,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:a},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:a}]}]},t,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},r,i,{className:"quote",begin:"^>\\s+",contains:a,end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},n,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}),Ts.registerLanguage("diff",function(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}});const Qs={js:"javascript",jsx:"javascript",mjs:"javascript",ts:"typescript",tsx:"typescript",py:"python",yml:"yaml",sh:"bash",shell:"bash",zsh:"bash",html:"xml",htm:"xml",md:"markdown"};function Xs(e){const t=new As({html:!1,linkify:!0,breaks:!0,highlight:e?(e,t)=>{const n=function(e){const t=(e||"").trim().toLowerCase();if(!t)return;const n=Qs[t]??t;return Ts.getLanguage(n)?n:void 0}(t);if(n)try{return Ts.highlight(e,{language:n,ignoreIllegals:!0}).value}catch{}return""}:void 0});return t}const eo=Xs(!0),to=Xs(!1);const no={ActivityBar:Zt,Statusbar:Qt,View:on,Views:un,KeyboardShortcuts:dn,Layout:bn,ContentTabs:wn,PanelTabs:vn,Profile:Mn,Markdown:{render:function(e,t){return(!1===t?.highlight?to:eo).render(String(e??""))},css:"\n.pnc-md { font-size: 14px; line-height: 1.65; word-break: break-word; }\n.pnc-md p { margin: 0 0 8px; }\n.pnc-md p:last-child { margin-bottom: 0; }\n.pnc-md h1, .pnc-md h2, .pnc-md h3,\n.pnc-md h4, .pnc-md h5, .pnc-md h6 {\n margin: 14px 0 6px;\n line-height: 1.3;\n font-weight: 600;\n}\n.pnc-md h1 { font-size: 1.4em; }\n.pnc-md h2 { font-size: 1.25em; }\n.pnc-md h3 { font-size: 1.12em; }\n.pnc-md h4 { font-size: 1em; }\n.pnc-md h5, .pnc-md h6 { font-size: 0.92em; color: var(--text-secondary, #9aa0a6); }\n.pnc-md ul, .pnc-md ol { margin: 0 0 8px; padding-left: 22px; }\n.pnc-md li { margin: 2px 0; }\n.pnc-md li:last-child { margin-bottom: 0; }\n.pnc-md a { color: var(--primary-main, #6ea8fe); text-decoration: underline; }\n.pnc-md blockquote {\n margin: 6px 0;\n padding: 2px 0 2px 12px;\n border-left: 3px solid var(--neutral-main, rgba(127, 127, 127, 0.35));\n color: var(--text-secondary, #9aa0a6);\n}\n.pnc-md table {\n border-collapse: collapse;\n margin: 8px 0;\n font-size: 13px;\n display: block;\n overflow-x: auto;\n}\n.pnc-md th, .pnc-md td {\n border: 1px solid var(--neutral-main, rgba(127, 127, 127, 0.3));\n padding: 4px 8px;\n text-align: left;\n}\n.pnc-md th { background: rgba(127, 127, 127, 0.12); font-weight: 600; }\n\n/* Inline code */\n.pnc-md code {\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n font-size: 0.92em;\n padding: 1px 5px;\n border-radius: 5px;\n background: rgba(127, 127, 127, 0.16);\n}\n\n/* Fenced code block — fixed dark surface (One Dark), independent of app theme */\n.pnc-md pre {\n margin: 6px 0 10px;\n border-radius: 8px;\n overflow: hidden;\n background: #282c34;\n border: 1px solid rgba(127, 127, 127, 0.28);\n}\n.pnc-md pre code {\n display: block;\n padding: 12px 14px;\n overflow-x: auto;\n background: none;\n border-radius: 0;\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n font-size: 12.5px;\n line-height: 1.55;\n color: #abb2bf;\n white-space: pre;\n}\n\n/* Code-block chrome (extension-added): top bar with language + copy button */\n.pnc-md-code { position: relative; }\n.pnc-md-code__bar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 4px 10px;\n background: #21252b;\n border-bottom: 1px solid rgba(127, 127, 127, 0.28);\n font-size: 11px;\n}\n.pnc-md-code__lang {\n color: #7f848e;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.pnc-md-code__copy {\n border: none;\n background: transparent;\n color: #abb2bf;\n cursor: pointer;\n font-size: 11px;\n padding: 2px 6px;\n border-radius: 4px;\n}\n.pnc-md-code__copy:hover { background: rgba(127, 127, 127, 0.2); }\n.pnc-md-code__copy--done { color: #98c379; }\n\n/* highlight.js — One Dark palette (matches the editor's code coloring) */\n.hljs-comment, .hljs-quote { color: #5c6370; font-style: italic; }\n.hljs-keyword, .hljs-selector-tag, .hljs-literal,\n.hljs-doctag, .hljs-name { color: #c678dd; }\n.hljs-built_in, .hljs-class .hljs-title, .hljs-title.class_,\n.hljs-attr, .hljs-attribute { color: #e5c07b; }\n.hljs-string, .hljs-symbol, .hljs-bullet,\n.hljs-addition, .hljs-regexp { color: #98c379; }\n.hljs-number, .hljs-meta .hljs-number { color: #d19a66; }\n.hljs-title, .hljs-title.function_, .hljs-section { color: #61afef; }\n.hljs-variable, .hljs-template-variable, .hljs-tag,\n.hljs-selector-id, .hljs-selector-class { color: #e06c75; }\n.hljs-meta, .hljs-comment .hljs-doctag { color: #56b6c2; }\n.hljs-deletion { color: #e06c75; }\n.hljs-emphasis { font-style: italic; }\n.hljs-strong { font-weight: 600; }\n"}};function ro(e,t){switch(e.mode){case"extension":return function(e,t){const n=t.path.split(".").pop();return!(!n||!1===t.path.endsWith(`.${n}`))&&n.toLowerCase()===e.toLowerCase()}(e.pattern,t);case"mime":return function(e,t){if(!t.mimeType)return!1;const n=e.toLowerCase(),r=t.mimeType.toLowerCase();if(n.endsWith("/*")){const e=n.slice(0,-2);return r.startsWith(e+"/")}return r===n}(e.pattern,t);case"glob":return function(e,t){const n="__DOUBLE_STAR_PLACEHOLDER__",r="__SINGLE_STAR_PLACEHOLDER__",i=e.replace(/\*\*/g,n).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),".*").replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"[^/]*");return new RegExp(`^${i}$`,"i").test(t.path)}(e.pattern,t);default:return!1}}const io=new class{#Ve=[];register(e){this.#Ve=this.#Ve.filter(t=>t.id!==e.id),this.#Ve.push({priority:0,...e}),this.#Ve.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#Ve=this.#Ve.filter(t=>t.id!==e)}clear(){this.#Ve=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#Ve){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>ro(t,e)))return console.log("[Runtime.FileOpeners] resolve",e.path,"→",n.id,"(",n.command,")"),{opener:n,command:n.command}}else t.push(n)}if(t.length>0){const n=t[0];return console.log("[Runtime.FileOpeners] resolve (fallback)",e.path,"→",n.id,"(",n.command,")"),{opener:n,command:n.command}}return console.warn("[Runtime.FileOpeners] resolve: no opener for",e.path),null}resolveAll(e){return this.#Ve.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>ro(t,e))}).map(e=>({opener:e,command:e.command}))}};let so,oo,ao,co,lo,uo;function po(){if(so)return so;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return so=punica.runtime.resources,so}function ho(){if(oo)return oo;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return oo=e,oo}function fo(){if(co)return co;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return co=e,co}function mo(){if(lo)return lo;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function go(){if(uo)return uo;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return uo=e,uo}function yo(e){let t,n;return{get(){if(void 0!==t)return t;const n=e.resolveHostFallback?.();if(void 0!==n)return t=n,t;throw new Error(e.noProviderMessage)},set(e){t=e,n=void 0},hasProvider:()=>void 0!==t,lastProviderId:()=>n,trackProviderId(e){const t=n;return n=e,{previous:t,changed:void 0!==t&&void 0!==e&&t!==e}}}}function bo(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!t?.publishEvent||!t?.createCorrelationId)&&(t.publishEvent({name:e.name,envelope:{id:t.createCorrelationId(),correlationId:e.correlationId,timestampMs:Date.now(),source:e.source,kind:e.kind??"info"},payload:e.payload}),!0)}catch{return!1}}const wo=yo({label:"Runtime.workspace",noProviderMessage:"[Runtime.workspace] No Workspace provider registered. Host must attach punica.runtime.workspace",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.workspace}});function vo(){return wo.get()}function ko(e){wo.set(e),e&&bo({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Io(e,t,n){try{const r=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!r?.publishEvent||!r?.createCorrelationId)&&(r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:t}),!0)}catch{return!1}}const Eo=Symbol("punica.llm.gatewayGovernedAi");let Ao,So,_o;function xo(){if(Ao)return Ao;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return Ao=punica.runtime.llm,Ao}function Co(e){if(Ao=e,So=void 0,_o=void 0,!e)return;const t=e;Io("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class To{providers=new Map;runtimes=new Map;registerProvider(e){if(!e.id)throw new Error("Provider must have an id");this.providers.set(e.id,e)}registerLanguageRuntime(e){if(!e.language)throw new Error("Language runtime must have a language");this.runtimes.set(e.language,e)}getProvider(e){return this.providers.get(e)}getLanguageRuntime(e){return this.runtimes.get(e)}listProviders(){return Array.from(this.providers.values())}}let No=null;function Mo(){return No||(No=new To),No}class Do{registry;constructor(e){this.registry=e}selectProvider(e){const t=e.provider?.id??"local",n=this.registry.getProvider(t);if(!n)throw new Error(`Compute provider not found: ${t}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return n}selectLanguageRuntime(e){const t=this.registry.getLanguageRuntime(e);if(!t)throw new Error(`Language runtime not found for language: ${e}. Available languages: ${Array.from(this.registry.runtimes.keys()).join(", ")}`);return t}resolveKernelSpec(e,t){return e.kernelspec?e.kernelspec:t.resolveKernelSpec?t.resolveKernelSpec(e):void 0}}class Po{providerSession;id;providerId;language;kernelspec;languageRuntime;constructor(e,t,n,r,i,s){this.providerSession=e,this.id=t,this.providerId=n,this.language=r,this.kernelspec=i,this.languageRuntime=s}run(e,t){const n=t?.runId??function(e="id"){const t=globalThis;if(t.crypto?.randomUUID)return`${e}_${t.crypto.randomUUID()}`;const n=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${n}`}("run"),r={id:this.id,providerId:this.providerId,language:this.language,kernelspec:this.kernelspec},i=this.languageRuntime.prepare(e,r);return this.providerSession.run(i,n,t)}async interrupt(){return this.providerSession.interrupt()}async restart(){return this.providerSession.restart()}async close(){return this.providerSession.close()}}const Oo={language:"python",resolveKernelSpec:e=>"python3",prepare(e,t){if("jeg"===t.providerId||void 0!==t.kernelspec)return{kind:"jupyter",code:e.code??"",kernelspec:t.kernelspec??"python3",env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata};return{kind:"process",command:["python","-u","-c",e.code??""],env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata}}},Ro={language:"node",resolveKernelSpec(e){},prepare(e,t){if("jeg"===t.providerId&&void 0!==t.kernelspec)return{kind:"jupyter",code:e.code??"",kernelspec:t.kernelspec,env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata};return{kind:"process",command:["node","-e",e.code??""],env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata}}},Lo={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},$o={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},jo={language:"scala",resolveKernelSpec:e=>"spark-scala",prepare(e,t){throw new Error("Scala execution is not yet supported. Use Python or Node.js for now.")}};function Fo(e="id"){const t=globalThis;if(t.crypto?.randomUUID)return`${e}_${t.crypto.randomUUID()}`;const n=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${n}`}class Bo{registry;router;constructor(e,t){this.registry=e,this.router=t}async open(e){const t=this.router.selectProvider(e),n=this.router.selectLanguageRuntime(e.language),r=this.router.resolveKernelSpec(e,n),i=await t.openSession({...e,kernelspec:r}),s=Fo("session");return new Po(i,s,t.id,e.language,r,n)}}class qo{providers=new Map;registerProvider(e){if(!e.id)throw new Error("Dataset provider must have an id");this.providers.set(e.id,e)}getProvider(e){return this.providers.get(e)}listProviders(){return Array.from(this.providers.values())}}let zo=null;function Uo(){return zo||(zo=new qo),zo}class Vo{registry;constructor(e){this.registry=e}selectProvider(e){const t=this.registry.getProvider(e.provider);if(!t)throw new Error(`Dataset provider not found: ${e.provider}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return t}}class Wo{providers=new Map;registerProvider(e){if(!e.id)throw new Error("Model provider must have an id");this.providers.set(e.id,e)}getProvider(e){return this.providers.get(e)}listProviders(){return Array.from(this.providers.values())}}let Ko=null;function Go(){return Ko||(Ko=new Wo),Ko}class Ho{registry;constructor(e){this.registry=e}selectProvider(e){const t=this.registry.getProvider(e.provider);if(!t)throw new Error(`Model provider not found: ${e.provider}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return t}}class Yo{#We=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#We.set(e.id,e)}get(e){return this.#We.get(e)}list(){return Array.from(this.#We.values())}select(e){return this.list().find(t=>t.canRun(e))}}let Jo=null;function Zo(){return Jo||(Jo=new Yo),Jo}function Qo(e,t){const n=Math.min(e.length,t.length);let r=0,i=0,s=0;for(let o=0;o<n;o++)r+=e[o]*t[o],i+=e[o]*e[o],s+=t[o]*t[o];return 0===i||0===s?0:r/(Math.sqrt(i)*Math.sqrt(s))}const Xo="default";class ea{#Ke=new Map;#Ge(e){const t=e||Xo;let n=this.#Ke.get(t);return n||(n=new Map,this.#Ke.set(t,n)),n}upsert(e,t=Xo){const n=this.#Ge(t);for(const t of e){if(!t||"string"!=typeof t.id)throw new Error("VectorRecord requires a string id.");n.set(t.id,t)}}query(e,t=10,n=Xo){const r=this.#Ge(n),i=[];for(const t of r.values())i.push({id:t.id,score:Qo(e,t.vector),text:t.text,metadata:t.metadata});return i.sort((e,t)=>t.score-e.score),i.slice(0,Math.max(0,t))}delete(e,t=Xo){const n=this.#Ge(t);for(const t of e)n.delete(t)}clear(e=Xo){this.#Ke.delete(e||Xo)}count(e=Xo){return this.#Ge(e).size}export(e=Xo){return Array.from(this.#Ge(e).values())}import(e,t=Xo){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#Ke.set(t||Xo,n)}}const ta=".punica/vectors";class na{#b=new ea;#He=new Set;#Ye(){try{return punica.runtime?.fs}catch{return}}#Je(e){return`${ta}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#Ze(e){const t=e||"default";if(this.#He.has(t))return;this.#He.add(t);const n=this.#Ye();if(n?.readFile)try{const e=await n.readFile(this.#Je(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#b.import(r.records,t)}catch{}}async#Qe(e){const t=this.#Ye();if(t)try{if(t.mkdir)try{await t.mkdir(ta)}catch{}const n={version:1,records:this.#b.export(e)},r=this.#Je(e),i=JSON.stringify(n);try{await t.updateFileContent(r,i)}catch{await t.createFileWithContent(r,i)}}catch(e){console.warn("[Runtime.vectors] Failed to persist collection:",e)}}async upsert(e,t){const n=t?.collection??"default";await this.#Ze(n),this.#b.upsert(e,n),await this.#Qe(n)}async query(e){const t=e.collection??"default";return await this.#Ze(t),this.#b.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#Ze(n),this.#b.delete(e,n),await this.#Qe(n)}async clear(e){const t=e?.collection??"default";await this.#Ze(t),this.#b.clear(t),await this.#Qe(t)}async count(e){const t=e?.collection??"default";return await this.#Ze(t),this.#b.count(t)}}let ra,ia,sa;function oa(){return ra||(ia||(ia=new na),ia)}function aa(){if(!sa)throw new Error("[Runtime.host] No host data-dir provider is registered. This surface is only available on hosts with a real filesystem (e.g. Electron); a browser host does not provide a data directory.");return sa}var ca;!function(e){e.CAPABILITY_SPEC_INVALID="CAPABILITY_SPEC_INVALID",e.CAPABILITY_ALREADY_REGISTERED="CAPABILITY_ALREADY_REGISTERED",e.CAPABILITY_NOT_FOUND="CAPABILITY_NOT_FOUND",e.CAPABILITY_PROVIDER_MISSING="CAPABILITY_PROVIDER_MISSING",e.CAPABILITY_HANDLER_MISSING="CAPABILITY_HANDLER_MISSING",e.EXTENSION_ACTIVATION_FAILED="EXTENSION_ACTIVATION_FAILED",e.CAPABILITY_INPUT_INVALID="CAPABILITY_INPUT_INVALID",e.CAPABILITY_PATH_TRAVERSAL_DENIED="CAPABILITY_PATH_TRAVERSAL_DENIED",e.CAPABILITY_ENCRYPTION_REQUIRED="CAPABILITY_ENCRYPTION_REQUIRED",e.CAPABILITY_NOT_IN_PROFILE="CAPABILITY_NOT_IN_PROFILE",e.CAPABILITY_DENIED="CAPABILITY_DENIED",e.CAPABILITY_APPROVAL_REQUIRED="CAPABILITY_APPROVAL_REQUIRED",e.CAPABILITY_RATE_LIMITED="CAPABILITY_RATE_LIMITED",e.CAPABILITY_IDEMPOTENCY_KEY_MISSING="CAPABILITY_IDEMPOTENCY_KEY_MISSING",e.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED="CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED",e.CAPABILITY_CIRCUIT_OPEN="CAPABILITY_CIRCUIT_OPEN",e.CAPABILITY_TIMEOUT="CAPABILITY_TIMEOUT",e.CAPABILITY_PROVIDER_ERROR="CAPABILITY_PROVIDER_ERROR"}(ca||(ca={}));class la extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const ua=new class{#Xe=new Map;#X=new Map;registerCapability(e){if(!e.name)throw new la(ca.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" must have a version`,{capability:e.name});if(!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(e.version))throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" version "${e.version}" is not valid semver (expected MAJOR.MINOR.PATCH, e.g. "1.0.0")`,{capability:e.name,version:e.version});if(this.#Xe.has(e.name))throw new la(ca.CAPABILITY_ALREADY_REGISTERED,`Capability "${e.name}" is already registered`,{capability:e.name});const t=function(e){const t=[];if(!e)return{ok:!0,errors:t};if(void 0!==e.timeoutMs&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)&&t.push(`timeoutMs must be a positive finite number, got ${e.timeoutMs}`),void 0!==e.retries&&(!Number.isInteger(e.retries)||e.retries<0)&&t.push(`retries must be a non-negative integer, got ${e.retries}`),void 0!==e.retryBackoffMs&&(!Number.isFinite(e.retryBackoffMs)||e.retryBackoffMs<=0)&&t.push(`retryBackoffMs must be a positive finite number, got ${e.retryBackoffMs}`),void 0!==e.rateLimit){const{perSecond:n}=e.rateLimit;(!Number.isFinite(n)||n<=0)&&t.push(`rateLimit.perSecond must be a positive finite number, got ${n}`)}if(void 0!==e.concurrency){const{key:n,max:r}=e.concurrency;"string"==typeof n&&0!==n.trim().length||t.push(`concurrency.key must be a non-empty string, got ${JSON.stringify(n)}`),(!Number.isInteger(r)||r<=0)&&t.push(`concurrency.max must be a positive integer, got ${r}`)}if(void 0!==e.circuitBreaker){const{failureThreshold:n,cooldownMs:r}=e.circuitBreaker;void 0!==n&&(!Number.isInteger(n)||n<=0)&&t.push(`circuitBreaker.failureThreshold must be a positive integer, got ${n}`),void 0!==r&&(!Number.isFinite(r)||r<=0)&&t.push(`circuitBreaker.cooldownMs must be a positive finite number, got ${r}`)}return{ok:0===t.length,errors:t}}(e.defaults);if(!t.ok)throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" has invalid middleware config: ${t.errors.join("; ")}`,{capability:e.name,errors:t.errors});if(e.requires&&e.requires.length>0){if(e.requires.includes(e.name))throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot require itself`,{capability:e.name,cycle:[e.name,e.name]});for(const t of e.requires){const n=this.#et(t,e.name);if(n)throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#Xe.set(e.name,e);try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.({name:"capability.registered",envelope:{id:`cap-reg-${e.name}-${Date.now()}`,correlationId:`cap-reg-${e.name}`,timestampMs:Date.now(),source:"runtime:capabilities:registry",kind:"info"},payload:{capability:e.name,version:e.version,origin:"core",risk:e.risk,sideEffect:e.sideEffect,deprecated:e.deprecated??null}})}catch{}}#et(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#Xe.get(e);if(!r?.requires)return null;for(const i of r.requires){const r=this.#et(i,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#Xe.has(e.name))throw new la(ca.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#X.set(e.name,e)}getSpec(e){return this.#Xe.get(e)}getProvider(e){return this.#X.get(e)}hasCapability(e){return this.#Xe.has(e)}hasProvider(e){return this.#X.has(e)}listCapabilities(){return Array.from(this.#Xe.keys())}getAllSpecs(){return Array.from(this.#Xe.values())}clear(){this.#Xe.clear(),this.#X.clear()}};function da(e){const t={id:e.name,title:e.name,version:e.version,policy:{risk:e.policy?.risk??e.risk,approval:e.policy?.approval??(r=e.risk,"high"===r?"step":"plan")},sideEffects:(n=e.sideEffect,"none"===n?[]:[n])};var n,r;return void 0!==e.inputSchema&&(t.inputs={schema:e.inputSchema}),void 0!==e.outputSchema&&(t.outputs={schema:e.outputSchema,kind:"direct"}),e.defaults&&(t.execution=function(e){const t={};void 0!==e.timeoutMs&&(t.timeoutMs=e.timeoutMs);void 0===e.retries&&void 0===e.retryBackoffMs||(t.retry={},void 0!==e.retries&&(t.retry.maxAttempts=e.retries),void 0!==e.retryBackoffMs&&(t.retry.initialDelayMs=e.retryBackoffMs));e.rateLimit&&(t.rateLimit={perSecond:e.rateLimit.perSecond});e.concurrency&&(t.concurrency={key:e.concurrency.key,max:e.concurrency.max});void 0!==e.idempotency&&(t.idempotency=e.idempotency);return t}(e.defaults)),e.deprecated&&(t.deprecated={...e.deprecated}),e.requires&&e.requires.length>0&&(t.requires=[...e.requires]),e.permissions&&e.permissions.length>0&&(t["x-permissions"]=[...e.permissions]),e.secretBearing&&(t["x-secretBearing"]=!0),t}function pa(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:ha(e.sideEffects),risk:e.policy?.risk??"low",permissions:n,inputSchema:e.inputs?.schema,outputSchema:e.outputs?.schema};return e.execution&&(r.defaults=function(e){const t={};void 0!==e.timeoutMs&&(t.timeoutMs=e.timeoutMs);void 0!==e.retry?.maxAttempts&&(t.retries=e.retry.maxAttempts);void 0!==e.retry?.initialDelayMs&&(t.retryBackoffMs=e.retry.initialDelayMs);void 0!==e.rateLimit?.perSecond&&(t.rateLimit={perSecond:e.rateLimit.perSecond});e.concurrency&&(t.concurrency={key:e.concurrency.key,max:e.concurrency.max});void 0!==e.idempotency&&(t.idempotency=e.idempotency);return t}(e.execution)),!0===t["x-secretBearing"]&&(r.secretBearing=!0),e.deprecated&&(r.deprecated={...e.deprecated}),Array.isArray(e.requires)&&e.requires.length>0&&(r.requires=[...e.requires]),e.policy&&(r.policy={...e.policy}),r}function ha(e){if(!e||0===e.length)return"none";const t=["none","read","write","network"];for(const n of e)if(t.includes(n))return n;return"none"}const fa=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function ma(){const e=globalThis;return e.punica?.extensions?.manager}function ga(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function ya(){const e=globalThis;return e.punica?.flow?.registry}function ba(){const e=globalThis;return e.punica?.flow?.agents}function wa(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const va={core:function(e){const t=ua.getSpec(e);if(t)return{origin:"core",definition:da(t)}},extension:function(e){const t=ma();if(!t)return;const n=t.getCapability(e);if(!n)return;const r=t.listCapabilities().find(t=>t.id===e);return{origin:"extension",definition:n,metadata:r?.extensionName?{extensionName:r.extensionName}:void 0}},"instruction-class":function(e){const t=ga();if(!t)return;const n=t.getCapability(e);if(!n)return;const r=t.get(e);return{origin:"instruction-class",definition:n,metadata:r?.productId?{productId:r.productId}:void 0}},"ivy-node":function(e){const t=ya();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-node",definition:r,metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},"ivy-agent":function(e){const t=ba();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-agent",definition:r,metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},mcp:function(e){const t=wa();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},ka={core:function(){return ua.getAllSpecs().map(e=>({origin:"core",definition:da(e)}))},extension:function(){const e=ma();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=ga();return e?e.listCapabilities().map(t=>{const n=e.get(t.id);return{origin:"instruction-class",definition:t,metadata:n?.productId?{productId:n.productId}:void 0}}):[]},"ivy-node":function(){const e=ya();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-node",definition:e,metadata:{packageRoot:n.manifestPath}})}return t},"ivy-agent":function(){const e=ba();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-agent",definition:e,metadata:{packageRoot:n.manifestPath}})}return t},mcp:function(){const e=wa();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Ia={getCapability(e){for(const t of fa){const n=va[t](e);if(n)return n}},listCapabilities(e){const t=(n=e?.origin,void 0===n?void 0:new Set(Array.isArray(n)?n:[n]));var n;const r=new Set,i=[];for(const e of fa)if(!t||t.has(e))for(const t of ka[e]()){const e=t.definition.id;r.has(e)||(r.add(e),i.push(t))}return i},hasCapability(e){return void 0!==this.getCapability(e)}};function Ea(e,t,n){switch(e){case"mcp":return function(e,t){const{mcpServerId:n,mcpToolName:r}=t;return{name:e.id,async execute(t,i){const s=globalThis.punica?.runtime?.mcp;if(!s?.callTool)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`MCP runtime is not initialized — cannot invoke "${e.id}". Ensure McpModule has started before calling MCP capabilities.`,{capability:e.id,origin:"mcp"});if(!n||!r)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`MCP capability "${e.id}" is missing serverId or toolName metadata`,{capability:e.id,origin:"mcp"});return await s.callTool(n,r,t??{})}}}(t,n??{});case"instruction-class":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.kernel?.llm?.api;if(!r?.invokeLlmCapability)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`LLM kernel API is not initialized — cannot invoke instruction-class capability "${e.id}".`,{capability:e.id,origin:"instruction-class"});const i=null!==t&&"object"==typeof t?t:{},s="string"==typeof i.instructionClass?i.instructionClass:e.id,o="string"==typeof i.userPrompt?i.userPrompt:"string"==typeof i.prompt?i.prompt:JSON.stringify(t);return await r.invokeLlmCapability({instructionClass:s,userPrompt:o,context:i.context??{}})}}}(t);case"ivy-node":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.runner;if(!r?.run)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Flow runner is not initialized — cannot invoke ivy-node capability "${e.id}". Ensure the flow module has started before calling IvyNode capabilities.`,{capability:e.id,origin:"ivy-node"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i});return s?.output??null}}}(t);case"ivy-agent":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.agents;if(!r?.run)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Agent registry is not initialized — cannot invoke ivy-agent capability "${e.id}". Ensure the flow module has started before calling IvyAgent capabilities.`,{capability:e.id,origin:"ivy-agent"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i});return s?.output??null}}}(t);case"extension":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.extensions?.manager;if(!r?.executeCapability)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Extension manager is not initialized — cannot invoke extension capability "${e.id}".`,{capability:e.id,origin:"extension"});return await r.executeCapability(e.id,t,n)}}}(t);case"core":throw new la(ca.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Aa={recordSpan:()=>{}};function Sa(e){try{Aa.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function _a(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,o={capability:i,"actor.type":s.actor.type,"origin.kind":s.origin.kind};s.actor.extensionName&&(o["actor.extension"]=s.actor.extensionName),s.origin.extension&&(o["origin.extension"]=s.origin.extension),s.workspaceId&&(o["workspace.id"]=s.workspaceId),r.tags={...r.tags,...o};try{const e=await t();return r.durationMs=Date.now()-r.startTimeMs,Sa({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"success",attributes:{...r.tags}}),e}catch(e){r.error=e instanceof Error?e:new Error(String(e)),r.durationMs=Date.now()-r.startTimeMs;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.failed",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,spanId:s.trace.parentSpanId??n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"error"},payload:{invocationId:n.invocationId,capability:i,error:r.error.message,durationMs:r.durationMs}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.failed event:",e)}throw Sa({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"error",errorCode:e instanceof la?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function xa(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(xa);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=xa(r);return t}return e}const Ca=new WeakMap;function Ta(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s}=n;if(!0===r.spec.secretBearing||i.startsWith("secrets."))r.redactedInput=xa(s);else{const e=function(e){const t=Ca.get(e);if(t)return t;const n=y(e.inputSchema);return Ca.set(e,n),n}(r.spec);r.redactedInput=e.length>0?b(s,e):s}return await t()}}function Na(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function Ma(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Na(t))}const Da=new class{validate(e,t){const n=[];if(!e||"object"!=typeof e)return{ok:!0,errors:n};const r=e,i=r.type;if(i&&(Ma(i,t)||n.push(`Expected type "${i}", got "${Na(t)}"`)),"object"===i&&t&&"object"==typeof t&&!Array.isArray(t)){const e=t,i=r.required,s=r.properties;if(Array.isArray(i))for(const t of i)t in e&&void 0!==e[t]||n.push(`Missing required field: "${t}"`);if(s)for(const[t,r]of Object.entries(e)){if(void 0===r)continue;const e=s[t];if(!e)continue;const i=e.type;i&&(Ma(i,r)||n.push(`Field "${t}": expected type "${i}", got "${Na(r)}"`))}}return{ok:0===n.length,errors:n}}};let Pa=Da;function Oa(){return Pa}function Ra(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=Oa().validate(s,i);if(!o.ok)throw new la(ca.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const La=yo({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function $a(){return La.get()}const ja=["path","oldPath","newPath","src","dst","target","linkPath"];function Fa(e,t){if(e.includes("\0"))return{ok:!1,reason:"null byte in path"};if(/(%2e|\.)(?:%2e|\.)/i.test(e)&&/%2e/i.test(e))return{ok:!1,reason:"URL-encoded traversal segment"};if(/^[A-Za-z]:[\\/]?/.test(e))return{ok:!1,reason:"drive-relative path"};if(e.startsWith("\\\\"))return{ok:!1,reason:"UNC path"};const n=e.replace(/\\/g,"/"),r=n.startsWith("/"),i=n.split("/").filter(e=>""!==e&&"."!==e),s=[];for(const e of i)if(".."===e){if(0===s.length)return{ok:!1,reason:"traversal above root"};s.pop()}else s.push(e);let o=(r?"/":"")+s.join("/");if(""===o&&(o=r?"/":"."),t&&r){const e=function(e){let t=e.replace(/\\/g,"/");t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1));return t}(t);if("/"===e);else if(o!==e&&!o.startsWith(`${e}/`))return{ok:!1,reason:"path is outside the workspace root"}}return{ok:!0,canonical:o}}function Ba(){try{return $a().cwd}catch{return}}function qa(){return async(e,t)=>{const{input:n}=e.req;if("object"!=typeof n||null===n)return await t();const r=n;let i,s=!1;for(const e of ja){const t=r[e];if("string"!=typeof t)continue;s||(i=Ba(),s=!0);const n=Fa(t,i);if(!n.ok)throw new la(ca.CAPABILITY_PATH_TRAVERSAL_DENIED,`Path traversal denied on field "${e}": ${n.reason}`,{field:e,reason:n.reason,value:t,...void 0!==i?{cwd:i}:{}})}return await t()}}const za="encrypted-at-rest";function Ua(){return async(e,t)=>{const n=e.state.spec;if("sensitive"!==(n.dataClassification??"internal"))return t();if(!(r=n.name).startsWith("fs.")&&!r.startsWith("workspace."))return t();var r;const i=function(){try{return $a()}catch{return}}();if(!i)throw new la(ca.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires an encryption-at-rest-capable FileSystemProvider, but no provider is registered`,{capability:n.name,required:za,reason:"provider not registered"});if(!i.capabilities?.has(za))throw new la(ca.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${za}" capability flag`,{capability:n.name,required:za,reason:"capability not advertised"});return bo({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:za}}),t()}}function Va(e,t,n,r,i){try{const s=globalThis.punica?.kernel?.Events?.manager;if(!s||"function"!=typeof s.publishEvent)return;s.publishEvent({name:"capability.denied_by_profile",source:"runtime:capabilities:middleware:profileBudget",kind:"warn",correlationId:i,payload:{invocationId:i,capability:e,profile:t,reason:n,origin:r??"unknown"}})}catch{}}function Wa(){return async(e,t)=>{const n=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()}catch{return}}();if(!n)return t();const{allowedIds:r,deniedIds:i,allowedOrigins:s}=n.capabilities;if("*"===r&&!i?.length&&!s?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(s&&s.length>0){const e=Ia.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw Va(o,c,"origin-not-allowed",t,a),new la(ca.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" origin "${t??"unknown"}" is not in profile "${c}" allowedOrigins`,{capability:o,profile:c,reason:"origin-not-allowed",origin:t??"unknown"})}if(i&&i.includes(o))throw Va(o,c,"in-denylist",void 0,a),new la(ca.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is explicitly denied by profile "${c}"`,{capability:o,profile:c,reason:"in-denylist"});if("*"!==r){const e=function(e){return"*"===e?"*":new Set(e)}(r);if("*"!==e&&!e.has(o))throw Va(o,c,"not-in-allowlist",void 0,a),new la(ca.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Ka={alg:"HS256",typ:"PUNICA-APPROVAL"};class Ga extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function Ha(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return("undefined"!=typeof btoa?btoa(t):globalThis.Buffer.from(e).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ya(e){const t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4);if("undefined"!=typeof atob){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}const n=globalThis.Buffer.from(t,"base64");return new Uint8Array(n)}function Ja(e){return(new TextEncoder).encode(e)}function Za(e){return Ha(Ja(JSON.stringify(e)))}function Qa(e){return JSON.parse((t=Ya(e),(new TextDecoder).decode(t)));var t}function Xa(){const e=globalThis.crypto?.subtle;if(!e)throw new Error("[ApprovalToken] crypto.subtle is unavailable. Host must inject a custom signer/verifier or run in an environment with Web Crypto (browser, Node 18+).");return e}function ec(){const e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("[ApprovalToken] crypto.getRandomValues unavailable.");const t=new Uint8Array(32);return e.getRandomValues(t),t}class tc{#tt;#nt;constructor(e){e?.secret instanceof Uint8Array?this.#tt=e.secret:this.#tt="string"==typeof e?.secret?Ja(e.secret):ec()}async sign(e){const t=await this.#rt(),n=Za(Ka),r=Za(e),i=Ja(`${n}.${r}`),s=await Xa().sign("HMAC",t,i);return`${n}.${r}.${Ha(new Uint8Array(s))}`}getSecret(){return this.#tt}async#rt(){return this.#nt||(this.#nt=await Xa().importKey("raw",this.#tt,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#nt}}class nc{#tt;#nt;#it=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#tt=e.secret:this.#tt="string"==typeof e?.secret?Ja(e.secret):ec()}async verify(e){const t=e.split(".");if(3!==t.length)throw new Ga("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=Qa(n)}catch{throw new Ga("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new Ga("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=Qa(r)}catch{throw new Ga("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#rt(),c=Ja(`${n}.${r}`);let l;try{l=Ya(i)}catch{throw new Ga("MALFORMED","Token signature is not valid base64url")}const u=Xa();if(!await u.verify("HMAC",a,l,c))throw new Ga("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new Ga("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new Ga("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#it.add(e)}isRevoked(e){return this.#it.has(e)}async#rt(){return this.#nt||(this.#nt=await Xa().importKey("raw",this.#tt,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#nt}}let rc;function ic(){return rc||(rc=function(){const e=new tc,t=new nc({secret:e.getSecret()});return{signer:e,verifier:t}}()),rc}const sc=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function oc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=globalThis.punica?.kernel?.Policy?.manager;if(!a){const e=o.policy??{},a=e.risk??o.risk??"low",c=e.approval??"none",l="high"===a||"step"===c||"plan"===c,u=!0===globalThis.punica?.kernel?.Policy?.failClosed,d=u&&l;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"policy.manager.missing",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:d?"error":"warning"},payload:{capability:i,risk:a,approval:c,actor:s.actor,decision:d?"deny":"allow",failClosed:u}})}catch{}if(console.warn(`[CapabilityGateway] Policy manager not available for "${i}" (risk=${a}, approval=${c}); `+(d?"DENYING (fail-closed)":"allowing (fail-open)")+"."),d)throw new la(ca.CAPABILITY_DENIED,`Policy manager unavailable and capability "${i}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:i,reason:"policy-manager-missing",risk:a,approval:c});return r.policyDecision={allowed:!0,requiresApproval:!1,reason:"policy-manager-missing (fail-open)"},await t()}const c=o.policy??{},l=c.risk??o.risk??"low",u=c.approval??"none";let d=!1,p="";if("ai"===s.actor.type){"approval"===sc({capabilityId:i,risk:o.risk,sideEffect:o.sideEffect})&&(d=!0,p=`agent-mode policy: ${o.sideEffect}/${o.risk}`)}"high"===o.risk&&(d=!0,p="High risk capability"),"step"!==u&&"plan"!==u||(d=!0,p=`Capability requires ${u} approval`);const h={kind:"capability",id:i,risk:l,approval:u,reason:o.description??o.title??`Capability: ${i}`},f=a.evaluate(h,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});if(r.policyDecision={allowed:f.allowed,requiresApproval:f.requiresApproval||d,approvalToken:s.policy.approvalToken,reason:f.reason||p},d||f.requiresApproval)if(s.policy.approvalToken)try{await ic().verifier.verify(s.policy.approvalToken)}catch(e){if(e instanceof Ga){try{const t=globalThis.punica?.kernel?.Events?.manager;t&&t.publishEvent({name:"token.invalid",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:"error"},payload:{capability:i,tokenError:e.code,actor:s.actor}})}catch{}throw new la(ca.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:i,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!(a.hasApproval(h,"always",{workspaceId:s.workspaceId})||a.hasApproval(h,"workspace",{workspaceId:s.workspaceId})||a.hasApproval(h,"once",{workspaceId:s.workspaceId}))){a.requestApproval(h,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:i,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}throw new la(ca.CAPABILITY_APPROVAL_REQUIRED,`Approval required: ${p}`,{capability:i,reason:p})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:s.workspaceId};if(!(a.hasApproval(h,"always",e)||a.hasApproval(h,"workspace",e))&&"function"==typeof a.revokeApproval)try{a.revokeApproval({kind:h.kind,id:h.id,scope:"once"})}catch{}}}if(!f.allowed&&!d&&"suggest"!==f.mode)throw new la(ca.CAPABILITY_DENIED,f.reason??"Policy denied execution",{capability:i,decision:f});return await t()}}const ac=new class{#f=new Map;#st;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#st=t<=0?1:t}get(e,t){const n=this.#ot(e,t),r=this.#f.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#f.delete(n),this.#f.set(n,r),r;this.#f.delete(n)}}set(e){const t=this.#ot(e.capabilityId,e.key);for(this.#f.delete(t),this.#f.set(t,e);this.#f.size>this.#st;){const e=this.#f.keys().next().value;if(void 0===e)break;this.#f.delete(e)}}delete(e,t){return this.#f.delete(this.#ot(e,t))}clear(){this.#f.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#f)r.expiresAtMs<=e&&(this.#f.delete(n),t++);return t}size(){return this.#f.size}#ot(e,t){return`${e}|${t}`}};let cc=ac;function lc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s,idempotencyKey:o}=n,a=r.spec.defaults?.idempotency??"none";if("none"===a)return t();if("required"===a&&!o)throw new la(ca.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=cc,l=function(e){const t=JSON.stringify(e??null);let n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}(s),u=c.get(i,o);if(u){if(u.inputHash!==l)throw function(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}({name:"idempotency.replay_blocked",envelope:{id:n.invocationId,correlationId:n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:idempotency",kind:"error"},payload:{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs,actor:n.ctx.actor}}),new la(ca.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED,`Capability "${i}" idempotencyKey "${o}" was previously used with a different input`,{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs});return r.output=u.response,r.tags["idempotency.hit"]="true",u.response}const d=await t(),p=Date.now();return c.set({key:o,capabilityId:i,inputHash:l,response:d,createdAtMs:p,expiresAtMs:p+864e5}),r.tags["idempotency.cached"]="true",d}}const uc=new class{#at=new Map;getBucket(e,t){let n=this.#at.get(e);return n||(n={tokens:t,lastRefillMs:Date.now(),perSecond:t,maxTokens:t},this.#at.set(e,n)),n}consumeToken(e,t){const n=this.getBucket(e,t),r=Date.now(),i=(r-n.lastRefillMs)/1e3*t;return n.tokens=Math.min(n.maxTokens,n.tokens+i),n.lastRefillMs=r,n.tokens>=1&&(n.tokens-=1,!0)}};function dc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=o.defaults?.rateLimit;if(!a||!a.perSecond)return await t();const c=function(e,t,n){const r=[e,t];return n&&r.push(n),r.join(":")}(i,s.actor.type,s.actor.extensionName??s.origin.extension);if(!uc.consumeToken(c,a.perSecond))throw new la(ca.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const pc=new class{#ct=new Map;getSemaphore(e,t){let n=this.#ct.get(e);return n||(n={count:0,max:t,queue:[]},this.#ct.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e){const t=this.#ct.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function hc(){return async(e,t)=>{const{req:n,state:r}=e,{ctx:i}=n,{spec:s}=r,o=s.defaults?.concurrency;if(!o||!o.key||!o.max)return await t();const a=function(e,t){let n=e;return n=n.replace(/\{workspaceId\}/g,t.workspaceId??""),n=n.replace(/\{tenantId\}/g,t.tenantId??""),n=n.replace(/\{extension\}/g,t.extension??""),n=n.replace(/\{actorType\}/g,t.actorType??""),n}(o.key,{workspaceId:i.workspaceId,tenantId:i.tenantId,extension:i.actor.extensionName??i.origin.extension,actorType:i.actor.type});try{await pc.acquire(a,o.max)}catch(e){throw new la(ca.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{pc.release(a)}}}const fc=new class{#lt=new Map;getBreaker(e){let t=this.#lt.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#lt.set(e,t)),t}};function mc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i}=n,s=r.spec.defaults?.circuitBreaker;if(!s)return await t();const o=s.failureThreshold??3,a=s.cooldownMs??6e4,c=fc.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new la(ca.CAPABILITY_CIRCUIT_OPEN,`Circuit breaker open for "${i}"`,{capability:i,openedAtMs:c.openedAtMs,cooldownMs:a,remainingMs:a-(l-c.openedAtMs)});try{const e=await t();return c.consecutiveFailures=0,c.status="closed",e}catch(e){c.consecutiveFailures++;throw("half-open"===c.status||c.consecutiveFailures>=o)&&(c.status="open",c.openedAtMs=l),e}}}function gc(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return["timeout","network","connection","temporary","retry","rate limit","503","502","504"].some(e=>t.includes(e))}async function yc(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new la(ca.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),s])}finally{void 0!==i&&clearTimeout(i)}}function bc(e){return{invocationId:e.invocationId,capability:e.capability,actor:e.actor,origin:e.origin,capabilityOrigin:e.capabilityOrigin,workspace:e.workspaceId,policyDecision:e.policyDecision?{allowed:e.policyDecision.allowed,requiresApproval:e.policyDecision.requiresApproval,reason:e.policyDecision.reason}:void 0,input:e.redactedInput,output:e.redactedOutput,duration:e.durationMs,error:e.error?{message:e.error.message,name:e.error.name}:void 0,timestamp:e.timestamp}}async function wc(e){try{if(function(e){const t=globalThis.punica?.kernel?.Events?.manager;if(!t||"function"!=typeof t.publishEvent||"function"!=typeof t.createCorrelationId)return!1;try{return t.publishEvent({name:"capability.audited",envelope:{id:t.createCorrelationId(),correlationId:e.invocationId,timestampMs:e.timestamp,source:"runtime:capabilities:gateway",kind:e.error?"error":"info"},payload:bc(e)}),!0}catch{return!1}}(e))return;if(await async function(e){const t=globalThis.punica?.kernel?.History?.auditWriter;if(!t||"function"!=typeof t.write)return!1;try{return await t.write(bc(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=$a()}catch{return!1}try{const n=".punica/audit";await t.createFolder(n).catch(()=>{});const r=`${n}/${e.invocationId}.json`;return await t.createFileWithContent(r,JSON.stringify(bc(e),null,2)),!0}catch{return!1}}(e))return;console.warn("[CapabilityGateway] Audit record dropped (no event manager / audit writer / FS provider available):",e.invocationId)}catch(e){console.warn("[CapabilityGateway] Failed to write audit record:",e)}}const vc=new WeakMap;function kc(e,t){if(!0===t.secretBearing)return Ic(e);const n=function(e){const t=vc.get(e);if(t)return t;const n=y(e.outputSchema);return vc.set(e,n),n}(t);return n.length>0?b(e,n):e}function Ic(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ic);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ic(r);return t}return e}function Ec(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a="object"==typeof n.input&&null!==n.input&&"path"in n.input&&"string"==typeof n.input.path&&/^\.punica\/audit\//.test(n.input.path);let c,l;try{c=await t(),r.output=c}catch(e){throw l=e instanceof Error?e:new Error(String(e)),r.error=l,e}finally{const e=globalThis.punica?.runtime,t=!e||"bootstrapping"===e.lifecyclePhase||"noWorkspace"===e.lifecyclePhase;if(!a&&!t){const e=kc(r.output,o);await wc({invocationId:n.invocationId,capability:i,actor:s.actor,origin:s.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:s.workspaceId,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Ac=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Sc(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const _c=new class{async call(e,t,n,r){const i=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let s=ua.getSpec(e),o=s?ua.getProvider(e):void 0,a="core";if(!s){const t=Ia.getCapability(e);if(!t)throw Sc({name:"capability.unknown_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:n.actor}}),new la(ca.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,s=pa(t.definition),o=Ea(t.origin,t.definition,t.metadata)}if(!o)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(s.requires)for(const t of s.requires)if(!ua.hasCapability(t))throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});s.deprecated&&Sc({name:"capability.deprecated_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:a,since:s.deprecated.since,reason:s.deprecated.reason,replacement:s.deprecated.replacement,actor:n.actor}});const c={req:{invocationId:i,name:e,input:t,ctx:n,idempotencyKey:r},state:{spec:s,capabilityOrigin:a,startTimeMs:Date.now(),tags:{}}},l=this.#ut(o);try{return await this.#dt(l,c)}catch(e){if(e instanceof la)throw e;throw new la(ca.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#ut(e){const t={auditTrail:Ec,traceMetrics:_a,redaction:Ta,validateInput:Ra,pathTraversalGuard:qa,encryptionRouting:Ua,profileBudget:Wa,policyGate:oc,idempotency:lc,rateLimit:dc,concurrency:hc,circuitBreaker:mc,timeoutRetry:()=>function(e){return async(t,n)=>{const{req:r,state:i}=t,{input:s,idempotencyKey:o}=r,{spec:a}=i,c=a.defaults?.timeoutMs??3e4,l=a.defaults?.retries??0,u=a.defaults?.retryBackoffMs??1e3,d="write"!==a.sideEffect||Boolean(o);let p=null,h=0;for(;h<=l;){h++;try{const n=await yc(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),h<=l&&d&&gc(p)){const e=u*Math.pow(2,h-1);await new Promise(t=>setTimeout(t,e));continue}throw i.error=p,p}}throw i.error=p??new Error("Execution failed"),i.error}}(e)};return Ac.map(e=>t[e]())}#dt(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const i=e[n];return n++,await i(t,r)};return r()}};function xc(e,t){const n=$a(),r=n[t];if("function"!=typeof r)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires FileSystemProvider.${String(t)}() but the registered provider does not expose it`,{capability:e,method:String(t)});return r.bind(n)}function Cc(e,t,n){const r=$a();if(!r.capabilities?.has(n))throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires the FileSystemProvider to advertise the "${n}" capability flag, but it does not`,{capability:e,method:String(t),requiredProviderCapability:n});const i=r[t];if("function"!=typeof i)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires FileSystemProvider.${String(t)}() but the registered provider does not expose it`,{capability:e,method:String(t),requiredProviderCapability:n});return i.bind(r)}class Tc{name="fs.readFile";async execute(e,t){const n=$a();return await n.readFile(e.path)}}class Nc{name="fs.writeFile";async execute(e,t){const n=$a();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class Mc{name="fs.listFiles";async execute(e,t){const n=$a();return await n.getFileTree()}}class Dc{name="fs.stat";async execute(e,t){return await xc("fs.stat","stat")(e.path)}}class Pc{name="fs.exists";async execute(e,t){return await xc("fs.exists","exists")(e.path)}}class Oc{name="fs.copy";async execute(e,t){await xc("fs.copy","copy")(e.src,e.dst)}}class Rc{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await xc("fs.mkdir","mkdir")(e.path,n)}}class Lc{name="fs.history";async execute(e,t){return await Cc("fs.history","history","versioning")(e.path)}}class $c{name="fs.readAtVersion";async execute(e,t){return await Cc("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class jc{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await xc("fs.list","list")(e.path,n)}}const Fc=yo({label:"Runtime.secrets",noProviderMessage:"[Runtime.secrets] No Secrets provider registered. Host must call punica.runtime.setSecretsProvider() before using Secrets API",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.secrets??function(){const e=new Map,t=new Map;return{set(n,r){const i=String(n??"").trim();if(!i)throw new Error("[Runtime.secrets] Secret name is required");const s=Date.now();if(t.has(i)){const e=t.get(i);t.set(i,{...e,updatedAtMs:s})}else t.set(i,{createdAtMs:s,updatedAtMs:s});e.set(i,String(r??""))},get(t){const n=String(t??"").trim();return n&&e.has(n)?e.get(n):null},delete(n){const r=String(n??"").trim();return!!r&&(t.delete(r),e.delete(r))},list(){const e=[];for(const[n,r]of t.entries())e.push({name:n,createdAtMs:r.createdAtMs,updatedAtMs:r.updatedAtMs});return e.sort((e,t)=>e.name.localeCompare(t.name)),e}}}()}});function Bc(){return Fc.get()}function qc(e){Fc.set(e),e&&bo({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class zc{name="secrets.get";async execute(e,t){return Bc().get(e.name)}}class Uc{name="secrets.set";async execute(e,t){Bc().set(e.name,e.value)}}function Vc(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Eo]=!0,n}class Wc{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=Vc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class Kc{name="llm.chatStream";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=globalThis.punica?.kernel?.Events?.manager,i=t.sessionId??t.trace?.traceId,s=e=>{if(r)try{r.publishEvent({name:"llm.chunk",envelope:{id:r.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"progress"},payload:{capabilityId:this.name,chunk:e}})}catch{}},o=Vc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);if("function"!=typeof n.chatStream){const e=await n.chat(o);return s({type:"done",response:e}),e}let a="",c="";const l=[];let u;for await(const e of n.chatStream(o)){if(t.signal?.aborted)break;switch(s(e),e.type){case"content":a+=e.text;break;case"thinking":c+=e.text;break;case"tool_call":l.push(e.toolCall);break;case"done":u=e.response;break;case"error":throw new Error(`[llm.chatStream] ${e.error.code}: ${e.error.message}`)}}const d={text:a||u?.text||"",modelId:u?.modelId,provider:u?.provider,usage:u?.usage,meta:u?.meta};return l.length>0&&(d.toolCalls=l),c&&(d.thinking=c),d}}class Gc{name="llm.invoke";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.invoke(e,{correlationId:t.sessionId??t.trace?.traceId})}}class Hc{name="llm.plan";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.plan(e)}}class Yc{name="search.query";async execute(e,t){const n=globalThis.punica?.runtime?.search;if(!n)throw new Error("Search provider not available");return await n.query({q:e.q,limit:e.limit})}}class Jc{name="vcs.status";async execute(e,t){const n=globalThis.punica?.runtime?.vcs;if(!n)throw new Error("VCS provider not available");return await n.status()}}class Zc{name="vcs.commit";async execute(e,t){const n=globalThis.punica?.runtime?.vcs;if(!n)throw new Error("VCS provider not available");return await n.commit({message:e.message,all:e.all})}}class Qc{name="workspace.readFile";async execute(e,t){const n=$a();return await n.readFile(e.path)}}class Xc{name="workspace.writeFile";async execute(e,t){const n=$a();await n.createFileWithContent(e.path,e.content)}}class el{name="workspace.listFiles";async execute(e,t){const n=$a(),r=await n.getFileTree(),i=[],s=e=>{for(const t of e??[])i.push({path:t.path,name:t.name,isDirectory:t.isDirectory}),t.isDirectory&&Array.isArray(t.children)&&t.children.length&&s(t.children)};return s(r??[]),{entries:i}}}class tl{name="terminals.create";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");return await n.create(e.title?{title:e.title}:void 0)}}class nl{name="terminals.send";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");n.write(e.id,e.text)}}class rl{name="tasks.runCommand";async execute(e,t){const n=globalThis.punica?.runtime?.tasks;if(!n)throw new Error("Tasks provider not available");return await n.run(e)}}class il{name="flow.migrate";async execute(e,t){const n=globalThis.punica,r=n?.flow?.primitives?.migrations;if(!r||"function"!=typeof r.migrate)throw new Error("[FlowMigrateProvider] Migration registry is not available — substrate bootstrap incomplete");return r.migrate(e)}}class sl{name="flow.runSubflow";async execute(e,t){const n=globalThis.punica,r=n?.flow?.engine?.manager;if(!r||"function"!=typeof r.runSubflow)throw new Error("[FlowRunSubflowProvider] Flow engine is not available — substrate bootstrap incomplete");const i={...e,workspaceId:e.workspaceId??t.workspaceId,parentTraceId:e.parentTraceId??t.trace?.traceId};return r.runSubflow(i)}}const ol="capability.catalog";class al{name=ol;async execute(e,t){const n=e??{},r=Ia.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>cl(e,n));return{capabilities:r,count:r.length}}}function cl(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=ll(t.risk);if(0===n.length)return!1;const r=e.definition.policy?.risk;if(!r||!n.includes(r))return!1}if(void 0!==t.tags){const n=ll(t.tags);if(0===n.length)return!1;const r=e.definition.tags;if(!Array.isArray(r)||0===r.length)return!1;if(!n.some(e=>r.includes(e)))return!1}if(void 0!==t.sideEffects){const n=ll(t.sideEffects);if(0===n.length)return!1;const r=e.definition.sideEffects;if(!Array.isArray(r)||0===r.length)return!1;if(!n.some(e=>r.includes(e)))return!1}return!0}function ll(e){return Array.isArray(e)?e:[e]}const ul=["examples","$comment","default","title"];function dl(e,t){let n=String(e??"");if(n=n.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[`*_#>]/g,"").replace(/\s+/g," ").trim(),!n)return n;const r=n.match(/^.{12,}?[.!?](?=\s|$)/)?.[0];return r&&(n=r),n.length>t&&(n=n.slice(0,t-1).trimEnd()+"…"),n}const pl=["properties","patternProperties","definitions","$defs"];function hl(e){if(Array.isArray(e))return e.map(e=>hl(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!ul.includes(n))if("description"!==n||"string"!=typeof r){if(pl.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=hl(n);t[n]=e;continue}t[n]=hl(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const fl="capability.schemaExport";class ml{name=fl;async execute(e,t){const n=e??{},r=n.filter??{},i=Ia.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>cl(e,r)),s=n.mode??"full",o=i.map(e=>{const t=function(e){const t=e.definition,n={id:t.id,origin:e.origin,version:t.version,title:t.title};void 0!==t.description&&(n.description=t.description);void 0!==t.inputs?.schema&&(n.inputSchema=t.inputs.schema);void 0!==t.outputs?.schema&&(n.outputSchema=t.outputs.schema);t.policy&&(n.policy={risk:t.policy.risk,approval:t.policy.approval});t.tags&&t.tags.length>0&&(n.tags=[...t.tags]);t.sideEffects&&t.sideEffects.length>0&&(n.sideEffects=[...t.sideEffects]);const r=t.requires;r&&r.length>0&&(n.requires=[...r]);t.deprecated&&(n.deprecated={...t.deprecated});if(e.metadata){const t={};for(const[n,r]of Object.entries(e.metadata))void 0!==r&&(t[n]=r);Object.keys(t).length>0&&(n.metadata=t)}return n}(e);return"ai-tools"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=dl(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=hl(e.inputSchema));e.policy&&(t.policy={...e.policy});return t}(t):"summary"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=dl(e.description??e.title,100);n&&(t.description=n);return t}(t):t});return{schemaVersion:"v1",generatedAt:Date.now(),capabilities:o,count:o.length}}}async function gl(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return[];const i=Ia.listCapabilities();if(0===i.length)return[];const s=function(e,t){const n=wl(bl(e));return t.map(e=>({...e,score:vl(n,wl(bl(e.text)))}))}(r,i.map(e=>({id:e.definition.id,description:e.definition.description,text:yl(e.definition)}))),o=s.slice().sort((e,t)=>t.score-e.score).slice(0,Math.max(0,n)).map(e=>({id:e.id,score:e.score,description:e.description}));return Io("llm.recommendIntent",{intent:r,limit:n,path:"text-similarity",topIds:o.map(e=>e.id),topScore:o[0]?.score??0}),o}function yl(e){const t=[];return t.push(e.id),e.title&&t.push(e.title),e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(e.tags.join(" ")),t.join(" ")}function bl(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(e=>e.length>0)}function wl(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function vl(e,t){if(0===e.size||0===t.size)return 0;let n=0,r=0,i=0;for(const[,t]of e)r+=t*t;for(const[,e]of t)i+=e*e;for(const[r,i]of e){const e=t.get(r);void 0!==e&&(n+=i*e)}const s=Math.sqrt(r)*Math.sqrt(i);return 0===s?0:n/s}const kl="capability.recommend";class Il{name=kl;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await gl(r,"number"==typeof n.limit?{limit:n.limit}:void 0);return{recommendations:i.map(e=>({id:e.id,score:e.score,description:e.description})),path:"text-similarity",count:i.length}}}const El="capability.describe",Al="capability.search";function Sl(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class _l{name=El;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new ml).execute({mode:"ai-tools"},t)).capabilities.filter(e=>r.has(String(e.id))),s=new Set(i.map(e=>String(e.id)));return{tools:i,missing:n.filter(e=>!s.has(e))}}}class xl{name=Al;async execute(e,t){const n=e??{},r=String(n.query??"").trim(),i=Math.min(Math.max(1,Math.floor(n.limit??16)),50);if(!r)return{results:[],count:0};const s=Ia.listCapabilities(),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await gl(r,{limit:i});e.reduce((e,t)=>"number"==typeof t.score&&t.score>e?t.score:e,0)>1e-9&&(a=e.map(e=>String(e.id)).filter(e=>o.has(e)))}catch{}if(0===a.length){const e=r.toLowerCase().split(/\s+/).filter(Boolean);a=s.filter(t=>{const n=`${t.definition.id} ${t.definition.title??""} ${t.definition.description??""}`.toLowerCase();return e.some(e=>n.includes(e))}).map(e=>String(e.definition.id))}const c=a.slice(0,i).map(e=>{const t=o.get(e);return{id:e,description:dl(t?.description??t?.title??e,100),category:Sl(e)}});return{results:c,count:c.length}}}function Cl(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Tl(e,t){return{name:e,version:"1.0.0",sideEffect:e.endsWith(".list")||e.endsWith(".get")?"read":"write",risk:t.risk??"low",permissions:[],inputSchema:{type:"object",...t.required?{required:t.required}:{},properties:t.properties??{}},outputSchema:{type:"object",properties:t.outputProperties??{}},defaults:{timeoutMs:5e3}}}class Nl{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Cl().create(n)}}}class Ml{name="ai.session.list";async execute(e,t){const n=Cl().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Dl{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Cl().get(n)}}}class Pl{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Cl().rename(String(n?.sessionId??""),String(n?.title??""))}}}class Ol{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Cl().archive(String(n?.sessionId??""),n?.archived)}}}class Rl{name="ai.session.delete";async execute(e,t){return{ok:Cl().delete(String(e?.sessionId??""))}}}const Ll={id:"missing-title",severity:"error",check(e){const t=e.title;return"string"==typeof t&&t.trim().length>0?[]:[{ruleId:"missing-title",severity:"error",message:`Capability "${e.id}" has no title — title is required and shown in UI + LLM prompts`,capabilityId:String(e.id),path:"title",code:"CAP_NO_TITLE"}]}},$l={id:"weak-description",severity:"warning",check(e){const t=e.description,n="string"==typeof t?t.trim():"";if(n.length>=20)return[];const r=0===n.length?"has no description":`has a very short description ("${n}")`;return[{ruleId:"weak-description",severity:"warning",message:`Capability "${e.id}" ${r} — the agent reads this to decide when to call the tool; write 1-2 sentences (what it does, when to pick it, side effects)`,capabilityId:String(e.id),path:"description",code:"CAP_WEAK_DESC"}]}},jl=new Set(["low","medium","high"]),Fl={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&jl.has(t.risk)?[]:[{ruleId:"invalid-risk",severity:"error",message:`Capability "${e.id}" declares policy.risk "${String(t.risk)}" — must be one of low | medium | high`,capabilityId:String(e.id),path:"policy.risk",code:"CAP_BAD_RISK"}]:[]}},Bl=new Set(["none","plan","step"]),ql={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Bl.has(t.approval)?[]:[{ruleId:"invalid-approval",severity:"error",message:`Capability "${e.id}" declares policy.approval "${String(t.approval)}" — must be one of none | plan | step`,capabilityId:String(e.id),path:"policy.approval",code:"CAP_BAD_APPROVAL"}]:[]}};const zl={id:"untyped-inputs",severity:"warning",check(e){const t=e.inputs;return t&&"object"==typeof t?function(e){const t=e.schema;if(t&&"object"==typeof t){const e=t;if(void 0!==e.type||void 0!==e.properties)return!0}for(const[t,n]of Object.entries(e))if("schema"!==t&&n&&"object"==typeof n&&void 0!==n.type)return!0;return!1}(t)?[]:[{ruleId:"untyped-inputs",severity:"warning",message:`Capability "${e.id}" declares inputs without type information — the agent generates arguments from this; add a JSON Schema (inputs.schema) or per-field types`,capabilityId:String(e.id),path:"inputs",code:"CAP_UNTYPED_INPUTS"}]:[]}},Ul=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Vl={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Ul.test(t)?[]:[{ruleId:"id-naming",severity:"warning",message:`Capability id "${String(t)}" is not a dotted <namespace>.<action> name (e.g. "editor.openFile") — consistent ids project cleanly to MCP and group related tools`,capabilityId:String(t),path:"id",code:"CAP_ID_NAMING"}]}},Wl=new Set(["low","medium","high"]),Kl=["write","delete","remove","modify","destroy"],Gl=[Ll,$l,Fl,ql,zl,Vl,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Wl.has(t.risk))return[];const n=[];"high"===t.risk&&"none"===t.approval&&n.push({ruleId:"risk-approval-consistency",severity:"warning",message:`Capability "${e.id}" is risk: high but approval: none — a high-risk capability the agent can run unattended; consider approval plan or step`,capabilityId:String(e.id),path:"policy.approval",code:"CAP_RISK_APPROVAL"});const r=e.sideEffects;if("low"===t.risk&&Array.isArray(r)){const t=r.find(e=>"string"==typeof e&&Kl.some(t=>e.toLowerCase().includes(t)));t&&n.push({ruleId:"risk-approval-consistency",severity:"warning",message:`Capability "${e.id}" declares a mutating side effect ("${String(t)}") but risk: low — risk is likely under-declared (medium/high for workspace-changing work)`,capabilityId:String(e.id),path:"policy.risk",code:"CAP_RISK_APPROVAL"})}return n}}];const Hl=new class{#pt=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#pt.values())try{const r=n.check(e);r&&r.length>0&&t.push(...r)}catch(r){t.push({ruleId:n.id,severity:"info",message:`Lint rule "${n.id}" threw during analysis: ${String(r?.message??r)}`,capabilityId:String(e.id),code:"CAP_LINT_RULE_ERROR"})}return{ok:!t.some(e=>"error"===e.severity),issues:t}}lintAll(e){return e.map(e=>({id:String(e.id),...this.lint(e)}))}register(e){if(!e||"function"!=typeof e.check)throw new Error("CapabilityLinter.register: rule must have a check(def) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("CapabilityLinter.register: rule.id must be a non-empty string");this.#pt.set(e.id,e)}unregister(e){return this.#pt.delete(e)}list(){return Array.from(this.#pt.keys())}reset(){this.#pt.clear();for(const e of Gl)this.#pt.set(e.id,e)}},Yl="capability.lint";class Jl{name=Yl;async execute(e,t){const n=e??{},r=Ia.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=Hl.lintAll(r).map(e=>({id:e.id,ok:e.ok,issues:e.issues}));return{results:i,ok:i.every(e=>e.ok),count:i.length}}}const Zl={type:"object"};function Ql(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Xl(e){let t;return t=function(e){if(e instanceof la)return!0;if(!e||"object"!=typeof e)return!1;const t=e;return"CapabilityError"===t.name&&"string"==typeof t.code}(e)?`[${e.code}] ${e.message}`:e instanceof Error?e.message:Ql(e),{content:[{type:"text",text:t}],isError:!0}}const eu="capability.serveList",tu="capability.serveCall",nu=new Set([eu,tu]);class ru{name=eu;async execute(e,t){const n=(e??{}).filter??{},r=Ia.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!nu.has(e.definition.id)).filter(e=>cl(e,n)).map(e=>function(e,t){const n=t??e.id,r=e.sideEffects??[];return{name:n,description:e.description??e.title??n,inputSchema:e.inputs?.schema??Zl,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class iu{name=tu;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||nu.has(r)||!Ia.getCapability(r))return Xl(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:Ql(e)}],isError:!1}}(await _c.call(r,n.arguments??{},t))}catch(e){return Xl(e)}}}const su="shell.revealView",ou="shell.hideView",au="shell.listViews",cu="shell.toggleView",lu="shell.toggleSlot";function uu(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new la(ca.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:su});return e}function du(e){const t=e?.actor?.type;return"user"===t?{kind:"user-gesture",id:e.origin?.id}:"extension"===t?{kind:"extension",id:e.actor?.extensionName??e.origin?.id}:{kind:"capability",id:e?.trace?.traceId??e?.origin?.id}}class pu{name=su;async execute(e,t){const{viewId:n,focus:r}=e??{},i=uu();if(!i.getPlacement(n))throw new la(ca.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:su,viewId:n});return await i.reveal(n,du(t),{focus:r}),{viewId:n,revealed:!0}}}class hu{name=ou;async execute(e,t){const{viewId:n}=e??{};return uu().hide(n,du(t)),{viewId:n,hidden:!0}}}class fu{name=au;async execute(e,t){return{views:uu().listViews()}}}class mu{name=cu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=uu();if(!i.getPlacement(n))throw new la(ca.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:cu,viewId:n});return"visible"===i.getState(n)?(i.hide(n,du(t)),{viewId:n,visible:!1}):(await i.reveal(n,du(t),{focus:r}),{viewId:n,visible:!0})}}const gu=new Map;class yu{name=lu;async execute(e,t){const{slot:n,focus:r}=e??{},i=uu(),s=i.getVisibleView(n);if(s)return gu.set(n,s),i.hide(s,du(t)),{slot:n,visible:!1,viewId:s};const o=gu.get(n);let a=o&&i.getPlacement(o)?o:void 0;return a||(a=i.listViews().find(e=>e.slot===n)?.viewId),a?(await i.reveal(a,du(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}function bu(e){try{ua.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function wu(e){const{definition:t,origin:n,metadata:r}=e;return{id:t.id,origin:n,title:t.title,risk:t.policy?.risk,approval:t.policy?.approval,outputKind:t.outputs?.kind,resultEvent:t.outputs?.resultEvent,extensionName:r?.extensionName,productId:r?.productId,packageRoot:r?.packageRoot}}function vu(e){const{definition:t,origin:n,metadata:r}=e;console.group(`[${n}] ${t.id}`),console.dir({title:t.title,description:t.description,version:t.version,tags:t.tags,inputs:t.inputs,outputs:t.outputs,policy:t.policy,sideEffects:t.sideEffects,execution:t.execution,deprecated:t.deprecated,...r?{_metadata:r}:{}},{depth:null}),console.groupEnd()}async function ku(e){const t=globalThis.punica;if(!t)return void console.warn("[Punica] logTrinityCatalog: global `punica` is missing — call after initialize().");try{await(t.flow?.registry?.discover?.())}catch{}if(e?.id){const t=Ia.getCapability(e.id);return t?void vu(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Ia.listCapabilities(n),i=r.map(wu);if(console.log("[Punica] Trinity capability catalog",{count:i.length}),i.length>0){if(console.table(i),e?.verbose){console.log("[Punica] Full definitions (same fields as .punica/capabilities.yaml):");for(const e of r)vu(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Iu(e){return ku({...e,verbose:!0})}function Eu(e){switch(e){case"core":return"Core";case"extension":return"Extension";case"instruction-class":return"Instruction class";case"ivy-node":return"Ivy node";case"ivy-agent":return"Ivy agent";case"mcp":return"MCP";default:return String(e)}}function Au(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,i=t.policy?.risk??"—",s=function(e){const t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t);return n.trim()}(t.description??t.title??"")||"—";return`| ${n} | ${r} | ${i} | ${function(e){return e.replace(/\|/g,"\\|")}(s)} |`}function Su(e){return JSON.stringify(e,null,2)}const _u=new class{#Oe=new Map;get(e){return this.#Oe.get(e)}list(){return[...this.#Oe.values()]}register(e,t){for(const e of t)this.#Oe.set(e.definition.id,e),this.#ht(e.definition.id)}unregister(e){for(const[t,n]of this.#Oe)n.serverId===e&&(this.#Oe.delete(t),this.#ft(t))}hasServer(e){for(const t of this.#Oe.values())if(t.serverId===e)return!0;return!1}#ht(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.registered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}#ft(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.unregistered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}},xu=16384,Cu="runtime:mcp:client";function Tu(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Nu(e,t){if("string"==typeof e){if(t<12){const n=function(e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{return}}(e);if(void 0!==n)return Nu(n,t+1)}return e.length>1024?e.slice(0,1024)+"…[truncated]":e}if(Array.isArray(e)){const n=e.slice(0,50).map(e=>Nu(e,t+1));return e.length>50&&n.push(`…[${e.length-50} more items truncated]`),n}if(e&&"object"==typeof e){if(t>=12)return"…[truncated]";const n={};for(const[r,i]of Object.entries(e))n[r]=Nu(i,t+1);return n}return e}function Mu(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=xu)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Nu(e,0),null,2)??"null";if(r.length<=xu)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,xu)+"\n… [truncated]",bytes:n,truncated:!0}}function Du(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const Pu=new class{#mt=new Map;async connect(e){if(this.#mt.has(e.id))return this.#mt.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return Fu}),r=e.toolOverrides??await t(e.id),i="stdio"===e.kind?n(e.env):e.env,s="streamable-http"===e.kind||"sse"===e.kind?n(e.headers):e.headers,o={...e,env:i,headers:s,toolOverrides:r&&Object.keys(r).length?r:void 0},a=function(e,t){const n=(t,n,r)=>({direction:"outbound",serverId:e.serverId,serverName:e.serverName,transport:e.transport,method:n,toolName:Du(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Tu(),s=Mu(r??{});bo({name:"mcp.request",source:Cu,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:fe().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Tu(),s=Date.now(),o=Mu(r??{});bo({name:"mcp.request",source:Cu,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:fe().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=Mu(o??null);return bo({name:"mcp.response",source:Cu,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:fe().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw bo({name:"mcp.response",source:Cu,correlationId:i,kind:"error",payload:{...n(i,e,r),kind:"request",isError:!0,durationMs:Date.now()-s,errorMessage:t instanceof Error?t.message:String(t)}}),t}}}}({serverId:o.id,serverName:o.name,transport:o.kind},await async function(e){if("stdio"===e.kind){if(!e.command)throw new Error(`MCP server "${e.id}": stdio transport requires 'command'`);const{StdioTransport:t}=await Promise.resolve().then(function(){return zb});return new t(e.command,e.args??[],e.env??{})}if("streamable-http"===e.kind||"sse"===e.kind){if(!e.url)throw new Error(`MCP server "${e.id}": http transport requires 'url'`);const{StreamableHttpTransport:t}=await Promise.resolve().then(function(){return Ub});return new t(e.url,e.headers??{})}throw new Error(`MCP server "${e.id}": unknown transport kind "${e.kind}"`)}(o));await a.connect(),await a.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"punica-editor",version:"1.0.0"}}),a.notify("notifications/initialized",{});const c=await a.request("tools/list",{}),l=c?.tools??[],u=l.map(e=>{const t=o.toolOverrides?.[e.name]??{},n=function(e,t,n={}){const r=t._meta?.punica??{},i={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},s={timeoutMs:n.executionDefaults?.timeoutMs??r.executionDefaults?.timeoutMs??3e4,idempotency:n.executionDefaults?.idempotency??r.executionDefaults?.idempotency??"none"},o=["mcp",e],a=r.tags??[],c=n.tags??[],l=[...new Set([...o,...a,...c])],u=n.sideEffects??r.sideEffects??["mcp-invocation","network"];return{id:`mcp.${e}.${t.name}`,title:t.name,description:t.description??`MCP tool ${t.name} from server ${e}`,version:"1.0.0",inputs:{schema:t.inputSchema??{type:"object"}},outputs:{schema:{type:"object",properties:{content:{type:"array",items:{type:"object",properties:{type:{type:"string"},text:{type:"string"}}}},isError:{type:"boolean"}}},kind:"direct"},policy:i,sideEffects:u,executionDefaults:s,tags:l}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});_u.register(o.id,u),console.log(`[Punica] MCP server "${o.id}" connected — ${l.length} tool(s) registered as capabilities`);const d={serverId:o.id,transportKind:o.kind,tools:l,disconnect:async()=>{a.close(),_u.unregister(e.id),this.#mt.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#mt.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#mt.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#mt.values()].map(e=>e.handle)}listTools(e){return e?this.#mt.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#mt.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},Ou=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Ru(e){if(!e)return{};const t={},n=function(){const e=globalThis.process,t=e?.env;return t&&"object"==typeof t?t:void 0}(),r=void 0!==n;for(const[i,s]of Object.entries(e)){const e="string"==typeof s?s.match(Ou):null;if(e){const s=e[1];if(!r){console.warn(`[Punica] MCP env placeholder \${env.${s}} skipped — not in Node/Electron`);continue}const o=n[s];void 0!==o?t[i]=o:console.warn(`[Punica] MCP env placeholder \${env.${s}} — variable unset`)}else t[i]=s}return t}async function Lu(e){try{const t=globalThis,n=t.punica?.runtime?.fs,r=n?.readFile,i=n?.exists;if(!r)return{};if(i){const t=`.punica/mcp/${e}.yaml`;if(!await i(t))return{}}let s;try{s=await r(`.punica/mcp/${e}.yaml`,{encoding:"utf8"})}catch{return{}}if("string"!=typeof s||""===s.trim())return{};const{parse:o}=await Promise.resolve().then(function(){return qf}),a=o(s);return a?.tools&&"object"==typeof a.tools?a.tools:{}}catch(t){return console.warn(`[Punica] MCP overrides for "${e}" failed:`,t?.message??t),{}}}async function $u(){try{const e=globalThis,t=e.punica?.runtime?.fs,n=t?.readFile,r=t?.exists;if(!n)return[];if(r){if(!await r(".punica/mcp.yaml"))return[]}let i;try{i=await n(".punica/mcp.yaml",{encoding:"utf8"})}catch{return[]}const{parseYamlMcpConfig:s}=await Promise.resolve().then(function(){return Vb}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await Lu(e.id),n="stdio"===e.kind?Ru(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?Ru(e.headers):e.headers;return{...e,env:n,headers:r,toolOverrides:Object.keys(t).length?t:void 0}}(e)))}catch(e){return console.error("[Punica] MCP config load failed:",e?.message??e),[]}}function ju(e){if(!e||"object"!=typeof e)return[];const t=e;if(!Array.isArray(t.servers))return[];const n=[];for(const e of t.servers){if(!e||"object"!=typeof e)continue;const t=e;if("string"!=typeof t.id)continue;const r=t.transport??t.kind??"stdio";if("stdio"===r){const e="object"==typeof t.env&&null!==t.env?Ru(t.env):{};n.push({id:t.id,name:"string"==typeof t.name?t.name:void 0,kind:"stdio",command:"string"==typeof t.command?t.command:void 0,args:Array.isArray(t.args)?t.args:[],env:e})}else if("streamable-http"===r||"sse"===r){const e="object"==typeof t.headers&&null!==t.headers?Ru(t.headers):{};n.push({id:t.id,name:"string"==typeof t.name?t.name:void 0,kind:r,url:"string"==typeof t.url?t.url:void 0,headers:e})}}return n}var Fu=Object.freeze({__proto__:null,loadMcpConfig:$u,loadServerOverrides:Lu,parseStaticConfig:ju,resolveEnvPlaceholders:Ru});class Bu{name=je.MCP;version="1.0.0";dependencies=[$e.EVENTS,je.FS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){this.#gt=e.BOOTSTRAPPING;const n=await $u();this.#yt(n),this.#gt=e.BOOTSTRAPPED}async#yt(e){for(const t of e)try{await Pu.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#gt=e.STARTING,this.#gt=e.STARTED,console.log(`[Punica] MCP module started — ${_u.list().length} capability(ies) active`)}}const qu=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const zu={get capabilities(){return La.hasProvider()?La.get().capabilities:void 0},get cwd(){return La.hasProvider()?La.get().cwd:void 0},getFileTree:()=>La.get().getFileTree(),readFile:e=>La.get().readFile(e),readBytes:(e,t,n)=>{const r=La.get();if("function"!=typeof r.readBytes)throw new Error("[Runtime.fs] Provider does not implement readBytes()");return r.readBytes(e,t,n)},updateFileContent:(e,t)=>La.get().updateFileContent(e,t),createFolder:e=>La.get().createFolder(e),deleteFolder:e=>La.get().deleteFolder(e),deleteFile:(e,t)=>La.get().deleteFile(e,t),renameFile:(e,t)=>La.get().renameFile(e,t),renameFolder:(e,t)=>La.get().renameFolder(e,t),createFileWithContent:(e,t)=>La.get().createFileWithContent(e,t),list:(e,t)=>{const n=La.get();if("function"!=typeof n.list)throw new Error("[Runtime.fs] Provider does not implement list()");return n.list(e,t)},stat:e=>{const t=La.get();if("function"!=typeof t.stat)throw new Error("[Runtime.fs] Provider does not implement stat()");return t.stat(e)},mkdir:(e,t)=>{const n=La.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},Uu=function(e){return e||{query:e=>ho().query(e),startIndex:e=>{const t=ho();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(qu?.search),Vu=function(e){return e||{status:()=>go().status(),branches:()=>go().branches(),logs:e=>go().logs(e),init:e=>go().init(e),clone:e=>go().clone(e),commit:e=>go().commit(e),stage:e=>go().stage(e),unstage:e=>go().unstage(e),discard:e=>go().discard(e),reset:e=>go().reset(e),switchBranch:e=>go().switchBranch(e),createBranch:(e,t)=>go().createBranch(e,t),fetch:e=>go().fetch(e),pull:e=>go().pull(e),push:e=>go().push(e)}}(qu?.vcs),Wu=function(e){return e||{create:e=>fo().create(e),write:(e,t)=>fo().write(e,t),resize:(e,t,n)=>fo().resize(e,t,n),close:e=>fo().close(e),onData:(e,t)=>fo().onData(e,t),onExit:(e,t)=>fo().onExit(e,t),list:()=>fo().list()}}(qu?.terminals),Ku=function(e){return e||{start:e=>mo().start(e),send:(e,t)=>mo().send(e,t),onMessage:(e,t)=>mo().onMessage(e,t),onStderr:(e,t)=>mo().onStderr(e,t),onExit:(e,t)=>mo().onExit(e,t),stop:e=>mo().stop(e),list:()=>mo().list()}}(qu?.debug),Gu=function(e){return e||{run:e=>function(){if(ao)return ao;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return ao=e,ao}().run(e)}}(qu?.tasks),Hu=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&ko(e),{getCurrent:()=>wo.get().getCurrent(),list:()=>wo.get().list(),open:e=>wo.get().open(e),setEnvironment:(e,t)=>wo.get().setEnvironment(e,t),onDidChange:e=>wo.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(qu?.workspace),Yu=function(e){return e||{list:async e=>po().list(e),get:e=>po().get(e),register:e=>po().register(e),unregister:e=>po().unregister(e),onDidChange:e=>po().onDidChange(e)}}(qu?.resources),Ju=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&Co(e),t)return e;function n(e){if("remote"===e?.route)return!0;if("local"===e?.route)return!1;if(e?.providerId){const t=String(e.providerId).toLowerCase();if(t.startsWith("remote:"))return!0;if(t.startsWith("local:"))return!1}return!0}async function r(e,t,n){!function(e,t){(So&&So!==e||_o&&t&&_o!==t)&&F.publishEvent({name:"llm.providerChanged",envelope:{id:F.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:So,newProviderId:e,previousEndpoint:_o,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),So=e,t&&(_o=t)}(t,n);const r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch(e){return void console.error("[LLM Facade] Error accessing punica.runtime.workspace (gateRemoteRequest):",e?.message??e)}})(),i=e?.correlationId??F.createCorrelationId(),s=ce.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!s.allowed)throw s.requiresApproval&&ce.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:i}),F.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:F.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(s.reason??"[Policy] Remote LLM request denied");return F.publishEvent({name:"llm.remoteRequestSent",envelope:{id:F.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),{...e,correlationId:i,route:"remote",providerId:t}}const i={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",i=e?.providerId??"remote",s=xo(),o=!0===e?.[Eo];if(!o&&("remote"===t||n(e))){const t=e?.endpoint,n=await r(e,i,t);return await s.chat(n)}const a=await s.chat(e);if(!a)throw new Error("[LLM Facade] No response returned from LLM provider");const c=a?.provider;if(!o&&function(e){if(!e)return!1;const t=String(e).toLowerCase();return!t.startsWith("local:")&&"local"!==t&&"mock"!==t&&"ollama"!==t&&!t.startsWith("ollama-")&&"llama.cpp"!==t&&"llamacpp"!==t}(c)){const n=c&&"remote"!==c?c:i,r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch{return}})(),s=e?.correlationId??F.createCorrelationId(),o=ce.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw F.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:F.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"error"},payload:{providerId:n,route:t,workspaceId:r,messageCount:e.messages?.length??0,reason:"Policy gate bypassed via auto route"}}),o.requiresApproval&&ce.requestApproval({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r,correlationId:s}),new Error(o.reason??"[Policy] Remote LLM request denied (auto route bypass detected)");F.publishEvent({name:"llm.remoteRequestSent",envelope:{id:F.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:n,workspaceId:r,messageCount:e.messages?.length??0,retroactive:!0,route:t}})}return a},chatStream:async function*(e){if(e?.signal?.aborted)return;const t=e?.route??"auto",i=e?.providerId??"remote",s=xo();let o=e;if(!(!0===e?.[Eo])&&("remote"===t||n(e))){const t=e?.endpoint;o=await r(e,i,t)}if("function"!=typeof s.chatStream){const e=await s.chat(o);if(!e)throw new Error("[LLM Facade] No response returned from LLM provider");if(o?.signal?.aborted)return;"string"==typeof e.text&&e.text.length>0&&(yield{type:"content",text:e.text});for(const t of e.toolCalls??[])yield{type:"tool_call",toolCall:t};return void(yield{type:"done",response:e})}for await(const e of s.chatStream(o)){if(o?.signal?.aborted)return;yield e}},__punicaWrappedLlmFacade:!0};return i.manager=function(){const e=("undefined"!=typeof window?window.api:void 0)?.llm;if(!e)return;return{listModels:async t=>await(e.listModels?.(t)),listInstalled:async()=>await(e.listInstalled?.()),setActiveModel:async t=>{await(e.setActive?.({modelId:t??null}))},removeModel:async t=>{await(e.remove?.({modelId:t}))},downloadModel:async t=>{await(e.download?.({modelId:t}))},pickModelFile:async()=>await(e.pickModelFile?.()),importModelFile:async t=>{await(e.importModelFile?.(t))},localServerStatus:async()=>await(e.localServerStatus?.()),startLocalServer:async t=>await(e.startLocalServer?.(t)),stopLocalServer:async()=>{await(e.stopLocalServer?.())}}}(),i}(qu?.llm),Zu=function(e){if(e)return e;const t=Mo(),n=new Do(t),r=new Bo(t,n);t.registerLanguageRuntime(Oo),t.registerLanguageRuntime(Ro),t.registerLanguageRuntime(Lo),t.registerLanguageRuntime($o),t.registerLanguageRuntime(jo);const i=new Map;return{async*run(e,t){const n=t?.runId??Fo("run"),s=await r.open({language:e.language,provider:e.metadata?.provider,kernelspec:e.metadata?.kernelspec,env:e.env,cwd:e.cwd,resources:e.resources,metadata:e.metadata});i.set(n,s);try{for await(const n of s.run(e,t))yield n}finally{i.delete(n),await s.close()}},async cancel(e){const t=i.get(e);t&&(await t.interrupt(),i.delete(e))},session:r,registry:t}}(qu?.compute),Qu=function(e){if(e)return e;const t=Uo(),n=new Vo(t),r={resolve:async e=>n.selectProvider(e).resolve(e),mount:async(e,t)=>n.selectProvider(e).mount(e,t),async unmount(e){const n=e.match(/^punica:\/\/dataset\/([^/]+)\/(.+)$/);if(!n)throw new Error(`Invalid dataset URI format: ${e}`);const r=n[1],i=t.getProvider(r);if(!i)throw new Error(`Dataset provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Dataset provider not found: ${e.provider}`);return n.list({query:e.query,tags:e.tags})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({query:e?.query,tags:e?.tags});r.push(...n)}catch(e){console.warn(`Failed to list datasets from provider ${t.id}:`,e)}return r},registry:t};return r}(qu?.datasets),Xu=function(e){if(e)return e;const t=Go(),n=new Ho(t),r={resolve:async e=>n.selectProvider(e).resolve(e),mount:async(e,t)=>n.selectProvider(e).mount(e,t),async unmount(e){const n=e.match(/^punica:\/\/model\/([^/]+)\/(.+)$/);if(!n)throw new Error(`Invalid model endpoint format: ${e}`);const r=n[1],i=t.getProvider(r);if(!i)throw new Error(`Model provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Model provider not found: ${e.provider}`);return n.list({task:e.task,query:e.query})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({task:e?.task,query:e?.query});r.push(...n)}catch(e){console.warn(`Failed to list models from provider ${t.id}:`,e)}return r},registry:t};return r}(qu?.models),ed=function(e){if(e)return e;const t=Zo();return{registry:t,async start(e){const n=function(e){if(e.format&&"unknown"!==e.format)return e.format;const t=e.filePath?.trim().toLowerCase();if(t){if(t.endsWith(".gguf"))return"gguf";if(t.endsWith(".safetensors"))return"safetensors";if(t.endsWith(".onnx"))return"onnx"}return"unknown"}(e),r=n!==e.format?{...e,format:n}:e,i=t.select(r);if(!i){const e=t.list().map(e=>e.id);throw new Error(`No model runtime can run record "${r.id}" (format=${r.format??"unknown"}). Registered runtimes: [${e.join(", ")||"none"}].`)}return i.start(r)},async stop(e){const n=t.get(e.runtimeId);if(!n)throw new Error(`No model runtime registered for handle runtimeId="${e.runtimeId}".`);await n.stop(e)}}}(qu?.modelRuntimes),td=function(e){if(e)return e;const t=Zo();return{async infer(e){const n=e.handle?.runtimeId;if(!n)throw new Error("inference.infer requires a started runtime handle (req.handle from runtime.modelRuntimes.start).");const r=t.get(n);if(!r)throw new Error(`No model runtime registered for handle runtimeId="${n}".`);if("function"!=typeof r.infer)throw new Error(`Model runtime "${n}" does not support inference (no infer()). Task: ${e.task}.`);return r.infer(e)}}}(qu?.inference),nd=function(e){return e||{upsert:(e,t)=>oa().upsert(e,t),query:e=>oa().query(e),delete:(e,t)=>oa().delete(e,t),clear:e=>oa().clear(e),count:e=>oa().count(e)}}(qu?.vectors),rd=function(e){if(e)return e;function t(){const e=aa().servers;if(!e)throw new Error("[Runtime.host] No managed-process (servers) surface is registered. This is only available on hosts that can spawn processes (e.g. Electron); a browser host does not provide it.");return e}function n(){const e=aa().mcpServer;if(!e)throw new Error("[Runtime.host] No inbound MCP server surface is registered. This is only available on hosts that can open a local listener (e.g. Electron); a browser host does not provide it.");return e}const r={start:e=>n().start(e),stop:()=>n().stop(),status:()=>n().status(),onRequest:e=>n().onRequest(e),reply:(e,t)=>n().reply(e,t)};return{dataDir:()=>aa().dataDir(),dataFs:{list:(e,t)=>aa().dataFs.list(e,t),readFile:e=>aa().dataFs.readFile(e),stat:e=>aa().dataFs.stat(e),mkdir:(e,t)=>aa().dataFs.mkdir(e,t),deleteFile:e=>aa().dataFs.deleteFile(e),deleteFolder:e=>aa().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=aa().dataFs;return"function"!=typeof r.readBytes?Promise.reject(new Error("[Runtime.host] readBytes is not supported by this host (only hosts with a real filesystem, e.g. Electron, provide it).")):r.readBytes(e,t,n)},readStrided:(e,t)=>{const n=aa().dataFs;return"function"!=typeof n.readStrided?Promise.reject(new Error("[Runtime.host] readStrided is not supported by this host (only hosts with a real filesystem, e.g. Electron, provide it).")):n.readStrided(e,t)}},servers:{start:e=>t().start(e),stop:e=>t().stop(e),status:e=>t().status(e)},http:{requestJson:e=>function(){const e=aa().http;if(!e)throw new Error("[Runtime.host] No JSON-over-HTTP (http) surface is registered. This is only available on hosts with network access (e.g. Electron); a browser host does not provide it.");return e}().requestJson(e)},get mcpServer(){return sa?.mcpServer?r:void 0}}}(qu?.host),id=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&qc(e);return{set:(e,t)=>Fc.get().set(e,t),get:e=>Fc.get().get(e),delete:e=>Fc.get().delete(e),list:()=>Fc.get().list(),__punicaWrappedSecretsFacade:!0}}(qu?.secrets);console.log("[Runtime] Facades created"),function(){bu({name:"fs.readFile",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Tc),bu({name:"fs.writeFile",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),ua.registerProvider(new Nc),bu({name:"fs.listFiles",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Mc),bu({name:"fs.stat",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"object",required:["size","mtimeMs","ctimeMs","isDirectory","isSymlink"],properties:{size:{type:"number"},mtimeMs:{type:"number"},ctimeMs:{type:"number"},mode:{type:"number"},isDirectory:{type:"boolean"},isSymlink:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Dc),bu({name:"fs.exists",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"boolean"},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Pc),bu({name:"fs.copy",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["src","dst"],properties:{src:{type:"string"},dst:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),ua.registerProvider(new Oc),bu({name:"fs.mkdir",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),ua.registerProvider(new Rc),bu({name:"fs.list",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new jc),bu({name:"fs.history",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Lc),bu({name:"fs.readAtVersion",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path","versionId"],properties:{path:{type:"string"},versionId:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new $c),bu({name:"secrets.get",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"}}},outputSchema:{type:["string","null"]},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3}}),ua.registerProvider(new zc),bu({name:"secrets.set",version:"1.0.0",sideEffect:"write",risk:"high",permissions:[],inputSchema:{type:"object",required:["name","value"],properties:{name:{type:"string"},value:{type:"string"}}},outputSchema:{type:"null"},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3,idempotency:"required"}}),ua.registerProvider(new Uc),bu({name:"llm.chat",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),ua.registerProvider(new Wc),bu({name:"llm.chatStream",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),ua.registerProvider(new Kc),bu({name:"llm.plan",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["query"],properties:{query:{type:"string"},capabilities:{type:"array"}}},outputSchema:{type:"object",properties:{ok:{type:"boolean"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),ua.registerProvider(new Hc),bu({name:"llm.invoke",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string"},userPrompt:{type:"string"},context:{type:"object"},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"},stream:{type:"boolean"},skipCache:{type:"boolean"},skipFallback:{type:"boolean"}}}}},outputSchema:{type:"object",properties:{ok:{type:"boolean"},result:{type:"string"},parsed:{}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),ua.registerProvider(new Gc),bu({name:"search.query",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["q"],properties:{q:{type:"string"},limit:{type:"number"}}},outputSchema:{type:"object",properties:{results:{type:"array"}}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Yc),bu({name:"vcs.status",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Jc),bu({name:"vcs.commit",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["message"],properties:{message:{type:"string"},all:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),ua.registerProvider(new Zc),bu({name:"workspace.readFile",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Qc),bu({name:"workspace.writeFile",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),ua.registerProvider(new Xc),bu({name:"workspace.listFiles",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object"}}}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new el),bu({name:"terminals.create",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",properties:{title:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),ua.registerProvider(new tl),bu({name:"terminals.send",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["id","text"],properties:{id:{type:"string"},text:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:5e3,idempotency:"optional"}}),ua.registerProvider(new nl),bu({name:"tasks.runCommand",version:"1.0.0",sideEffect:"write",risk:"high",permissions:[],inputSchema:{type:"object",required:["command"],properties:{command:{type:"string"},args:{type:"array"},cwd:{type:"string"},env:{type:"object"}}},outputSchema:{type:"object",properties:{exitCode:{type:["number","null"]},stdout:{type:"string"},stderr:{type:"string"}}},defaults:{timeoutMs:3e5,concurrency:{key:"workspace:{workspaceId}",max:3},idempotency:"required"}}),ua.registerProvider(new rl),bu({name:"flow.migrate",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["document","targetVersion"],properties:{document:{type:"object"},targetVersion:{type:"string"},policy:{type:"string",enum:["auto-migrate","warn","reject"]}}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new il),bu({name:"flow.runSubflow",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["spec"],properties:{spec:{type:"object"},workspaceId:{type:"string"},input:{},parentRunId:{type:"string"},parentTraceId:{type:"string"},parentDepth:{type:"number",minimum:0,maximum:8},filePathOrUri:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:3e5,idempotency:"optional"}}),ua.registerProvider(new sl),bu({name:ol,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{origin:{type:["string","array"]},extension:{type:"string"},tags:{type:["string","array"]},risk:{type:["string","array"]},sideEffects:{type:["string","array"]}}},outputSchema:{type:"object",required:["capabilities","count"],properties:{capabilities:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new al),bu({name:fl,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{version:{type:"string"},filter:{type:"object"},mode:{type:"string",enum:["full","ai-tools","summary"]}}},outputSchema:{type:"object",required:["schemaVersion","generatedAt","capabilities","count"],properties:{schemaVersion:{type:"string"},generatedAt:{type:"number"},capabilities:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new ml),bu({name:kl,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["intent"],properties:{intent:{type:"string"},limit:{type:"number"}}},outputSchema:{type:"object",required:["recommendations","path","count"],properties:{recommendations:{type:"array"},path:{type:"string"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new Il),bu({name:Al,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",description:"What you need to do, in natural language."},limit:{type:"number"}}},outputSchema:{type:"object",required:["results","count"],properties:{results:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new xl),bu({name:El,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},minItems:1,maxItems:16,description:"Capability ids to load full definitions for."}}},outputSchema:{type:"object",required:["tools","missing"],properties:{tools:{type:"array"},missing:{type:"array",items:{type:"string"}}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new _l);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Tl("ai.session.create",{properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),Tl("ai.session.list",{properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),Tl("ai.session.get",{required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),Tl("ai.session.rename",{required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),Tl("ai.session.archive",{required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),Tl("ai.session.delete",{risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())bu(e);for(const e of[new Nl,new Ml,new Dl,new Pl,new Ol,new Rl])ua.registerProvider(e);bu({name:Yl,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{capabilityId:{type:"string"}}},outputSchema:{type:"object",required:["results","ok","count"],properties:{results:{type:"array"},ok:{type:"boolean"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new Jl),bu({name:eu,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{filter:{type:"object"}}},outputSchema:{type:"object",required:["tools","count"],properties:{tools:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new ru),bu({name:tu,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"},arguments:{type:"object"}}},outputSchema:{type:"object",required:["content"],properties:{content:{type:"array"},isError:{type:"boolean"}}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new iu),bu({name:su,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["viewId","revealed"],properties:{viewId:{type:"string"},revealed:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new pu),bu({name:ou,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"}}},outputSchema:{type:"object",required:["viewId","hidden"],properties:{viewId:{type:"string"},hidden:{type:"boolean"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new hu),bu({name:au,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",required:["views"],properties:{views:{type:"array"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new fu),bu({name:cu,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["viewId","visible"],properties:{viewId:{type:"string"},visible:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new mu),bu({name:lu,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["slot"],properties:{slot:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["slot","visible"],properties:{slot:{type:"string"},visible:{type:"boolean"},viewId:{type:"string"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new yu)}(),console.log("[Runtime] Capabilities registered");const sd={lifecyclePhase:qu?.lifecyclePhase??"bootstrapping",fs:zu,fileOpeners:qu?.fileOpeners??io,search:Uu,vcs:Vu,terminals:Wu,debug:Ku,tasks:Gu,workspace:Hu,resources:Yu,secrets:id,llm:Ju,compute:Zu,datasets:Qu,models:Xu,modelRuntimes:ed,inference:td,vectors:nd,host:rd,capabilities:{gateway:_c,unifiedRegistry:Ia,logTrinityCatalog:ku,docs:{formatCapabilityMarkdown:function(e){const t=e.definition,n=[];n.push(`# \`${t.id}\``),n.push(""),n.push(function(e){const t=e.definition,n=[];n.push(`**Origin:** ${e.origin}`),n.push(`**Version:** ${t.version}`);const r=t.policy?.risk??"—",i=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${i}`);const s=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";return n.push(`**Side effects:** ${s}`),n.join(" · ")}(e)),n.push("");const r=t.description??t.title;r&&r.length>0&&(n.push(r),n.push("")),void 0!==t.inputs?.schema&&(n.push("## Input schema"),n.push(""),n.push("```json"),n.push(Su(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Su(t.outputs.schema)),n.push("```"),n.push("")),t.tags&&t.tags.length>0&&(n.push("## Tags"),n.push(""),n.push(t.tags.join(", ")),n.push(""));const i=t.requires;if(i&&i.length>0){n.push("## Requires"),n.push("");for(const e of i)n.push(`- \`${e}\``);n.push("")}if(t.deprecated){n.push("## Deprecated"),n.push("");const e=[];e.push(`**Since:** ${t.deprecated.since}`),t.deprecated.reason&&e.push(`— ${t.deprecated.reason}`),n.push(e.join(" ")),t.deprecated.replacement&&(n.push(""),n.push(`**Replacement:** \`${t.deprecated.replacement}\``)),n.push("")}const s=function(e){const t=e.metadata;if(!t)return;const n=[];t.extensionName&&n.push(`- Extension: \`${t.extensionName}\``);t.productId&&n.push(`- Product: \`${t.productId}\``);t.packageRoot&&n.push(`- Manifest: \`${t.packageRoot}\``);return n.length>0?n.join("\n"):void 0}(e);for(s&&(n.push("## Source"),n.push(""),n.push(s),n.push(""));n.length>1&&""===n[n.length-1];)n.pop();return n.join("\n")+"\n"},formatCapabilitiesIndex:function(e){const t=[];t.push("# Capability Reference"),t.push(""),t.push("Auto-generated from the substrate's unified capability registry."),t.push("Run `npm run docs:capabilities` to regenerate — CI gates drift."),t.push("");const n=function(e){const t=new Map;for(const n of e){const e=t.get(n.origin)??[];e.push(n),t.set(n.origin,e)}for(const e of t.values())e.sort((e,t)=>e.definition.id.localeCompare(t.definition.id));return t}(e),r=["core","extension","instruction-class","ivy-node"];for(const e of r){const r=n.get(e);if(r&&0!==r.length){t.push(`## ${Eu(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(Au(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:_u,connect:e=>Pu.connect(e),disconnect:e=>Pu.disconnect(e),listServers:()=>Pu.listServers(),listTools:e=>Pu.listTools(e),callTool:(e,t,n)=>Pu.callTool(e,t,n)},setFsProvider:function(e){La.set(e),e&&bo({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:Co,setComputeProvider:function(e){Mo().registerProvider(e)},setComputeRuntime:function(e){Mo().registerLanguageRuntime(e)},setDatasetProvider:function(e){Uo().registerProvider(e)},setModelProvider:function(e){Go().registerProvider(e)},setModelRuntime:function(e){Zo().register(e)},setHostProvider:function(e){sa=e},setVectorsProvider:function(e){ra=e},setSearchProvider:function(e){oo=e},setWorkspaceProvider:ko,setTerminalProvider:function(e){co=e},setDebugProvider:function(e){lo=e},setVcsProvider:function(e){uo=e},setResourcesProvider:function(e){so=e},setTasksProvider:function(e){ao=e},setSecretsProvider:qc};class od{#bt;constructor(e){this.#bt=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#bt);n?e(n):t(new Error("Extension not found"))})}}let ad=class{#wt;constructor(e){this.#wt=e}async execute(){return await this.#wt.execute()}},cd=class extends ad{constructor(e){super(e)}async execute(){return await super.execute()}},ld=class extends ad{constructor(e){super(e)}async execute(){try{const e=await super.execute(),t=`${e.moduleURL}${e.main}`,n=(await import(/* webpackIgnore: true */`${t}`)).default;return e.module=n,e}catch(e){if(e instanceof Error)throw e;throw new Error(String(e))}}},ud=class extends ad{constructor(e){super(e)}async execute(){return await super.execute()}};const dd=Symbol.for("yaml.alias"),pd=Symbol.for("yaml.document"),hd=Symbol.for("yaml.map"),fd=Symbol.for("yaml.pair"),md=Symbol.for("yaml.scalar"),gd=Symbol.for("yaml.seq"),yd=Symbol.for("yaml.node.type"),bd=e=>!!e&&"object"==typeof e&&e[yd]===dd,wd=e=>!!e&&"object"==typeof e&&e[yd]===pd,vd=e=>!!e&&"object"==typeof e&&e[yd]===hd,kd=e=>!!e&&"object"==typeof e&&e[yd]===fd,Id=e=>!!e&&"object"==typeof e&&e[yd]===md,Ed=e=>!!e&&"object"==typeof e&&e[yd]===gd;function Ad(e){if(e&&"object"==typeof e)switch(e[yd]){case hd:case gd:return!0}return!1}function Sd(e){if(e&&"object"==typeof e)switch(e[yd]){case dd:case hd:case md:case gd:return!0}return!1}const _d=Symbol("break visit"),xd=Symbol("skip children"),Cd=Symbol("remove node");function Td(e,t){const n=Pd(t);if(wd(e)){Nd(null,e.contents,n,Object.freeze([e]))===Cd&&(e.contents=null)}else Nd(null,e,n,Object.freeze([]))}function Nd(e,t,n,r){const i=Od(e,t,n,r);if(Sd(i)||kd(i))return Rd(e,r,i),Nd(e,i,n,r);if("symbol"!=typeof i)if(Ad(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Nd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===_d)return _d;i===Cd&&(t.items.splice(e,1),e-=1)}}}else if(kd(t)){r=Object.freeze(r.concat(t));const e=Nd("key",t.key,n,r);if(e===_d)return _d;e===Cd&&(t.key=null);const i=Nd("value",t.value,n,r);if(i===_d)return _d;i===Cd&&(t.value=null)}return i}async function Md(e,t){const n=Pd(t);if(wd(e)){await Dd(null,e.contents,n,Object.freeze([e]))===Cd&&(e.contents=null)}else await Dd(null,e,n,Object.freeze([]))}async function Dd(e,t,n,r){const i=await Od(e,t,n,r);if(Sd(i)||kd(i))return Rd(e,r,i),Dd(e,i,n,r);if("symbol"!=typeof i)if(Ad(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await Dd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===_d)return _d;i===Cd&&(t.items.splice(e,1),e-=1)}}}else if(kd(t)){r=Object.freeze(r.concat(t));const e=await Dd("key",t.key,n,r);if(e===_d)return _d;e===Cd&&(t.key=null);const i=await Dd("value",t.value,n,r);if(i===_d)return _d;i===Cd&&(t.value=null)}return i}function Pd(e){return"object"==typeof e&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Od(e,t,n,r){return"function"==typeof n?n(e,t,r):vd(t)?n.Map?.(e,t,r):Ed(t)?n.Seq?.(e,t,r):kd(t)?n.Pair?.(e,t,r):Id(t)?n.Scalar?.(e,t,r):bd(t)?n.Alias?.(e,t,r):void 0}function Rd(e,t,n){const r=t[t.length-1];if(Ad(r))r.items[e]=n;else if(kd(r))"key"===e?r.key=n:r.value=n;else{if(!wd(r)){const e=bd(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Td.BREAK=_d,Td.SKIP=xd,Td.REMOVE=Cd,Md.BREAK=_d,Md.SKIP=xd,Md.REMOVE=Cd;const Ld={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},$d=e=>e.replace(/[!,[\]{}]/g,e=>Ld[e]);class jd{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},jd.defaultYaml,e),this.tags=Object.assign({},jd.defaultTags,t)}clone(){const e=new jd(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new jd(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:jd.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},jd.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:jd.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},jd.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(2!==n.length&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[e,r]=n;return this.tags[e]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==n.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=n;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const n=e.slice(2,-1);return"!"===n||"!!"===n?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),n)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return"!"===n?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+$d(e.substring(n.length));return"!"===e[0]?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&Sd(e.contents)){const t={};Td(e.contents,(e,n)=>{Sd(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(const[i,s]of n)"!!"===i&&"tag:yaml.org,2002:"===s||e&&!r.some(e=>e.startsWith(s))||t.push(`%TAG ${i} ${s}`);return t.join("\n")}}function Fd(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);throw new Error(`Anchor must not contain whitespace or control characters: ${t}`)}return!0}function Bd(e){const t=new Set;return Td(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function qd(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function zd(e,t,n,r){if(r&&"object"==typeof r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){const n=r[t],i=zd(e,r,String(t),n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),i=zd(e,r,t,n);void 0===i?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(const t of Array.from(r)){const n=zd(e,r,t,t);void 0===n?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(const[t,n]of Object.entries(r)){const i=zd(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function Ud(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Ud(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Id(r=e)&&!Ad(r)||!r.anchor))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=e=>{i.res=e,delete n.onCreate};const s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}var r;return"bigint"!=typeof e||n?.keep?e:Number(e)}jd.defaultYaml={explicit:!1,version:"1.2"},jd.defaultTags={"!!":"tag:yaml.org,2002:"};class Vd{constructor(e){Object.defineProperty(this,yd,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!wd(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=Ud(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?zd(i,{"":o},"",o):o}}class Wd extends Vd{constructor(e){super(dd),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Td(e,{Node:(e,n)=>{if(n===this)return Td.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,s=this.resolve(r);if(!s){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(s);if(o||(Ud(s,null,t),o=n.get(s)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(i>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=Kd(r,s,n)),o.count*o.aliasCount>i)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return o.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(Fd(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${r} `}return r}}function Kd(e,t,n){if(bd(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Ad(t)){let r=0;for(const i of t.items){const t=Kd(e,i,n);t>r&&(r=t)}return r}if(kd(t)){const r=Kd(e,t.key,n),i=Kd(e,t.value,n);return Math.max(r,i)}return 1}const Gd=e=>!e||"function"!=typeof e&&"object"!=typeof e;class Hd extends Vd{constructor(e){super(md),this.value=e}toJSON(e,t){return t?.keep?this.value:Ud(this.value,e,t)}toString(){return String(this.value)}}Hd.BLOCK_FOLDED="BLOCK_FOLDED",Hd.BLOCK_LITERAL="BLOCK_LITERAL",Hd.PLAIN="PLAIN",Hd.QUOTE_DOUBLE="QUOTE_DOUBLE",Hd.QUOTE_SINGLE="QUOTE_SINGLE";function Yd(e,t,n){if(wd(e)&&(e=e.contents),Sd(e))return e;if(kd(e)){const t=n.schema[hd].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||"undefined"!=typeof BigInt&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n;let c;if(r&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=i(e)),new Wd(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t="tag:yaml.org,2002:"+t.slice(2));let l=function(e,t,n){if(t){const e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}(e,t,o.tags);if(!l){if(e&&"function"==typeof e.toJSON&&(e=e.toJSON()),!e||"object"!=typeof e){const t=new Hd(e);return c&&(c.node=t),t}l=e instanceof Map?o[hd]:Symbol.iterator in Object(e)?o[gd]:o[hd]}s&&(s(l),delete n.onTagObj);const u=l?.createNode?l.createNode(n.schema,e,n):"function"==typeof l?.nodeClass?.from?l.nodeClass.from(n.schema,e,n):new Hd(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Jd(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){const n=t[e];if("number"==typeof n&&Number.isInteger(n)&&n>=0){const e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Yd(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const Zd=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class Qd extends Vd{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>Sd(t)||kd(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Zd(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Ad(i))i.addIn(r,t);else{if(void 0!==i||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,Jd(this.schema,r,t))}}}deleteIn(e){const[t,...n]=e;if(0===n.length)return this.delete(t);const r=this.get(t,!0);if(Ad(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return 0===r.length?!t&&Id(i)?i.value:i:Ad(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!kd(t))return!1;const n=t.value;return null==n||e&&Id(n)&&null==n.value&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(0===n.length)return this.has(t);const r=this.get(t,!0);return!!Ad(r)&&r.hasIn(n)}setIn(e,t){const[n,...r]=e;if(0===r.length)this.set(n,t);else{const e=this.get(n,!0);if(Ad(e))e.setIn(r,t);else{if(void 0!==e||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,Jd(this.schema,r,t))}}}}Qd.maxFlowStringSingleLineLength=60;const Xd=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ep(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const tp=(e,t,n)=>e.endsWith("\n")?ep(n,t):n.includes("\n")?"\n"+ep(n,t):(e.endsWith(" ")?"":" ")+n,np="flow",rp="block",ip="quoted";function sp(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let d,p,h=i-t.length;"number"==typeof r&&(r>i-Math.max(2,s)?l.push(0):h=i-r);let f=!1,m=-1,g=-1,y=-1;n===rp&&(m=op(e,m,t.length),-1!==m&&(h=m+c));for(let r;r=e[m+=1];){if(n===ip&&"\\"===r){switch(g=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if("\n"===r)n===rp&&(m=op(e,m,t.length)),h=m+t.length+c,d=void 0;else{if(" "===r&&p&&" "!==p&&"\n"!==p&&"\t"!==p){const t=e[m+1];t&&" "!==t&&"\n"!==t&&"\t"!==t&&(d=m)}if(m>=h)if(d)l.push(d),h=d+c,d=void 0;else if(n===ip){for(;" "===p||"\t"===p;)p=r,r=e[m+=1],f=!0;const t=m>y+1?m-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,h=t+c,d=void 0}else f=!0}p=r}if(f&&a&&a(),0===l.length)return e;o&&o();let b=e.slice(0,l[0]);for(let r=0;r<l.length;++r){const i=l[r],s=l[r+1]||e.length;0===i?b=`\n${t}${e.slice(0,s)}`:(n===ip&&u[i]&&(b+=`${e[i]}\\`),b+=`\n${t}${e.slice(i+1,s)}`)}return b}function op(e,t,n){let r=t,i=t+1,s=e[i];for(;" "===s||"\t"===s;)if(t<i+n)s=e[++t];else{do{s=e[++t]}while(s&&"\n"!==s);r=t,i=t+1,s=e[i]}return r}const ap=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),cp=e=>/^(%|---|\.\.\.)/m.test(e);function lp(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(cp(e)?" ":"");let o="",a=0;for(let e=0,t=n[e];t;t=n[++e])if(" "===t&&"\\"===n[e+1]&&"n"===n[e+2]&&(o+=n.slice(a,e)+"\\ ",e+=1,a=e,t="\\"),"\\"===t)switch(n[e+1]){case"u":{o+=n.slice(a,e);const t=n.substr(e+2,4);switch(t){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===t.substr(0,2)?o+="\\x"+t.substr(2):o+=n.substr(e,6)}e+=5,a=e+1}break;case"n":if(r||'"'===n[e+2]||n.length<i)e+=1;else{for(o+=n.slice(a,e)+"\n\n";"\\"===n[e+2]&&"n"===n[e+3]&&'"'!==n[e+4];)o+="\n",e+=2;o+=s," "===n[e+2]&&(o+="\\"),e+=1,a=e+1}break;default:e+=1}return o=a?o+n.slice(a):n,r?o:sp(o,s,ip,ap(t,!1))}function up(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return lp(e,t);const n=t.indent||(cp(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:sp(r,n,np,ap(t,!1))}function dp(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=lp;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?up:i&&!t?lp:n?up:lp}return r(e,t)}let pp;try{pp=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{pp=/\n+(?!\n|$)/g}function hp({comment:e,type:t,value:n},r,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return dp(n,r);const l=r.indent||(r.forceBlockIndent||cp(n)?" ":""),u="literal"===o||"folded"!==o&&t!==Hd.BLOCK_FOLDED&&(t===Hd.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}(n,c,l.length));if(!n)return u?"|\n":">\n";let d,p;for(p=n.length;p>0;--p){const e=n[p-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let h=n.substring(p);const f=h.indexOf("\n");-1===f?d="-":n===h||f!==h.length-1?(d="+",s&&s()):d="",h&&(n=n.slice(0,-h.length),"\n"===h[h.length-1]&&(h=h.slice(0,-1)),h=h.replace(pp,`$&${l}`));let m,g=!1,y=-1;for(m=0;m<n.length;++m){const e=n[m];if(" "===e)g=!0;else{if("\n"!==e)break;y=m}}let b=n.substring(0,y<m?y+1:m);b&&(n=n.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let w=(u?"|":">")+(g?l?"2":"1":"")+d;if(e&&(w+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),u)return`${w}\n${l}${b}${n=n.replace(/\n+/g,`$&${l}`)}${h}`;return`${w}\n${l}${sp(`${b}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${h}`,l,rp,ap(r,!0))}`}function fp(e,t,n,r){const{implicitKey:i,inFlow:s}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Hd.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Hd.QUOTE_DOUBLE);const c=e=>{switch(e){case Hd.BLOCK_FOLDED:case Hd.BLOCK_LITERAL:return i||s?dp(o.value,t):hp(o,t,n,r);case Hd.QUOTE_DOUBLE:return lp(o.value,t);case Hd.QUOTE_SINGLE:return up(o.value,t);case Hd.PLAIN:return function(e,t,n,r){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&s.includes("\n")||u&&/[[\]{},]/.test(s))return dp(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?dp(s,t):hp(e,t,n,r);if(!a&&!u&&i!==Hd.PLAIN&&s.includes("\n"))return hp(e,t,n,r);if(cp(s)){if(""===c)return t.forceBlockIndent=!0,hp(e,t,n,r);if(a&&c===l)return dp(s,t)}const d=s.replace(/\n+/g,`$&\n${c}`);if(o){const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return dp(s,t)}return a?d:sp(d,c,np,ap(t,!1))}(o,t,n,r);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}function mp(e,t){const n=Object.assign({blockQuote:!0,commentString:Xd,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof n.indent?" ".repeat(n.indent):" ",inFlow:r,options:n}}function gp(e,t,n,r){if(kd(e))return e.toString(t,n,r);if(bd(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=Sd(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i||(i=function(e,t){if(t.tag){const n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(Id(t)){r=t.value;const i=e.filter(e=>e.identify?.(r));n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n)throw new Error(`Tag not resolved for ${r?.constructor?.name??typeof r} value`);return n}(t.doc.schema.tags,s));const o=function(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const i=[],s=(Id(e)||Ad(e))&&e.anchor;s&&Fd(s)&&(n.add(s),i.push(`&${s}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&i.push(r.directives.tagString(o)),i.join(" ")}(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof i.stringify?i.stringify(s,t,n,r):Id(s)?fp(s,t,n,r):s.toString(t,n,r);return o?Id(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function yp(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function bp(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&wp(n))if(r=bd(r)?r.resolve(e.doc):r,Ed(r))for(const n of r.items)vp(e,t,n);else if(Array.isArray(r))for(const n of r)vp(e,t,n);else vp(e,t,r);else{const i=Ud(n,"",e);if(t instanceof Map)t.set(i,Ud(r,i,e));else if(t instanceof Set)t.add(i);else{const s=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(Sd(e)&&n?.doc){const t=mp(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;const r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+'..."'),yp(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}(n,i,e),o=Ud(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const wp=e=>"<<"===e||Id(e)&&"<<"===e.value&&(!e.type||e.type===Hd.PLAIN);function vp(e,t,n){const r=e&&bd(n)?n.resolve(e.doc):n;if(!vd(r))throw new Error("Merge sources must be maps or map aliases");const i=r.toJSON(null,e,Map);for(const[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function kp(e,t,n){const r=Yd(e,void 0,n),i=Yd(t,void 0,n);return new Ip(r,i)}class Ip{constructor(e,t=null){Object.defineProperty(this,yd,{value:fd}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Sd(t)&&(t=t.clone(e)),Sd(n)&&(n=n.clone(e)),new Ip(t,n)}toJSON(e,t){return bp(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,r,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n;let p=Sd(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Ad(e)||!Sd(e)&&"object"==typeof e)throw new Error("With simple keys, collection cannot be used as a key value")}let h=!d&&(!e||p&&null==t&&!n.inFlow||Ad(e)||(Id(e)?e.type===Hd.BLOCK_FOLDED||e.type===Hd.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(d||!s),indent:a+c});let f,m,g,y=!1,b=!1,w=gp(e,n,()=>y=!0,()=>b=!0);if(!h&&!n.inFlow&&w.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||null==t)return y&&r&&r(),""===w?"?":h?`? ${w}`:w}else if(s&&!d||null==t&&h)return w=`? ${w}`,p&&!y?w+=tp(w,n.indent,l(p)):b&&i&&i(),w;y&&(p=null),h?(p&&(w+=tp(w,n.indent,l(p))),w=`? ${w}\n${a}:`):(w=`${w}:`,p&&(w+=tp(w,n.indent,l(p)))),Sd(t)?(f=!!t.spaceBefore,m=t.commentBefore,g=t.comment):(f=!1,m=null,g=null,t&&"object"==typeof t&&(t=o.createNode(t))),n.implicitKey=!1,h||p||!Id(t)||(n.indentAtStart=w.length+1),b=!1,u||!(c.length>=2)||n.inFlow||h||!Ed(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let v=!1;const k=gp(t,n,()=>v=!0,()=>b=!0);let I=" ";if(p||f||m)I=f?"\n":"",m&&(I+=`\n${ep(l(m),n.indent)}`),""!==k||n.inFlow?I+=`\n${n.indent}`:"\n"===I&&(I="\n\n");else if(!h&&Ad(t)){const e=k[0],r=k.indexOf("\n"),i=-1!==r,s=n.inFlow??t.flow??0===t.items.length;if(i||!s){let t=!1;if(i&&("&"===e||"!"===e)){let n=k.indexOf(" ");"&"===e&&-1!==n&&n<r&&"!"===k[n+1]&&(n=k.indexOf(" ",n+1)),(-1===n||r<n)&&(t=!0)}t||(I=`\n${n.indent}`)}}else""!==k&&"\n"!==k[0]||(I="");return w+=I+k,n.inFlow?v&&r&&r():g&&!v?w+=tp(w,n.indent,l(g)):b&&i&&i(),w}(this,e,t,n):JSON.stringify(this)}}function Ep(e,t,n){return(t.inFlow??e.flow?Sp:Ap)(e,t,n)}function Ap({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null});let d=!1;const p=[];for(let e=0;e<t.length;++e){const i=t[e];let o=null;if(Sd(i))!d&&i.spaceBefore&&p.push(""),_p(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(kd(i)){const e=Sd(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),_p(n,p,e.commentBefore,d))}d=!1;let a=gp(i,u,()=>o=null,()=>d=!0);o&&(a+=tp(a,s,l(o))),d&&o&&(d=!1),p.push(r+a)}let h;if(0===p.length)h=i.start+i.end;else{h=p[0];for(let e=1;e<p.length;++e){const t=p[e];h+=t?`\n${c}${t}`:"\n"}}return e?(h+="\n"+ep(l(e),c),a&&a()):d&&o&&o(),h}function Sp({items:e},t,{flowChars:n,itemIndent:r}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;r+=s;const c=Object.assign({},t,{indent:r,inFlow:!0,type:null});let l=!1,u=0;const d=[];for(let n=0;n<e.length;++n){const i=e[n];let s=null;if(Sd(i))i.spaceBefore&&d.push(""),_p(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(kd(i)){const e=Sd(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),_p(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Sd(i.value)?i.value:null;n?(n.comment&&(s=n.comment),n.commentBefore&&(l=!0)):null==i.value&&e?.comment&&(s=e.comment)}s&&(l=!0);let o=gp(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=tp(o,r,a(s))),!l&&(d.length>u||o.includes("\n"))&&(l=!0),d.push(o),u=d.length}const{start:p,end:h}=n;if(0===d.length)return p+h;if(!l){const e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=p;for(const t of d)e+=t?`\n${s}${i}${t}`:"\n";return`${e}\n${i}${h}`}return`${p}${o}${d.join(" ")}${o}${h}`}function _p({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=ep(t(r),e);n.push(i.trimStart())}}function xp(e,t){const n=Id(t)?t.value:t;for(const r of e)if(kd(r)){if(r.key===t||r.key===n)return r;if(Id(r.key)&&r.key.value===n)return r}}class Cp extends Qd{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(hd,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:i}=n,s=new this(e),o=(e,o)=>{if("function"==typeof i)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(void 0!==o||r)&&s.items.push(kp(e,o,n))};if(t instanceof Map)for(const[e,n]of t)o(e,n);else if(t&&"object"==typeof t)for(const e of Object.keys(t))o(e,t[e]);return"function"==typeof e.sortMapEntries&&s.items.sort(e.sortMapEntries),s}add(e,t){let n;n=kd(e)?e:e&&"object"==typeof e&&"key"in e?new Ip(e.key,e.value):new Ip(e,e?.value);const r=xp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Id(r.value)&&Gd(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const e=this.items.findIndex(e=>i(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=xp(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=xp(this.items,e),r=n?.value;return(!t&&Id(r)?r.value:r)??void 0}has(e){return!!xp(this.items,e)}set(e,t){this.add(new Ip(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const e of this.items)bp(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!kd(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ep(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Tp={collection:"map",default:!0,nodeClass:Cp,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(vd(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Cp.from(e,t,n)};class Np extends Qd{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(gd,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Mp(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Mp(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Id(r)?r.value:r}has(e){const t=Mp(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Mp(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Id(r)&&Gd(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const e of this.items)n.push(Ud(e,String(r++),t));return n}toString(e,t,n){return e?Ep(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let s of t){if("function"==typeof r){const n=t instanceof Set?s:String(e++);s=r.call(t,n,s)}i.items.push(Yd(s,void 0,n))}}return i}}function Mp(e){let t=Id(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const Dp={collection:"seq",default:!0,nodeClass:Np,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Ed(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Np.from(e,t,n)},Pp={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>fp(e,t=Object.assign({actualString:!0},t),n,r)},Op={identify:e=>null==e,createNode:()=>new Hd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Hd(null),stringify:({source:e},t)=>"string"==typeof e&&Op.test.test(e)?e:t.options.nullStr},Rp={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Hd("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Rp.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Lp({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const i="number"==typeof r?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(s)){let e=s.indexOf(".");e<0&&(e=s.length,s+=".");let n=t-(s.length-e-1);for(;n-- >0;)s+="0"}return s}const $p={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Lp},jp={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():Lp(e)}},Fp={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const t=new Hd(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Lp},Bp=e=>"bigint"==typeof e||Number.isInteger(e),qp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function zp(e,t,n){const{value:r}=e;return Bp(r)&&r>=0?n+r.toString(t):Lp(e)}const Up={identify:e=>Bp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>qp(e,2,8,n),stringify:e=>zp(e,8,"0o")},Vp={identify:Bp,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>qp(e,0,10,n),stringify:Lp},Wp={identify:e=>Bp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>qp(e,2,16,n),stringify:e=>zp(e,16,"0x")},Kp=[Tp,Dp,Pp,Op,Rp,Up,Vp,Wp,$p,jp,Fp];function Gp(e){return"bigint"==typeof e||Number.isInteger(e)}const Hp=({value:e})=>JSON.stringify(e),Yp=[Tp,Dp].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Hp},{identify:e=>null==e,createNode:()=>new Hd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Hp},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:Hp},{identify:Gp,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Gp(e)?e.toString():JSON.stringify(e)},{identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Hp}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),Jp={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if("function"==typeof Buffer)return Buffer.from(e,"base64");if("function"==typeof atob){const t=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,i,s){const o=n;let a;if("function"==typeof Buffer)a=o instanceof Buffer?o.toString("base64"):Buffer.from(o.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);a=btoa(e)}}if(t||(t=Hd.BLOCK_LITERAL),t!==Hd.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(a.length/e),i=new Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=a.substr(r,e);a=i.join(t===Hd.BLOCK_LITERAL?"\n":" ")}return fp({comment:e,type:t,value:a},r,i,s)}};function Zp(e,t){if(Ed(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!kd(r)){if(vd(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Ip(new Hd(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){const t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=kd(r)?r:new Ip(r)}}else t("Expected a sequence for this tag");return e}function Qp(e,t,n){const{replacer:r}=n,i=new Np(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){let o,a;if("function"==typeof r&&(e=r.call(t,String(s++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);o=e[0],a=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);o=t[0],a=e[o]}else o=e;i.items.push(kp(o,a,n))}return i}const Xp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zp,createNode:Qp};class eh extends Np{constructor(){super(),this.add=Cp.prototype.add.bind(this),this.delete=Cp.prototype.delete.bind(this),this.get=Cp.prototype.get.bind(this),this.has=Cp.prototype.has.bind(this),this.set=Cp.prototype.set.bind(this),this.tag=eh.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const e of this.items){let r,i;if(kd(e)?(r=Ud(e.key,"",t),i=Ud(e.value,r,t)):r=Ud(e,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,i)}return n}static from(e,t,n){const r=Qp(e,t,n),i=new this;return i.items=r.items,i}}eh.tag="tag:yaml.org,2002:omap";const th={collection:"seq",identify:e=>e instanceof Map,nodeClass:eh,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=Zp(e,t),r=[];for(const{key:e}of n.items)Id(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new eh,n)},createNode:(e,t,n)=>eh.from(e,t,n)};function nh({value:e,source:t},n){return t&&(e?rh:ih).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const rh={identify:e=>!0===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hd(!0),stringify:nh},ih={identify:e=>!1===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hd(!1),stringify:nh},sh={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Lp},oh={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():Lp(e)}},ah={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){const t=new Hd(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(-1!==n){const r=e.substring(n+1).replace(/_/g,"");"0"===r[r.length-1]&&(t.minFractionDigits=r.length)}return t},stringify:Lp},ch=e=>"bigint"==typeof e||Number.isInteger(e);function lh(e,t,n,{intAsBigInt:r}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const s=parseInt(e,n);return"-"===i?-1*s:s}function uh(e,t,n){const{value:r}=e;if(ch(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return Lp(e)}const dh={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>lh(e,2,2,n),stringify:e=>uh(e,2,"0b")},ph={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>lh(e,1,8,n),stringify:e=>uh(e,8,"0")},hh={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>lh(e,0,10,n),stringify:Lp},fh={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>lh(e,2,16,n),stringify:e=>uh(e,16,"0x")};class mh extends Cp{constructor(e){super(e),this.tag=mh.tag}add(e){let t;t=kd(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Ip(e.key,null):new Ip(e,null);xp(this.items,t.key)||this.items.push(t)}get(e,t){const n=xp(this.items,e);return!t&&kd(n)?Id(n.key)?n.key.value:n.key:n}set(e,t){if("boolean"!=typeof t)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof t);const n=xp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ip(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof r&&(e=r.call(t,e,e)),i.items.push(kp(e,null,n));return i}}mh.tag="tag:yaml.org,2002:set";const gh={collection:"map",identify:e=>e instanceof Set,nodeClass:mh,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>mh.from(e,t,n),resolve(e,t){if(vd(e)){if(e.hasAllNullValues(!0))return Object.assign(new mh,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function yh(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,i=e=>t?BigInt(e):Number(e),s=r.replace(/_/g,"").split(":").reduce((e,t)=>e*i(60)+i(t),i(0));return"-"===n?i(-1)*s:s}function bh(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Lp(e);let r="";t<0&&(r="-",t*=n(-1));const i=n(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),r+s.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const wh={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>yh(e,n),stringify:bh},vh={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>yh(e,!1),stringify:bh},kh={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){const t=e.match(kh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,i,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=yh(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")},Ih=[Tp,Dp,Pp,Op,rh,ih,dh,ph,hh,fh,sh,oh,ah,Jp,th,Xp,gh,wh,vh,kh],Eh=new Map([["core",Kp],["failsafe",[Tp,Dp,Pp]],["json",Yp],["yaml11",Ih],["yaml-1.1",Ih]]),Ah={binary:Jp,bool:Rp,float:Fp,floatExp:jp,floatNaN:$p,floatTime:vh,int:Vp,intHex:Wp,intOct:Up,intTime:wh,map:Tp,null:Op,omap:th,pairs:Xp,seq:Dp,set:gh,timestamp:kh},Sh={"tag:yaml.org,2002:binary":Jp,"tag:yaml.org,2002:omap":th,"tag:yaml.org,2002:pairs":Xp,"tag:yaml.org,2002:set":gh,"tag:yaml.org,2002:timestamp":kh};function _h(e,t){let n=Eh.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(Eh.keys()).filter(e=>"yaml11"!==e).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}n=[]}if(Array.isArray(e))for(const t of e)n=n.concat(t);else"function"==typeof e&&(n=e(n.slice()));return n.map(e=>{if("string"!=typeof e)return e;const t=Ah[e];if(t)return t;const n=Object.keys(Ah).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const xh=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Ch{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?_h(e,"compat"):e?_h(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Sh:{},this.tags=_h(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,hd,{value:Tp}),Object.defineProperty(this,md,{value:Pp}),Object.defineProperty(this,gd,{value:Dp}),this.sortMapEntries="function"==typeof s?s:!0===s?xh:null}clone(){const e=Object.create(Ch.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Th{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,yd,{value:pd});let r=null;"function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:s}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new jd({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Th.prototype,{[yd]:{value:pd}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Sd(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Nh(this.contents)&&this.contents.add(e)}addIn(e,t){Nh(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Bd(this);e.anchor=!t||n.has(t)?qd(t||"a",n):t}return new Wd(e.anchor)}createNode(e,t,n){let r;if("function"==typeof t)e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,n=t.filter(e).map(String);n.length>0&&(t=t.concat(n)),r=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:s,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=function(e,t){const n=[],r=new Map;let i=null;return{onAnchor:r=>{n.push(r),i||(i=Bd(e));const s=qd(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Id(t.node)&&!Ad(t.node)){const t=new Error("Failed to resolve repeated object (this should not happen)");throw t.source=e,t}t.node.anchor=t.anchor}},sourceObjects:r}}(this,s||"a"),h=Yd(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&Ad(h)&&(h.flow=!0),d(),h}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Ip(r,i)}delete(e){return!!Nh(this.contents)&&this.contents.delete(e)}deleteIn(e){return Zd(e)?null!=this.contents&&(this.contents=null,!0):!!Nh(this.contents)&&this.contents.deleteIn(e)}get(e,t){return Ad(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Zd(e)?!t&&Id(this.contents)?this.contents.value:this.contents:Ad(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!Ad(this.contents)&&this.contents.has(e)}hasIn(e){return Zd(e)?void 0!==this.contents:!!Ad(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=Jd(this.schema,[e],t):Nh(this.contents)&&this.contents.set(e,t)}setIn(e,t){Zd(e)?this.contents=t:null==this.contents?this.contents=Jd(this.schema,Array.from(e),t):Nh(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){let n;switch("number"==typeof e&&(e=String(e)),e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new jd({version:"1.1"}),n={merge:!0,resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new jd({version:e}),n={merge:!1,resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else{if(!n)throw new Error("With a null YAML version, the { schema: Schema } option is required");this.schema=new Ch(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},a=Ud(this.contents,t??"",o);if("function"==typeof i)for(const{count:e,res:t}of o.anchors.values())i(t,e);return"function"==typeof s?zd(s,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return function(e,t){const n=[];let r=!0===t.directives;if(!1!==t.directives&&e.directives){const t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");const i=mp(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(ep(t,""))}let o=!1,a=null;if(e.contents){if(Sd(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(ep(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=gp(e.contents,i,()=>a=null,t);a&&(c+=tp(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(gp(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(ep(t,""))):n.push(`... ${t}`)}else n.push("...");else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,"")),t&&(o&&!a||""===n[n.length-1]||n.push(""),n.push(ep(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Nh(e){if(Ad(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Mh extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Dh extends Mh{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ph extends Mh{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Oh=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){const e=Math.min(s-39,o.length-79);o="…"+o.substring(e),s-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+"…\n"),o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];t&&t.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-s)));const a=" ".repeat(s)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function Rh(e,{flow:t,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",p="",h=!1,f=!1,m=!1,g=null,y=null,b=null,w=null,v=null,k=null;for(const i of e)switch(m&&("space"!==i.type&&"newline"!==i.type&&"comma"!==i.type&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&"comment"!==i.type&&"newline"!==i.type&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),i.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!i.source.includes("\t")||(g=i),u=!0;break;case"comment":{u||s(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=i.source.substring(1)||" ";d?d+=p+e:d=e,p="",l=!1;break}case"newline":l?d?d+=i.source:c=!0:p+=i.source,l=!0,h=!0,(y||b)&&(f=!0),u=!0;break;case"anchor":y&&s(i,"MULTIPLE_ANCHORS","A node can have at most one anchor"),i.source.endsWith(":")&&s(i.offset+i.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=i,null===k&&(k=i.offset),l=!1,u=!1,m=!0;break;case"tag":b&&s(i,"MULTIPLE_TAGS","A node can have at most one tag"),b=i,null===k&&(k=i.offset),l=!1,u=!1,m=!0;break;case n:(y||b)&&s(i,"BAD_PROP_ORDER",`Anchors and tags must be after the ${i.source} indicator`),v&&s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.source} in ${t??"collection"}`),v=i,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){w&&s(i,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=i,l=!1,u=!1;break}default:s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.type} token`),l=!1,u=!1}const I=e[e.length-1],E=I?I.offset+I.source.length:i;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||"block-map"===r?.type||"block-seq"===r?.type)&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:v,spaceBefore:c,comment:d,hasNewline:h,hasNewlineAfterProp:f,anchor:y,tag:b,end:E,start:k??E}}function Lh(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes("\n"))return!0;if(e.end)for(const t of e.end)if("newline"===t.type)return!0;return!1;case"flow-collection":for(const t of e.items){for(const e of t.start)if("newline"===e.type)return!0;if(t.sep)for(const e of t.sep)if("newline"===e.type)return!0;if(Lh(t.key)||Lh(t.value))return!0}return!1;default:return!0}}function $h(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&Lh(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function jh(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Id(t)&&Id(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const Fh="All mapping items must start at the same column";function Bh(e,t,n,r){let i="";if(e){let s=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}const qh="Block collections are not allowed within flow collections",zh=e=>e&&("block-map"===e.type||"block-seq"===e.type);function Uh(e,t,n,r,i,s){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Cp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const s of r.items){const{start:l,key:u,sep:d,value:p}=s,h=Rh(l,{indicator:"explicit-key-ind",next:u??d?.[0],offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0}),f=!h.found;if(f){if(u&&("block-seq"===u.type?i(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&i(a,"BAD_INDENT",Fh)),!h.anchor&&!h.tag&&!d){c=h.end,h.comment&&(o.comment?o.comment+="\n"+h.comment:o.comment=h.comment);continue}(h.hasNewlineAfterProp||Lh(u))&&i(u??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&i(a,"BAD_INDENT",Fh);const m=h.end,g=u?e(n,u,h,i):t(n,m,l,null,h,i);n.schema.compat&&$h(r.indent,u,i),jh(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Rh(d??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){f&&("block-map"!==p?.type||y.hasNewline||i(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<y.found.offset-1024&&i(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const c=p?e(n,p,y,i):t(n,a,d,null,y,i);n.schema.compat&&$h(r.indent,p,i),a=c.range[2];const l=new Ip(g,c);n.options.keepSourceTokens&&(l.srcToken=s),o.items.push(l)}else{f&&i(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const e=new Ip(g);n.options.keepSourceTokens&&(e.srcToken=s),o.items.push(e)}}return c&&c<a&&i(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[r.offset,a,c??a],o}(e,t,n,r,s):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Np)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Rh(s,{indicator:"seq-item-ind",next:l,offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(!(u.anchor||u.tag||l)){c=u.end,u.comment&&(o.comment=u.comment);continue}l&&"block-seq"===l.type?i(u.end,"BAD_INDENT","All sequence items must start at the same column"):i(a,"MISSING_CHAR","Sequence item without - indicator")}const d=l?e(n,l,u,i):t(n,u.end,s,null,u,i);n.schema.compat&&$h(r.indent,l,i),a=d.range[2],o.items.push(d)}return o.range=[r.offset,a,c??a],o}(e,t,n,r,s):function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o="{"===r.start.source,a=o?"flow map":"flow sequence",c=new(s?.nodeClass??(o?Cp:Np))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1);let u=r.offset+r.start.source.length;for(let s=0;s<r.items.length;++s){const l=r.items[s],{start:d,key:p,sep:h,value:f}=l,m=Rh(d,{flow:a,indicator:"explicit-key-ind",next:p??h?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!m.found){if(!(m.anchor||m.tag||h||f)){0===s&&m.comma?i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):s<r.items.length-1&&i(m.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),m.comment&&(c.comment?c.comment+="\n"+m.comment:c.comment=m.comment),u=m.end;continue}!o&&n.options.strict&&Lh(p)&&i(p,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===s)m.comma&&i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||i(m.start,"MISSING_CHAR",`Missing , between ${a} items`),m.comment){let e="";e:for(const t of d)switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}if(e){let t=c.items[c.items.length-1];kd(t)&&(t=t.value??t.key),t.comment?t.comment+="\n"+e:t.comment=e,m.comment=m.comment.substring(e.length+1)}}if(o||h||m.found){const s=m.end,g=p?e(n,p,m,i):t(n,s,d,null,m,i);zh(p)&&i(g.range,"BLOCK_IN_FLOW",qh);const y=Rh(h??[],{flow:a,indicator:"map-value-ind",next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(y.found){if(!o&&!m.found&&n.options.strict){if(h)for(const e of h){if(e===y.found)break;if("newline"===e.type){i(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<y.found.offset-1024&&i(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else f&&("source"in f&&f.source&&":"===f.source[0]?i(f,"MISSING_CHAR",`Missing space after : in ${a}`):i(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const b=f?e(n,f,y,i):y.found?t(n,y.end,h,null,y,i):null;b?zh(f)&&i(b.range,"BLOCK_IN_FLOW",qh):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const w=new Ip(g,b);if(n.options.keepSourceTokens&&(w.srcToken=l),o){const e=c;jh(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(w)}else{const e=new Cp(n.schema);e.flow=!0,e.items.push(w),c.items.push(e)}u=b?b.range[2]:y.end}else{const r=f?e(n,f,m,i):t(n,m.end,h,null,m,i);c.items.push(r),u=r.range[2],zh(f)&&i(r.range,"BLOCK_IN_FLOW",qh)}}const d=o?"}":"]",[p,...h]=r.end;let f=u;if(p&&p.source===d)f=p.offset+p.source.length;else{const e=a[0].toUpperCase()+a.substring(1);i(u,l?"MISSING_CHAR":"BAD_INDENT",l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`),p&&1!==p.source.length&&h.unshift(p)}if(h.length>0){const e=Bh(h,f,n.options.strict,i);e.comment&&(c.comment?c.comment+="\n"+e.comment:c.comment=e.comment),c.range=[r.offset,f,e.offset]}else c.range=[r.offset,f,f];return c}(e,t,n,r,s),a=o.constructor;return"!"===i||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Vh(e,t,n){const r=t.offset,i=function({offset:e,props:t},n,r){if("block-scalar-header"!==t[0].type)return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=t[0],s=i[0];let o=0,a="",c=-1;for(let t=1;t<i.length;++t){const n=i[t];if(a||"-"!==n&&"+"!==n){const r=Number(n);!o&&r?o=r:-1===c&&(c=e+t)}else a=n}-1!==c&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":l=!0;case"newline":d+=i.source.length;break;case"comment":if(n&&!l){r(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=i.source.length,u=i.source.substring(1);break;case"error":r(i,"UNEXPECTED_TOKEN",i.message),d+=i.source.length;break;default:{r(i,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${i.type}`);const e=i.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:s,indent:o,chomp:a,comment:u,length:d}}(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};const s=">"===i.mode?Hd.BLOCK_FOLDED:Hd.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}(t.source):[];let a=o.length;for(let e=o.length-1;e>=0;--e){const t=o[e][1];if(""!==t&&"\r"!==t)break;a=e}if(0===a){const e="+"===i.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:s,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<a;++t){const[r,s]=o[t];if(""!==s&&"\r"!==s){if(r.length<c){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+r.length,"MISSING_CHAR",e)}if(0===i.indent&&(c=r.length),u=t,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===i.indent&&r.length>c&&(c=r.length),l+=r.length+s.length+1}for(let e=o.length-1;e>=a;--e)o[e][0].length>c&&(a=e+1);let d="",p="",h=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+"\n";for(let e=u;e<a;++e){let[t,r]=o[e];l+=t.length+r.length+1;const a="\r"===r[r.length-1];if(a&&(r=r.slice(0,-1)),r&&t.length<c){const e=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(l-r.length-(a?2:1),"BAD_INDENT",e),t=""}s===Hd.BLOCK_LITERAL?(d+=p+t.slice(c)+r,p="\n"):t.length>c||"\t"===r[0]?(" "===p?p="\n":h||"\n"!==p||(p="\n\n"),d+=p+t.slice(c)+r,p="\n",h=!0):""===r?"\n"===p?d+="\n":p="\n":(d+=p+r,p=" ",h=!1)}switch(i.chomp){case"-":break;case"+":for(let e=a;e<o.length;++e)d+="\n"+o[e][0].slice(c);"\n"!==d[d.length-1]&&(d+="\n");break;default:d+="\n"}const f=r+i.length+t.source.length;return{value:d,type:s,comment:i.comment,range:[r,f,f]}}function Wh(e,t,n){const{offset:r,type:i,source:s,end:o}=e;let a,c;const l=(e,t,i)=>n(r+e,t,i);switch(i){case"scalar":a=Hd.PLAIN,c=function(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":n=`block scalar indicator ${e[0]}`;break;case"@":case"`":n=`reserved character ${e[0]}`}n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return Kh(e)}(s,l);break;case"single-quoted-scalar":a=Hd.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Kh(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=Hd.QUOTE_DOUBLE,c=function(e,t){let n="";for(let r=1;r<e.length-1;++r){const i=e[r];if("\r"!==i||"\n"!==e[r+1])if("\n"===i){const{fold:t,offset:i}=Gh(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=Hh[i];if(s)n+=s;else if("\n"===i)for(i=e[r+1];" "===i||"\t"===i;)i=e[1+ ++r];else if("\r"===i&&"\n"===e[r+1])for(i=e[1+ ++r];" "===i||"\t"===i;)i=e[1+ ++r];else if("x"===i||"u"===i||"U"===i){const s={x:2,u:4,U:8}[i];n+=Yh(e,r+1,s,t),r+=s}else{const i=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),n+=i}}else if(" "===i||"\t"===i){const t=r;let s=e[r+1];for(;" "===s||"\t"===s;)s=e[1+ ++r];"\n"===s||"\r"===s&&"\n"===e[r+2]||(n+=r>t?e.slice(t,r+1):i)}else n+=i}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}const u=r+s.length,d=Bh(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Kh(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch(e){t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],s=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)""===r[1]?"\n"===s?i+=s:s="\n":(i+=s+r[1],s=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,r=a.exec(e),i+s+(r?.[1]??"")}function Gh(e,t){let n="",r=e[t+1];for(;!(" "!==r&&"\t"!==r&&"\n"!==r&&"\r"!==r||"\r"===r&&"\n"!==e[t+2]);)"\n"===r&&(n+="\n"),r=e[(t+=1)+1];return n||(n=" "),{fold:n,offset:t}}const Hh={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function Yh(e,t,n,r){const i=e.substr(t,n),s=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(s)){const i=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}return String.fromCodePoint(s)}function Jh(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?Vh(e,t,r):Wh(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,"TAG_RESOLVE_FAILED",e)):null,l=n&&c?function(e,t,n,r,i){if("!"===n)return e[md];const s=[];for(const t of e.tags)if(!t.collection&&t.tag===n){if(!t.default||!t.test)return t;s.push(t)}for(const e of s)if(e.test?.test(t))return e;const o=e.knownTags[n];if(o&&!o.collection)return e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o;return i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[md]}(e.schema,i,c,n,r):"scalar"===t.type?function({directives:e,schema:t},n,r,i){const s=t.tags.find(e=>e.default&&e.test?.test(n))||t[md];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[md];if(s.tag!==o.tag){i(r,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${e.tagString(s.tag)} or ${e.tagString(o.tag)}`,!0)}}return s}(e,i,t,r):e.schema[md];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Id(s)?s:new Hd(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new Hd(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Zh(e,t,n){if(t){null===n&&(n=t.length);for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];"space"===n?.type;)e+=n.source.length,n=t[++r];break}}return e}const Qh={composeNode:Xh,composeEmptyNode:ef};function Xh(e,t,n,r){const{spaceBefore:i,comment:s,anchor:o,tag:a}=n;let c,l=!0;switch(t.type){case"alias":c=function({options:e},{offset:t,source:n,end:r},i){const s=new Wd(n.substring(1));""===s.source&&i(t,"BAD_ALIAS","Alias cannot be an empty string");s.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=Bh(r,o,e.strict,i);s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment);return s}(e,t,r),(o||a)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Jh(e,t,a,r),o&&(c.anchor=o.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":c=function(e,t,n,r,i){const s=r?t.directives.tagName(r.source,e=>i(r,"TAG_RESOLVE_FAILED",e)):null,o="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!s||"!"===s||s===Cp.tagName&&"map"===o||s===Np.tagName&&"seq"===o||!o)return Uh(e,t,n,i,s);let a=t.schema.tags.find(e=>e.tag===s&&e.collection===o);if(!a){const c=t.schema.knownTags[s];if(!c||c.collection!==o)return c?.collection?i(r,"BAD_COLLECTION_TYPE",`${c.tag} used for ${o} collection, but expects ${c.collection}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),Uh(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=Uh(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Sd(l)?l:new Hd(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(Qh,e,t,a,r),o&&(c.anchor=o.source.substring(1));break;default:r(t,"UNEXPECTED_TOKEN","error"===t.type?t.message:`Unsupported token (type: ${t.type})`),c=ef(e,t.offset,void 0,null,n,r),l=!1}return o&&""===c.anchor&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),i&&(c.spaceBefore=!0),s&&("scalar"===t.type&&""===t.source?c.comment=s:c.commentBefore=s),e.options.keepSourceTokens&&l&&(c.srcToken=t),c}function ef(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=Jh(e,{type:"scalar",offset:Zh(t,n,r),indent:-1,source:""},a,l);return o&&(u.anchor=o.source.substring(1),""===u.anchor&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function tf(e){if("number"==typeof e)return[e,e+1];if(Array.isArray(e))return 2===e.length?e:[e[0],e[1]];const{offset:t,source:n}=e;return[t,t+("string"==typeof n?n.length:1)]}function nf(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){const s=e[i];switch(s[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(s.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[i+1]?.[0]&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}class rf{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=tf(e);r?this.warnings.push(new Ph(i,t,n)):this.errors.push(new Dh(i,t,n))},this.directives=new jd({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=nf(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Ad(i)&&!i.flow&&i.items.length>0){let e=i.items[0];kd(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:nf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=tf(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=function(e,t,{offset:n,start:r,value:i,end:s},o){const a=Object.assign({_directives:t},e),c=new Th(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rh(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!i||"block-map"!==i.type&&"block-seq"!==i.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Xh(l,i,u,o):ef(l,u.end,r,null,u,o);const d=c.contents.range[2],p=Bh(s,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[n,d,p.offset],c}(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Dh(tf(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const t="Unexpected doc-end without preceding document";this.errors.push(new Dh(tf(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=Bh(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Dh(tf(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const e=Object.assign({_directives:this.directives},this.options),n=new Th(void 0,e);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}}function sf(e,t){if(t)for(const n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function of(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{const r=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{const r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{const r="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}function af(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=af(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=cf(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=cf(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=cf(e);if(e.end)for(const n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(const n of e.end)t+=n.source;return t}}}function cf({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=af(t)),n)for(const e of n)i+=e.source;return r&&(i+=af(r)),i}const lf=Symbol("break visit"),uf=Symbol("skip children"),df=Symbol("remove item");function pf(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),hf(Object.freeze([]),e,t)}function hf(e,t,n){let r=n(t,e);if("symbol"==typeof r)return r;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let t=0;t<s.items.length;++t){const r=hf(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===lf)return lf;r===df&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}pf.BREAK=lf,pf.SKIP=uf,pf.REMOVE=df,pf.itemAtPath=(e,t)=>{let n=e;for(const[e,r]of t){const t=n?.[e];if(!t||!("items"in t))return;n=t.items[r]}return n},pf.parentCollection=(e,t)=>{const n=pf.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};const ff="\ufeff",mf="",gf="",yf="";function bf(e){switch(e){case ff:return"byte-order-mark";case mf:return"doc-mode";case gf:return"flow-error-end";case yf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}var wf=Object.freeze({__proto__:null,BOM:ff,DOCUMENT:mf,FLOW_END:gf,SCALAR:yf,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=fp({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:"\n"}];switch(a[0]){case"|":case">":{const e=a.indexOf("\n"),t=a.substring(0,e),n=a.substring(e+1)+"\n",i=[{type:"block-scalar-header",offset:s,indent:r,source:t}];return sf(i,c)||i.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:s,indent:r,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:c};default:return{type:"scalar",offset:s,indent:r,source:a,end:c}}},isCollection:e=>!!e&&"items"in e,isScalar:e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),prettyToken:function(e){switch(e){case ff:return"<BOM>";case mf:return"<DOC>";case gf:return"<FLOW_END>";case yf:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const r=(e,t,r)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new Dh([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Wh(e,t,r);case"block-scalar":return Vh({options:{strict:t}},e,r)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(r&&"number"==typeof a&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");o=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=fp({type:o,value:t},{implicitKey:i||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),i=t.substring(n+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=r,e.source=i}else{const{offset:t}=e,n="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:t,indent:n,source:r}];sf(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:s,source:i})}}(e,c);break;case'"':of(e,c,"double-quoted-scalar");break;case"'":of(e,c,"single-quoted-scalar");break;default:of(e,c,"scalar")}},stringify:e=>"type"in e?af(e):cf(e),tokenType:bf,visit:pf});function vf(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const kf=new Set("0123456789ABCDEFabcdef"),If=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ef=new Set(",[]{}"),Af=new Set(" ,[]{}\n\r\t"),Sf=e=>!e||Af.has(e);class _f{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if("string"!=typeof e)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;" "===t||"\t"===t;)t=this.buffer[++e];return!t||"#"===t||"\n"===t||"\r"===t&&"\n"===this.buffer[e+1]}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;" "===t;)t=this.buffer[++n+e];if("\r"===t){const t=this.buffer[n+e+1];if("\n"===t||!t&&!this.atEnd)return e+n+1}return"\n"===t||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if("-"===t||"."===t){const t=this.buffer.substr(e,3);if(("---"===t||"..."===t)&&vf(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return("number"!=typeof e||-1!==e&&e<this.pos)&&(e=this.buffer.indexOf("\n",this.pos),this.lineEndPos=e),-1===e?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[e-1]&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(null===e)return this.setNext("stream");if(e[0]===ff&&(yield*this.pushCount(1),e=e.substring(1)),"%"===e[0]){let t=e.length,n=e.indexOf("#");for(;-1!==n;){const r=e[n-1];if(" "===r||"\t"===r){t=n-1;break}n=e.indexOf("#",n+1)}for(;;){const n=e[t-1];if(" "!==n&&"\t"!==n)break;t-=1}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield mf,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if("-"===e||"."===e){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if("---"===e&&vf(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&vf(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!vf(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if(("-"===e||"?"===e||":"===e)&&vf(t)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(null===e)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Sf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=(yield*this.parseBlockScalarHeader()),t+=(yield*this.pushSpaces(!0)),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do{e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=(yield*this.pushSpaces(!0))}while(e+t>0);const r=this.getLine();if(null===r)return this.setNext("flow");if(-1!==n&&n<this.indentNext&&"#"!==r[0]||0===n&&(r.startsWith("---")||r.startsWith("..."))&&vf(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield gf,yield*this.parseLineStart()}let i=0;for(;","===r[i];)i+=(yield*this.pushCount(1)),i+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(i+=(yield*this.pushIndicators()),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Sf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||vf(e)||","===e)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if("'"===e)for(;-1!==t&&"'"===this.buffer[t+1];)t=this.buffer.indexOf("'",t+2);else for(;-1!==t;){let e=0;for(;"\\"===this.buffer[t-1-e];)e+=1;if(e%2==0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf("\n",this.pos);if(-1!==r){for(;-1!==r;){const e=this.continueScalar(r+1);if(-1===e)break;r=n.indexOf("\n",e)}-1!==r&&(t=r-("\r"===n[r-1]?2:1))}if(-1===t){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if("+"===t)this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if("-"!==t)break}return yield*this.pushUntil(e=>vf(e)||"#"===e)}*parseBlockScalar(){let e,t=this.pos-1,n=0;e:for(let r=this.pos;e=this.buffer[r];++r)switch(e){case" ":n+=1;break;case"\n":t=r,n=0;break;case"\r":{const e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if("\n"===e)break}default:break e}if(!e&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(t+1);if(-1===e)break;t=this.buffer.indexOf("\n",e)}while(-1!==t);if(-1===t){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(e=this.buffer[r];" "===e;)e=this.buffer[++r];if("\t"===e){for(;"\t"===e||" "===e||"\r"===e||"\n"===e;)e=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)for(;;){let e=t-1,r=this.buffer[e];"\r"===r&&(r=this.buffer[--e]);const i=e;for(;" "===r;)r=this.buffer[--e];if(!("\n"===r&&e>=this.pos&&e+1+n>i))break;t=e}return yield yf,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t,n=this.pos-1,r=this.pos-1;for(;t=this.buffer[++r];)if(":"===t){const t=this.buffer[r+1];if(vf(t)||e&&Ef.has(t))break;n=r}else if(vf(t)){let i=this.buffer[r+1];if("\r"===t&&("\n"===i?(r+=1,t="\n",i=this.buffer[r+1]):n=r),"#"===i||e&&Ef.has(i))break;if("\n"===t){const e=this.continueScalar(r+1);if(-1===e)break;r=Math.max(r,e-2)}}else{if(e&&Ef.has(t))break;n=r}return t||this.atEnd?(yield yf,yield*this.pushToIndex(n+1,!0),e?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Sf))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(vf(t)||e&&Ef.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,t=this.buffer[e];for(;!vf(t)&&">"!==t;)t=this.buffer[++e];return yield*this.pushToIndex(">"===t?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(If.has(t))t=this.buffer[++e];else{if("%"!==t||!kf.has(this.buffer[e+1])||!kf.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,n=this.pos-1;do{t=this.buffer[++n]}while(" "===t||e&&"\t"===t);const r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class xf{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(0===t)return{line:0,col:e};return{line:t,col:e-this.lineStarts[t-1]+1}}}}function Cf(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Tf(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Nf(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Mf(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Df(e){if(0===e.length)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;"space"===e[++t]?.type;);return e.splice(t,e.length)}function Pf(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Cf(t.start,"explicit-key-ind")||Cf(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Nf(t.value)?t.value.end?Array.prototype.push.apply(t.value.end,t.sep):t.value.end=t.sep:Array.prototype.push.apply(t.start,t.sep),delete t.sep)}class Of{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new _f,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=e.length);const t=bf(e);if(t)if("scalar"===t)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&" "===e[0]&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if("doc-end"!==this.type||e&&"doc-end"===e.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&Pf(t),e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const n=e.items[e.items.length-1];if(n.value)return e.items.push({start:[],key:t,sep:[]}),void(this.onKeyLine=!0);if(!n.sep)return Object.assign(n,{key:t,sep:[]}),void(this.onKeyLine=!n.explicitKey);n.value=t;break}case"block-seq":{const n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{const n=e.items[e.items.length-1];return void(!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]}))}default:yield*this.pop(),yield*this.pop(t)}if(!("document"!==e.type&&"block-map"!==e.type&&"block-seq"!==e.type||"block-map"!==t.type&&"block-seq"!==t.type)){const n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&-1===Tf(n.start)&&(0===t.indent||n.start.every(e=>"comment"!==e.type||e.indent<t.indent))&&("document"===e.type?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}else{const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}}*stream(){switch(this.type){case"directive-line":return void(yield{type:"directive",offset:this.offset,source:this.source});case"byte-order-mark":case"space":case"comment":case"newline":return void(yield this.sourceToken);case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};return"doc-start"===this.type&&e.start.push(this.sourceToken),void this.stack.push(e)}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":return void(-1!==Tf(e.start)?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken));case"anchor":case"tag":case"space":case"comment":case"newline":return void e.start.push(this.sourceToken)}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if("map-value-ind"===this.type){const t=Df(Mf(this.peek(2)));let n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let i=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const i=t.sep[r];switch(i.type){case"newline":n.push(r);break;case"space":break;case"comment":i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Cf(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Nf(t.key)&&!Cf(t.sep,"newline")){const e=Df(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Cf(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Df(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Cf(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0))}default:{const t=this.startBlockValue(e);if(t)return n&&"block-seq"!==t.type&&e.items.push({start:i}),void this.stack.push(t)}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||Cf(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken))}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t)return void this.stack.push(t)}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if("flow-error-end"===this.type){let e;do{yield*this.pop(),e=this.peek(1)}while(e&&"flow-collection"===e.type)}else if(0===e.end.length){switch(this.type){case"comma":case"explicit-key-ind":return void(!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken));case"map-value-ind":return void(!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]}));case"space":case"comment":case"newline":case"anchor":case"tag":return void(!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]}))}case"flow-map-end":case"flow-seq-end":return void e.end.push(this.sourceToken)}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const t=this.peek(2);if("block-map"===t.type&&("map-value-ind"===this.type&&t.indent===e.indent||"newline"===this.type&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if("map-value-ind"===this.type&&"flow-collection"!==t.type){const n=Df(Mf(t));Pf(e);const r=e.end.splice(1,e.end.length);r.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=Df(Mf(e));return t.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=Df(Mf(e));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return"comment"===this.type&&(!(this.indent<=t)&&e.every(e=>"newline"===e.type||"space"===e.type))}*documentEnd(e){"doc-mode"!==this.type&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}}function Rf(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new xf||null,prettyErrors:t}}function Lf(e,t={}){const{lineCounter:n,prettyErrors:r}=Rf(t),i=new Of(n?.addNewLine),s=new rf(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(Oh(e,n)),t.warnings.forEach(Oh(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function $f(e,t={}){const{lineCounter:n,prettyErrors:r}=Rf(t),i=new Of(n?.addNewLine),s=new rf(t);let o=null;for(const t of s.compose(i.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new Dh(t.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else o=t;return r&&n&&(o.errors.forEach(Oh(e,n)),o.warnings.forEach(Oh(e,n))),o}function jf(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=$f(e,n);if(!i)return null;if(i.warnings.forEach(e=>yp(i.options.logLevel,e)),i.errors.length>0){if("silent"!==i.options.logLevel)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function Ff(e,t,n){let r=null;if("function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t),"string"==typeof n&&(n=n.length),"number"==typeof n){const e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(void 0===e){const{keepUndefined:e}=n??t??{};if(!e)return}return new Th(e,r,n).toString(n)}var Bf=Object.freeze({__proto__:null,Alias:Wd,CST:wf,Composer:rf,Document:Th,Lexer:_f,LineCounter:xf,Pair:Ip,Parser:Of,Scalar:Hd,Schema:Ch,YAMLError:Mh,YAMLMap:Cp,YAMLParseError:Dh,YAMLSeq:Np,YAMLWarning:Ph,isAlias:bd,isCollection:Ad,isDocument:wd,isMap:vd,isNode:Sd,isPair:kd,isScalar:Id,isSeq:Ed,parse:jf,parseAllDocuments:Lf,parseDocument:$f,stringify:Ff,visit:Td,visitAsync:Md}),qf=Object.freeze({__proto__:null,Alias:Wd,CST:wf,Composer:rf,Document:Th,Lexer:_f,LineCounter:xf,Pair:Ip,Parser:Of,Scalar:Hd,Schema:Ch,YAMLError:Mh,YAMLMap:Cp,YAMLParseError:Dh,YAMLSeq:Np,YAMLWarning:Ph,default:Bf,isAlias:bd,isCollection:Ad,isDocument:wd,isMap:vd,isNode:Sd,isPair:kd,isScalar:Id,isSeq:Ed,parse:jf,parseAllDocuments:Lf,parseDocument:$f,stringify:Ff,visit:Td,visitAsync:Md});class zf{#vt;constructor(e){this.#vt=e}execute(){return new Promise((e,t)=>{const n=`${this.#vt}.punica/config.yaml`;fetch(n,{method:"GET"}).then(e=>{if(!e.ok)throw new Error(`Failed to load extension config: ${n} (${e.status})`);return e.text()}).then(async t=>{const n=Bf.parse(t);if(n.moduleURL=this.#vt,n.hasCapabilities){const e=`${this.#vt}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=Bf.parse(await t.text());n.capabilities=e??{}}else console.warn(`[Extensions] ${n.name}: hasCapabilities is set but ${e} could not be loaded (${t.status}).`)}catch{n.capabilities={}}}const r=n.instructionClasses;if(Array.isArray(r)&&r.length>0){const e=await Promise.all(r.map(async e=>{const t=`${this.#vt}.punica/instruction-classes/${e}`,n=await fetch(t,{method:"GET"});if(!n.ok)throw new Error(`Failed to load instruction class: ${t} (${n.status})`);return Bf.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Uf{#wt;constructor(e){this.#wt=e}async execute(){return await this.#wt.execute()}}class Vf{#n;#kt;constructor(){this.#n=new Map,this.#kt=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#kt.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#kt.has(t)||console.warn(`Unknown event type: ${t}`)}}class Wf{}class Kf extends Wf{#It;constructor(e){super(),this.#It=e}execute(){}}let Gf=class extends Uf{#Et;constructor(e){super(e),this.#Et=new Vf,this.#Et.register("onExtension",Kf),this.#Et.markKnown("onCommand"),this.#Et.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Et.handleEvent(e)),e}},Hf=class extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,activationEvents:n}=e,r=e.capabilities,i=[];if(r&&"object"==typeof r)for(const[e,t]of Object.entries(r)){if(!e)continue;const n="string"==typeof t?.title?t.title:e,r="string"==typeof t?.description?t.description:void 0;i.push({id:e,title:n,description:r})}return i.length&&i.forEach(({id:t,title:i,description:s})=>{if(!t)return;const o=punica.kernel.Commands.manager,a=punica.extensions.manager,c=punica.kernel.Events.manager;if(n?.some(e=>e===`onCommand:${t}`||"onCommand"===e)??!1)return;const l=r?.[t],u=l?.outputs?.resultEvent,d=l?.outputs?.errorEvent;o.registerCommand(t,{title:i??t,description:s,execute:(...n)=>{const r=n.length?n[n.length-1]:void 0,i=r?.__punica?.correlationId;a.activate(e.name,{reason:"command",trigger:t}).then(()=>{u&&c.publishEvent({name:u,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"result"},payload:{ok:!0,dispatched:!0,capabilityId:t,activatedExtension:e.name}})}).catch(n=>{d&&c.publishEvent({name:d,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"error"},payload:{ok:!1,capabilityId:t,activatedExtension:e.name,error:String(n?.message??n)}})})}})}),e}};function Yf(e,t=function(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}()){const n=e.split("+").map(e=>e.trim().toLowerCase()),r={key:""};return n.forEach(e=>{switch(e){case"ctrl":case"control":r.ctrlKey=!0;break;case"shift":r.shiftKey=!0;break;case"alt":case"option":r.altKey=!0;break;case"meta":case"cmd":case"command":r.metaKey=!0;break;case"mod":case"cmdorctrl":t?r.metaKey=!0:r.ctrlKey=!0;break;default:r.key=e}}),r}let Jf=class extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(t){const{keybindings:e}=t;e&&e.forEach(e=>{if(!e.capability)return void console.warn(`[Keybindings] Missing capability for keybinding: ${e.key}`);const t=e.capability,n=e.key,r=e.when;punica.shell.KeyboardShortcuts.manager.registerShortcut({command:t,keys:[Yf(n)],when:r})})}return e}},Zf=class extends Uf{constructor(e){super(e)}async execute(){return await super.execute()}},Qf=class extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,name:n}=e;if(t&&t.fileOpeners){const e=t.fileOpeners,r=sd.fileOpeners;e.forEach((e,t)=>{if(!e.capability)return void console.warn(`[FileOpeners] Missing capability for file opener: ${e.id??t}`);const i=e.capability,s=e.id??`${n}:${i||"opener"}:${t.toString(10)}`;r.register({id:s,label:e.label,command:i,priority:e.priority,matches:e.matches})})}return e}};class Xf extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(!t)return e;const{views:n}=t;if(!n)return e;const{activityBar:r,statusBar:i,primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c}=n;if(r){const e={...r};e.capability&&(e.command=e.capability),s&&!e.viewId&&(e.viewId=s.id),punica.shell.ActivityBar.manager.addItem(e)}if(i){const e={...i};e.capability&&(e.command=e.capability),punica.shell.Statusbar.manager.addItem(e)}return this.#At(e,{primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r}),e}#At(e,t){const n=punica.shell?.Views?.manager;if(!n?.registerPlacement)return;const{primarySidebar:r,secondarySidebar:i,contentSidebar:s,panel:o,activityBar:a}=t;if(r?.id&&n.registerPlacement({viewId:r.id,slot:"primarySidebar",extensionName:e.name,title:r.title??r.name,icon:r.icon,fallbackCommand:r.capability??a?.capability??a?.command}),i?.id&&n.registerPlacement({viewId:i.id,slot:"secondarySidebar",extensionName:e.name,title:i.title??i.name,icon:i.icon,fallbackCommand:i.capability}),s?.id&&n.registerPlacement({viewId:s.id,slot:"contentSidebar",extensionName:e.name,title:s.title??s.name,icon:s.icon,fallbackCommand:s.capability}),o?.id){n.registerPlacement({viewId:o.id,slot:"panel",extensionName:e.name,title:o.title??o.name,icon:o.icon,order:o.order,fallbackCommand:o.capability});const t=punica.shell?.PanelTabs;t?.open?.({id:o.id,title:o.title??o.name??o.id,commandId:o.capability??"",iconClass:o.icon,order:o.order,autoActivate:!1,toolbar:Array.isArray(o.toolbar)?o.toolbar:void 0})}}}const em=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#St(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#St(e))}getExtensionCapabilities(e){const t=punica.extensions.manager.getExtension(e);if(!t)return;const n=t.capabilities;return n?Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>{const n=t;return[e,Object.freeze({id:n.id??e,title:n.title,description:n.description,inputs:n.inputs?Object.freeze({schema:n.inputs.schema?Object.freeze(n.inputs.schema):void 0}):void 0,outputs:n.outputs?Object.freeze({schema:n.outputs.schema?Object.freeze(n.outputs.schema):void 0,kind:n.outputs.kind,resultEvent:n.outputs.resultEvent,errorEvent:n.outputs.errorEvent}):void 0,policy:n.policy?Object.freeze({risk:n.policy.risk,approval:n.policy.approval}):void 0,sideEffects:n.sideEffects?Object.freeze([...n.sideEffects]):void 0,requiredContext:n.requiredContext?Object.freeze([...n.requiredContext]):void 0,examples:n.examples?Object.freeze(n.examples.map(e=>Object.freeze({input:e.input,output:e.output,description:e.description}))):void 0,version:n.version,tags:n.tags?Object.freeze([...n.tags]):void 0})]}))):void 0}#St(e){const t=e.integrations?.configuration?{title:e.integrations.configuration.title,properties:Object.freeze(Object.fromEntries(Object.entries(e.integrations.configuration.properties??{}).map(([e,t])=>{const n=t,r={type:n.type,default:n.default,description:n.description};let i;return"string"===n.type&&"enum"in n&&Array.isArray(n.enum)&&(i=Object.freeze([...n.enum])),[e,Object.freeze({...r,enum:i})]})))}:void 0;return Object.freeze({name:e.name,displayName:e.displayName,description:e.description,version:e.version,configuration:t?Object.freeze(t):void 0,capabilities:this.getExtensionCapabilities(e.name)})}};const tm=new class{#_t=".punica/settings.json";#xt;#Ct=null;#Tt=null;#Nt=new Map;#Mt=null;#He=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#xt=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#xt="localStorage:punica.settings":this.#xt="settings.json"}async load(){this.#He||(await this.#Dt(),await this.#Pt(),this.#He=!0)}async#Dt(){try{if(this.#xt.startsWith("localStorage:")){const e=this.#xt.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#Tt=await this.#Ot(e)}else this.#Tt={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#xt),t=JSON.parse(e);this.#Tt=await this.#Ot(t)}catch{this.#Tt={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Tt={version:"1.0",extensions:{},system:{}}}}async#Pt(){try{const e=await punica.runtime.fs.readFile(this.#_t),t=JSON.parse(e);this.#Ct=await this.#Ot(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Ct=null}}async save(e="project"){this.#Mt&&clearTimeout(this.#Mt),this.#Mt=window.setTimeout(async()=>{"global"===e?await this.#Rt():await this.#Lt(),this.#Mt=null},500)}async#Rt(){if(this.#Tt)if(this.#xt.startsWith("localStorage:")){const e=this.#xt.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#Tt,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#xt,JSON.stringify(this.#Tt,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#Lt(){this.#Ct||(this.#Ct={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#_t,JSON.stringify(this.#Ct,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#He)return void this.load();if("system"===e){const e=this.#Ct?.system?.[t];if(void 0!==e)return e;const n=this.#Tt?.system?.[t];return void 0!==n?n:void 0}const n=this.#Ct?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#Tt?.extensions?.[e]?.[t];if(void 0!==r)return r;const i=punica.extensions.metadata.manager.getExtension(e);return i?.configuration?.properties?.[t]?.default}async set(e,t,n,r="project"){if(this.#He||await this.load(),"system"===e){const i=this.get(e,t);return"global"===r?(this.#Tt||(this.#Tt={version:"1.0",extensions:{},system:{}}),this.#Tt.system||(this.#Tt.system={}),this.#Tt.system[t]=n,await this.save("global")):(this.#Ct||(this.#Ct={version:"1.0",extensions:{},system:{}}),this.#Ct.system||(this.#Ct.system={}),this.#Ct.system[t]=n,await this.save("project")),void this.#$t(e,t,n,i)}const i=this.validate(e,t,n);if(!i.ok)throw new Error(`Invalid setting value: ${i.errors?.join(", ")}`);const s=this.get(e,t);"global"===r?(this.#Tt||(this.#Tt={version:"1.0",extensions:{},system:{}}),this.#Tt.extensions[e]||(this.#Tt.extensions[e]={}),this.#Tt.extensions[e][t]=n,await this.save("global")):(this.#Ct||(this.#Ct={version:"1.0",extensions:{},system:{}}),this.#Ct.extensions[e]||(this.#Ct.extensions[e]={}),this.#Ct.extensions[e][t]=n,await this.save("project")),this.#$t(e,t,n,s)}getAll(e){if(!this.#He)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#Tt?.extensions?.[e]??{},i=this.#Ct?.extensions?.[e]??{},s={};for(const[e,t]of Object.entries(n)){const n=t;s[e]=n.default}return{...s,...r,...i}}validate(e,t,n){const r=punica.extensions.metadata.manager.getExtension(e),i=r?.configuration?.properties?.[t];if(!i)return{ok:!1,errors:[`Setting "${t}" not found in extension "${e}"`]};const s=[];switch(i.type){case"boolean":"boolean"!=typeof n&&s.push(`Setting "${t}" must be a boolean`);break;case"string":"string"!=typeof n?s.push(`Setting "${t}" must be a string`):i.enum&&!i.enum.includes(n)&&s.push(`Setting "${t}" must be one of: ${i.enum.join(", ")}`);break;case"number":("number"!=typeof n||isNaN(n))&&s.push(`Setting "${t}" must be a number`)}return{ok:0===s.length,errors:s.length>0?s:void 0}}getTyped(e,t,n){const r=this.get(e,t);if(void 0!==r&&typeof r===n)return r}async reset(e,t){const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Ct?.extensions?.[e]&&(delete this.#Ct.extensions[e][t],await this.save("project")),this.#Tt?.extensions?.[e]&&(delete this.#Tt.extensions[e][t],await this.save("global"))):await this.set(e,t,r,"project")}async resetExtension(e){const t=punica.extensions.metadata.manager.getExtension(e);if(t?.configuration?.properties)for(const n of Object.keys(t.configuration.properties))await this.reset(e,n)}getScope(e,t){return this.#He?"system"===e?void 0!==this.#Ct?.system?.[t]?"project":void 0!==this.#Tt?.system?.[t]?"global":"default":void 0!==this.#Ct?.extensions?.[e]?.[t]?"project":void 0!==this.#Tt?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#Nt.has(e)||this.#Nt.set(e,new Set),this.#Nt.get(e).add(t),()=>{this.#Nt.get(e)?.delete(t)}}async export(e){this.#He||await this.load();const t=e?.scope??"merged",n={version:this.#Tt?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Ct?.system:"global"===t?this.#Tt?.system:{...this.#Tt?.system,...this.#Ct?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#Tt?.extensions??{}),...Object.keys(this.#Ct?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Ct?.extensions?.[e]??{}:"global"===t?this.#Tt?.extensions?.[e]??{}:this.getAll(e);return JSON.stringify(n,null,2)}async import(e,t){const n=JSON.parse(e),r=t?.scope??"project";if(n.version&&"1.0"!==n.version&&console.warn(`[Settings] Imported settings version ${n.version} may need migration`),t?.merge){("project"===r?this.#Ct:this.#Tt)||("project"===r?this.#Ct={version:"1.0",extensions:{},system:{}}:this.#Tt={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Ct:this.#Tt;for(const[r,i]of Object.entries(n.extensions??{}))t.extensions&&!t.extensions.includes(r)||(e.extensions[r]={...e.extensions[r],...i});n.system&&(e.system={...e.system,...n.system})}else{if(t?.extensions)for(const e of t.extensions)n.extensions[e]&&("project"===r?(this.#Ct||(this.#Ct={version:"1.0",extensions:{},system:{}}),this.#Ct.extensions[e]=n.extensions[e]):(this.#Tt||(this.#Tt={version:"1.0",extensions:{},system:{}}),this.#Tt.extensions[e]=n.extensions[e]));else"project"===r?this.#Ct={...this.#Ct,...n,version:this.#Ct?.version??"1.0"}:this.#Tt={...this.#Tt,...n,version:this.#Tt?.version??"1.0"};n.system&&("project"===r?(this.#Ct||(this.#Ct={version:"1.0",extensions:{},system:{}}),this.#Ct.system=n.system):(this.#Tt||(this.#Tt={version:"1.0",extensions:{},system:{}}),this.#Tt.system=n.system))}await this.save(r)}async#Ot(e){return e.version,e}#$t(e,t,n,r){const i=this.#Nt.get(e);i&&i.forEach(e=>e(t,n,r)),punica.kernel.Events.manager&&punica.kernel.Events.manager.publishEvent({name:"settings.changed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"extension-settings",kind:"info"},payload:{extensionName:e,key:t,newValue:n,oldValue:r}})}};function nm(e,t){try{const n=globalThis.punica?.kernel?.Events?.manager;if(!n?.publishEvent||!n?.createCorrelationId)return;n.publishEvent({name:e,envelope:{id:n.createCorrelationId(),timestampMs:Date.now(),source:"extensions:lifecycle",kind:"info"},payload:t})}catch{}}const rm=new Map;function im(e){const t=rm.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),rm.delete(e)}const sm={register(e,t,n){const r=n?.target??document.head,i=rm.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),rm.set(e,i),{id:e,dispose(){im(e)}};const s=document.createElement("style");if(s.id=e,n?.attrs)for(const[e,t]of Object.entries(n.attrs))s.setAttribute(e,t);return s.textContent=t,r.appendChild(s),rm.set(e,s),{id:e,dispose(){im(e)}}},unregister(e){im(e)},has:e=>!!rm.has(e)||!!document.getElementById(e)};const om={manager:new class{#jt;#Ft;#Bt;#qt;#zt;#Ut;#Vt;#Wt;#Kt;constructor(){this.#jt=new Map,this.#Ft=new Map,this.#Bt=new Map,this.#qt=new Map,this.#zt=new Set,this.#Ut=new Set,this.#Vt=new Map,this.#Wt=new Map,this.#Kt=new Map}getRuntimeState(e){return this.#Ft.get(e)}registerBuiltinCapabilities(e){const t=Array.isArray(e)?e:[];for(const e of t){const t=String(e?.id??""),n=String(e?.extensionName??""),r=e?.definition??{};if(!t)throw new Error("[Extensions] registerBuiltinCapabilities: Missing id");if(!n)throw new Error(`[Extensions] registerBuiltinCapabilities: Missing extensionName (id="${t}")`);const i=this.#Wt.get(t);if(i&&i.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${i.extensionName}" and "${n}".`);this.#Wt.set(t,{id:t,extensionName:n,definition:r})}}#Gt(e){const t=e,n=t?.capabilities;if(n&&"object"==typeof n){for(const[t,r]of Object.entries(n)){if(!t)continue;const n=r??{};n.id||(n.id=t);const i={id:t,extensionName:e.name,definition:n},s=this.#Wt.get(t);s&&s.extensionName!==e.name&&console.warn(`[Extensions] Capability id collision "${t}" between "${s.extensionName}" and "${e.name}". Keeping the last loaded.`),this.#Wt.set(t,i)}this.#Ht(e,n)}}#Ht(e,t){const n=Hl.lintAll(Object.values(t));let r=0;for(const t of n)for(const n of t.issues)"error"===n.severity?console.warn(`[Extensions] capability lint [${e.name}] ${n.message}`):"warning"===n.severity&&r++;r>0&&console.warn(`[Extensions] capability lint [${e.name}]: ${r} authoring warning(s) — run capability.lint for detail`)}#Yt(e){const t=e.instructionClasses;if(!Array.isArray(t)||0===t.length)return;const n=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;if(n){for(const r of t)try{n.register(r,e.name)}catch(e){console.error(`[Extensions] IC register failed ${r?.id}:`,e)}console.log(`[Extensions] Registered ${t.length} instruction class(es) from "${e.name}"`)}}async load(e,...t){try{const n=[e,...t],r=await Promise.allSettled(n.map(e=>(e=>{const t=new zf(e),n=new Hf(t),r=new Jf(n),i=new Zf(r),s=new Qf(i),o=new Xf(s);return new Gf(o)})(e).execute()));r.forEach((e,t)=>{if("rejected"===e.status)return void console.error(`[Extensions] analysis failed for ${n[t]}:`,e.reason);const r=e.value;this.#jt.set(r.name,r),this.#Ft.set(r.name,"loaded"),this.#Gt(r),this.#Yt(r);const i=r.activationEvents??[];(i.includes("onStartup")||i.includes("onStartup:begin"))&&this.#zt.add(r.name),i.includes("onStartup:finish")&&this.#Ut.add(r.name),i.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#Vt.get(t);n||(n=new Set,this.#Vt.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#Ft.get(e))return;const n=this.#Bt.get(e);if(n)return n;if(!this.#jt.get(e))return void console.error(`Extension "${e}" not found.`);const r=function(e){const t=e?.reason??"host",n=e?.presentation??("capability"===t||"extension"===t?"headless":"interactive");return{reason:t,trigger:e?.trigger,presentation:n}}(t),i=this.#Jt(e,r);this.#Bt.set(e,i);try{await i}finally{this.#Bt.delete(e)}}async#Jt(e,t){this.#Ft.set(e,"activating"),nm("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new od(e),n=new ld(t),r=new ud(n);return new cd(r)})(e),r=await n.execute();if(!r||!r.module||"function"!=typeof r.module.activate)throw new Error(`Failed to activate extension "${e}". The "activate" method is missing or invalid.`);{const n=this.#Zt(e,t);"headless"===t.presentation?await fn(()=>r.module.activate(n)):await r.module.activate(n);const i=this.#qt.get(e);i&&(i.module=r.module),this.#Ft.set(e,"active"),nm("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#Ft.set(e,"failed"),nm("extension.lifecycle.activationFailed",{extensionName:e,reason:t.reason,trigger:t.trigger,error:n instanceof Error?n.message:String(n)}),console.error(`Error activating extension "${e}":`,n),n}}#Zt(e,t){const n=[];this.#qt.set(e,{subscriptions:n});const r={activation:Object.freeze({reason:t.reason,trigger:t.trigger,presentation:t.presentation}),subscriptions:n,capabilities:{registerHandler:(t,n)=>{this.#Kt.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const i=globalThis.punica?.shell?.Views?.manager;if(!i?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const s=i.registerProvider(t,r,e);return n.push(s),s},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway;if(i?.call){const s=r.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await i.call("shell.revealView",{viewId:e,focus:n?.focus??!1},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:o},policy:{mode:"execute"}})}const s=r.punica?.shell?.Views?.manager;if(!s?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await s.reveal(e,{kind:"extension",id:t})}(t,e,n)},hide:async t=>{await async function(e,t){const n=globalThis,r=n.punica?.runtime?.capabilities?.gateway;if(r?.call){const i=n.punica?.kernel?.Events?.manager,s=i?.createCorrelationId?.()??`ext-hide-${Date.now()}`;return void await r.call("shell.hideView",{viewId:e},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:s},policy:{mode:"execute"}})}const i=n.punica?.shell?.Views?.manager;if(!i?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);i.hide(e,{kind:"extension",id:t})}(t,e)}}};return r}async startupBegin(){await this.#Qt(this.#zt,"startup:begin")}async startupFinish(){await this.#Qt(this.#Ut,"startup:finish")}async#Qt(e,t){for(const n of e)try{await this.activate(n,{reason:t})}catch(e){console.error(`Error activating extension "${n}" on${t}:`,e)}}getExtension(e){return this.#jt.get(e)}getAllExtensions(){return Array.from(this.#jt.values())}getCapability(e){return this.#Wt.get(e)?.definition}listCapabilities(){return Array.from(this.#Wt.values())}validateCapabilityInput(e,t){const n=this.getCapability(e);if(!n)return{ok:!0};const r=n.inputs?.schema;if(!r)return{ok:!0};const i=Oa().validate(r,t);return i.ok?{ok:!0}:{ok:!1,errors:i.errors}}registerCapabilityHandler(e,t){this.#Kt.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#Wt.get(e);if(!r)throw new la(ca.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#Ft.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new la(ca.EXTENSION_ACTIVATION_FAILED,`Extension "${r.extensionName}" failed to activate for capability "${e}": `+(t instanceof Error?t.message:String(t)),{capability:e,extensionName:r.extensionName})}const i=this.#Kt.get(e);if(!i)throw new la(ca.CAPABILITY_HANDLER_MISSING,`Extension "${r.extensionName}" declared capability "${e}" but did not register a handler. Call context.capabilities.registerHandler("${e}", handler) inside activate().`,{capability:e,extensionName:r.extensionName});return await i.fn(t,n)}async deactivate(e){if("active"!==this.#Ft.get(e))return;const t=this.#jt.get(e);this.#Ft.set(e,"deactivating");try{const n=globalThis.punica?.shell?.Views?.manager;try{n?.unmountByExtension?.(e)}catch(t){console.warn(`[Extensions] view unmount failed for "${e}":`,t)}try{const n=this.#qt.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#qt.get(e);if(r){for(const t of r.subscriptions)try{t.dispose()}catch(t){console.warn(`[Extensions] subscription dispose failed for "${e}":`,t)}this.#qt.delete(e)}for(const[t,n]of this.#Kt)n.extensionName===e&&this.#Kt.delete(t)}finally{this.#Ft.set(e,"loaded"),nm("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#Ft.get(e);if(void 0===t)return;if("loaded"!==t&&"failed"!==t)throw new Error(`[Extensions] cannot unload "${e}" while ${t} — deactivate() it first.`);try{const t=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;t?.unregisterByOrigin?.(e)}catch(t){console.warn(`[Extensions] instruction-class unregister failed for "${e}":`,t)}for(const[t,n]of this.#Wt)n.extensionName===e&&this.#Wt.delete(t);for(const[t,n]of this.#Vt)n.delete(e)&&0===n.size&&this.#Vt.delete(t);const n=this.#jt.get(e)?.integrations?.views;if(n){const t=globalThis.punica?.shell;try{n.activityBar?.id&&t?.ActivityBar?.manager?.removeItem?.(n.activityBar.id),n.statusBar?.id&&t?.Statusbar?.manager?.removeItem?.(n.statusBar.id),n.panel?.id&&t?.PanelTabs?.close?.(n.panel.id)}catch(t){console.warn(`[Extensions] UI contribution retract failed for "${e}":`,t)}}this.#zt.delete(e),this.#Ut.delete(e),this.#Bt.delete(e),this.#qt.delete(e),this.#jt.delete(e),this.#Ft.delete(e),nm("extension.lifecycle.unloaded",{extensionName:e})}async reload(e,t,n){if(await this.deactivate(e),await this.unload(e),await this.load(t),"loaded"!==this.#Ft.get(e))throw new Error(`[Extensions] reload failed: "${e}" did not load from ${t}`);await this.activate(e,n??{reason:"host",trigger:e})}getExtensionsForCommand(e){const t=this.#Vt.get(e);return t?Array.from(t):[]}},Styles:sm,metadata:{manager:em},settings:{manager:tm}};function am(e){if(null==e)return!1;if(Array.isArray(e))return e.some(am);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(am)}return!1}function cm(e){const t=[];if(!e||"object"!=typeof e)return{ok:!1,issues:[{path:"",message:"Manifest must be an object",code:"INVALID_TYPE",severity:"error"}]};const n=e;if("ivy.node/v0.2"!==n.apiVersion&&t.push({path:"apiVersion",message:`Expected "ivy.node/v0.2", got "${n.apiVersion}"`,code:"INVALID_API_VERSION",severity:"error"}),"IvyNode"!==n.kind&&t.push({path:"kind",message:`Expected "IvyNode", got "${n.kind}"`,code:"INVALID_KIND",severity:"error"}),!n.capability||"object"!=typeof n.capability)return t.push({path:"capability",message:"capability is required and must be an object (CapabilityDefinition)",code:"MISSING_CAPABILITY",severity:"error"}),{ok:!1,issues:t};const r=n.capability;if(r.id&&"string"==typeof r.id?/^[a-z0-9]+(\.[a-z0-9-]+)+$/.test(r.id)||t.push({path:"capability.id",message:'capability.id must be in CapabilityId format (namespace-prefixed, kebab-case, e.g., "ivy.node.email-builder")',code:"INVALID_ID_FORMAT",severity:"error"}):t.push({path:"capability.id",message:"capability.id is required and must be a string (CapabilityId format)",code:"MISSING_ID",severity:"error"}),r.title&&"string"==typeof r.title||t.push({path:"capability.title",message:"capability.title is required and must be a string",code:"MISSING_TITLE",severity:"error"}),r.version&&"string"==typeof r.version?/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(r.version)||t.push({path:"capability.version",message:'capability.version must be in semver format (e.g., "0.0.0", "1.2.3-beta.1")',code:"INVALID_VERSION_FORMAT",severity:"warning"}):t.push({path:"capability.version",message:"capability.version is required and must be a string (semver format)",code:"MISSING_VERSION",severity:"error"}),r.inputs&&r.inputs.schema){const e=lm(r.inputs.schema,"capability.inputs.schema");t.push(...e)}else t.push({path:"capability.inputs.schema",message:"capability.inputs.schema is required",code:"MISSING_INPUTS_SCHEMA",severity:"error"});if(r.outputs&&r.outputs.schema){const e=lm(r.outputs.schema,"capability.outputs.schema");t.push(...e)}else t.push({path:"capability.outputs.schema",message:"capability.outputs.schema is required",code:"MISSING_OUTPUTS_SCHEMA",severity:"error"});if(n.program&&"object"==typeof n.program){if("cells"!==n.program.format&&t.push({path:"program.format",message:'program.format must be "cells"',code:"INVALID_PROGRAM_FORMAT",severity:"error"}),Array.isArray(n.program.cells)){n.program.cells.forEach((e,n)=>{e&&"object"==typeof e?(e.id&&"string"==typeof e.id||t.push({path:`program.cells[${n}].id`,message:"Cell id is required and must be a string",code:"MISSING_CELL_ID",severity:"error"}),e.cell_type&&["code","markdown","raw"].includes(e.cell_type)||t.push({path:`program.cells[${n}].cell_type`,message:'Cell cell_type must be "code", "markdown", or "raw"',code:"INVALID_CELL_TYPE",severity:"error"}),void 0===e.source&&t.push({path:`program.cells[${n}].source`,message:"Cell source is required",code:"MISSING_CELL_SOURCE",severity:"error"})):t.push({path:`program.cells[${n}]`,message:"Cell must be an object",code:"INVALID_CELL_TYPE",severity:"error"})});const e=n.program;if(e?.roles){if(e.roles.inputCellId||t.push({path:"program.roles.inputCellId",message:"program.roles.inputCellId is required",code:"MISSING_INPUT_CELL_ID",severity:"error"}),e.roles.outputCellId||t.push({path:"program.roles.outputCellId",message:"program.roles.outputCellId is required",code:"MISSING_OUTPUT_CELL_ID",severity:"error"}),e.roles.inputCellId){if(e.cells.some(t=>t.id===e.roles.inputCellId)){const n=e.cells.find(t=>t.id===e.roles.inputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["input"]')||r.includes("['input']"));r.includes("__ivy_input__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_input__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["input"].',code:"LEGACY_INPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Input cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["input"] protocol.',code:"INVALID_INPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.inputCellId",message:`Input cell id "${e.roles.inputCellId}" not found in cells`,code:"INVALID_INPUT_CELL_ID",severity:"error"})}if(e.roles.outputCellId){if(e.cells.some(t=>t.id===e.roles.outputCellId)){const n=e.cells.find(t=>t.id===e.roles.outputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["output"]')||r.includes("['output']"));r.includes("__ivy_output__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_output__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["output"].',code:"LEGACY_OUTPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Output cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["output"] protocol.',code:"INVALID_OUTPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.outputCellId",message:`Output cell id "${e.roles.outputCellId}" not found in cells`,code:"INVALID_OUTPUT_CELL_ID",severity:"error"})}}else t.push({path:"program.roles",message:"program.roles is required for ivy.node/v0.2 (inputCellId/outputCellId)",code:"MISSING_PROGRAM_ROLES",severity:"error"})}else t.push({path:"program.cells",message:"program.cells is required and must be an array",code:"MISSING_PROGRAM_CELLS",severity:"error"});n.program.language&&"string"==typeof n.program.language||t.push({path:"program.language",message:"program.language is required and must be a string",code:"MISSING_PROGRAM_LANGUAGE",severity:"error"})}else t.push({path:"program",message:"program is required and must be an object",code:"MISSING_PROGRAM",severity:"error"});if(r.policy){const e=["low","medium","high"];r.policy.risk&&e.includes(r.policy.risk)||t.push({path:"capability.policy.risk",message:`capability.policy.risk must be one of: ${e.join(", ")}`,code:"INVALID_POLICY_RISK",severity:"error"});const n=["none","plan","step"];r.policy.approval&&n.includes(r.policy.approval)||t.push({path:"capability.policy.approval",message:`capability.policy.approval must be one of: ${n.join(", ")}`,code:"INVALID_POLICY_APPROVAL",severity:"error"})}else t.push({path:"capability.policy",message:"capability.policy is required",code:"MISSING_POLICY",severity:"error"});if(void 0!==n.runtime&&"object"!=typeof n.runtime&&t.push({path:"runtime",message:"runtime must be an object",code:"INVALID_RUNTIME_TYPE",severity:"error"}),void 0!==n.tests)if("object"!=typeof n.tests)t.push({path:"tests",message:"tests must be an object",code:"INVALID_TESTS_TYPE",severity:"error"});else{const e=["draft","verified","certified"];n.tests.tier&&e.includes(n.tests.tier)||t.push({path:"tests.tier",message:`tests.tier must be one of: ${e.join(", ")}`,code:"INVALID_TESTS_TIER",severity:"error"}),n.tests.cases&&!Array.isArray(n.tests.cases)?t.push({path:"tests.cases",message:"tests.cases must be an array",code:"INVALID_TESTS_CASES",severity:"error"}):Array.isArray(n.tests.cases)&&n.tests.cases.forEach((e,n)=>{e&&"object"==typeof e?("string"==typeof e.id&&e.id||t.push({path:`tests.cases[${n}].id`,message:"Test case id is required and must be a string",code:"MISSING_TEST_CASE_ID",severity:"error"}),"string"==typeof e.description&&e.description||t.push({path:`tests.cases[${n}].description`,message:"Test case description is required and must be a string",code:"MISSING_TEST_CASE_DESCRIPTION",severity:"error"}),"input"in e?am(e.input)&&t.push({path:`tests.cases[${n}].input`,message:'Test case input must not contain a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }) — it is not resolvable in isolated runner tests. Use literal JSON values in test inputs. (Domain $ref strings, e.g. inside a Swagger/JSON-Schema document, are allowed.)',code:"TEST_INPUT_REF_NOT_ALLOWED",severity:"error"}):t.push({path:`tests.cases[${n}].input`,message:"Test case input is required",code:"MISSING_TEST_CASE_INPUT",severity:"error"})):t.push({path:`tests.cases[${n}]`,message:"Test case must be an object",code:"INVALID_TEST_CASE",severity:"error"})})}return{ok:0===t.filter(e=>"error"===e.severity).length,issues:t}}function lm(e,t){const n=[];if(!e||"object"!=typeof e)return n.push({path:t,message:"Schema must be an object",code:"INVALID_SCHEMA_TYPE",severity:"error"}),n;const r=e;if(void 0!==r.type){const e=["object","string","number","boolean","array","null"];"string"!=typeof r.type||e.includes(r.type)||n.push({path:`${t}.type`,message:`Invalid type: ${r.type}. Must be one of: ${e.join(", ")}`,code:"INVALID_SCHEMA_TYPE",severity:"warning"})}return void 0!==r.properties&&("object"!=typeof r.properties||Array.isArray(r.properties))&&n.push({path:`${t}.properties`,message:"properties must be an object",code:"INVALID_SCHEMA_PROPERTIES",severity:"error"}),void 0!==r.required&&(Array.isArray(r.required)||n.push({path:`${t}.required`,message:"required must be an array",code:"INVALID_SCHEMA_REQUIRED",severity:"error"})),n}class um{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await vo().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=$a();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[NodeRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return dm(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[NodeRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n),i=cm(r);if(!i.ok)return void console.warn(`[NodeRegistry] Invalid manifest at ${t}:`,i.issues);const s=r,o=s.capability;if(!o||"object"!=typeof o||!("id"in o))return void console.warn(`[NodeRegistry] Missing capability.id in ${t}`);const a=t.lastIndexOf("/"),c=a>=0?t.slice(0,a):"";this.packages.set(o.id,{packageRoot:c,manifestPath:t,manifest:s})}catch(e){console.warn(`[NodeRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.runtime&&(t=t.filter(t=>t.manifest.runtime?.kind===e.runtime)),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}setTestReport(e,t){this.testReports.set(e,t)}getLatestTestReport(e){return this.testReports.get(e)}clear(){this.packages.clear(),this.testReports.clear()}}function dm(e,t){for(const n of e)n.isDirectory?n.children&&dm(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let pm;function hm(){return pm||(pm=new um),pm}function fm(e,t,n,r=!1){if("code"!==e.cell_type)throw new Error("Cell must be a code cell");let i=Array.isArray(e.source)?e.source.join(""):String(e.source||"");const s=JSON.stringify(t);return i=i.replace(/__ivy_node_id__/g,s),i}async function mm(e,t,n,r){let i={};for await(const s of e.run({id:"ivy-snapshot",language:"python",code:"import json as __ivy_json\ndef __ivy_snapshot__():\n out = {}\n __ivy_skip = ('In', 'Out', 'get_ipython', 'exit', 'quit', 'json')\n for __ivy_k in list(globals().keys()):\n if __ivy_k.startswith('_'):\n continue\n if __ivy_k in __ivy_skip:\n continue\n try:\n __ivy_v = globals()[__ivy_k]\n except Exception:\n continue\n if callable(__ivy_v):\n continue\n __ivy_tn = type(__ivy_v).__name__\n __ivy_m = getattr(type(__ivy_v), '__module__', '') or ''\n if __ivy_tn == 'module':\n continue\n try:\n if __ivy_tn in ('DataFrame', 'Series') and 'pandas' in __ivy_m:\n __ivy_shape = getattr(__ivy_v, 'shape', None)\n out[__ivy_k] = {'__type__': __ivy_tn, 'shape': list(__ivy_shape) if __ivy_shape is not None else None}\n elif __ivy_tn == 'ndarray' and 'numpy' in __ivy_m:\n out[__ivy_k] = {'__type__': 'ndarray', 'shape': list(__ivy_v.shape), 'dtype': str(__ivy_v.dtype)}\n else:\n try:\n __ivy_enc = __ivy_json.dumps(__ivy_v)\n if len(__ivy_enc) > 2000:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n else:\n out[__ivy_k] = __ivy_v\n except Exception:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n except Exception:\n try:\n out[__ivy_k] = repr(__ivy_v)[:500]\n except Exception:\n out[__ivy_k] = '<unrepr>'\n return out\nprint(__ivy_json.dumps(__ivy_snapshot__(), default=lambda o: repr(o)[:500]))\n",resources:r?{timeoutMs:r}:void 0},{runId:`${t}:snapshot:${n}`}))if("stdout"===s.type&&"text"in s){const e=s.text;try{const t=JSON.parse(e.trim());t&&"object"==typeof t&&(i=t)}catch{}}return i}function gm(e,t){const n={};for(const r of Object.keys(t))r in e&&JSON.stringify(e[r])===JSON.stringify(t[r])||(n[r]=t[r]);return n}const ym=/token|secret|key|password|passwd|api[_-]?key/i;function bm(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=ym.test(i)?"[REDACTED]":e[i],o=i.length+JSON.stringify(s??null).length;n+o>16e3?r=!0:(n+=o,t[i]=s)}return r&&(t.__truncated__=!0),t}async function wm(e,t){const n=Date.now(),r=hm().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=cm(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(am(t.input))throw new Error('Input contains a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }). punica.ivy.runner.run executes a single node in isolation and cannot resolve references. Resolve inputs before calling runner, or execute inside the workflow engine.');const o=s.capability;if(!o||"object"!=typeof o||!("inputs"in o))throw new Error("Manifest missing capability.inputs");const a=o.inputs;if(!a.schema)throw new Error("Manifest missing capability.inputs.schema");const c=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Input must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required property: ${e}`)}return{valid:0===n.length,errors:n}}(t.input,a.schema);if(!c.valid)throw new Error(`Input validation failed: ${c.errors.join(", ")}`);if(!s.program)throw new Error("Manifest missing program");const l=s.program,u=l.cells,d=l.roles?.inputCellId,p=l.roles?.outputCellId;if(!d)throw new Error("Program missing roles.inputCellId");if(!p)throw new Error("Program missing roles.outputCellId");const h=u.find(e=>e.id===d),f=u.find(e=>e.id===p);if(!h)throw new Error(`Input cell with id "${d}" not found in program.cells`);if(!f)throw new Error(`Output cell with id "${p}" not found in program.cells`);const m=function(){if(!punica.runtime?.compute)throw new Error("[IvyNodeRunner] Runtime compute API not available. Ensure compute provider is registered.");return punica.runtime.compute}(),g=[],y=l.language||(s.runtime,"python"),b=t.runId??`ivynode-${e}-${n}`,w=(e,t)=>{try{punica.kernel.Events.manager.publish(e,t)}catch{}},v=(e,t)=>{const n=Array.isArray(e.source)?e.source[0]:e.source;return String(n??"").replace(/^#+\s*/,"").trim().slice(0,50)||`Cell ${t+1}`},k=e=>{const t=e;return"stdout"!==t.type&&"stderr"!==t.type||"string"!=typeof t.text?"":t.text},I=await m.session.open({language:y}),E=t.runId||`ivynode-${e}-${Date.now()}`;let A={};try{const r=["# IvyNode runner context init (v0.2)","import json",'__ivy_ctx__ = {"nodes": {}}',`__ivy_ctx__["nodes"][${JSON.stringify(e)}] = {"input": json.loads(${JSON.stringify(JSON.stringify(t.input))}), "output": {}}`].join("\n");for await(const e of I.run({id:"init-ivy-ctx",language:"python",code:r,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:init`}))g.push({type:e.type,data:e});for(let n=0;n<u.length;n++){const r=u[n];if("code"!==r.cell_type)continue;const i=fm(r,e),s=r.id||`cell-${n}`,o=v(r,n),a=Date.now();let c,l="";w("ivy.node.cell.started",{runId:b,nodeId:e,cellId:s,index:n,label:o,startedAtMs:a});try{let e=null;for await(const n of I.run({id:s,language:y,code:i,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:cell:${s}`})){g.push({type:n.type,data:n}),l+=k(n);const t=n;if("error"===t.type){e=`${t.name?`${t.name}: `:""}${t.message??"cell execution error"}`.trim()}else if("finished"===t.type&&!1===t.ok){const n=null!=t.exitCode?` (exit code ${t.exitCode})`:"",r=l.trim()?`:\n${l.trim()}`:"";e=e??`Cell execution failed${n}${r}`}}if(e)throw new Error(e)}catch(t){throw w("ivy.node.cell.failed",{runId:b,nodeId:e,cellId:s,index:n,label:o,durationMs:Date.now()-a,error:t instanceof Error?t.message:String(t),logs:l}),t}try{const e=await mm(I,E,s,t.timeoutMs),n=bm(gm(A,e));Object.keys(n).length&&(c=n),A=e}catch{}w("ivy.node.cell.finished",{runId:b,nodeId:e,cellId:s,index:n,label:o,durationMs:Date.now()-a,logs:l,...c?{variables:c}:{}})}const i=await async function(e,t,n,r){const i=JSON.stringify(t),s=`\nimport json\ntry:\n if '__ivy_ctx__' in globals() and isinstance(__ivy_ctx__, dict):\n if "nodes" in __ivy_ctx__ and ${i} in __ivy_ctx__["nodes"]:\n node_data = __ivy_ctx__["nodes"][${i}]\n if "output" in node_data:\n print(json.dumps(node_data["output"]))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\nexcept Exception as e:\n print(json.dumps({"error": str(e)}))\n`;for await(const t of e.run({id:"extract-output",language:"python",code:s,resources:r?{timeoutMs:r}:void 0},{runId:`${n}:extract-output`}))if("stdout"===t.type&&"text"in t){const e=t.text;try{const t=JSON.parse(e.trim());if(t&&"object"==typeof t)return t}catch(e){}}throw new Error("Failed to extract output from execution context")}(I,e,E,t.timeoutMs),s=o.outputs;if(!s?.schema)throw new Error("Manifest missing capability.outputs.schema");const a=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Output must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required output property: ${e}`)}return{valid:0===n.length,errors:n}}(i,s.schema);if(!a.valid)throw new Error(`Output validation failed: ${a.errors.join(", ")}`);return{output:i,events:g,durationMs:Date.now()-n}}finally{await I.close()}}function vm(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function km(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function Im(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Em(e,t){const n=e.value;switch(e.type){case"isType":return{passed:km(t)===String(n??""),expected:String(n??""),actual:km(t)};case"equals":return{passed:Im(t,n),expected:JSON.stringify(n),actual:JSON.stringify(t)};case"matches":return{passed:void 0!==t&&new RegExp(String(n??"")).test(String(t)),expected:String(n??""),actual:void 0===t?void 0:String(t)};case"contains":return"string"==typeof t?{passed:t.includes(String(n??"")),expected:String(n??""),actual:t}:Array.isArray(t)?{passed:t.some(e=>Im(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:km(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:km(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):km(t)};case"greaterThan":return{passed:"number"==typeof t&&t>Number(n),expected:`> ${n}`,actual:String(t)};case"lessThan":return{passed:"number"==typeof t&&t<Number(n),expected:`< ${n}`,actual:String(t)};case"between":{const e=Array.isArray(n)?n:[];return{passed:"number"==typeof t&&2===e.length&&t>=Number(e[0])&&t<=Number(e[1]),expected:JSON.stringify(n),actual:String(t)}}default:return{passed:!0,expected:`unsupported matcher: ${e.type}`,actual:km(t)}}}function Am(e,t,n=""){const r=e.assertions||{},i={},s=[];if(void 0!==r.schema){const e=!0===r.schema;i.schema={passed:e},s.push(!e)}if(void 0!==r.expectsError){const e=!1===r.expectsError;i.error={passed:e},s.push(!e)}if(r.errorPattern&&r.expectsError){const e=new RegExp(r.errorPattern).test(n);i.error={passed:e,expected:r.errorPattern,actual:n||void 0},s.push(!e)}if(r.properties&&"object"==typeof r.properties){const e={};for(const[n,i]of Object.entries(r.properties)){if(!i||"object"!=typeof i)continue;const r=vm(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=Em(a,r);else if("string"==typeof a)o=Em({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=Em({type:"equals",value:i.expected},r)}e[n]=o,s.push(!o.passed)}Object.keys(e).length&&(i.properties=e)}return{status:s.some(Boolean)?"fail":"pass",assertions:Object.keys(i).length>0?i:void 0}}function Sm(e,t,n){const r=!0===e.assertions?.expectsError,i=e.assertions?.errorPattern;let s;return s=r?i?new RegExp(i).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:s,error:t,assertions:{error:{passed:r,expected:i,actual:t}}}}function _m(e){const{capabilityId:t,version:n,tier:r,results:i,startedAtMs:s}=e,o=i.filter(e=>"pass"===e.status).length,a=i.filter(e=>"fail"===e.status).length,c=i.filter(e=>"skip"===e.status).length,l=i.filter(e=>"error"===e.status).length;return{reportId:`report-${t}-${n}-${Date.now()}`,capabilityId:t,capabilityVersion:n,specVersion:"v0.1",timestampMs:Date.now(),runner:{version:"0.1.0",environment:"punica-editor"},summary:{tier:r,status:0===a&&0===l?"pass":a>0?"fail":"flaky",totalCases:i.length,passedCases:o,failedCases:a,skippedCases:c,durationMs:Date.now()-s},cases:i}}function xm(){return Date.now()}function Cm(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Tm(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function Nm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Mm(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"gateway"in t)return t.gateway}}function Dm(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"registry"in t){const e=t.registry;if(e&&"object"==typeof e&&"getSpec"in e)return{getSpec:e.getSpec}}}}function Pm(e){if(!e?.defaults)return;const t=e.defaults;if("object"!=typeof t||null===t)return;const n=t,r={};return"number"==typeof n.timeoutMs&&(r.timeoutMs=n.timeoutMs),"number"==typeof n.retries&&n.retries>0&&(r.retry={maxAttempts:n.retries,initialDelayMs:"number"==typeof n.retryBackoffMs?n.retryBackoffMs:1e3,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1}),n.rateLimit&&"object"==typeof n.rateLimit&&(r.rateLimit=n.rateLimit),n.concurrency&&"object"==typeof n.concurrency&&(r.concurrency=n.concurrency),"write"===e.sideEffect&&(r.requireIdempotencyKeyForWriteRetry=!0),Object.keys(r).length>0?r:void 0}async function Om(e){try{const n=Mm();if(!n)throw new Error("[FlowEngine] Capability gateway not available. Gateway is mandatory for all FS operations.");{const r=await t();await n.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}}catch{}}async function Rm(e,n){const r=Mm();if(!r)throw new Error("[FlowEngine] writeTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");const i=await t();await r.call("fs.writeFile",{path:e,content:n},{sessionId:"internal",workspaceId:i,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}function Lm(e,t,n,r,i){const s=i?.traceId??t;punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:t,traceId:s,spanId:i?.spanId,parentSpanId:i?.parentSpanId,timestampMs:xm(),source:i?.source??"flow:engine",kind:n},payload:r})}const $m=new Set(["sensitive","secret"]);function jm(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Fm(e,t,n,r){if(!function(e,t,n){return!(!n||!$m.has(n)||"meta"===t)||!(!e||"none"===e)&&("all"===e?"input"===t||"output"===t:"input"===e?"input"===t:"output"===e&&"output"===t)}(t,n,r))return e;return{redacted:!0,reason:"policy",policy:t,surface:n,originalBytes:jm(e)}}const Bm=new class{#Xt=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#Xt.set(e,(this.#Xt.get(e)??0)+r),!0;const i=this.#Xt.get(e)??0;return!(i+r>n)&&(this.#Xt.set(e,i+r),!0)}used(e){return this.#Xt.get(e)??0}release(e){this.#Xt.delete(e)}reset(){this.#Xt.clear()}};class qm{async ensureBase(){await Om(".punica"),await Om(Nm(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await Om(Nm(".punica","workflow-runs",e)),await Om(Nm(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=xm();await this.ensureRunDirs(e);const s=n.surface??"output",o=n.payload,a=n.text;let c,l=o,u=a;if(n.redactionPolicy||n.capabilityClassification){const e=Fm(o??a,n.redactionPolicy,s,n.capabilityClassification);e&&"object"==typeof e&&!0===e.redacted&&(c=e,l=c,u=void 0)}const d="string"==typeof u,p=Nm(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let h;h=d?String(u??""):Cm(l??{},2);const f=n.sizeBudget?.maxBytes;if(c||"number"!=typeof f)"number"==typeof f&&Bm.acquire(e,h.length,f);else{Bm.acquire(e,h.length,f)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,h.length),h=Cm(c,2),Bm.acquire(e,h.length,f))}await Rm(p,h);const m=h.length,g=Tm(d?String(u??""):Cm(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs:i,name:n.name,mimeType:n.mimeType,uri:p,preview:g,sizeBytes:m,meta:c?{...n.meta??{source:"flow:engine"},redacted:c}:n.meta??{source:"flow:engine"}};return Lm("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function zm(e,t){return Object.freeze(function(e,t){const n=[];for(const r of e.readyNodes){if(t&&n.length>=t)break;n.push(r)}return n}(e,t).slice())}function Um(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Vm(e){return function(e){const t=new Map,n=new Set;for(const n of e.graph.nodes){if(n.disabled)continue;const e={nodeId:n.id,status:"pending",dependencies:new Set,dependents:new Set,completedDependencies:new Set};t.set(n.id,e)}for(const n of e.graph.edges){const e=t.get(n.fromId),r=t.get(n.toId);e&&r&&(r.dependencies.add(n.fromId),e.dependents.add(n.toId))}for(const[e,r]of t.entries())0===r.dependencies.size&&(n.add(e),r.status="ready");return{nodes:t,readyNodes:n}}(e)}function Wm(e,t,n){t?function(e,t){const n=t.nodes.get(e);if(n){n.status="completed";for(const r of n.dependents){const n=t.nodes.get(r);n&&(n.completedDependencies.add(e),n.completedDependencies.size===n.dependencies.size&&"pending"===n.status&&(n.status="ready",t.readyNodes.add(r)))}}}(e,n):function(e,t){const n=t.nodes.get(e);n&&(n.status="failed",t.readyNodes.delete(e))}(e,n)}function Km(e,t){!function(e,t){const n=t.nodes.get(e);n&&"ready"===n.status&&(n.status="running",t.readyNodes.delete(e))}(e,t)}function Gm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Hm(e){const t=globalThis.punica,n=t?.runtime?.capabilities?.gateway;if(!n)throw new Error(`[FlowEngine] persistence.${e}: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).`);return n}async function Ym(e,t,n){const r=Hm(e);await r.call("fs.writeFile",{path:t,content:n},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}async function Jm(e,t){const n=Hm(e);try{await n.call("fs.ensureDir",{path:t},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}catch{}}async function Zm(e,t){const n=Hm(e);await n.call("fs.deleteFile",{path:t},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}async function Qm(e,t=".punica"){const n=Gm(t,"workflow-runs",e.runId),r=Gm(n,"checkpoint.json"),i=Gm(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await Jm("writeCheckpoint",n),await Ym("writeCheckpoint",i,s);try{await async function(e,t,n){const r=Hm(e);await r.call("fs.rename",{from:t,to:n},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}("writeCheckpoint",i,r)}catch{try{await Zm("writeCheckpoint",r)}catch{}await Ym("writeCheckpoint",r,s);try{await Zm("writeCheckpoint",i)}catch{}}}async function Xm(e,t=".punica"){const n=Gm(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=Hm(e);return await n.call("fs.readFile",{path:t},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}("readCheckpoint",n);return JSON.parse(e)}catch{return null}}function eg(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!t?.publishEvent||!t?.createCorrelationId)&&(t.publishEvent({name:e.name,envelope:{id:t.createCorrelationId(),correlationId:e.correlationId,traceId:e.traceId,timestampMs:Date.now(),source:e.source??"flow:engine",kind:e.kind??"info"},payload:e.payload}),!0)}catch{return!1}}class tg{runs;runIdToSession;artifactStore;constructor(e,t,n){this.runs=e,this.runIdToSession=t,this.artifactStore=n}async startRun(e){const t=e?.spec,n=e?.workspaceId,r=e?.filePathOrUri,i=e?.input??null;if(!t||"ivy.workflow/v0.1"!==t.apiVersion||"Workflow"!==t.kind)throw new Error('Invalid WorkflowDocument: must have apiVersion="ivy.workflow/v0.1" and kind="Workflow"');if(!t.graph||!t.graph.nodes||!t.graph.edges)throw new Error("Invalid WorkflowDocument: missing graph.nodes or graph.edges");if(!t.graph.entryNodeId)throw new Error("Invalid WorkflowDocument: missing graph.entryNodeId");if(!t.graph.nodes.some(e=>e.id===t.graph.entryNodeId))throw new Error(`Invalid WorkflowDocument: entryNodeId "${t.graph.entryNodeId}" not found in graph.nodes`);const s=t,o=function(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=e.graph.edges.filter(e=>n.has(e.fromId)&&n.has(e.toId)),i=new Map,s=new Map;t.forEach(e=>{i.set(e.id,0),s.set(e.id,[])}),r.forEach(e=>{s.get(e.fromId).push(e.toId),i.set(e.toId,(i.get(e.toId)??0)+1)});const o=[];for(const[e,t]of i.entries())0===t&&o.push(e);const a=[];for(;o.length;){const e=o.shift();a.push(e);for(const t of s.get(e)??[])i.set(t,(i.get(t)??0)-1),0===(i.get(t)??0)&&o.push(t)}if(a.length!==t.length)throw new Error("Workflow graph is not a DAG (cycle detected).");return a}(s),a=punica.kernel.Events.manager.createCorrelationId(),c=a,l=punica.kernel.Events.manager.createCorrelationId(),u={runId:a,specVersion:"0.1",status:"QUEUED",createdAtMs:xm(),startedAtMs:xm(),traceId:c,entryNodeId:s.graph.entryNodeId,metadata:{title:s.title,tags:s.tags},steps:[]};for(const e of o){const t=s.graph.nodes.find(t=>t.id===e);if(!t)continue;const n="ivyNode"===t.ref.kind?"capability.call":"workflow"===t.ref.kind?"workflow.run":"flowInput"===t.ref.kind?"flow.input":"flowOutput"===t.ref.kind?"flow.output":"primitive"===t.ref.kind?`primitive.${t.ref.primitive}`:"unknown",r={stepId:t.id,nodeId:t.id,nodeType:n,attempt:0,status:t.disabled?"SKIPPED":"PENDING",cellId:void 0};u.steps.push(r)}u.status="RUNNING";const d=Vm(s),p=s.graph.runBudget?.maxInFlight;return this.runs.set(a,{run:u,spec:s,order:o,cursor:0,paused:!1,cancelled:!1,rootSpanId:l,filePathOrUri:r,dependencyGraph:d,inFlightNodes:new Set,maxInFlight:p,nodeOutputs:new Map,input:i}),Lm("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),eg({name:"flow.run.started",correlationId:a,traceId:c,payload:{runId:a,flowId:s.id,workspaceId:n,startedAtMs:u.startedAtMs??u.createdAtMs,entryNodeId:u.entryNodeId}}),await this.persistRun(a),await this.persistIndex(),{runId:a,workspaceId:n}}async pauseRun(e){const t=this.runs.get(e);return!!t&&(t.paused=!0,t.run.status="PAUSED",Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),!0)}async resumeRun(e){let t=this.runs.get(e);if(!t){const n=await Xm(e);if(!n)return!1;{const r=n.dependencyGraphState?Vm(n.spec):void 0;t={run:n.run,spec:n.spec,order:n.spec.graph.nodes.map(e=>e.id),cursor:n.cursor??0,paused:!1,cancelled:!1,rootSpanId:n.run.traceId,dependencyGraph:r,inFlightNodes:new Set(n.inFlightNodes??[]),maxInFlight:n.spec.graph.runBudget?.maxInFlight},this.runs.set(e,t)}}return t.paused=!1,"RUNNING"!==t.run.status&&(t.run.status="RUNNING"),Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"RUNNING"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),!0}async cancelRun(e,t){const n=this.runs.get(e);if(!n)return!1;n.cancelled=!0,n.run.status="CANCELLED",n.run.endedAtMs=xm();const r=this.runIdToSession.get(e);if(r){try{"hard"===(t??"best-effort")?await r.restart():await r.interrupt()}catch(t){console.warn(`[FlowEngine] Error cancelling session for run ${e}:`,t)}this.runIdToSession.delete(e)}return Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Lm("workflow.runFinished",e,"info",{runId:e,status:"CANCELLED",endedAtMs:n.run.endedAtMs},{traceId:n.run.traceId,spanId:n.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),await this.persistIndex(),!0}getRun(e){return this.runs.get(e)?.run??null}listRuns(e){const t=Array.from(this.runs.values()).map(e=>({runId:e.run.runId,status:e.run.status,createdAtMs:e.run.createdAtMs,startedAtMs:e.run.startedAtMs,endedAtMs:e.run.endedAtMs,traceId:e.run.traceId,metadata:{title:e.run.metadata?.title}})),n=e?.status?t.filter(t=>t.status===e.status):t,r="number"==typeof e?.limit&&e.limit>0?e.limit:n.length;return n.sort((e,t)=>(t.createdAtMs??0)-(e.createdAtMs??0)),n.slice(0,r)}async persistRun(e){const t=this.runs.get(e);if(!t)return;await this.artifactStore.ensureRunDirs(e);const n=Nm(".punica","workflow-runs",e,"run.json");await Rm(n,Cm({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=Nm(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Rm(e,Cm({version:1,updatedAtMs:xm(),runs:t},2))}async persistCheckpoint(e){const t=this.runs.get(e);if(!t)return;const n={runId:e,timestampMs:Date.now(),run:t.run,spec:t.spec,cursor:t.cursor,inFlightNodes:Array.from(t.inFlightNodes??[])};await Qm(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=Nm(".punica","workflow-runs","index.json"),n=await async function(e){const n=Mm();if(!n)throw new Error("[FlowEngine] readTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");try{const r=await t();return await n.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}catch{return null}}(e);if(n)try{const e=JSON.parse(n);Lm("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class ng{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,i,s){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=i,this.resumeRunLoop=s}setupApprovalSubscription(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{const t=e?.event?.payload?e.event:e,n=t?.envelope?.correlationId;if(!n)return;const r=this.pendingToRunStep.get(n);if(!r)return;const i=t?.payload??{},s=i?.request??{},o=i?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(s?.kind??"capability"),id:String(s?.id??""),risk:String(s?.risk??"low"),approval:String(s?.approval??"once"),reason:"string"==typeof s?.reason?s.reason:void 0,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:xm()};this.pendingByCorrelation.set(n,c);const l=this.runs.get(r.runId);if(l){const e=l.run.steps.find(e=>e.stepId===r.stepId);e&&(e.status="WAITING_APPROVAL",e.approval={pendingId:a,required:!0,requestedAtMs:xm(),resolved:!1},Lm("workflow.stepUpdated",l.run.runId,"info",{runId:l.run.runId,stepId:e.stepId,patch:{status:e.status,approval:e.approval}},{traceId:l.run.traceId,spanId:e.spanId,parentSpanId:l.rootSpanId})),l.run.status="WAITING_APPROVAL",Lm("workflow.runUpdated",l.run.runId,"info",{runId:l.run.runId,patch:{status:l.run.status,currentNodeId:e?.nodeId}},{traceId:l.run.traceId,spanId:l.rootSpanId}),Lm("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),eg({name:"flow.approval.requested",correlationId:l.run.runId,traceId:l.run.traceId,payload:{runId:l.run.runId,stepId:r.stepId,pendingId:c.pendingId,attemptCorrelationId:n,capability:{kind:c.kind,id:c.id},risk:c.risk,approval:c.approval,workspaceId:c.workspaceId}}),this.persistRun(l.run.runId)}})}approvePending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=e?.scope??"once",r=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!r)return!1;const i=this.pendingToRunStep.get(r.attemptCorrelationId);if(!i)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id},n,{workspaceId:r.workspaceId})}catch{}Lm("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:xm()},{traceId:i.runId}),eg({name:"flow.approval.granted",correlationId:i.runId,traceId:i.runId,payload:{runId:i.runId,stepId:i.stepId,pendingId:t,scope:n,capability:{kind:r.kind,id:r.id}}}),this.pendingByCorrelation.delete(r.attemptCorrelationId);const s=this.runs.get(i.runId);if(s){const e=s.run.steps.find(e=>e.stepId===i.stepId);e?.approval&&(e.approval.resolved=!0,e.approval.decision="approved"),s.run.status="RUNNING",Lm("workflow.runUpdated",s.run.runId,"info",{runId:s.run.runId,patch:{status:"RUNNING"}},{traceId:s.run.traceId,spanId:s.rootSpanId}),this.persistRun(s.run.runId),this.resumeRunLoop(s.run.runId)}return!0}rejectPending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!n)return!1;const r=this.pendingToRunStep.get(n.attemptCorrelationId);if(!r)return!1;Lm("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:xm()},{traceId:r.runId}),eg({name:"flow.approval.rejected",kind:"warn",correlationId:r.runId,traceId:r.runId,payload:{runId:r.runId,stepId:r.stepId,pendingId:t,capability:{kind:n.kind,id:n.id}}}),this.pendingByCorrelation.delete(n.attemptCorrelationId);const i=this.runs.get(r.runId);return i&&(i.run.status="FAILED",i.run.endedAtMs=xm(),Lm("workflow.runUpdated",i.run.runId,"error",{runId:i.run.runId,patch:{status:"FAILED",endedAtMs:i.run.endedAtMs,error:{message:"Approval rejected",nodeId:r.stepId}}},{traceId:i.run.traceId,spanId:i.rootSpanId}),Lm("workflow.runFinished",i.run.runId,"error",{runId:i.run.runId,status:"FAILED",endedAtMs:i.run.endedAtMs},{traceId:i.run.traceId,spanId:i.rootSpanId}),this.persistRun(i.run.runId),this.persistIndex()),!0}}const rg=3e4,ig={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const sg=new class{#ct=new Map;getSemaphore(e,t){let n=this.#ct.get(e);return n||(n={count:0,max:t,queue:[]},this.#ct.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e,t){const n=this.#ct.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function og(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function ag(e,t){if(!t.retry)return 0;const n=t.retry.initialDelayMs??1e3,r=t.retry.maxDelayMs??3e4,i=t.retry.backoffMultiplier??2,s=t.retry.jitter??"none";return function(e,t){if("none"===t)return e;if("full"===t)return Math.floor(Math.random()*e);if("decorrelated"===t){const t=e/2;return Math.floor(t+Math.random()*t)}return e}(Math.min(n*Math.pow(i,e-1),r),s)}const cg=new class{#en=new Map;register(e,t){this.#en.set(e,t)}get(e){return this.#en.get(e)}resolveOrThrow(e){const t=this.#en.get(e.ref.kind);if(!t)throw new Error(`No executor registered for node ref.kind: "${e.ref.kind}" (node id: ${e.id})`);return t}clear(){this.#en.clear()}};function lg(e,t){let n=e;for(const e of t){if(null==n)return;if("object"!=typeof n)return;if(Array.isArray(n)){const t=Number(e);if(!Number.isInteger(t)||t<0||t>=n.length)return;n=n[t];continue}if(!Object.prototype.hasOwnProperty.call(n,e))return;n=n[e]}return n}function ug(e,t){if(!e||"object"!=typeof e)return{ok:!1,reason:"invalid-ref"};if("literal"===e.kind)return{ok:!0,value:e.value};if("path"===e.kind){const n=String(e.path??"").split(".").filter(e=>e.length>0);if(0===n.length)return{ok:!1,reason:"invalid-ref"};const[r,...i]=n;if(!t.has(r))return{ok:!1,reason:"missing-node"};const s=t.get(r);if(0===i.length)return{ok:!0,value:s??null};const o=lg(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function dg(e){return null!=e&&("boolean"==typeof e?e:"number"==typeof e?0!==e&&!Number.isNaN(e):"string"==typeof e||Array.isArray(e)?e.length>0:"object"==typeof e&&Object.keys(e).length>0)}function pg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hg(e){return String(e??"").split(".").filter(e=>e.length>0)}function fg(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];pg(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function mg(e,t,n){const r=t.filter(t=>t.toId===e.id&&(void 0!==t.fromPath||void 0!==t.toPath)),i=e.data?.input;if(0===r.length)return void 0!==i?i:void 0!==e.defaults?e.defaults:void 0;const s={...pg(e.defaults)?e.defaults:{},...pg(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?hg(e.fromPath):[],i=r.length?lg(t,r):t;if(void 0===i)continue;const o=e.toPath?hg(e.toPath):[];o.length?fg(s,o,i):pg(i)?Object.assign(s,i):s[e.fromId]=i}return s}class gg extends Error{code="RUN_CANCELLED";runId;mode;constructor(e,t){super(`Run ${e??"<unknown>"} was cancelled (${t??"best-effort"} mode) — substrate refuses to continue in-flight node attempts.`),this.name="RunCancelledError",this.runId=e,this.mode=t}}function yg(e,t){if(function(e){return!0===e.cancelled}(e))throw new gg(e.run?.runId,t)}class bg{runs;pendingToRunStep;runIdToSession;artifactStore;persistRun;persistCheckpoint;persistIndex;notifyTerminal;constructor(e,t,n,r,i,s,o,a){this.runs=e,this.pendingToRunStep=t,this.runIdToSession=n,this.artifactStore=r,this.persistRun=i,this.persistCheckpoint=s,this.persistIndex=o,this.notifyTerminal=a}async executeSequential(e,t){const n=this.runs.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;if(!n.notebook&&n.filePathOrUri)try{const e=Mm();if(!e)throw new Error("[FlowEngine] notebook lazy-load: capability gateway is mandatory — substrate refuses to fall back to runtime.fs.");const r=await e.call("fs.readFile",{path:n.filePathOrUri},{sessionId:"internal",workspaceId:t?.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:n.run.traceId,parentSpanId:n.rootSpanId},policy:{mode:"execute"}});n.notebook=JSON.parse(r)}catch{}const r=n.run.traceId,i=n.rootSpanId;for(;n.cursor<n.order.length;){if(n.cancelled)return;if(n.paused)return;const s=n.order[n.cursor];n.run.currentNodeId=s;const o=n.spec.graph.nodes.find(e=>e.id===s),a=n.run.steps.find(e=>e.stepId===s);if(!o||!a){n.cursor++;continue}if(o.disabled){a.status="SKIPPED",n.cursor++;continue}const c=o.data?.breakpoint;if(c&&"PAUSED"!==n.run.status)return n.paused=!0,n.run.status="PAUSED",Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const l=this.prepareNodeExecutionConfig(o,n),u=l.retry,d=u?.maxAttempts??0,p=u?.retryOnTimeout??!1,h=l.timeoutMs;let f=a.attempt??0;for(;f<=d;){f++,a.attempt=f,"PENDING"!==a.status&&"RETRYING"!==a.status&&"WAITING_APPROVAL"!==a.status&&(a.status="PENDING"),a.status="RUNNING",a.startedAtMs=xm(),a.endedAtMs=void 0,a.error=void 0;const c=punica.kernel.Events.manager.createCorrelationId(),u=punica.kernel.Events.manager.createCorrelationId();a.attemptCorrelationId=c,a.spanId=u,this.pendingToRunStep.set(c,{runId:e,stepId:a.stepId}),Lm("workflow.stepStarted",e,"info",{runId:e,step:{stepId:a.stepId,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,status:"RUNNING",startedAtMs:a.startedAtMs,cellId:a.cellId,attemptCorrelationId:c,spanId:u,inputsPreview:a.inputsPreview}},{traceId:r,spanId:u,parentSpanId:i}),eg({name:"flow.node.started",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,attemptCorrelationId:c,spanId:u}});try{const s=await this.executeNodeAttempt(o,a,l,{attemptCorrelationId:c,spanId:u,rootSpanId:i,traceId:r,workspaceId:t?.workspaceId,filePathOrUri:n.filePathOrUri,notebook:n.notebook,timeoutMs:h,nodeOutputs:n.nodeOutputs,runBudget:n.spec.graph.runBudget,runInput:n.input,resolvedInput:mg(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),Lm("workflow.stepFinished",e,"result",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"SUCCESS",endedAtMs:a.endedAtMs,outputsPreview:a.outputsPreview,artifactIds:a.artifactIds}},{traceId:r,spanId:u,parentSpanId:i}),eg({name:"flow.node.completed",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,attempt:a.attempt,endedAtMs:a.endedAtMs,attemptCorrelationId:c,spanId:u}}),n.cursor++,await this.persistRun(e),await this.persistCheckpoint(e),await this.persistIndex();break}catch(t){const o=String(t?.message??t);if(o.includes("Approval required"))return a.status="WAITING_APPROVAL",Lm("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const h=o.includes("Timed out")||o.includes("timeout");if(!(f<=d&&(p||!h)&&!o.includes("Policy")&&!o.includes("Invalid input"))||f>d)return"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="FAILED",a.endedAtMs=xm(),a.error={message:o},Lm("workflow.stepFinished",e,"error",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"FAILED",endedAtMs:a.endedAtMs,error:{message:o},artifactIds:a.artifactIds??[]}},{traceId:r,spanId:u,parentSpanId:i}),eg({name:"flow.node.failed",kind:"error",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,attempt:a.attempt,endedAtMs:a.endedAtMs,attemptCorrelationId:c,spanId:u,error:{message:o}}}),n.run.status="FAILED",n.run.endedAtMs=xm(),n.run.error={message:o,nodeId:s,correlationId:c},Lm("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),Lm("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),eg({name:"flow.run.failed",kind:"error",correlationId:e,traceId:r,payload:{runId:e,endedAtMs:n.run.endedAtMs,error:n.run.error}}),await this.persistRun(e),await this.persistIndex(),void this.notifyTerminal?.(e,"FAILED");const m=ag(f,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Lm("workflow.stepRetry",e,"info",{runId:e,stepId:a.stepId,attempt:f,maxAttempts:d,delayMs:m,error:o},{traceId:r,spanId:u,parentSpanId:i}),await new Promise(e=>setTimeout(e,m))}}}"RUNNING"!==n.run.status&&"PAUSED"!==n.run.status&&console.warn(`[FlowEngine] Invalid state transition to COMPLETED from ${n.run.status}`),n.run.status="COMPLETED",n.run.endedAtMs=xm(),Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),Lm("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),eg({name:"flow.run.completed",correlationId:e,traceId:r,payload:{runId:e,endedAtMs:n.run.endedAtMs}}),await this.persistRun(e),await this.persistCheckpoint(e),await this.persistIndex(),await async function(e,t,n=".punica"){const r=Gm(n,"workflow-runs",e.runId),i=Gm(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await Jm("writeRunHistory",r),await Ym("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=Gm(t,"workflow-runs",e,"checkpoint.json");try{await Zm("deleteCheckpoint",n)}catch{}}(e);const s=this.runIdToSession.get(e);if(s){try{await s.close()}catch(t){console.warn(`[FlowEngine] Error closing session for run ${e}:`,t)}this.runIdToSession.delete(e)}this.notifyTerminal?.(e,"COMPLETED")}async executeParallel(e,t,n,r){const i=r.run.traceId,s=r.rootSpanId,o=r.maxInFlight??1/0,a=!!(c=r.spec.graph.runBudget)&&!0===c.failFast;for(var c;!Um(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=zm(n,c>0?c:void 0);if(0===l.length){if(0===(r.inFlightNodes?.size??0))break;await new Promise(e=>setTimeout(e,100));continue}const u=l.map(async o=>{Km(o,n),r.inFlightNodes?.add(o),r.run.currentNodeId=o;const c=r.spec.graph.nodes.find(e=>e.id===o),l=r.run.steps.find(e=>e.stepId===o);if(!c||!l)return r.inFlightNodes?.delete(o),void Wm(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Wm(o,!0,n);try{const a=this.prepareNodeExecutionConfig(c,r),u=a.retry,d=u?.maxAttempts??0,p=a.timeoutMs;let h=l.attempt??0,f=!1;for(;h<=d&&!f;){yg(r),h++,l.attempt=h,l.status="RUNNING",l.startedAtMs=xm();const e=punica.kernel.Events.manager.createCorrelationId(),n=punica.kernel.Events.manager.createCorrelationId();l.attemptCorrelationId=e,l.spanId=n;try{const o=await this.executeNodeAttempt(c,l,a,{attemptCorrelationId:e,spanId:n,rootSpanId:s,traceId:i,workspaceId:t?.workspaceId,filePathOrUri:r.filePathOrUri,notebook:r.notebook,timeoutMs:p,nodeOutputs:r.nodeOutputs,runBudget:r.spec.graph.runBudget,runInput:r.input,resolvedInput:mg(c,r.spec.graph.edges,r.nodeOutputs??new Map)});void 0!==o.output&&r.nodeOutputs&&r.nodeOutputs.set(c.id,o.output),f=!0}catch(e){if(e instanceof gg)throw l.status="CANCELLED",l.endedAtMs=xm(),e;const t=String(e?.message??e);if(h<=d){const e=ag(h,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=xm(),l.error={message:t},e}}f&&(Wm(o,!0,n),await this.persistRun(e))}catch(t){Wm(o,!1,n),t instanceof gg||(r.run.status="FAILED",r.run.endedAtMs=xm(),r.run.error={message:String(t?.message??t),nodeId:o},a&&(r.cancelled=!0),await this.persistRun(e))}finally{r.inFlightNodes?.delete(o)}});await Promise.allSettled(u)}"RUNNING"===r.run.status?(r.run.status="COMPLETED",r.run.endedAtMs=xm(),Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),Lm("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),eg({name:"flow.run.completed",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs}}),await this.persistRun(e),await this.persistIndex(),this.notifyTerminal?.(e,"COMPLETED")):"FAILED"===r.run.status&&(eg({name:"flow.run.failed",kind:"error",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs,error:r.run.error}}),this.notifyTerminal?.(e,"FAILED"))}prepareNodeExecutionConfig(e,t){const n=cg.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:rg,retry:{...ig},requireIdempotencyKeyForWriteRetry:!1};return e&&(void 0!==e.timeoutMs&&(n.timeoutMs=e.timeoutMs),e.retry&&(n.retry={...n.retry,...e.retry}),e.rateLimit&&(n.rateLimit={...e.rateLimit}),e.concurrency&&(n.concurrency={...e.concurrency}),void 0!==e.requireIdempotencyKeyForWriteRetry&&(n.requireIdempotencyKeyForWriteRetry=e.requireIdempotencyKeyForWriteRetry)),t&&(void 0!==t.timeoutMs&&(n.timeoutMs=t.timeoutMs),t.retry&&(n.retry={...n.retry,...t.retry}),t.rateLimit&&(n.rateLimit={...t.rateLimit}),t.concurrency&&(n.concurrency={...t.concurrency})),n}(r,e.executionOverride,t.spec.graph.runBudget)}async executeNodeAttempt(e,t,n,r){const i=cg.get(e.ref.kind);let s;try{s=await(i?.acquireResources?.(e,n,{workspaceId:r.workspaceId}))}catch(e){throw new Error(`Concurrency limit reached: ${e?.message??String(e)}`)}try{const n=this.executeNode(e,r),i=r.timeoutMs?await async function(e,t){return Promise.race([e,og(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=xm(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return cg.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class wg extends Error{code="SUBFLOW_DEPTH_EXCEEDED";parentDepth;cap;constructor(e,t=8){super(`Subflow depth ${e+1} exceeds substrate cap (${t}). Substrate refuses to spawn deeper subflows — restructure the flow or reduce nesting before retrying.`),this.name="SubflowDepthExceededError",this.parentDepth=e,this.cap=t}}function vg(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new wg(e??0,t);return n}const kg="__default__";class Ig{workspaceId;#tn=new Map;#nn=new Map;#rn=new Map;#in=new qm;#be=!1;#sn=new Map;#on;#an;#cn;constructor(e=kg){this.workspaceId=e,this.#on=new tg(this.#tn,this.#sn,this.#in),this.#an=new ng(this.#tn,this.#nn,this.#rn,e=>this.#on.persistRun(e),()=>this.#on.persistIndex(),e=>this.#ln(e)),this.#cn=new bg(this.#tn,this.#rn,this.#sn,this.#in,e=>this.#on.persistRun(e),e=>this.#on.persistCheckpoint(e),()=>this.#on.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#be||(this.#be=!0,this.#an.setupApprovalSubscription(),this.#on.loadIndex())}async startRun(e){const t=await this.#on.startRun(e);return this.#ln(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#on.pauseRun(e)}async resumeRun(e){const t=await this.#on.resumeRun(e);return t&&this.#ln(e,{}),t}async cancelRun(e,t){return this.#on.cancelRun(e,t)}getRun(e){return this.#on.getRun(e)}listRuns(e){return this.#on.listRuns(e)}approvePending(e){return this.#an.approvePending(e)}rejectPending(e){return this.#an.rejectPending(e)}hasRun(e){return this.#tn.has(e)}getNodeOutput(e,t){const n=this.#tn.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=vg(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#on.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;eg({name:"flow.subflow.spawned",correlationId:n,traceId:e.parentTraceId,payload:{runId:n,depth:t,parentRunId:e.parentRunId,parentTraceId:e.parentTraceId,workspaceId:this.workspaceId,flowId:e.spec.id}});const r=new Promise(e=>{const t=this.#un.get(n);if(t)return this.#un.delete(n),void e(t);this.#dn.set(n,e)});this.#ln(n,{workspaceId:this.workspaceId});const i=await r,s=this.getRun(n),o=this.getNodeOutput(n,"flow-output");return{runId:n,parentRunId:e.parentRunId,depth:t,status:i,output:o,startedAtMs:s?.startedAtMs,endedAtMs:s?.endedAtMs,error:s?.error}}notifyTerminal(e,t){const n=this.#dn.get(e);if(n)return this.#dn.delete(e),void n(t);this.#un.set(e,t)}#dn=new Map;#un=new Map;hasPending(e){return this.#rn.has(e)}async#ln(e,t){const n=this.#tn.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;const r=void 0!==n.dependencyGraph,i=n.dependencyGraph;r&&i?await this.#cn.executeParallel(e,t,i,n):await this.#cn.executeSequential(e,t)}}const Eg=new Map,Ag=new Map,Sg=new Map;function _g(e){const t=e??kg;let n=Eg.get(t);return n||(n=new Ig(t),Eg.set(t,n)),n}let xg=!1;const Cg=new class{initialize(){if(xg)return;xg=!0;const e=punica.kernel.Commands.manager;e.registerCommand(We.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(We.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(We.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(We.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(We.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(We.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(We.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(We.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(We.RUN_SUBFLOW,{title:"Workflow: Run Subflow",execute:e=>this.runSubflow(e)})}async startRun(e){const t=function(e){const t=e?.workspaceId;return"string"==typeof t&&t.length>0?t:kg}(e),n=_g(t);n.initialize();const r=await n.startRun(e);return Ag.set(r.runId,t),r}async pauseRun(e){const t=this.#pn(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#pn(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#pn(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#pn(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#pn(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of Eg.values())t.push(...n.listRuns({status:e?.status}));return"number"==typeof e?.limit&&e.limit>0?t.slice(0,e.limit):t}approvePending(e){const t=this.#hn(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#hn(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(vg(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=_g(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Ag.set(n.runId,t.workspaceId),n}#pn(e){const t=Ag.get(e);if(t)return Eg.get(t);for(const[t,n]of Eg.entries())if(n.hasRun(e))return Ag.set(e,t),n}#hn(e){const t=Sg.get(e);if(t)return Eg.get(t);for(const[t,n]of Eg.entries())if(n.hasPending(e))return Sg.set(e,t),n}};function Tg(e){const t=e?.capability??{},n=t.outputs&&"object"==typeof t.outputs?t.outputs:{schema:{type:"object",properties:{}}};return{apiVersion:"ivy.workflow/v0.1",kind:"Workflow",id:t.id??e?.id,version:t.version??"0.0.0",title:t.title??"agent",description:t.description??"",tags:t.tags??[],inputs:t.inputs??{schema:{type:"object",properties:{}}},outputs:{...n,kind:n.kind??"direct"},policy:t.policy??{risk:"low",approval:"none"},graph:e?.graph??{entryNodeId:"flow-input",nodes:[],edges:[]}}}function Ng(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class Mg{packages=new Map;async discover(){this.packages.clear();try{if(!await vo().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=$a();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[AgentRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return Dg(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[AgentRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n);if(!Ng(r))return void console.warn(`[AgentRegistry] Not an IvyAgent manifest: ${t}`);const i=r,s=i.capability;if(!s||"object"!=typeof s||!("id"in s))return void console.warn(`[AgentRegistry] Missing capability.id in ${t}`);const o=t.lastIndexOf("/"),a=o>=0?t.slice(0,o):"";this.packages.set(s.id,{packageRoot:a,manifestPath:t,manifest:i})}catch(e){console.warn(`[AgentRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}unregister(e){return this.packages.delete(e)}clear(){this.packages.clear()}}function Dg(e,t){for(const n of e)n.isDirectory?n.children&&Dg(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let Pg;function Og(){return Pg||(Pg=new Mg),Pg}const Rg=new Set(["COMPLETED","FAILED","CANCELLED"]);function Lg(e){return new Promise(t=>setTimeout(t,e))}async function $g(e,t,n){const r=Date.now()+n;let i=e.getRun(t);for(;Date.now()<r;){i=e.getRun(t);const n=i?.status;if(n&&(Rg.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await Lg(250)}return{record:i,timedOut:!0}}async function jg(e,t,n,r,i){const s=Date.now(),o=(e,t)=>({caseId:n.id,status:e.status,durationMs:Date.now()-s,...void 0!==t?{output:t}:{},...void 0!==e.error?{error:e.error}:{},...e.assertions?{assertions:e.assertions}:{}});let a;try{const r=await e.startRun({spec:t,workspaceId:i,input:n.input});if(a=r?.runId,!a)throw new Error("Engine did not return a runId")}catch(e){const t=e instanceof Error?e.message:String(e);return o(Sm(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await $g(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(Sm(n,`Run did not complete in ${r}ms (status ${c?.status??"unknown"})`,{infrastructure:!0}))}const u=c?.status;if("WAITING_APPROVAL"===u){try{await e.cancelRun(a)}catch{}return o(Sm(n,"Run requires approval — not auto-approved in a test run",{infrastructure:!0}))}if("COMPLETED"===u){let t;try{t=e.getNodeOutput(a,"flow-output")}catch{t=void 0}return o(Am(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(Sm(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const Fg={validator:{validate:cm},registry:{discover:()=>hm().discover(),get:e=>hm().get(e),list:()=>hm().list(),search:e=>hm().search(e),setTestReport:(e,t)=>hm().setTestReport(e,t),getLatestTestReport:e=>hm().getLatestTestReport(e)},runner:{run:wm},test:{run:async function(e,t){const n=hm(),r=n.get(e);if(!r){if(t?.manifest){if(Ng(t.manifest))return async function(e,t){const n=e,r=String(n?.capability?.id??n?.id??"");if(!r)throw new Error("Agent manifest has no capability id — cannot run tests.");const i=n?.tests;if(!i||!Array.isArray(i.cases)||!i.cases.length)throw new Error(`No test specification found for agent: ${r}`);const s=Cg,o=Tg(n),a=Date.now(),c=[];for(const e of i.cases){if(e.skip){c.push({caseId:e.id,status:"skip",durationMs:0,error:"string"==typeof e.skip?e.skip:void 0});continue}const n=e.timeoutMs??i.timeoutMs??3e4;c.push(await jg(s,o,e,n,t?.workspaceId))}const l=_m({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{hm().setTestReport(r,l)}catch{}return l}(t.manifest);throw new Error(`Manifest for ${e} is not a testable IvyAgent (expected kind 'IvyAgent' with a graph).`)}throw new Error(`IvyNode not found: ${e}`)}const i=r.manifest,s=i.tests;if(!s)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of s.cases||[]){if(t.skip){a.push({caseId:t.id,status:"skip",durationMs:0,error:"string"==typeof t.skip?t.skip:void 0});continue}const n=Date.now();let r;try{const i=await wm(e,{input:t.input,runId:`test-${e}-${t.id}-${Date.now()}`,timeoutMs:s.timeoutMs||3e4}),o=i.events.filter(e=>"error"===e.type).map(e=>{const t=e.data;return t?.message||""}).join(" "),a=Am(t,i.output,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:i.output,assertions:a.assertions}}catch(e){const i=Sm(t,e instanceof Error?e.message:String(e));r={caseId:t.id,status:"error"===i.status?"fail":i.status,durationMs:Date.now()-n,error:i.error,assertions:i.assertions}}a.push(r)}const c=i.capability,l=_m({capabilityId:e,version:c&&"object"==typeof c&&"version"in c?String(c.version||"0.0.0"):"0.0.0",tier:s.tier,results:a,startedAtMs:o});return n.setTestReport(e,l),l}}},Bg={discover:()=>Og().discover(),get:e=>Og().get(e),list:()=>Og().list(),search:e=>Og().search(e),unregister:e=>Og().unregister(e),run:(e,t)=>async function(e,t){const n=Og().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??Cg,i=t?.timeoutMs??3e4,s=Tg(n.manifest),o=Date.now(),a=await r.startRun({spec:s,workspaceId:t?.workspaceId,input:t?.input??{}}),c=a?.runId;if(!c)throw new Error(`Engine did not return a runId for agent ${e}`);const{record:l,timedOut:u}=await $g(r,c,i);if(u){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} did not complete in ${i}ms (status ${l?.status??"unknown"})`)}const d=l?.status;if("WAITING_APPROVAL"===d){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} requires approval — approve the workflow run or lower the capability's approval policy`)}if("COMPLETED"===d){let e;try{e=r.getNodeOutput(c,"flow-output")}catch{e=void 0}return{output:e,runId:c,durationMs:Date.now()-o}}const p=l?.steps?.find(e=>"FAILED"===e.status);throw new Error(`Agent ${e} failed: ${l?.error?.message??p?.error?.message??`Run ended with status ${d??"unknown"}`}`)}(e,t),envelope:Tg,isAgentManifest:Ng},qg=new Map([["QUEUED",["RUNNING","CANCELLED"]],["RUNNING",["WAITING_APPROVAL","PAUSED","RETRYING","COMPLETED","FAILED","CANCELLED"]],["WAITING_APPROVAL",["RUNNING","FAILED","CANCELLED"]],["PAUSED",["RUNNING","CANCELLED"]],["RETRYING",["RUNNING","FAILED","CANCELLED"]],["COMPLETED",[]],["FAILED",[]],["CANCELLED",[]]]),zg=new Set(["COMPLETED","FAILED","CANCELLED"]);const Ug=new class{canTransitionTo(e,t){if(e===t)return!1;const n=qg.get(e);return!!n&&n.includes(t)}assertTransition(e,t){if(!this.canTransitionTo(e,t))throw new Error(`[RunStatusStateMachine] invalid transition: ${e} → ${t} (valid next states: ${this.getValidTransitions(e).join(", ")||"∅ (terminal)"})`)}getValidTransitions(e){return qg.get(e)??[]}isTerminal(e){return zg.has(e)}},Vg=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Wg={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Kg={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function Gg(e){return{x:Kg.marginX+e%6*240,y:Kg.marginY+120*Math.floor(e/6)}}function Hg(e){const t=Math.max(0,e.inputCount??0),n=Math.max(0,e.outputCount??0),r=22*(t+n),i=t>0&&n>0?9:0;return 60+Math.max(56,16+r+i)}function Yg(e,t){const n={...Kg,...t??{}},r=e.nodes??[],i={};if(!r.length)return i;const s=new Map;r.forEach((e,t)=>s.set(e.id,t));const o=(e.edges??[]).filter(e=>e.source!==e.target&&s.has(e.source)&&s.has(e.target));if(1===r.length)return i[r[0].id]={x:n.marginX,y:n.marginY},i;const a=new Map,c=new Map;for(const e of r)a.set(e.id,[]),c.set(e.id,[]);for(const e of o)a.get(e.source).push(e.target),c.get(e.target).push(e.source);const l=new Map;for(const e of r)l.set(e.id,c.get(e.id).length);const u=r.filter(e=>0===l.get(e.id)).map(e=>e.id),d=[];for(;u.length;){const e=u.shift();d.push(e);for(const t of a.get(e)){const e=l.get(t)-1;l.set(t,e),0===e&&u.push(t)}}if(d.length<r.length)return r.forEach((e,t)=>{i[e.id]=Gg(t)}),i;const p=e=>a.get(e).length>0||c.get(e).length>0,h=r.filter(e=>!p(e.id)),f=r.filter(e=>p(e.id));if(!f.length)return r.forEach((e,t)=>{i[e.id]=Gg(t)}),i;const m=new Map;for(const e of d){if(!p(e))continue;const t=c.get(e),n=t.length?Math.max(...t.map(e=>m.get(e)??0))+1:0;m.set(e,n)}const g=Math.max(...Array.from(m.values())),y=Array.from({length:g+1},()=>[]);for(const e of f)y[m.get(e.id)].push(e.id);const b=new Map,w=(e,t)=>{const n=e.map((e,n)=>{const r=t(e).filter(e=>b.has(e));return{id:e,i:n,score:r.length?r.reduce((e,t)=>e+b.get(t),0)/r.length:n}});return n.sort((e,t)=>e.score-t.score||e.i-t.i),n.map(e=>e.id)},v=e=>e.forEach((e,t)=>b.set(e,t));y.forEach(v);for(let e=1;e<y.length;e++)y[e]=w(y[e],e=>c.get(e)),v(y[e]);for(let e=y.length-2;e>=0;e--)y[e]=w(y[e],e=>a.get(e)),v(y[e]);const k=new Map;for(const e of r)k.set(e.id,Hg(e));const I=e=>e.reduce((e,t)=>e+k.get(t),0)+Math.max(0,e.length-1)*n.verticalGap,E=Math.max(...y.map(I)),A=n.marginY+E/2;y.forEach((e,t)=>{const r=n.marginX+t*(n.cardWidth+n.horizontalGap);let s=A-I(e)/2;for(const t of e)i[t]={x:r,y:s},s+=k.get(t)+n.verticalGap});const S=n.marginY+E+2*n.verticalGap;return h.forEach((e,t)=>{i[e.id]={x:n.marginX+t*(n.cardWidth+n.horizontalGap/2),y:S}}),i}let Jg;function Zg(e){if(!Jg)throw new Error(`[flow.shell] ${e}: no FlowRendererProvider injected — substrate refuses to ship a DOM implementation (D1). Hosts must call punica.flow.shell.setRendererProvider(...) before invoking the renderer.`);return Jg}function Qg(e){if(!e)throw new Error("flow.shell.setRendererProvider: provider must not be null");if("function"!=typeof e.createRenderer)throw new Error("flow.shell.setRendererProvider: provider must implement createRenderer");if("function"!=typeof e.createViewportController)throw new Error("flow.shell.setRendererProvider: provider must implement createViewportController");if("function"!=typeof e.attachZoomControl)throw new Error("flow.shell.setRendererProvider: provider must implement attachZoomControl");if("function"!=typeof e.attachMinimap)throw new Error("flow.shell.setRendererProvider: provider must implement attachMinimap");Jg=e}function Xg(){Jg=void 0}function ey(){return Jg}function ty(e){return Zg("createFlowRenderer").createRenderer(e)}function ny(e){return Zg("createViewportController").createViewportController(e)}function ry(e,t){return Zg("attachZoomControl").attachZoomControl(e,t)}function iy(e,t){return Zg("attachMinimap").attachMinimap(e,t)}function sy(e,t){const n={...e,metadata:{...e.metadata??{}}},r=n.metadata,i=r.ivy=r.ivy?{...r.ivy}:{},s=i.view??{},o={x:t.viewport?.x??s.viewport?.x??0,y:t.viewport?.y??s.viewport?.y??0,zoom:t.viewport?.zoom??s.viewport?.zoom??1},a={...s.nodes??{}};return t.nodes.forEach(e=>{e&&e.id&&(a[e.id]={x:e.x,y:e.y})}),i.view={...s,viewport:o,nodes:a},n}var oy={setRendererProvider:Qg,resetRendererProvider:Xg,getRendererProvider:ey,createFlowRenderer:ty,createViewportController:ny,attachZoomControl:ry,attachMinimap:iy,mergeViewSnapshotIntoNotebook:sy,computeFlowLayout:Yg,gridFallbackPosition:Gg,get rendererProvider(){return Jg}},ay=Object.freeze({__proto__:null,attachMinimap:iy,attachZoomControl:ry,computeFlowLayout:Yg,createFlowRenderer:ty,createViewportController:ny,default:oy,getRendererProvider:ey,gridFallbackPosition:Gg,mergeViewSnapshotIntoNotebook:sy,resetRendererProvider:Xg,setRendererProvider:Qg});function cy(e,t,n){return{path:e,message:t,severity:"error",code:n}}function ly(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const uy="WF_INVALID_VERSION",dy="WF_INVALID_EDGE_REF",py=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function hy(e){return"string"==typeof e&&py.test(e)}const fy=new class{#fn=new Map;register(e,t){if("string"!=typeof e||0===e.length)throw new Error("LambdaRegistry.register: id must be a non-empty string");if("function"!=typeof t)throw new Error("LambdaRegistry.register: fn must be a function");this.#fn.set(e,t)}unregister(e){return this.#fn.delete(e)}get(e){return this.#fn.get(e)}list(){return Array.from(this.#fn.keys())}clear(){this.#fn.clear()}},my={id:"capability-not-declared",severity:"error",check(e,t){const n=t.hasCapability??(e=>!!t.getCapability?.(e));if(!t.hasCapability&&!t.getCapability)return[];const r=[];for(let t=0;t<e.graph.nodes.length;t++){const i=e.graph.nodes[t];if(i.disabled)continue;const s=i.ref;if("ivyNode"!==s.kind&&"workflow"!==s.kind)continue;const o=s.id;"string"==typeof o&&0!==o.length&&(n(o)||r.push({ruleId:"capability-not-declared",severity:"error",message:`Capability "${o}" is not declared in the unified registry — flow refs must exist in at least one origin (extension / instruction-class / ivy-node)`,path:`graph.nodes[${t}].ref.id`,nodeId:i.id,code:"WF_UNKNOWN_CAPABILITY"}))}return r}},gy={id:"unreachable-node",severity:"warning",check(e){const t=[],n=e.graph.nodes.filter(e=>!e.disabled),r=new Set(n.map(e=>e.id)),i=e.graph.entryNodeId;if(!i||!r.has(i))return t;const s=new Map;for(const e of r)s.set(e,[]);for(const t of e.graph.edges)r.has(t.fromId)&&r.has(t.toId)&&s.get(t.fromId).push(t.toId);const o=new Set([i]),a=[i];for(;a.length>0;){const e=a.shift();for(const t of s.get(e)??[])o.has(t)||(o.add(t),a.push(t))}for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];r.disabled||(o.has(r.id)||t.push({ruleId:"unreachable-node",severity:"warning",message:`Node "${r.id}" is unreachable from entry node "${i}"`,path:`graph.nodes[${n}].id`,nodeId:r.id,code:"WF_UNREACHABLE_NODE"}))}return t}},yy={id:"dep-cycle",severity:"error",check(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=new Map,i=new Map;for(const e of t)r.set(e.id,0),i.set(e.id,[]);for(const t of e.graph.edges)n.has(t.fromId)&&n.has(t.toId)&&(i.get(t.fromId).push(t.toId),r.set(t.toId,(r.get(t.toId)??0)+1));const s=[];for(const[e,t]of r.entries())0===t&&s.push(e);let o=0;const a=new Set;for(;s.length>0;){const e=s.shift();a.add(e),o++;for(const t of i.get(e)??[])r.set(t,(r.get(t)??0)-1),0===(r.get(t)??0)&&s.push(t)}if(o===t.length)return[];const c=[],l=[];for(const e of t)a.has(e.id)||l.push(e.id);return c.push({ruleId:"dep-cycle",severity:"error",message:`Workflow graph contains a cycle among enabled nodes: ${l.join(", ")}`,path:"graph.edges",code:"WF_CYCLE"}),c}},by={id:"idempotency-required-but-no-key",severity:"error",check(e,t){if(!t.getCapability)return[];const n=[];for(let r=0;r<e.graph.nodes.length;r++){const i=e.graph.nodes[r];if(i.disabled)continue;if("ivyNode"!==i.ref.kind)continue;const s=i.ref.id;if("string"!=typeof s||0===s.length)continue;const o=t.getCapability(s);if(!o)continue;const a=o.defaults;if(!("required"===a?.execution?.idempotency))continue;const c=i.executionOverride;("none"===c?.idempotency||!0===i.data?.skipIdempotencyKey)&&n.push({ruleId:"idempotency-required-but-no-key",severity:"error",message:`Capability "${s}" declares idempotency: 'required' but node "${i.id}" opts out of key derivation — write/retry semantics will double-execute on a network retry`,path:`graph.nodes[${r}]`,nodeId:i.id,code:"WF_IDEMPOTENCY_REQUIRED"})}return n}};function wy(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function vy(e,t){if(!e)return;if(!t)return e;const n=t.split(".").filter(e=>e.length>0);let r=e;for(const e of n){if(!r||"object"!=typeof r)return;r=r.properties?.[e]}return r}const ky={id:"schema-mismatch",severity:"warning",check(e,t){if(!t.getCapability)return[];const n=[],r=new Map(e.graph.nodes.map(e=>[e.id,e]));for(let i=0;i<e.graph.edges.length;i++){const s=e.graph.edges[i],o=r.get(s.fromId),a=r.get(s.toId);if(!o||!a)continue;if(o.disabled||a.disabled)continue;const c=wy(o.ref),l=wy(a.ref);if(!c||!l)continue;const u=t.getCapability(c),d=t.getCapability(l);if(!u||!d)continue;const p=u.outputs?.schema,h=d.inputs?.schema;if(!p||!h)continue;const f=vy(p,s.fromPath),m=vy(h,s.toPath);f&&m&&(f.type&&m.type&&f.type!==m.type&&n.push({ruleId:"schema-mismatch",severity:"warning",message:`Edge ${s.fromId} → ${s.toId} type mismatch: upstream emits "${f.type}" but downstream expects "${m.type}"`,path:`graph.edges[${i}]`,code:"WF_SCHEMA_MISMATCH"}))}return n}},Iy=["while","forEach"],Ey={id:"infinite-loop",severity:"error",check(e){const t=[];for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];if(r.disabled)continue;if("primitive"!==r.ref.kind)continue;const i=r.ref.primitive;if(!Iy.includes(i))continue;const s=r.data,o=s?.maxIterations;"number"==typeof o?o<=0&&t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" has maxIterations=${o} — loops with zero or negative caps never execute the body`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"}):t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" is missing maxIterations — substrate refuses to ship unbounded loops`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"})}return t}};function Ay(e,t,n){let r=0;for(const i of e.graph.nodes){if(i.disabled)continue;if("workflow"!==i.ref.kind)continue;const e=i.ref,s=e.id??"<unnamed>";if(n.has(s))return t+1;if(!e.inline)continue;const o=new Set(n);o.add(s);const a=1+Ay(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const Sy={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Ay(e,n,new Set([i]));return s<=n||r.push({ruleId:"subflow-depth-exceeded",severity:"error",message:`Flow "${i}" has a statically-derivable inline subflow chain of depth ${s} — exceeds cap (${n}). Direct cycles count as depth > cap.`,path:"graph",code:"WF_SUBFLOW_DEPTH_EXCEEDED"}),r}},_y=[my,gy,yy,by,ky,Ey,Sy];const xy=new class{#pt=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#pt.values())try{const i=t.check(e,r);i&&i.length>0&&n.push(...i)}catch(e){n.push({ruleId:t.id,severity:"info",message:`Lint rule "${t.id}" threw during analysis: ${String(e?.message??e)}`,code:"WF_LINT_RULE_ERROR"})}return{ok:!n.some(e=>"error"===e.severity),issues:n}}register(e){if(!e||"function"!=typeof e.check)throw new Error("FlowLinter.register: rule must have a check(spec, ctx) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("FlowLinter.register: rule.id must be a non-empty string");this.#pt.set(e.id,e)}unregister(e){return this.#pt.delete(e)}list(){return Array.from(this.#pt.keys())}reset(){this.#pt.clear();for(const e of _y)this.#pt.set(e.id,e)}};function Cy(e,t,n){if(t===n)return[];const r=new Map;for(const t of e.values()){const e=r.get(t.from)??[];e.push(t),r.set(t.from,e)}const i=new Set([t]),s=new Map,o=[t];for(;o.length>0;){const e=o.shift();if(e===n)break;for(const t of r.get(e)??[])if(!i.has(t.to)){if(i.add(t.to),s.set(t.to,t),t.to===n){o.length=0;break}o.push(t.to)}}if(!i.has(n))return;const a=[];let c=n;for(;c!==t;){const e=s.get(c);if(!e)return;a.unshift(e),c=e.from}return a}function Ty(e){return e.map(e=>`${e.from}=>${e.to}`)}function Ny(e,t){return`${e}=>${t}`}const My=new class{#mn=new Map;register(e){if(!e||"function"!=typeof e.transform)throw new Error("MigrationRegistry.register: transformer must have a transform(doc) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("MigrationRegistry.register: transformer.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("MigrationRegistry.register: transformer.to must be a non-empty string");if(e.from===e.to)throw new Error("MigrationRegistry.register: transformer.from must differ from transformer.to (no self-edges)");this.#mn.set(Ny(e.from,e.to),e)}unregister(e,t){return this.#mn.delete(Ny(e,t))}find(e,t){return this.#mn.get(Ny(e,t))}list(){return Array.from(this.#mn.values())}clear(){this.#mn.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,i=e.targetVersion;if(!hy(r))return{ok:!1,reason:"invalid-result",message:`WorkflowDocument.version "${String(r)}" is not a valid semver — substrate refuses to migrate from an unrecognized version.`,appliedTransformers:[]};if(!hy(i))return{ok:!1,reason:"invalid-result",message:`targetVersion "${String(i)}" is not a valid semver — substrate refuses to migrate to an unrecognized version.`,appliedTransformers:[]};if(r===i)return{ok:!0,document:e.document,appliedTransformers:[],fromVersion:r,toVersion:i};if("reject"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'reject'. Re-invoke with 'auto-migrate' to apply registered transformers.`,appliedTransformers:[]};if("warn"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'warn'. Substrate did not migrate; downstream consumers may see a stale IR.`,partialDocument:e.document,appliedTransformers:[]};const s=("function"==typeof t.__plan?t.__plan.bind(t):(e,n)=>Cy(new Map(t.list().map(e=>[`${e.from}=>${e.to}`,e])),e,n))(r,i);if(!s||0===s.length)return{ok:!1,reason:"no-path",message:`No transformer chain from ${r} to ${i}. Register transformers via punica.flow.primitives.migrations.register(...).`,appliedTransformers:[]};let o=e.document;const a=[];for(const e of s)try{const t=e.transform(o);if(!t||"object"!=typeof t)return{ok:!1,reason:"invalid-result",message:`Transformer ${e.from}=>${e.to} returned a non-object — substrate refuses to thread an invalid document through the chain.`,partialDocument:o,appliedTransformers:Ty(a)};if(t.version!==e.to)return{ok:!1,reason:"invalid-result",message:`Transformer ${e.from}=>${e.to} produced a document with version "${String(t.version)}" — substrate enforces version-stamping on the output.`,partialDocument:o,appliedTransformers:Ty(a)};o=t,a.push(e)}catch(t){return{ok:!1,reason:"transformer-threw",message:`Transformer ${e.from}=>${e.to} threw during migration: ${String(t?.message??t)}`,partialDocument:o,appliedTransformers:Ty(a)}}return{ok:!0,document:o,appliedTransformers:Ty(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Cy(this.#mn,e,t)}};function Dy(){return Date.now()}class Py{#Oe=new Map;#Nt=new Set;register(e,t){if(!e||"string"!=typeof e.id||0===e.id.length)throw new Error("ManualTriggerProvider.register: trigger.id must be a non-empty string");if("string"!=typeof e.kind||0===e.kind.length)throw new Error("ManualTriggerProvider.register: trigger.kind must be a non-empty string");if("string"!=typeof e.flowId||0===e.flowId.length)throw new Error("ManualTriggerProvider.register: trigger.flowId must be a non-empty string");if("function"!=typeof t)throw new Error("ManualTriggerProvider.register: callback must be a function");const n={trigger:e,callback:t,unsubscribed:!1};return this.#Oe.set(e.id,n),this.#gn({type:"registered",triggerId:e.id,kind:e.kind,ts:Dy()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#Oe.get(e.id)===n&&(this.#Oe.delete(e.id),this.#gn({type:"unregistered",triggerId:e.id,ts:Dy()}))}}}unregister(e){const t=this.#Oe.get(e);return!!t&&(t.unsubscribed=!0,this.#Oe.delete(e),this.#gn({type:"unregistered",triggerId:e,ts:Dy()}),!0)}list(){return Array.from(this.#Oe.values()).map(e=>e.trigger)}subscribe(e){return this.#Nt.add(e),()=>{this.#Nt.delete(e)}}async fire(e,t){const n=this.#Oe.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Dy()}-${Math.floor(1e6*Math.random())}`,i=Dy();this.#gn({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),eg({name:"flow.trigger.fired",source:"flow:triggers",correlationId:r,payload:{triggerId:e,kind:n.trigger.kind,flowId:n.trigger.flowId,firedAtMs:i,payload:t??null}});try{return await n.callback({triggerId:e,firedAtMs:i,payload:t,correlationId:r}),!0}catch(t){return this.#gn({type:"error",triggerId:e,ts:Dy(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#Oe.values())e.unsubscribed=!0;this.#Oe.clear(),this.#Nt.clear()}#gn(e){for(const t of this.#Nt)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const Oy=new Py;let Ry=Oy;const Ly={get manager(){return Ry},setProvider(e){if(!e)throw new Error("triggers.setProvider: provider must not be null");if("function"!=typeof e.register)throw new Error("triggers.setProvider: provider must implement register()");if("function"!=typeof e.unregister)throw new Error("triggers.setProvider: provider must implement unregister()");if("function"!=typeof e.list)throw new Error("triggers.setProvider: provider must implement list()");if("function"!=typeof e.subscribe)throw new Error("triggers.setProvider: provider must implement subscribe()");Ry!==e&&Ry instanceof Py&&Ry.clear(),Ry=e},resetProvider(){Ry instanceof Py&&Ry.clear(),Ry=Oy}};function $y(e,t){return`${e}=>${t}`}const jy={migrators:new class{#yn=new Map;register(e){if(!e||"function"!=typeof e.migrate)throw new Error("CheckpointMigratorRegistry.register: migrator must have a migrate(checkpoint) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("CheckpointMigratorRegistry.register: migrator.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("CheckpointMigratorRegistry.register: migrator.to must be a non-empty string");if(e.from===e.to)throw new Error("CheckpointMigratorRegistry.register: migrator.from must differ from migrator.to");this.#yn.set($y(e.from,e.to),e)}unregister(e,t){return this.#yn.delete($y(e,t))}find(e,t){return this.#yn.get($y(e,t))}list(){return Array.from(this.#yn.values())}clear(){this.#yn.clear()}},isFresh:function(e,t,n=Date.now()){if("number"!=typeof e||Number.isNaN(e))return!1;if(!t||"number"!=typeof t.maxAgeMs)return!0;if(t.maxAgeMs<0)return!0;const r=n-e;return r>=0&&r<=t.maxAgeMs}},Fy={...Fg,agents:Bg,engine:{manager:Cg,statusStateMachine:Ug,subscribeNodeStatuses:function(e,t){const n=new Set(e.nodeIds);let r=null;const i=(e,i,s)=>{const o=String(e??"");if(!o||!n.has(o))return;const a=String(i??"").toUpperCase(),c=Wg[a];if(!c)return;const l=s?String(s):null,u=null!==l&&l!==r;u&&(r=l),t({nodeId:o,status:c,runId:l,isNewRun:u,stepStatus:a})},s=e=>{const t=e?.payload?.payload??e?.payload??{};switch(e?.name){case"workflow.stepStarted":return i(t?.step?.stepId,t?.step?.status??"RUNNING",t?.runId);case"workflow.stepUpdated":return i(t?.stepId,t?.patch?.status,t?.runId);case"workflow.stepFinished":return i(t?.step?.stepId,t?.step?.status,t?.runId);default:return}};let o=null;try{o=punica.kernel.Events.manager.subscribeMany(Vg,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:ay,validateWorkflowDocument:function(e,t){const n=[],r=[],i=t?.mode??"best-effort",s=t?.hasCapability;if(!e||"ivy.workflow/v0.1"!==e.apiVersion)return n.push(cy("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',uy)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(cy("kind",'kind must equal "Workflow"',uy)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!hy(o)){const e=cy("version","version must be a semver string (major.minor.patch[-prerelease][+build]); got "+("string"==typeof o?`"${o}"`:typeof o),"WF_INVALID_SEMVER");"strict"===i?n.push(e):r.push({...e,severity:"warning"})}if(!e.graph||"object"!=typeof e.graph)return n.push(cy("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(cy("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(cy("graph.edges","graph.edges must be an array")),{ok:!1,errors:n,warnings:r};const a=Array.isArray(e.graph.nodes)?e.graph.nodes:[],c=Array.isArray(e.graph.edges)?e.graph.edges:[],l=new Set;a.forEach((e,t)=>{const r=String(e?.id??"");if(r||n.push(cy(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(cy(`graph.nodes[${t}].id`,`id "${r}" must be unique`,"WF_DUPLICATE_ID")),l.add(r)),e.ref&&"object"==typeof e.ref){const r=e.ref;if(r.kind){const e=["flowInput","flowOutput","ivyNode","workflow","primitive"];if(e.includes(r.kind)||n.push(cy(`graph.nodes[${t}].ref.kind`,`ref.kind must be one of: ${e.join(", ")}`)),"ivyNode"!==r.kind&&"workflow"!==r.kind||"id"in r&&"string"==typeof r.id||n.push(cy(`graph.nodes[${t}].ref.id`,"ref.id is required for ivyNode/workflow refs")),"primitive"===r.kind){const e=["if","else","forEach","while","try","catch","finally","lambda"],i=r.primitive;"string"==typeof i&&e.includes(i)||n.push(cy(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(cy(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(cy(`graph.nodes[${t}].ref`,"ref is required"))});const u=a.some(e=>"flow-input"===e.id),d=a.some(e=>"flow-output"===e.id),p=c.some(e=>"flow-input"===e.fromId),h=c.some(e=>"flow-output"===e.toId);return p&&!u&&n.push(cy("graph.nodes","flow-input node is required when edges reference it")),h&&!d&&n.push(cy("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(cy("graph.entryNodeId",`entryNodeId "${e.graph.entryNodeId}" must reference an existing node`,"WF_INVALID_ENTRY")),c.forEach((e,t)=>{const r=String(e?.fromId??""),i=String(e?.toId??"");r||n.push(cy(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(cy(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(cy(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,dy)),i&&!l.has(i)&&n.push(cy(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,dy))}),"strict"===i&&function(e,t,n){const r=e.filter(e=>!e.disabled),i=new Set(r.map(e=>e.id)),s=t.filter(e=>i.has(e.fromId)&&i.has(e.toId)),o=new Map,a=new Map;for(const e of r)o.set(e.id,0),a.set(e.id,[]);for(const e of s)a.get(e.fromId).push(e.toId),o.set(e.toId,(o.get(e.toId)??0)+1);const c=[];for(const[e,t]of o.entries())0===t&&c.push(e);let l=0;for(;c.length;){const e=c.shift();l++;for(const t of a.get(e)??[])o.set(t,(o.get(t)??0)-1),0===(o.get(t)??0)&&c.push(t)}l!==r.length&&n.push(cy("edges","Workflow graph is not a DAG (cycle detected among enabled nodes).","WF_CYCLE"))}(a,c,n),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)&&function(e,t,n,r){const i=e.filter(e=>!e.disabled),s=new Set(i.map(e=>e.id));if(!s.has(n))return;const o=t.filter(e=>s.has(e.fromId)&&s.has(e.toId)),a=new Set,c=[n];for(a.add(n);c.length>0;){const e=c.shift();for(const t of o)t.fromId!==e||a.has(t.toId)||(a.add(t.toId),c.push(t.toId))}for(const t of i)if(!a.has(t.id)){const i=e.indexOf(t);r.push(ly(`graph.nodes[${i}].id`,`Node "${t.id}" is unreachable from entry node "${n}"`,"WF_UNREACHABLE_NODE"))}}(a,c,e.graph.entryNodeId,r),s&&a.forEach((e,t)=>{if(e.disabled)return;const o=e.ref;if(!o||"ivyNode"!==o.kind&&"workflow"!==o.kind)return;const a=o.id;if("string"!=typeof a||0===a.length)return;if(s(a))return;("strict"===i?n:r).push(("strict"===i?cy:ly)(`graph.nodes[${t}].ref.id`,`Capability "${a}" not found in the unified registry — flow references must exist in at least one origin (extension / instruction-class / ivy-node)`,"WF_UNKNOWN_CAPABILITY"))}),{ok:0===n.length,errors:n,warnings:r}},primitives:{lambdas:fy,linter:xy,migrations:My,checkpoints:jy},triggers:Ly};class By{name=qe.MANAGER;version="1.0.0";dependencies=[$e.COMMANDS,$e.EVENTS,je.WORKSPACE,Fe.LAYOUT];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.COMMANDS),s=r.getState($e.EVENTS),o=r.getState(je.WORKSPACE),a=r.getState(Fe.LAYOUT);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(a!==e.BOOTSTRAPPED)throw new Error("shell.layout must be bootstrapped before extensions.manager");if(!n.extensions?.manager)throw new Error("Extensions manager not available")}async start(e){}}class qy{name=Be.VALIDATOR;version="1.0.0";dependencies=[];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.kernel)throw new Error("Kernel not available");if(!t.flow?.validateWorkflowDocument)throw new Error("Flow validator not available")}async start(e){}}function zy(e){const t=e.data,n=t?.capabilityId;if(n)return String(n);const r=e.ref;return"ivyNode"===r?.kind&&null!=r.id?String(r.id):""}class Uy{prepareExecutionConfig(e){const t=zy(e);if(!t)return{};const n=Dm(),r=n?.getSpec?.(t);return{capabilityDefaults:Pm(r)}}async acquireResources(e,t,n){const r=zy(e);return async function(e,t){if(!e.concurrency)return()=>{};const n=function(e,t){let n=e;return n=n.replace(/\{workspaceId\}/g,t.workspaceId??""),n=n.replace(/\{capabilityId\}/g,t.capabilityId??""),n}(e.concurrency.key,t);return await sg.acquire(n,e.concurrency.max),()=>{sg.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=zy(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Mm();if(!o)throw new Error("[FlowEngine] Capability gateway not available");const a=function(e,t){return`${e.attemptCorrelationId}::${t}`}(t,e.id),c=await o.call(i,s,{sessionId:t.workspaceId??"default",workspaceId:t.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:t.traceId},trace:{traceId:t.traceId,parentSpanId:t.rootSpanId},policy:{mode:"execute"}},a),l=Dm(),u=l?.getSpec?.(i),d=u?.defaults?.dataClassification,p=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`${i}.result`,payload:c,meta:{source:"capability.call",capabilityId:i},redactionPolicy:e.redactionPolicy,surface:"output",capabilityClassification:d,sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Tm(Cm(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Vy(e){return e.data??{}}function Wy(e){return e.nodeOutputs??new Map}async function Ky(e,t,n,r,i){const s=await e.artifactStore.writeArtifact(t.traceId,n.id,{type:"json",name:`primitive.${r}.decision`,payload:i,meta:{source:"primitive",primitive:r},redactionPolicy:n.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Tm(Cm(i,0),320),artifactIds:[s.id]}}class Gy{async execute(e,t,n){const r=function(e){if("primitive"===e.ref.kind)return e.ref.primitive}(e);if(!r)throw new Error(`[PrimitiveExecutor] node "${e.id}" is not a primitive ref (ref.kind="${e.ref.kind}")`);switch(r){case"if":return async function(e,t,n){const r=Vy(e),i=ug(r.predicate,Wy(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:dg(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Ky(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Ky(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Vy(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:forEach] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:forEach] bodyFlowId is required on node "${e.id}"`);const i=ug(r.collection,Wy(t));if(!i.ok&&"missing-node"!==i.reason)throw new Error(`[primitive:forEach] collection did not resolve (${i.reason}) on node "${e.id}"`);const s=i.ok?i.value:null,o=Array.isArray(s)?s:[],a=o.length>r.maxIterations,c=Math.min(o.length,r.maxIterations),l={bodyFlowId:r.bodyFlowId,itemBinding:r.itemBinding??"item",maxIterations:r.maxIterations,plannedIterations:c,sourceLength:o.length,truncated:a};return{...await Ky(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Vy(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:while] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:while] bodyFlowId is required on node "${e.id}"`);const i=ug(r.predicate,Wy(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=dg(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Ky(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Vy(e);if(!r.tryBodyFlowId)throw new Error(`[primitive:try] tryBodyFlowId is required on node "${e.id}"`);const i={tryBodyFlowId:r.tryBodyFlowId,catchBodyFlowId:r.catchBodyFlowId??null,finallyBodyFlowId:r.finallyBodyFlowId??null};return{...await Ky(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Ky(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Ky(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Vy(e),i=r.lambdaId??"";if("string"!=typeof i||0===i.length)throw new Error(`[primitive:lambda] lambdaId is required on node "${e.id}"`);const s=fy.get(i);if(!s)throw new Error(`[primitive:lambda] lambdaId "${i}" is not registered (node "${e.id}")`);let o=null;if(void 0!==r.input){const n=ug(r.input,Wy(t));if(!n.ok)throw new Error(`[primitive:lambda] input did not resolve (${n.reason}) on node "${e.id}"`);o=n.value}const a=await s(o,{nodeId:e.id,attemptCorrelationId:t.attemptCorrelationId,traceId:t.traceId}),c=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`primitive.lambda.${i}.result`,payload:a,meta:{source:"primitive",primitive:"lambda",lambdaId:i},redactionPolicy:e.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Tm(Cm(a??{},0),320),artifactIds:[c.id],output:a}}(e,t,n);default:throw new Error(`[PrimitiveExecutor] unknown primitive kind: "${String(r)}" on node "${e.id}"`)}}}class Hy{async execute(e,t){return{output:t.runInput??null}}}class Yy{async execute(e,t){return{output:t.resolvedInput??null}}}let Jy=!1;class Zy{name=Be.ENGINE;version="1.0.0";dependencies=[$e.EVENTS,$e.POLICY,$e.COMMANDS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.EVENTS),s=r.getState($e.POLICY),o=r.getState($e.COMMANDS);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(Jy||(cg.register("ivyNode",new Uy),cg.register("primitive",new Gy),cg.register("flowInput",new Hy),cg.register("flowOutput",new Yy),Jy=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class Qy{name=Be.SHELL;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before shell.flow");if(!n.flow?.shell)throw new Error("Flow shell API not available")}async start(e){}}class Xy{name=$e.EVENTS;version="1.0.0";dependencies=[];#gt=e.CREATED;#l=null;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Events?.manager)throw new Error("Events manager not available");this.#l=t.kernel.Events.manager}async start(e){}get api(){return this.#l}}class eb{name=$e.COMMANDS;version="1.0.0";dependencies=[];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class tb{name=$e.POLICY;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.policy");if(!n.kernel?.Policy?.manager)throw new Error("Policy manager not available")}async start(e){}}class nb{name=$e.HISTORY;version="1.0.0";dependencies=[];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class rb{name=$e.TIME_SERVER;version="1.0.0";dependencies=[];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class ib{name=$e.TASKS;version="1.0.0";dependencies=[je.TERMINALS,je.WORKSPACE];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(je.TERMINALS),s=r.getState(je.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before kernel.tasks");if(!n.kernel?.Tasks)throw new Error("Tasks API not available")}async start(e){}}class sb{name=$e.NOTIFICATIONS;version="1.0.0";dependencies=[];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class ob{name=$e.AI;version="1.0.0";dependencies=[$e.EVENTS,$e.POLICY,$e.LLM];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.EVENTS),s=r.getState($e.POLICY),o=r.getState($e.LLM);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.llm must be bootstrapped before kernel.ai");if(!n.kernel?.AI?.manager?.initialize)throw new Error("AI manager not available");n.kernel.AI.manager.initialize()}async start(e){}}let ab=class{name=$e.LLM;version="1.0.0";dependencies=[$e.EVENTS,$e.POLICY];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.EVENTS),s=r.getState($e.POLICY);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.llm");if(!n.kernel?.llm?.manager)throw new Error("LLM manager not available");const o=n;if(o.kernel||(o.kernel={}),o.kernel.llm||(o.kernel.llm={}),!Object.prototype.hasOwnProperty.call(o.kernel.llm,"CodegenBundleV0_1Schema"))try{Object.defineProperty(o.kernel.llm,"CodegenBundleV0_1Schema",{value:Gt,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class cb{name=je.FS;version="1.0.0";dependencies=[];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class lb{name=je.SEARCH;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.search");if(!n.runtime?.search)throw new Error("Search facade not available")}async start(e){}}class ub{name=je.VCS;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.vcs");if(!n.runtime?.vcs)throw new Error("VCS facade not available")}async start(e){}}class db{name=je.WORKSPACE;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.workspace");if(!n.runtime?.workspace)throw new Error("Workspace facade not available")}async start(e){}}class pb{name=je.LLM;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.llm");if(!n.runtime?.llm)throw new Error("LLM facade not available")}async start(e){}}class hb{name=je.TASKS;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.tasks");if(!n.runtime?.tasks)throw new Error("Tasks facade not available")}async start(e){}}class fb{name=je.SECRETS;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.secrets");if(!n.runtime?.secrets)throw new Error("Secrets API not available")}async start(e){}}class mb{name=je.TERMINALS;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.terminals");if(!n.runtime?.terminals)throw new Error("Terminals facade not available")}async start(e){}}class gb{name=Fe.ACTIVITY_BAR;version="1.0.0";dependencies=[$e.COMMANDS,je.WORKSPACE];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.COMMANDS),s=r.getState(je.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.activityBar");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before shell.activityBar");if(!n.shell?.ActivityBar?.manager)throw new Error("ActivityBar manager not available")}async start(e){}}class yb{name=Fe.STATUSBAR;version="1.0.0";dependencies=[$e.EVENTS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before shell.statusbar");if(!n.shell?.Statusbar?.manager)throw new Error("Statusbar manager not available")}async start(e){}}class bb{name=Fe.VIEW;version="1.0.0";dependencies=[$e.COMMANDS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.view");if(!n.shell?.View)throw new Error("View API not available")}async start(e){const{punica:t}=e;if(t.shell?.View?.Theme?.manager)try{await t.shell.View.Theme.manager.initialize(),console.log("[ViewModule] Theme manager initialized")}catch(e){console.error("[ViewModule] Failed to initialize theme manager:",e)}}}class wb{name=Fe.VIEWS;version="1.0.0";dependencies=[Fe.LAYOUT,$e.COMMANDS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Fe.LAYOUT)!==e.BOOTSTRAPPED)throw new Error("shell.layout must be bootstrapped before shell.views");if(!n.shell?.Views?.manager)throw new Error("Views API not available")}async start(e){}}class vb{name=Fe.KEYBOARD_SHORTCUTS;version="1.0.0";dependencies=[$e.COMMANDS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.keyboardShortcuts");if(!n.shell?.KeyboardShortcuts?.manager)throw new Error("KeyboardShortcuts manager not available")}async start(e){!function(){const e=globalThis.punica?.shell?.KeyboardShortcuts?.manager;if(!e)return;const t=(t,n,r)=>{e.registerShortcut({command:n,keys:[Yf(t)],when:r})};t("mod+j",ze.TOGGLE_PANEL),t("mod+b",ze.TOGGLE_PRIMARY_SIDEBAR),t("mod+l",ze.TOGGLE_SECONDARY_SIDEBAR)}()}}class kb{name=Fe.LAYOUT;version="1.0.0";dependencies=[$e.COMMANDS,je.WORKSPACE];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.COMMANDS),s=r.getState(je.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.layout");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before shell.layout");if(!n.shell?.Layout?.manager)throw new Error("Layout manager not available")}async start(e){}}class Ib{name=Fe.CONTENT_TABS;version="1.0.0";dependencies=[$e.COMMANDS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.contentTabs");if(!n.shell?.ContentTabs)throw new Error("ContentTabs API not available")}async start(e){}}class Eb{name=Fe.PANEL_TABS;version="1.0.0";dependencies=[$e.COMMANDS];#gt=e.CREATED;get state(){return this.#gt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.panelTabs");if(!n.shell?.PanelTabs)throw new Error("PanelTabs API not available")}async start(e){}}const Ab={schemaVersion:"1",identity:{id:"ivyx-classic",name:"ivyx",version:"1.0.0",audience:"ml-engineer",branding:{productName:"ivyx"}},shell:{activeModules:["shell.activityBar","shell.statusbar","shell.view","shell.keyboardShortcuts","shell.layout","shell.views","shell.contentTabs","shell.panelTabs","flow.shell"],layout:{id:"classic-editor",root:{type:"row",sizes:[70,30],children:[{type:"column",sizes:[80,20],children:[{type:"slot",id:"content",role:"content"},{type:"slot",id:"panel",role:"panel"}]},{type:"slot",id:"secondarySidebar",role:"secondarySidebar"}]}}},theme:{mode:"auto",density:"comfortable",branding:{productName:"ivyx"}},capabilities:{allowedIds:"*"}},Sb={schemaVersion:"1",identity:{id:"agent-ops-console",name:"Agent Ops Console",version:"1.0.0",audience:"compliance-officer",branding:{productName:"Agent Ops Console"}},shell:{activeModules:["shell.statusbar","shell.view","shell.layout","shell.views","shell.contentTabs"],layout:{id:"agent-ops-dashboard",root:{type:"column",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]}}},theme:{mode:"dark",density:"compact",branding:{productName:"Agent Ops Console"}},capabilities:{allowedIds:["capability.catalog","capability.schemaExport","event.query","event.replay","llm.listProviders","workspace.get","fs.read","fs.stat","fs.exists","fs.list","fs.snapshot","approval.grant","approval.revoke","delegation.create","flow.validate","cost.report"],deniedIds:["fs.write","fs.delete","fs.copy","fs.migrate","fs.restore","workspace.create","workspace.delete","secrets.set","secrets.delete","vcs.commit","vcs.push"],allowedOrigins:["core","extension","instruction-class"]}};function _b(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"gateway"in t)return t.gateway}}function xb(e,t,n){const r=t?.__punica??{};punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,timestampMs:Date.now(),source:r.source??"core.capabilities",kind:"result"},payload:n})}function Cb(e,t,n){const r=t?.__punica??{};punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,timestampMs:Date.now(),source:r.source??"core.capabilities",kind:"error"},payload:n})}async function Tb(e,n,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await t(),actor:{type:"user",id:void 0},origin:{kind:n,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function Nb(){const e=(e,t)=>{punica.kernel.Commands.manager.registerCommand(e,t)};e("workspace.readFile",{title:"Core: workspace.readFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=_b();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");xb("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Tb("workspace.readFile","command",t))})}catch(e){Cb("capability.workspace.readFile.error",t,{error:String(e?.message??e)})}}}),e("workspace.writeFile",{title:"Core: workspace.writeFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=String(e?.content??""),i=_b();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await Tb("workspace.writeFile","command",t)),xb("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Cb("capability.workspace.writeFile.error",t,{error:String(e?.message??e)})}}}),e("workspace.listFiles",{title:"Core: workspace.listFiles",execute:async(e,t)=>{try{const e=await punica.runtime.fs.getFileTree();xb("capability.workspace.listFiles.result",t,{entries:function(e){const t=[],n=e=>{for(const r of e??[])t.push({path:r.path,name:r.name,isDirectory:r.isDirectory}),r.isDirectory&&Array.isArray(r.children)&&r.children.length>0&&n(r.children)};return n(e??[]),t}(e)})}catch(e){Cb("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{xb("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Tb("vcs.status","command",t))})}catch(e){Cb("capability.vcs.status.error",t,{error:String(e?.message??e)})}}}),e("tasks.runCommand",{title:"Core: tasks.runCommand",execute:async(e,t)=>{try{const n=String(e?.command??""),r=Array.isArray(e?.args)?e.args.map(String):[],i=null!=e?.cwd?String(e.cwd):void 0,s=e?.env&&"object"==typeof e.env?e.env:void 0;xb("capability.tasks.runCommand.result",t,{command:n,args:r,cwd:i,...await punica.runtime.capabilities.gateway.call("tasks.runCommand",{command:n,args:r,cwd:i,env:s},await Tb("tasks.runCommand","command",t))})}catch(e){Cb("capability.tasks.runCommand.error",t,{error:String(e?.message??e)})}}}),e("llm.invoke",{title:"Core: llm.invoke",execute:async(e,t)=>{const n="capability.llm.invoke.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.invoke(e);return r.ok?xb("capability.llm.invoke.result",t,r):Cb(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Cb(n,t,i),i}}}),e("llm.plan",{title:"Core: llm.plan",execute:async(e,t)=>{const n="capability.llm.plan.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.plan(e);r.ok?xb("capability.llm.plan.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"planner",role:"planner"}})}}}),e("llm.generate-code",{title:"Core: llm.generate-code",execute:async(e,t)=>{const n="capability.llm.generate-code.result",r="capability.llm.generate-code.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const i=await punica.kernel.llm.manager.api.generateCode(e);if(i.ok)if(i.structured&&"object"==typeof i.structured){const e=i.structured;if("0.1"===e.specVersion&&Array.isArray(e.files)){const r=await(punica.runtime.workspace?.getCurrent?.());if(!r?.rootUri)throw new Error("No active workspace");const s=r.rootUri.replace(/^file:\/\//,"");xb(n,t,"confirm"===await punica.shell.View.showChangesPreview({title:"Code Generation Preview",summary:e.summary||`Generated ${e.files.length} file(s)`,files:e.files.map(e=>({path:e.path,action:e.action,content:e.content})),onConfirm:async()=>{const t=await Kt(e,s);if(t.errors.length>0)throw new Error(`Failed to apply some files:\n${t.errors.map(e=>`${e.path}: ${e.error}`).join("\n")}`)}})?{...i,metadata:{...i.metadata,applied:!0}}:{...i,metadata:{...i.metadata,applied:!1,cancelled:!0}})}else xb(n,t,i)}else xb(n,t,i);else Cb(r,t,i)}catch(e){Cb(r,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"code-generator",role:"code-generator"}})}}}),e("llm.validator",{title:"Core: llm.validator",execute:async(e,t)=>{const n="capability.llm.validator.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.validator(e);r.ok?xb("capability.llm.validator.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"validator",role:"validator"}})}}}),e("llm.edit-workflow",{title:"Core: llm.edit-workflow",execute:async(e,t)=>{const n="capability.llm.edit-workflow.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.editWorkflow(e);r.ok?xb("capability.llm.edit-workflow.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"workflow-editor",role:"workflow-editor"}})}}}),e("llm.reviewer",{title:"Core: llm.reviewer",execute:async(e,t)=>{const n="capability.llm.reviewer.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.reviewer(e);r.ok?xb("capability.llm.reviewer.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"reviewer",role:"reviewer"}})}}});const t=e=>async(t,n)=>{try{await punica.runtime.capabilities.gateway.call("shell.toggleSlot",{slot:e},await Tb("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(ze.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(ze.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(ze.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Mb="1.0.0",Db=Jt,Pb=no,Ob=sd,Rb=om,Lb=Fy,$b=new class{#bn=new Map;#wn=new Map;#vn=new Map;register(t){if(this.#bn.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#bn.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#bn.set(t.name,t),this.#wn.set(t.name,e.CREATED)}get(e){return this.#bn.get(e)}getAll(){return Array.from(this.#bn.values())}resolveBootstrapOrder(){return this.#kn()}resolveStartOrder(){return this.#kn()}#kn(){const e=new Set,t=new Set,n=[],r=i=>{if(t.has(i)){const e=Array.from(t).concat(i);throw new Error(`Circular dependency detected: ${e.join(" → ")}`)}if(e.has(i))return;t.add(i);const s=this.#bn.get(i);if(!s)throw new Error(`Module ${i} not found`);for(const e of s.dependencies)r(e);t.delete(i),e.add(i),n.push(i)};for(const t of this.#bn.keys())e.has(t)||r(t);return n}async bootstrapAll(){const t=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${t.join(" → ")}`);for(const n of t){const t=this.#bn.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#wn.set(n,e.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#wn.set(n,e.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#wn.set(n,e.BOOTSTRAP_FAILED),this.#vn.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} bootstrap failed:`,r),new Error(`Critical module ${n} failed to bootstrap: ${r.message}`)}}console.log("[ModuleRegistry] All modules bootstrapped successfully")}async startAll(){const t=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${t.join(" → ")}`);for(const n of t){const t=this.#bn.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#wn.get(n);if(r!==e.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#wn.set(n,e.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#wn.set(n,e.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#wn.set(n,e.START_FAILED),this.#vn.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} start failed:`,r),new Error(`Critical module ${n} failed to start: ${r.message}`)}}for(const n of t){this.#wn.get(n)===e.STARTED&&this.#wn.set(n,e.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#wn.get(e)}areAllModulesReady(){for(const[t,n]of this.#bn){if(this.#wn.get(t)!==e.READY)return!1}return!0}getError(e){return this.#vn.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#bn.keys())t.includes(n)&&e.push(n);return e}},jb={"shell.statusbar":()=>new yb,"shell.view":()=>new bb,"shell.views":()=>new wb,"shell.keyboardShortcuts":()=>new vb,"flow.shell":()=>new Qy,"shell.contentTabs":()=>new Ib,"shell.panelTabs":()=>new Eb,"shell.layout":()=>new kb,"shell.activityBar":()=>new gb};function Fb(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Mb,kernel:Db,shell:Pb,runtime:Ob,extensions:Rb,flow:Lb};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e);const t=e.debug??{};t.logTrinityCatalog=ku,t.logTrinityCatalogVerbose=Iu,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=ku,n.logTrinityCatalogVerbose=Iu);try{!function(){const e=(e,t)=>({id:e,extensionName:"core",definition:{...t,id:e,version:t.version||"1.0.0"}}),t=[e("workspace.readFile",{title:"Read file",description:"Read a file from the current workspace.",inputs:{schema:{type:"object",required:["path"],properties:{path:{type:"string"}}}},outputs:{kind:"event",resultEvent:"capability.workspace.readFile.result",errorEvent:"capability.workspace.readFile.error"},policy:{risk:"low",approval:"none"}}),e("workspace.writeFile",{title:"Write file",description:"Write textual content to a file in the current workspace.",inputs:{schema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}}},outputs:{kind:"event",resultEvent:"capability.workspace.writeFile.result",errorEvent:"capability.workspace.writeFile.error"},policy:{risk:"medium",approval:"step"}}),e("workspace.listFiles",{title:"List workspace files",description:"List the workspace file tree.",inputs:{schema:{type:"object",properties:{}}},outputs:{kind:"event",resultEvent:"capability.workspace.listFiles.result",errorEvent:"capability.workspace.listFiles.error"},policy:{risk:"low",approval:"none"}}),e("vcs.status",{title:"VCS status",description:"Get version control (git) status for the current workspace.",inputs:{schema:{type:"object",properties:{}}},outputs:{kind:"event",resultEvent:"capability.vcs.status.result",errorEvent:"capability.vcs.status.error"},policy:{risk:"low",approval:"none"}}),e("tasks.runCommand",{title:"Run task/command",description:"Run a command via the host task runner.",inputs:{schema:{type:"object",required:["command"],properties:{command:{type:"string"},args:{type:"array"},cwd:{type:"string"},env:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.tasks.runCommand.result",errorEvent:"capability.tasks.runCommand.error"},policy:{risk:"high",approval:"step"}}),e("llm.invoke",{title:"Invoke LLM with instruction class",description:"Invoke an LLM using a predefined instruction class (planner, code-generator, validator, etc.)",inputs:{schema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",description:"Instruction class ID (e.g., planner, code-generator, validator). Available classes are registered at runtime."},userPrompt:{type:"string"},context:{type:"object",properties:{workspaceId:{type:"string"},filePath:{type:"string"},previousOutputs:{type:"object"},capabilities:{type:"array"}}},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"}}}}}},outputs:{kind:"event",resultEvent:"capability.llm.invoke.result",errorEvent:"capability.llm.invoke.error"},policy:{risk:"medium",approval:"step"}}),e("llm.plan",{title:"LLM Planner",description:"Generate Workflow IR from natural language query",inputs:{schema:{type:"object",required:["query"],properties:{query:{type:"string"},capabilities:{type:"array"}}}},outputs:{kind:"event",resultEvent:"capability.llm.plan.result",errorEvent:"capability.llm.plan.error"},policy:{risk:"medium",approval:"step"}}),e("llm.generate-code",{title:"LLM Code Generator",description:"Generate code from requirements",inputs:{schema:{type:"object",required:["requirements"],properties:{requirements:{type:"string"},language:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.generate-code.result",errorEvent:"capability.llm.generate-code.error"},policy:{risk:"low",approval:"none"}}),e("llm.validator",{title:"LLM Code Validator",description:"Validate code and identify issues",inputs:{schema:{type:"object",required:["code"],properties:{code:{type:"string"},language:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.validator.result",errorEvent:"capability.llm.validator.error"},policy:{risk:"low",approval:"none"}}),e("llm.reviewer",{title:"LLM Code Reviewer",description:"Provide code review feedback",inputs:{schema:{type:"object",required:["code"],properties:{code:{type:"string"},language:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.reviewer.result",errorEvent:"capability.llm.reviewer.error"},policy:{risk:"low",approval:"none"}}),e("flow.migrate",{title:"Migrate WorkflowDocument",description:"Apply a host-registered transformer chain to bring a WorkflowDocument from its declared version to the requested target. Substrate ships an empty migration registry; hosts inject transformers. Pure analysis — no run state mutated.",inputs:{schema:{type:"object",required:["document","targetVersion"],properties:{document:{type:"object"},targetVersion:{type:"string"},policy:{type:"string",enum:["auto-migrate","warn","reject"]}}}},outputs:{kind:"event",resultEvent:"capability.flow.migrate.result",errorEvent:"capability.flow.migrate.error"},policy:{risk:"low",approval:"none"},sideEffects:[]}),e("flow.runSubflow",{title:"Run subflow",description:'Spawn a child Workflow run from an in-flight parent. Substrate enforces MAX_SUBFLOW_DEPTH (8) and inherits the parent workspace + approval scope so a parent "once" approval is not re-prompted by the child.',inputs:{schema:{type:"object",required:["spec"],properties:{spec:{type:"object",description:"WorkflowDocument to run. Must validate against the substrate validator before dispatch."},workspaceId:{type:"string"},input:{description:"Optional structured input threaded into the child flow-input node."},parentRunId:{type:"string"},parentTraceId:{type:"string"},parentDepth:{type:"number",minimum:0,maximum:8},filePathOrUri:{type:"string"}}}},outputs:{kind:"event",resultEvent:"capability.flow.runSubflow.result",errorEvent:"capability.flow.runSubflow.error"},policy:{risk:"medium",approval:"none"},sideEffects:["workflow-spawn"]}),e("llm.edit-workflow",{title:"LLM Workflow Editor",description:"Edit and optimize Workflow IR structures",inputs:{schema:{type:"object",required:["workflow"],properties:{workflow:{type:"object"},requirements:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.edit-workflow.result",errorEvent:"capability.llm.edit-workflow.error"},policy:{risk:"medium",approval:"step"}})];punica.extensions.manager.registerBuiltinCapabilities(t)}(),console.log("[Punica] Core capabilities registered")}catch(e){console.error("[Punica] Failed to register core capabilities:",e?.message??e,e?.stack)}try{Nb(),console.log("[Punica] Core commands registered")}catch(e){console.error("[Punica] Failed to register core commands:",e?.message??e,e?.stack)}console.log("[Punica] Initialization completed successfully")}catch(e){throw console.error("[Punica] CRITICAL: Initialization failed:",e?.message??e,e?.stack),e}}async function Bb(e){try{console.log("[Punica] Starting module bootstrap...");const t=Pb.Profile.manager;t.registry.has("ivyx-classic")||t.registry.register(Ab),t.registry.has("agent-ops-console")||t.registry.register(Sb),void 0!==e?.profile?t.loadProfile(e.profile):t.registry.setActive("ivyx-classic");const n=t.registry.getActive();console.log(`[Punica] Active ApplicationProfile: ${n.identity.id}`);try{Pb.Layout.manager.applyApplicationProfile(n)}catch{}$b.register(new Xy),$b.register(new eb),$b.register(new nb),$b.register(new rb),$b.register(new sb),$b.register(new qy),$b.register(new tb),$b.register(new ab),$b.register(new ob),$b.register(new Zy),$b.register(new cb),$b.register(new lb),$b.register(new ub),$b.register(new db),$b.register(new pb),$b.register(new fb),$b.register(new mb),$b.register(new hb),$b.register(new Bu),$b.register(new ib);const r=t.getActiveModules();for(const e of r){const t=jb[e];t&&($b.register(t()),console.log(`[Punica] Shell module registered: ${e}`))}$b.register(new By),console.log(`[Punica] Module registry initialized with ${$b.getAll().length} modules`),await $b.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}}async function qb(){try{console.log("[Punica] Starting system..."),await $b.startAll(),$b.areAllModulesReady()&&punica.kernel?.Events?.manager&&punica.kernel.Events.manager.publishEvent({name:"punica.ready",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"punica:core",kind:"lifecycle"},payload:{version:Mb}}),console.log("[Punica] System started successfully"),ku()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}}var zb=Object.freeze({__proto__:null,StdioTransport:class{#In;#En;#An;#Sn=null;#_n=null;#xn=null;#Cn=null;#Tn=null;#Nn=new Map;#Mn=1;#Dn="";constructor(e,t=[],n={}){this.#In=e,this.#En=t,this.#An=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#Pn(e):await this.#On()}async#Pn(e){this.#xn=e;const{sessionId:t}=await e.spawn({command:this.#In,args:this.#En,env:this.#An});this.#_n=t,this.#Cn=e.onData(e=>{e.sessionId===t&&this.#Rn(e.chunk)}),this.#Tn=e.onExit(e=>{if(e.sessionId!==t)return;const n=new Error(e.error??`MCP stdio process exited (${e.code})`);for(const{reject:e}of this.#Nn.values())e(n);this.#Nn.clear()})}async#On(){const e=await import(
|
|
2
|
-
/* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#
|
|
1
|
+
var e;!function(e){e.CREATED="created",e.BOOTSTRAPPING="bootstrapping",e.BOOTSTRAPPED="bootstrapped",e.BOOTSTRAP_FAILED="bootstrap_failed",e.STARTING="starting",e.STARTED="started",e.START_FAILED="start_failed",e.READY="ready"}(e||(e={}));async function t(){try{const e=punica.runtime?.workspace;if(!e)return;const t=await e.getCurrent();return t?.id}catch(e){return void console.warn("[hostAccess] Failed to get current workspace id:",e)}}function n(){return punica.runtime?.fs}const r={manager:new class{#e=new Map;#t=new Map;registerCommand(e,t){const n={dispose:()=>{this.#e.delete(e),this.#t.delete(e)}};t.disposable=n,this.#t.set(e,n),this.#e.set(e,t)}executeCommand(e,...t){const n=this.#e.get(e);if(!n){const n=punica.extensions?.manager;if(!n)return void console.error(`[Commands] Command ${e} not found (extension manager unavailable)`);const r=n.getExtensionsForCommand(e);if(0===r.length)return void console.error(`[Commands] Command ${e} not found`);const i=r[0];return n.activate(i,{reason:"command",trigger:e}).then(()=>{const n=this.#e.get(e);return n?(console.log("[Commands] execute after activate",e,"via extension",i),n.execute(...t)):void console.error(`Command ${e} not found after activating extension "${i}"`)}).catch(t=>{console.error(`Error activating extension "${i}" for command ${e}:`,t)})}console.log("[Commands] execute",e,"with args",t);try{const r=n.execute(...t);return r&&"function"==typeof r.then&&r.catch(t=>{console.error(`[Commands] Command ${e} rejected:`,t)}),r}catch(t){throw console.error(`[Commands] Command ${e} threw:`,t),t}}disposeCommand(e){const t=this.#t.get(e);t?t.dispose():console.error(`Command ${e} not found or already disposed`)}getAllCommands(){return Array.from(this.#e.entries()).map(([e,t])=>({id:e,command:t}))}}};const i=new class{async write(e){try{const t=n();if(!t)return;const r=".punica/audit";await t.createFolder(r).catch(()=>{});const i=new Date(e.timestamp).toISOString().split("T")[0],s=`${r}/${`${i}_${e.invocationId}.json`}`;await t.createFileWithContent(s,JSON.stringify(e,null,2))}catch(e){console.warn("[AuditWriter] Failed to write audit record:",e)}}async read(e){try{const t=n();if(!t)return[];const r=".punica/audit",i=await t.getFileTree(),s=(e,t)=>{const n=[];for(const r of e)(r.path.startsWith(t+"/")||r.path===t)&&(r.isDirectory||n.push(r),r.isDirectory&&r.children&&n.push(...s(r.children,t)));return n},o=s(i,r),a=[];for(const n of o)if(n.name.endsWith(".json"))try{const r=await t.readFile(n.path),i=JSON.parse(r);if(e?.since&&i.timestamp<e.since)continue;if(e?.until&&i.timestamp>e.until)continue;if(e?.capability&&i.capability!==e.capability)continue;if(e?.workspaceId&&i.workspace!==e.workspaceId)continue;a.push(i)}catch(e){console.warn(`[AuditWriter] Failed to read audit file ${n.name}:`,e)}return a.sort((e,t)=>t.timestamp-e.timestamp),a}catch(e){return console.warn("[AuditWriter] Failed to read audit records:",e),[]}}};const s={manager:new class{#n=new Map;#r=[];#i=[];registerCommand(e){this.#n.set(e.id,e)}executeCommand(e){const t=this.#n.get(e);t?(t.execute(),this.#r.push(t),this.#i=[]):console.error(`Command with ID ${e} not found.`)}undo(){const e=this.#r.pop();e?(e.undo(),this.#i.push(e)):console.error("No command to undo.")}redo(){const e=this.#i.pop();e?(e.execute(),this.#r.push(e)):console.error("No command to redo.")}},auditWriter:i};const o={manager:new class{#s=[];#o=null;#a(){null===this.#o&&(this.#o=window.setInterval(()=>{const e=new Date;this.#s.forEach(t=>t.update(e))},1e3))}#c(){null!==this.#o&&(window.clearInterval(this.#o),this.#o=null)}subscribe(e){this.#s.push(e),1==this.#s.length&&this.#a()}unsubscribe(e){this.#s=this.#s.filter(t=>t!==e),0==this.#s.length&&this.#c()}}};function a(){return(new Date).toISOString()}function c(e,t){const n=new Map,r=new Map,i=new Set;function s(e){for(const t of i)try{t(e)}catch{}try{const t=window,n=t.punica?.Commands?.manager,r=t.punica?.runtime,i="failed"===e.status?"error":"cancelled"===e.status?"warning":"info";let s=`[${e.label}] ${e.status}`;null!=e.exitCode&&(s+=` (exitCode=${e.exitCode})`),n&&n.executeCommand("output.append",{channel:"Tasks",text:s,level:i}),r?.events?.publish("tasks.runChanged",{run:e}),!r?.notifications||"failed"!==e.status&&"success"!==e.status||r.notifications.push({id:"",level:"failed"===e.status?"error":"success",title:e.label,message:s,timestamp:"",source:"tasks",actionCommandId:"tasks.open"})}catch{}}const o={listDefinitions:async()=>Array.from(n.values()),registerDefinition(e){n.set(e.id,e)},unregisterDefinition(e){n.delete(e)},async run(i,c){const l=n.get(i);if(!l)throw new Error(`[Runtime.tasks] Task definition not found: ${i}`);const u=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`task_${Date.now()}_${Math.floor(1e6*Math.random())}`}(),d=a(),{env:p,workspaceId:h,resolvedEnvironmentId:f}=await async function(e,n){if(!t)return{env:e};try{const r=await t.getCurrent();if(!r)return{env:e};const i=n??r.currentEnvironmentId,s=r.environments.find(e=>e.id===i),o={...s?.variables??{},...e??{}};return{env:Object.keys(o).length?o:void 0,workspaceId:r.id,resolvedEnvironmentId:s?.id}}catch{return{env:e}}}(l.env,c?.environmentId),m=await e.create({cwd:l.cwd,env:p,title:l.label}),g={runId:u,definitionId:l.id,label:l.label,status:"running",startedAt:d,terminalId:m.id,workspaceId:h,environmentId:f};r.set(u,g),s(g);const y=[l.command,...l.args??[]].join(" ").trim();try{const e=window,t=e.punica?.Commands?.manager;t&&"function"==typeof t.executeCommand&&(y?t.executeCommand("terminal.openForTaskSession",{sessionId:m.id,commandLine:y}):t.executeCommand("terminal.openForSession",m.id))}catch{}return e.onExit(m.id,e=>{const t=r.get(u);if(!t)return;const n={...t,status:0===e||null==e?"success":"failed",finishedAt:a(),exitCode:e??null};r.set(u,n),s(n),l.autoRerun&&setTimeout(()=>{o.run(l.id,{environmentId:f}).catch(()=>{})},300)}),g},getRun:async e=>r.get(e)??null,async listRuns(e){let t=Array.from(r.values());return e?.status&&e.status.length&&(t=t.filter(t=>e.status.includes(t.status))),e?.definitionId&&(t=t.filter(t=>t.definitionId===e.definitionId)),e?.workspaceId&&(t=t.filter(t=>t.workspaceId===e.workspaceId)),t},async cancel(t){const n=r.get(t);if(!n)return;if("running"!==n.status||!n.terminalId)return;try{e.close(n.terminalId)}catch{}const i={...n,status:"cancelled",finishedAt:a()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const l=new class{#l=null;#u(){if(this.#l)return this.#l;const e=globalThis.punica;if(!e)throw new Error("[Tasks.manager] Punica not initialized. Call punica.initialize() first.");const t=e.runtime?.terminals;if(!t)throw new Error("[Tasks.manager] Runtime terminals not available. Host must provide punica.runtime.terminals");const n=e.runtime?.workspace;return this.#l=c(t,n),this.#l}async listDefinitions(){return this.#u().listDefinitions()}registerDefinition(e){this.#u().registerDefinition(e)}unregisterDefinition(e){this.#u().unregisterDefinition(e)}async run(e,t){return this.#u().run(e,t)}async getRun(e){return this.#u().getRun(e)}async listRuns(e){return this.#u().listRuns(e)}async cancel(e){return this.#u().cancel(e)}onDidChangeRun(e){return this.#u().onDidChangeRun(e)}};var u={manager:l},d=Object.freeze({__proto__:null,createTasksApi:c,default:u,manager:l});function p(e){let t=String(e??"");try{const e=punica.runtime?.secrets;if(e){const n=e.list();for(const r of n){const n=e.get(r.name);n&&"string"==typeof n&&n.length>=4&&(t=t.split(n).join("[REDACTED]"))}}}catch{}return t}function h(e){return p(function(e){let t=String(e??"");const n=[/\bsk-[A-Za-z0-9]{20,}\b/g,/\bghp_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*\b/g,/(\b(password|passwd|pwd|secret|token|api[_-]?key)\b\s*[:=]\s*)([^\s'"]+)/gi];for(const e of n)t=t.replace(e,(e,t)=>"string"==typeof t?`${t}[REDACTED]`:"[REDACTED]");return t}(e))}const f=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function m(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||f.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function g(e,t=2){const n=function(e){const t=new WeakSet;return function e(n){if(null===n||"object"!=typeof n)return n;if(t.has(n))return"[Circular]";if(t.add(n),Array.isArray(n))return n.map(e);const r={};for(const[t,i]of Object.entries(n))m(t)?r[t]=null==i?i:"[REDACTED]":r[t]=e(i);return r}(e)}(e);return h(JSON.stringify(n,null,t))}function y(e){const t=[];return function e(n,r){if(!n||"object"!=typeof n)return;const i=n,s=i.properties;if(s&&"object"==typeof s)for(const[n,i]of Object.entries(s)){if(!i||"object"!=typeof i)continue;const s=i,o=[...r,n];!0===s.sensitive&&t.push(o),e(s,o)}const o=i.items;if(o&&"object"==typeof o)if(Array.isArray(o))for(const t of o)e(t,[...r,"*"]);else e(o,[...r,"*"]);for(const t of["anyOf","oneOf","allOf"]){const n=i[t];if(Array.isArray(n))for(const t of n)e(t,r)}}(e,[]),t}function b(e,t){if(0===t.length)return e;return function e(t,n){if(null===t||"object"!=typeof t)return t;if(0===n.length)return t;if(Array.isArray(t)){const r=[];let i=!1;for(const e of n)"*"===e[0]&&(1===e.length?i=!0:r.push(e.slice(1)));return i&&0===r.length?t.map(e=>null==e?e:"[REDACTED]"):t.map(t=>e(t,r))}const r={};for(const[i,s]of Object.entries(t)){const t=[];let o=!1;for(const e of n)e[0]===i&&(1===e.length?o=!0:t.push(e.slice(1)));o?r[i]=null==s?s:"[REDACTED]":t.length>0?r[i]=e(s,t):r[i]=s}return r}(e,t)}const w=6048e5,v={rules:[],defaultTtlMs:w};function k(e,t){if(t===e)return!0;if("*"===t)return!0;if(t.endsWith(".*")){const n=t.slice(0,-1);return e.startsWith(n)}return!1}function I(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(k(e,i.pattern)){const e=i.pattern.length;e>r&&(n=i,r=e)}return n}(e,t.rules??[]);return n-(r?.ttlMs??t.defaultTtlMs??w)}const E=".punica/events";let A={};function S(e){const t=[],n=[...e];for(;n.length>0;){const e=n.pop();if(e){if(Array.isArray(e.children))for(const t of e.children)n.push(t);!0!==e.isDirectory&&"string"==typeof e.path&&e.path.startsWith(E)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function _(e,t){if(!t)return!0;const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId&&n?.id!==t.correlationId)return!1;if(void 0!==t.name){if(!(Array.isArray(t.name)?t.name:[t.name]).includes(e.name))return!1}return!(void 0!==t.since&&(n?.timestampMs??0)<t.since)&&!(void 0!==t.until&&(n?.timestampMs??0)>t.until)}const x=new class{#d;#p=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const r=n();if(!r)return;if(punica.runtime?.workspace&&!await t())return;const i=Date.now();try{await r.createFolder(E)}catch{}if(!this.#p){this.#p=!0;try{await r.createFileWithContent(`${E}/.gitignore`,"*\n!.gitignore\n")}catch{}}for(const t of e)try{const e=t.envelope?.timestampMs??Date.now(),n=new Date(e).toISOString().split("T")[0],i=t.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,s=`${E}/${n}_${i}.json`,o=g(t);await r.createFileWithContent(s,o)}catch{}try{A.onWrite?.(Date.now()-i,e.length)}catch{}}async query(e){const t=n();if(!t)return[];let r;try{r=await t.getFileTree()}catch{return[]}if(!Array.isArray(r))return[];const i=S(r),s=[];for(const n of i)try{const r=await t.readFile(n),i=JSON.parse(r);_(i,e)&&s.push(i)}catch{}return s.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),e?.limit&&e.limit>0?s.slice(-e.limit):s}async delete(e){const t=n();if(!t)return 0;let r;try{r=await t.getFileTree()}catch{return 0}if(!Array.isArray(r))return 0;const i=S(r);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(_(JSON.parse(r),e))await t.deleteFile(n),s++;else{const e=n.split("/").pop()??"",t=e.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]??"";o.push({path:n,dateKey:t})}}catch{}if(o.length>this.#d){o.sort((e,t)=>e.dateKey.localeCompare(t.dateKey));const e=o.length-this.#d;for(const n of o.slice(0,e))try{await t.deleteFile(n.path),s++}catch{}}return s}async applyRetention(e,t=Date.now()){const r=n();if(!r)return 0;let i;try{i=await r.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=S(i);let o=0;for(const n of s)try{const i=await r.readFile(n),s=JSON.parse(i),a=s.envelope?.timestampMs??0;a<I(s.name,e,t)&&(await r.deleteFile(n),o++)}catch{}return o}};let C=x;function T(){return C}const N=new class{#h=void 0;get(){return this.#h}runWith(e,t){const n=this.#h;let r;this.#h=e;try{r=t()}catch(e){throw this.#h=n,e}return r&&"function"==typeof r.then?r.then(e=>(this.#h=n,e),e=>{throw this.#h=n,e}):(this.#h=n,r)}};let M=N;function D(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=M.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function P(e,t){const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId)return!1;if(void 0!==t.traceId&&n?.traceId!==t.traceId)return!1;if(void 0!==t.kind){const e=Array.isArray(t.kind)?t.kind:[t.kind];if(0===e.length)return!1;if(!e.includes(n?.kind))return!1}if(void 0!==t.source){const e=Array.isArray(t.source)?t.source:[t.source];if(0===e.length)return!1;if(!n?.source||!e.includes(n.source))return!1}if(void 0!==t.name){const n=Array.isArray(t.name)?t.name:[t.name];if(0===n.length)return!1;let r=!1;for(const t of n)if(k(e.name,t)){r=!0;break}if(!r)return!1}return!0}class O extends Error{constructor(e){super(e),this.name="EventReplayError"}}let R={exportSpan:()=>{}};function L(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function $(){return Date.now()}function j(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;function o(){try{A.onQueueDepthChange?.(i.length)}catch{}}async function a(){if(0===i.length)return;const e=[...i];i=[],o(),s&&(clearTimeout(s),s=null);try{await T().write(e),U()}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function c(e){(function(e){const t=e.name;return r.some(e=>e.test(t))})(e)&&(i.push(e),o(),i.length>=10?a():s||(s=setTimeout(()=>{a()},5e3)))}function l(n,r){if("string"==typeof n){const t=n;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(r),()=>{i?.delete(r),i&&0===i.size&&e.delete(t)}}const i={filter:n,listener:r};return t.push(i),()=>{const e=t.indexOf(i);e>=0&&t.splice(e,1)}}function u(r,i){const s=i,o=s&&"object"==typeof s&&s.name===r?s:{name:r,envelope:{id:L(),timestampMs:$()},payload:i};try{n.push(o),n.length>200&&n.splice(0,n.length-200),c(o)}catch{}const a=e.get(r);if(a&&a.size>0)for(const e of a)try{e(i)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(P(o,t.filter))try{t.listener(o)}catch{}}}async function d(e){try{return await T().query(e)}catch{return[]}}function p(e){let t=[...n];if(e?.correlationId){const n=e.correlationId;t=t.filter(e=>e.envelope?.correlationId===n||e.envelope?.id===n)}if(e?.name){const n=Array.isArray(e.name)?e.name:[e.name];t=t.filter(e=>n.includes(e.name))}if(e?.kind){const n=Array.isArray(e.kind)?e.kind:[e.kind];t=t.filter(e=>n.includes(e.envelope?.kind))}if(e?.source){const n=Array.isArray(e.source)?e.source:[e.source];t=t.filter(e=>e.envelope?.source&&n.includes(e.envelope.source))}return"number"==typeof e?.since&&(t=t.filter(t=>(t.envelope?.timestampMs??0)>=e.since)),"number"==typeof e?.until&&(t=t.filter(t=>(t.envelope?.timestampMs??0)<=e.until)),t.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),"number"==typeof e?.limit&&e.limit>0&&(t=t.slice(-e.limit)),t}const h={publish:u,subscribe:l,subscribeMany(e,t){const n=e.map(e=>l(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:L,publishEvent:function(e){const t=D({id:e.envelope?.id??L(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??$(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{R.exportSpan(function(e){const t=e.envelope,n={};if(void 0!==t.source&&(n.source=t.source),void 0!==e.payload&&null!==e.payload){const t=g(e.payload);try{n.payload=JSON.parse(t)}catch{n.payload=t}}return{traceId:t.traceId,spanId:t.spanId??t.id,parentSpanId:t.parentSpanId,correlationId:t.correlationId,name:e.name,timestampMs:t.timestampMs,kind:t.kind,source:t.source,attributes:n}}(n))}catch{}return u(n.name,n),t},getRecent(e){const t="number"==typeof e&&e>0?e:n.length;return n.slice(Math.max(0,n.length-t))},filterEvents:p,getTrace:function(e){return p({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?p(e.filter):[...n].sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0));if("csv"===t){const e=["timestamp","name","kind","source","correlationId","id","payload"],t=r.map(e=>[e.envelope?.timestampMs?new Date(e.envelope.timestampMs).toISOString():"",e.name,e.envelope?.kind??"",e.envelope?.source??"",e.envelope?.correlationId??"",e.envelope?.id??"",g(e.payload??{},0)]);return[e.join(","),...t.map(e=>e.map(e=>{const t=String(e);return t.includes(",")||t.includes('"')||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}).join(","))].join("\n")}return g({exportedAt:$(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:d,replay:async function(e){"dispatch"===e.mode&&function(){throw new O('events.replay({ mode: "dispatch" }) is disabled. Host must call setReplayDispatchAllowed(true) during bootstrap (test/dev only — side-effectful listeners will fire again).')}();const t=!1!==e.includePersisted,r=[...n];let i=[];if(t)try{i=await d({name:e.name,since:e.since,until:e.until})}catch{i=[]}const s=function(e,t,n){const r=new Set,i=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}i.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}i.push(e)}const s={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=i.filter(e=>{if(!P(e,s))return!1;const t=e.envelope?.timestampMs??0;return!(void 0!==n.since&&t<n.since||void 0!==n.until&&t>n.until)});return o.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),void 0!==n.limit&&n.limit>0&&(o=o.slice(-n.limit)),o}(r,i,{name:e.name,correlationId:e.correlationId,traceId:e.traceId,kind:e.kind,source:e.source,since:e.since,until:e.until,limit:e.limit});if("log"===e.mode)for(const e of s)console.log("[Punica Replay]",e.name,e);else for(const e of s)u(e.name,e);return{count:s.length,events:s}}};return h}const F=j();var B={manager:F};let q=v;function z(){return q}async function U(){try{const e=T(),t=z();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??w;return await e.delete({until:$()-n})??0}catch{return 0}}var V=Object.freeze({__proto__:null,createCorrelationId:L,createEventsApi:j,default:B,getRetentionConfig:z,manager:F,runEventRetentionCleanup:U,setRetentionConfig:function(e){q=e??v}});function W(){let e=[];const t=new Set;function n(){for(const e of t)try{e()}catch{}}const r={list:async()=>e.slice(),push(t){const r=t.id||`notif_${Date.now()}_${Math.random().toString(36).slice(2)}`,i=t.timestamp||(new Date).toISOString(),s={...t,id:r,timestamp:i};e=[s,...e],n()},markRead(t){e=e.map(e=>e.id===t?{...e,read:!0}:e),n()},clear(t){e=t?e.filter(e=>e.source!==t):[],n()},onDidChange:e=>(t.add(e),()=>{t.delete(e)})};return r}const K=W();var G={manager:K},H=Object.freeze({__proto__:null,createNotificationsApi:W,default:G,manager:K});const Y="punica.kernel.policy.v2";function J(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function Z(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class Q{#f=new Map;constructor(){this.#m()}set(e,t,n){let r=this.#f.get(e);r||(r=new Map,this.#f.set(e,r)),r.set(t,n),this.#g()}get(e,t){return this.#f.get(e)?.get(t)}has(e,t){return this.#f.get(e)?.has(t)??!1}delete(e,t){const n=this.#f.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#f.delete(e),r&&this.#g(),r}list(){const e=[];for(const t of this.#f.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#f.size&&(this.#f.clear(),this.#g())}restoreAll(e){this.#f.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=Z(n);if(!e)continue;let r=this.#f.get(n.key);r||(r=new Map,this.#f.set(n.key,r)),r.set(e,n),t++}return this.#g(),t}#m(){const e=J();if(e)try{const t=e.getItem(Y);if(!t)return;const n=JSON.parse(t);if(!Array.isArray(n?.approvals))return;for(const e of n.approvals){if(!e||"string"!=typeof e.key)continue;const t=Z(e);if(!t)continue;let n=this.#f.get(e.key);n||(n=new Map,this.#f.set(e.key,n)),n.set(t,e)}}catch{}}#g(){const e=J();if(e)try{let t={};try{const n=e.getItem(Y);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,approvals:this.list(),exportedAt:Date.now()};e.setItem(Y,JSON.stringify(n))}catch{}}}let X=new Q;function ee(){return Date.now()}function te(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function ne(e){return`${e.kind}:${e.id}`}function re(e,t){return"workspace"===e?`workspace:${t??""}`:e}function ie(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const se="punica.kernel.policy.v1",oe="punica.kernel.policy.v2";class ae{#y="execute";#b;#w=new Set;#v=new Map;#k=[];#I=1e3;constructor(e){this.#b=e??new Q,this.#E()}#E(){const e=ie();if(e)try{const t=e.getItem(oe);if(t){const e=JSON.parse(t);if(e&&2===e.v)return void("suggest"!==e.mode&&"execute"!==e.mode||(this.#y=e.mode))}const n=e.getItem(se);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#y=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#b.restoreAll(n),this.#g();try{e.removeItem(se)}catch{}return}}}catch{}}#g(){const e=ie();if(e)try{let t={};try{const n=e.getItem(oe);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#y,exportedAt:ee()};e.setItem(oe,JSON.stringify(n))}catch{}}setMode(e){this.#y=e,this.#g()}getMode(){return this.#y}clearApprovals(){this.#b.clear(),this.#w.clear()}#A(e,t,n="info"){try{F.publishEvent({name:e,envelope:{id:F.createCorrelationId(),timestampMs:ee(),source:"kernel:policy",kind:n},payload:t})}catch{}}#S(e,t){return`${e}|${t}`}revokeApproval(e){const t=ne({kind:e.kind,id:e.id}),n="workspace"===e.scope?re("workspace",e.workspaceId):re(e.scope),r=this.#b.delete(t,n);return r&&(this.#_("revocation",{kind:e.kind,id:e.id,risk:"low",approval:"none"},void 0,e.scope,e.workspaceId),this.#A("approval.revoked",{kind:e.kind,id:e.id,scope:e.scope,workspaceId:e.workspaceId}),this.#w.delete(this.#S(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#b.list();if(t)return n;const r=ee();return n.filter(e=>!te(e,r))}hasApproval(e,t,n){const r=ne(e),i="workspace"===t?n?.workspaceId?re("workspace",n.workspaceId):null:re(t);if(null===i)return!1;const s=this.#b.get(r,i);if(!s)return!1;if(te(s,ee())){const e=this.#S(r,i);return this.#w.has(e)||(this.#w.add(e),this.#A("approval.expired",{kind:s.kind,id:s.id,scope:s.scope,workspaceId:s.workspaceId,expiresAt:s.expiresAt,decidedBy:s.decidedBy},"warn")),!1}return!0}recordApproval(e,t,n){if("workspace"===t&&!n?.workspaceId)throw new Error("[Policy] Workspace scope requires workspaceId in context");const r=ne(e),i="workspace"===t?re("workspace",n?.workspaceId):re(t),s={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:ee(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,chainRef:n?.chainRef};return this.#b.set(r,i,s),this.#_("approval",e,void 0,t,n?.workspaceId),this.#w.delete(this.#S(r,i)),this.#A("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:n?.decidedBy,expiresAt:n?.expiresAt}),s}#_(e,t,n,r,i){this.#k.push({timestampMs:ee(),type:e,request:t,decision:n,scope:r,workspaceId:i}),this.#k.length>this.#I&&this.#k.splice(0,this.#k.length-this.#I)}evaluate(e,t){const n=n=>{const r=t,i=r?.correlationId,s=r?.traceId??i;F.publishEvent({name:"policy.evaluated",envelope:{id:F.createCorrelationId(),correlationId:i,traceId:s,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})};if("suggest"===this.#y){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===e.approval){const r={allowed:!0,mode:"execute",requiresApproval:!1};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}if("plan"===e.approval){const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (plan)."};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (step)."};return this.#_("decision",e,r,void 0,t?.workspaceId),n(r),r}requestApproval(e,t){F.publishEvent({name:"policy.approvalRequested",envelope:{id:F.createCorrelationId(),correlationId:t?.correlationId,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,context:{workspaceId:t?.workspaceId,traceId:t?.traceId}}})}exportState(){return{version:2,exportedAt:ee(),mode:this.#y,approvals:this.listApprovals({includeExpired:!0})}}importState(e,t){if(!e||"object"!=typeof e)throw new Error("[Policy] Invalid export data");if(2!==e.version)throw new Error(`[Policy] Unsupported export version: ${e.version}. Expected 2.`);const n=t?.merge??!1,r=Array.isArray(e.approvals)?e.approvals:[];"suggest"!==e.mode&&"execute"!==e.mode||(this.#y=e.mode);let i=0;if(n)for(const e of r){if(!e||"string"!=typeof e.key)continue;const t=e.key,n=e.scope,r=e.workspaceId;if("workspace"===n&&!r)continue;const s="workspace"===n?re("workspace",r):re(n);"string"==typeof s&&s&&(this.#b.has(t,s)||(this.#b.set(t,s,e),i++))}else i=this.#b.restoreAll(r),this.#w.clear();return this.#g(),F.publishEvent({name:"policy.stateImported",envelope:{id:F.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:i,merged:n}}),i}saveTemplate(e,t,n){const r=n??"global";let i=this.#v.get(r);i||(i=new Map,this.#v.set(r,i));const s={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??ee(),updatedAtMs:ee()};i.set(e,s),this.#g()}getTemplate(e,t){const n=t??"global",r=this.#v.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#v.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#v.get(n);if(!r)return!1;const i=r.delete(e);return i&&this.#g(),i}exportAuditLog(e){const t=e?.format??"json";let n=[...this.#k];if(e?.since&&(n=n.filter(t=>t.timestampMs>=e.since)),e?.until&&(n=n.filter(t=>t.timestampMs<=e.until)),e?.workspaceId&&(n=n.filter(t=>t.workspaceId===e.workspaceId)),"csv"===t){const e=["timestamp","type","kind","id","risk","approval","allowed","requiresApproval","scope","workspaceId","reason"],t=n.map(e=>[new Date(e.timestampMs).toISOString(),e.type,e.request.kind,e.request.id,e.request.risk,e.request.approval,e.decision?.allowed?"true":"false",e.decision?.requiresApproval?"true":"false",e.scope??"",e.workspaceId??"",e.decision?.reason??e.request.reason??""]);return[e.join(","),...t.map(e=>e.map(e=>{const t=String(e);return t.includes(",")||t.includes('"')||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}).join(","))].join("\n")}return JSON.stringify({exportedAt:ee(),version:1,count:n.length,entries:n},null,2)}}const ce=new ae(X);var le={manager:ce},ue=Object.freeze({__proto__:null,PolicyManager:ae,default:le,manager:ce});async function de(e,n,r){if(r())e.status="cancelled";else if("success"!==e.status&&"cancelled"!==e.status){e.status="running",e.startedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runStepStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=n,s=await t(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:n,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:n},trace:{traceId:i,parentSpanId:void 0},policy:{mode:"execute"}});e.status="success",e.finishedAtMs=Date.now(),e.correlationId=r,e.resultPayload=o,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:n,step:e}})}catch(t){const r=String(t?.message??t);if(r.includes("Approval required")||r.includes("CAPABILITY_APPROVAL_REQUIRED"))throw e.status="blocked",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}}),new Error("blocked");throw e.status="failed",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:n,step:e}}),t}}}async function pe(e,t,n,r){let i=e;if(i||(i=function(){try{const e=punica.kernel.Events.manager.getRecent(200);for(let t=e.length-1;t>=0;t--){const n=e[t],r=n?.name??n?.event?.name,i=n?.payload??n?.event?.payload;if("ai.planGenerated"===r&&i?.plan?.planId)return i.plan}}catch{}return null}(),i&&r(i)),!i)throw new Error("[AI] No plan to run");return await async function(e,t,n){const r=t&&t.planId===e.planId&&!t.finishedAtMs?t:{runId:punica.kernel.Events.manager.createCorrelationId(),planId:e.planId,startedAtMs:Date.now(),steps:e.steps.map(e=>({...e,status:"pending"}))};punica.kernel.Events.manager.publishEvent({name:"ai.runStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}});for(const e of r.steps)try{await de(e,r.runId,n)}catch(e){if("blocked"===e?.message)break;break}return r.finishedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}}),r}(i,t,n)}const he={estimate:e=>Math.ceil(e.length/4)};function fe(){return he}function me(e){const t=fe();let n=0;for(const r of e)if(n+=4+t.estimate(r.content??""),r.toolCalls&&r.toolCalls.length>0)try{n+=t.estimate(JSON.stringify(r.toolCalls))}catch{}return n}const ge={fast:{maxContextTokens:12e3,keepLastTurnsVerbatim:2,toolResultMaxChars:1500,summarizeWhenOver:!1},balanced:{maxContextTokens:32e3,keepLastTurnsVerbatim:4,toolResultMaxChars:4e3,summarizeWhenOver:!0},accurate:{maxContextTokens:96e3,keepLastTurnsVerbatim:6,toolResultMaxChars:8e3,summarizeWhenOver:!0}};const ye="[elided tool result:";function be(e){const t=(e.content??"").length;return`${ye} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function we(e,t){let n=0;for(let r=e.length-1;r>0;r--){const i=e[r].role;if(("assistant"===i||"user"===i)&&(n++,n>=t))return r}return 1}async function ve(e,t,n,r){const i=me(e);if(i<=t.maxContextTokens)return{messages:[...e],compacted:!1,strategy:"none",preTokens:i,postTokens:i,estSavedTokens:0};const s=Math.floor(.6*t.maxContextTokens),o=we(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(ye)?{...e,content:be(e)}:e);let c=me(a);if(c<=s||!t.summarizeWhenOver||!n){const e=c<i;return{messages:a,compacted:e,strategy:e?"elide":"none",preTokens:i,postTokens:c,estSavedTokens:i-c}}const l=a.slice(1,o),u=a.slice(o);try{const e="Summarize this agent conversation segment so a follow-up model call can continue the task without the originals. Keep: the user goal, decisions made, tool outcomes (names + key results), and open questions. Be dense and factual; no preamble.\n\n"+l.map(e=>`${e.role}: ${e.content??""}`).join("\n"),t=await n("llm.chat",{messages:[{role:"user",content:e}],profile:"fast"},r??{}),s=(t?.text??"").trim();if(s){const e=[a[0],{role:"assistant",content:`[conversation summary]\n${s}`},...u];return c=me(e),{messages:e,compacted:!0,strategy:"summarize",preTokens:i,postTokens:c,estSavedTokens:i-c}}}catch{}return{messages:a,compacted:c<i,strategy:"elide",preTokens:i,postTokens:c,estSavedTokens:i-c}}const ke=["capability.search","capability.describe"];function Ie(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function Ee(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Ae(e,t,n,r){const i=punica.kernel?.Events?.manager;i&&i.publishEvent({name:e,envelope:{id:i.createCorrelationId(),correlationId:t,timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}async function Se(e,t,n,r){try{const i=await e("capability.recommend",{intent:n,limit:200},r),s=i?.recommendations??[],o=new Map;let a=!1,c=0;s.forEach((e,t)=>{null!=e?.id&&o.set(String(e.id),t),"number"==typeof e?.score&&(a=!0,e.score>c&&(c=e.score))});const l=new Map;for(const e of t){const t=Ie(String(e.id)),n=l.get(t);n?n.push(e):l.set(t,[e])}if(0===o.size||a&&c<=1e-9)return function(e,t){const n=[],r=[...e.values()],i=new Array(r.length).fill(0);let s=!0;for(;s&&n.length<t;){s=!1;for(let e=0;e<r.length&&n.length<t;e++){const t=i[e];t<r[e].length&&(n.push(r[e][t]),i[e]=t+1,s=!0)}}return n}(l,100);const u=e=>o.has(String(e.id))?o.get(String(e.id)):Number.POSITIVE_INFINITY,d=[...l.keys()],p=new Map(d.map(e=>[e,Math.min(...l.get(e).map(u))])),h=new Map(d.map((e,t)=>[e,t]));d.sort((e,t)=>{const n=p.get(e)-p.get(t);return 0!==n?n:h.get(e)-h.get(t)});const f=[];for(const e of d.slice(0,64)){const t=l.get(e),n=t.filter(e=>o.has(String(e.id))).sort((e,t)=>u(e)-u(t)),r=t.filter(e=>!o.has(String(e.id)));f.push(...n,...r)}return f.slice(0,100)}catch{return t}}function _e(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function xe(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function Ce(e){const t=String(e.description??e.title??e.id).replace(/\s+/g," ").trim();return t.length>100?t.slice(0,99).trimEnd()+"…":t}async function Te(e,t,n){const r=await e("capability.schemaExport",{filter:t.toolFilter,mode:"ai-tools"},n);let i=r?.capabilities??[];if(console.log("[AgentLoop] schemaExport raw catalog",{total:i.length,byCategory:i.reduce((e,t)=>{const n=Ie(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(_e).sort(xe),deferredIndex:[]};const s=i.filter(e=>ke.includes(String(e.id)));if(i=i.filter(e=>{return!ke.includes(String(e.id))&&(!((n=String(e.id)).startsWith("ai.")||(n.startsWith("capability.")?!ke.includes(n):n.startsWith("llm.")))&&(!(!t.includeIvyNodes&&"ivy-node"===String(e.origin))&&!("mcp"===String(e.origin)&&!function(e,t){if(t.includeMcp)return!0;const n=function(e){const t=e.split(".");return"mcp"===t[0]&&t.length>=3?t[1]:void 0}(e);return!!n&&(t.allowedMcpServers??[]).includes(n)}(String(e.id),t))));var n}),console.log("[AgentLoop] after default-exclude filter",{remaining:i.length,includeIvyNodes:!!t.includeIvyNodes,includeMcp:!!t.includeMcp,allowedMcpServers:t.allowedMcpServers??[],willTier:!1!==t.deferToolLoading&&i.length>24,narrowThreshold:24}),i.length<=24)return{hot:i.map(_e).sort(xe),deferredIndex:[]};if(!1===t.deferToolLoading){return{hot:(await Se(e,i,t.query,n)).map(_e).sort(xe),deferredIndex:[]}}const o="number"==typeof t.hotSetSize&&t.hotSetSize>0?Math.floor(t.hotSetSize):16,a=(await Se(e,i,t.query,n)).slice(0,o),c=new Set(a.map(e=>String(e.id))),l=s.length===ke.length?s.map(_e):[{name:"capability.search",description:"Search the deferred tool index by natural-language need; returns candidate tool ids with one-line descriptions.",parameters:{type:"object",required:["query"],properties:{query:{type:"string"},limit:{type:"number"}}}},{name:"capability.describe",description:"Load full definitions (input schema) for up to 16 tool ids from the deferred index; described tools become directly callable.",parameters:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},maxItems:16}}}}],u=i.filter(e=>!c.has(String(e.id))).map(e=>({id:String(e.id),line:Ce(e),category:Ie(String(e.id))})).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0);return console.log("[AgentLoop] tiered catalog",{hot:a.length,deferred:u.length,hotIds:[...c]}),{hot:[...l,...a.map(_e)].sort(xe),deferredIndex:u}}async function Ne(e,t,n,r){const i={id:t.id,name:t.name,arguments:t.arguments,status:"success"};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){if(!function(e){const t=String(e?.message??e);return t.includes("Approval required")||t.includes("CAPABILITY_APPROVAL_REQUIRED")}(e))return{...i,status:"failed",error:String(e?.message??e)}}const s=String(n.trace?.traceId??n.sessionId??""),o=await function(e,t,n){return new Promise(r=>{const i=punica.kernel.Events.manager;let s=!1;const o=e=>{if(!s){s=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=i.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed"],n=>{const r=n?.payload?.payload??n?.payload,i=r?.pending;i?.id===e&&(i?.traceId&&i.traceId!==t||o("ai.approvalRecorded"===n?.name?"approved":"dismissed"))})??void 0,c=setInterval(()=>{n()&&o("cancelled")},250),l=setTimeout(()=>o("timeout"),18e4)})}(t.name,s,r);if("approved"!==o)return{...i,status:"blocked",error:`tool "${t.name}" not approved (${o})`};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){return{...i,status:"failed",error:String(e?.message??e)}}}async function Me(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Oe(n)}\nRejected arguments:\n${Oe(r)}\nValidation errors: ${i}\nReturn ONLY a JSON object with the corrected arguments — no prose, no code fence.`;try{const t=await e("llm.chat",{messages:[{role:"user",content:o}],correlationId:s.sessionId},s);return function(e){let t=(e??"").trim();if(!t)return;const n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");e>=0&&n>e&&(t=t.slice(e,n+1))}try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch{}}(t?.text??"")}catch{return}}async function De(e,t,n,r,i){let s=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Ne(e,{...t,arguments:s},r,i);if("failed"!==l.status||!Ee(l.error))return o?{...l,arguments:s,repaired:!0}:l;if(a=l.error??"",2===c||i())break;const u=await Me(e,t.name,n,s,a,r);if(!u)break;s=u,o=!0}const c={id:t.id,name:t.name,arguments:s,status:"failed",error:a||"input validation failed"};return o&&(c.repaired=!0),c}function Pe(e){return fe().estimate(e)}function Oe(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Re(e,n,r,i){const s=punica.kernel.Events.manager,o=i??s.createCorrelationId(),a="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,c=(l=e.profile,ge[l??"balanced"]);var l;const u=[],d=e.sessionId?punica.kernel?.AI?.sessions:void 0,p=[];let h=0;const f=[],m=Date.now();let g=0,y=0,b=0,w=0,v=!1,k=0,I=!1,E=0;const A=(t,n)=>{const r={inputTokens:g,outputTokens:y,totalTokens:b,latencyMs:Date.now()-m,steps:u.length,toolCalls:E};I&&(r.totalCost=k),v&&(r.cacheReadTokens=w);const i={runId:o,finishReason:t,steps:u,usage:r};if(void 0!==n&&(i.finalText=n),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:u.length}),(t=>{if(d&&e.sessionId&&0!==h)try{const n=[{role:"user",content:e.query},...f];t&&n.push({role:"assistant",content:t});const r=n.map(e=>({id:"",createdAtMs:0,role:e.role,content:e.content??"",...e.name?{name:e.name}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolCalls&&e.toolCalls.length>0?{toolCalls:e.toolCalls}:{}}));d.appendMessages(e.sessionId,r,{runId:o})}catch(e){console.warn("[AgentLoop] session persist failed:",e)}})(n),d&&e.sessionId&&h>0)try{d.recordUsage?.(e.sessionId,r)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Ae("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),i};Ae("ai.agentStarted",o,"info",{runId:o,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{}});const S=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!S)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),A("error");const _=await t(),x=function(e,t,n){return{sessionId:e,workspaceId:t,actor:{type:"ai",id:"ai:agent"},origin:{kind:"ai",id:e},trace:{traceId:e,parentSpanId:void 0},policy:{mode:"execute"},...n?{signal:n}:{}}}(o,_,r);let C;e.sessionId&&(x.conversationId=e.sessionId);try{C=await Te(S,e,x)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),A("error")}const T=[...C.hot];console.log("[AgentLoop] tool catalog built",{hot:T.length,deferred:C.deferredIndex.length,toolFilter:e.toolFilter??null,names:T.map(e=>e.name)});const N=new Map(T.map(e=>[e.name,e.parameters])),M=new Map(C.deferredIndex.map(e=>[e.id,e])),D=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!N.has(String(e.id))).map(_e).sort(xe);for(const e of n)T.push(e),N.set(e.name,e.parameters),M.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:T.length}),n.length};if(p.push({role:"system",content:"You are an autonomous agent operating inside an IDE. You are given a set of tools (capabilities). To accomplish the user request, call the tools you need one or more times; after each tool result, decide whether to call another tool or to answer. When you have enough information, reply with a concise final answer and no further tool calls."}),C.deferredIndex.length>0&&p.push(function(e){const t=new Map;for(const n of e){const e=t.get(n.category);e?e.push(n):t.set(n.category,[n])}const n=[];for(const e of[...t.keys()].sort())for(const r of t.get(e))n.push(`[${e}] ${r.id} — ${r.line}`);return{role:"system",content:"Additional tools exist but are not loaded yet. Index (id — purpose):\n"+n.join("\n")+"\nTo use one: call capability.search to find candidates, then capability.describe to load full schemas. You may also call an indexed tool directly by its id if its arguments are obvious."}}(C.deferredIndex)),d&&e.sessionId)try{p.push(...d.getContextMessages(e.sessionId))}catch(e){console.warn("[AgentLoop] session seed failed; running cold:",e)}p.push({role:"user",content:e.query}),h=p.length;let P=0;for(let t=0;t<a;t++){if(n())return A("cancelled");let r,i=!1;if(me(p)>c.maxContextTokens){const e=await ve(p,c,S,x);e.compacted&&(p.splice(0,p.length,...e.messages),P=0,i=!0,Ae("ai.agentContextCompacted",o,"info",{runId:o,step:t,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const s=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:t,messageCount:p.length,toolsSent:T.length,toolChoice:"auto",toolNames:T.map(e=>e.name)});const n={stableToolsAndSystem:!0,stableMessagePrefix:P,cacheKey:o};r=await S("llm.chatStream",{messages:p,tools:T,toolChoice:"auto",correlationId:o,cacheHints:n,...e.profile?{profile:e.profile}:{}},x),P=p.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:t,textLen:(r?.text??"").length,toolCalls:r?.toolCalls?.length??0})}catch(e){return console.error("[AgentLoop] llm.chatStream call failed; aborting run:",e),A("error")}if(n())return A("cancelled");const a=Date.now()-s,l=(r.text??"").trim(),d="string"==typeof r.thinking?r.thinking:void 0,h=r.toolCalls??[],m={index:t,assistantText:l||void 0,thinking:d,toolCalls:[],latencyMs:a},_=r.usage,C=r.meta;_?(m.usage=_,g+=_.inputTokens??0,y+=_.outputTokens??0,b+=_.totalTokens??(_.inputTokens??0)+(_.outputTokens??0),"number"==typeof _.cacheReadInputTokens&&(w+=_.cacheReadInputTokens,v=!0)):C&&(m.usage={inputTokens:C.promptTokens,outputTokens:C.completionTokens,totalTokens:C.promptTokens+C.completionTokens},g+=C.promptTokens,y+=C.completionTokens,b+=C.promptTokens+C.completionTokens),C&&"number"==typeof C.totalCost&&(k+=C.totalCost,I=!0);const O={runId:o,step:t,estToolDefTokens:Pe(JSON.stringify(T)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+Pe(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+Pe(t.content??""),0),toolCount:T.length,deferredToolCount:M.size,compactionApplied:i};if(m.usage&&(O.reportedInputTokens=m.usage.inputTokens,O.reportedOutputTokens=m.usage.outputTokens,"number"==typeof m.usage.cacheReadInputTokens&&(O.cacheReadTokens=m.usage.cacheReadInputTokens)),Ae("ai.agentTurnUsage",o,"info",{...O}),0===h.length)return u.push(m),Ae("ai.agentStep",o,"info",{runId:o,turn:m}),A("final",l);u.push(m),Ae("ai.agentStep",o,"info",{runId:o,turn:m});const R=h.map(e=>`${e.name}(${Oe(e.arguments)})`).join(", "),L={role:"assistant",content:l?`${l}\n[calling tools: ${R}]`:`[calling tools: ${R}]`,toolCalls:h.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};p.push(L),f.push(L);let $=!1;for(const e of h){if(n())return A("cancelled");if(Ae("ai.agentToolCall",o,"info",{runId:o,toolCall:{id:e.id,name:e.name,arguments:e.arguments},status:"running"}),!N.has(e.name)&&M.has(e.name))try{D(await S("capability.describe",{ids:[e.name]},x))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const r=await De(S,e,N.get(e.name),x,n);m.toolCalls.push(r),E++,"success"===r.status&&"capability.describe"===r.name&&D(r.resultPayload),console.log("[AgentLoop] tool dispatched",{step:t,name:r.name,arguments:r.arguments,status:r.status,repaired:r.repaired??!1,error:r.error,resultPreview:"success"===r.status?Oe(r.resultPayload).slice(0,300):void 0}),Ae("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const i={role:"tool",content:"success"===r.status?Oe(r.resultPayload,c.toolResultMaxChars):`ERROR: ${r.error??"tool failed"}`,name:r.name,toolCallId:r.id};p.push(i),f.push(i),"blocked"===r.status&&($=!0)}if($)return A("blocked")}return A("maxSteps")}function Le(e,t=2){const n=new WeakSet;return JSON.stringify(e,(e,t)=>{if("object"==typeof t&&null!==t){if(n.has(t))return"[Circular]";n.add(t)}return"bigint"==typeof t?t.toString():t},t)}const $e={EVENTS:"kernel.events",COMMANDS:"kernel.commands",HISTORY:"kernel.history",TIME_SERVER:"kernel.timeServer",NOTIFICATIONS:"kernel.notifications",AI:"kernel.ai",LLM:"kernel.llm",POLICY:"kernel.policy",TASKS:"kernel.tasks"},je={FS:"runtime.fs",SEARCH:"runtime.search",VCS:"runtime.vcs",WORKSPACE:"runtime.workspace",LLM:"runtime.llm",SECRETS:"runtime.secrets",TASKS:"runtime.tasks",TERMINALS:"runtime.terminals",MCP:"runtime.mcp"},Fe={ACTIVITY_BAR:"shell.activityBar",STATUSBAR:"shell.statusbar",VIEW:"shell.view",VIEWS:"shell.views",KEYBOARD_SHORTCUTS:"shell.keyboardShortcuts",LAYOUT:"shell.layout",CONTENT_TABS:"shell.contentTabs",PANEL_TABS:"shell.panelTabs"},Be={SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},qe={MANAGER:"extensions.manager"},ze={TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},Ue={AGENT_RUN:"ai.agent.run",APPROVE_PENDING:"ai.approvePending",ASK:"ai.ask",CANCEL_RUN:"ai.cancelRun",DISMISS_PENDING:"ai.dismissPending",DO:"ai.do",RUN_PLAN:"ai.runPlan",SESSION_ARCHIVE:"ai.session.archive",SESSION_CREATE:"ai.session.create",SESSION_DELETE:"ai.session.delete",SESSION_LIST:"ai.session.list",SESSION_RENAME:"ai.session.rename",SHOW_LAST_TRACE:"ai.showLastTrace",SUMMARIZE:"ai.summarize"},Ve={EXPORT:"policy.export",IMPORT:"policy.import",LIST_APPROVALS:"policy.listApprovals",SET_MODE:"policy.setMode",SHOW_MODE:"policy.showMode"},We={APPROVAL_APPROVE:"workflow.approval.approve",APPROVAL_REJECT:"workflow.approval.reject",RUN_CANCEL:"workflow.run.cancel",RUN_GET:"workflow.run.get",RUN_LIST:"workflow.run.list",RUN_PAUSE:"workflow.run.pause",RUN_RESUME:"workflow.run.resume",RUN_START:"workflow.run.start",RUN_SUBFLOW:"workflow.run.subflow"};function Ke(e,t=220){let n=String(e??"");const r=[/\bsk-[A-Za-z0-9]{20,}\b/g,/\bghp_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*\b/g,/(\b(password|passwd|pwd|secret|token|api[_-]?key)\b\s*[:=]\s*)([^\s'"]+)/gi];for(const e of r)n=n.replace(e,(e,t)=>"string"==typeof t?`${t}[REDACTED]`:"[REDACTED]");return n=n.replace(/\s+/g," ").trim(),n.length>t?n.slice(0,t)+"…":n}function Ge(e,t,n,r,i,s,o,a){punica.kernel?.Events?.manager&&punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:r,spanId:i,parentSpanId:s,timestampMs:Date.now(),source:o,kind:t},payload:a})}const He="punica.kernel.ai.sessions.index.v1";function Ye(e){return`punica.kernel.ai.session.${e}.v1`}function Je(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const Ze=new class{readIndex(){const e=Je();if(!e)return[];try{const t=e.getItem(He);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=Je();if(t)try{t.setItem(He,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=Je();if(t)try{const n=t.getItem(Ye(e));if(!n)return;const r=JSON.parse(n);if(!r||1!==r.version||!r.meta?.sessionId)return;return r}catch{return}}writeSession(e){const t=Je();if(t)try{t.setItem(Ye(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=Je();if(t)try{t.removeItem(Ye(e))}catch{}}};let Qe=Ze;function Xe(){return Qe}const et="New chat";function tt(){return Date.now()}function nt(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${tt().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function rt(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:tt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function it(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function st(e){const t={role:e.role,content:e.content};return e.name&&(t.name=e.name),e.toolCallId&&(t.toolCallId=e.toolCallId),e.toolCalls&&e.toolCalls.length>0&&(t.toolCalls=e.toolCalls),t}const ot=new class{#x=null;#C=null;#T=new Map;#N=!1;#M=new Map;initialize(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{!function(e,t){const n=e?.payload??e,r=n?.request;if(!r?.id)return;const i=e?.envelope?.correlationId,s=n?.context?.workspaceId,o=n?.context?.traceId,a=punica.kernel.Events.manager.createCorrelationId(),c={pendingId:a,kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason,correlationId:i,...o?{traceId:o}:{},workspaceId:s,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#T)}),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#x=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(Ve.SET_MODE,{title:"Policy: Set Mode…",description:"Switch policy mode: suggest (plan only) or execute (allow running capabilities).",execute:e=>{const t="execute"===("string"==typeof e?e:e?.mode??"suggest")?"execute":"suggest";punica.kernel?.Policy?.manager&&punica.kernel?.Events?.manager&&(punica.kernel.Policy.manager.setMode(t),punica.kernel.Events.manager.publishEvent({name:"policy.modeChanged",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{mode:t}}))}}),t.registerCommand(Ve.SHOW_MODE,{title:"Policy: Show Mode",description:"Print current policy mode to console.",execute:()=>{punica.kernel?.Policy?.manager&&console.log("[Policy] mode",punica.kernel.Policy.manager.getMode())}}),t.registerCommand(Ve.EXPORT,{title:"Policy: Export State…",description:"Export policy state (mode + approvals) as JSON.",execute:e=>{const t="boolean"==typeof e?e:e?.download??!1;if(!punica.kernel?.Policy?.manager)return;const n=Le(punica.kernel.Policy.manager.exportState(),2);if(t){const e=globalThis;if(void 0===e.document||void 0===e.Blob||void 0===e.URL)return console.warn("[Policy] Download not available in this environment. Exporting to console:"),void console.log("[Policy] Export:\n"+n);const t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),i=e.document.createElement("a");i.href=r,i.download=`punica-policy-export-${Date.now()}.json`,e.document.body.appendChild(i),i.click(),e.document.body.removeChild(i),URL.revokeObjectURL(r)}else console.log("[Policy] Export:\n"+n)}}),t.registerCommand(Ve.IMPORT,{title:"Policy: Import State…",description:"Import policy state from JSON (file or clipboard).",execute:async e=>{let t;const n=e?.merge??!1;if(e&&"object"==typeof e&&e.data){const n=e.data;if("string"==typeof n)try{t=JSON.parse(n)}catch(e){throw new Error(`[Policy] Failed to parse import data: ${String(e)}`)}else"object"==typeof n&&(t=n)}if(!t){const e=globalThis;if(!e.navigator?.clipboard?.readText)throw new Error("[Policy] No import data provided. Pass data in arg or copy JSON to clipboard.");try{const n=await e.navigator.clipboard.readText();t=JSON.parse(n)}catch{throw new Error("[Policy] No import data provided. Pass data in arg or copy valid JSON to clipboard.")}}if(!punica.kernel?.Policy?.manager)return;const r=punica.kernel.Policy.manager.importState(t,{merge:n});console.log(`[Policy] Imported ${r} approval(s) (merge: ${n})`)}}),t.registerCommand(Ve.LIST_APPROVALS,{title:"Policy: List Approvals",description:"List all recorded approvals.",execute:()=>{if(!punica.kernel?.Policy?.manager)return;const e=punica.kernel.Policy.manager.listApprovals();console.log(`[Policy] ${e.length} approval(s):\n`+Le(e,2))}}),t.registerCommand(Ue.ASK,{title:"AI: Ask…",description:"Ask the AI to suggest a plan (no execution).",execute:e=>{const t="string"==typeof e?e:e?.query;if(!t||!String(t).trim())return;if(!punica.kernel?.Events?.manager)return;const n="object"==typeof e&&null!==e?e:{},r={query:String(t).trim(),mode:"suggest"};n.productId&&(r.productId=n.productId),n.targetArtifact&&(r.targetArtifact=n.targetArtifact),n.profile&&(r.profile=n.profile),n.originExtension&&(r.originExtension=n.originExtension),punica.kernel.Events.manager.publishEvent({name:"ai.planRequested",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:r})}}),t.registerCommand(Ue.DO,{title:"AI: Do…",description:"Single-shot: ask the AI, generate a plan, and execute it (when policy mode allows).",execute:e=>{const t="string"==typeof e?e:e?.query;if(!t||!String(t).trim())return;if(!punica.kernel?.Events?.manager)return;const n="object"==typeof e&&null!==e?e:{},r={query:String(t).trim(),mode:"execute"};n.productId&&(r.productId=n.productId),n.targetArtifact&&(r.targetArtifact=n.targetArtifact),n.profile&&(r.profile=n.profile),n.originExtension&&(r.originExtension=n.originExtension),punica.kernel.Events.manager.publishEvent({name:"ai.planRequested",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:r})}}),t.registerCommand(Ue.RUN_PLAN,{title:"AI: Run Plan",description:"Execute the last suggested plan (optionally a user-edited copy).",execute:t=>{const n=t&&"object"==typeof t&&"string"==typeof t.planId&&Array.isArray(t.steps)?t:void 0;e.runLastPlan(n).catch(e=>{console.error("[AI] run failed",e)})}}),t.registerCommand(Ue.AGENT_RUN,{title:"AI: Run Agent",description:"Run the agentic tool-use loop: the model calls capabilities as tools, sees results, and iterates until it answers.",execute:t=>{const n="string"==typeof t?{query:t}:t&&"object"==typeof t&&"string"==typeof t.query?t:void 0;n&&n.query.trim()&&e.runAgent(n).catch(e=>{console.error("[AI] agent run failed",e)})}}),t.registerCommand(Ue.APPROVE_PENDING,{title:"AI: Approve Pending Action…",description:"Approve a pending policy-gated action by ID.",execute:t=>{let n,r;if("string"==typeof t?n=t:t&&"object"==typeof t&&(n=t.pendingId,r=t.scope),!n){const t=e.getPendingApprovals();if(0===t.length)return;n=t[0].pendingId}const i="always"===r?"always":"workspace"===r?"workspace":"once";e.approvePending(n,i)||console.warn("[AI] Failed to approve pending",n)}}),t.registerCommand(Ue.DISMISS_PENDING,{title:"AI: Dismiss Pending Action…",description:"Dismiss a pending policy-gated action by ID.",execute:t=>{let n;"string"==typeof t?n=t:t&&"object"==typeof t&&(n=t.pendingId),n&&(e.dismissPending(n)||console.warn("[AI] Failed to dismiss pending",n))}}),t.registerCommand(Ue.CANCEL_RUN,{title:"AI: Cancel Run",description:"Cancel AI runs. Bare: everything (legacy Stop). Pass { runId } or { sessionId } to cancel one run / one conversation only.",execute:t=>{const n=t&&"object"==typeof t&&(t.runId||t.sessionId)?{runId:t.runId,sessionId:t.sessionId}:void 0;e.setCancelRequested(!0,n)}}),t.registerCommand(Ue.SESSION_CREATE,{title:"AI: New Session…",description:"Create a new AI conversation session.",execute:e=>{const t=punica.kernel?.AI?.sessions;if(t)return t.create(e&&"object"==typeof e?e:void 0)}}),t.registerCommand(Ue.SESSION_LIST,{title:"AI: List Sessions",description:"List AI conversation sessions (most recent first).",execute:e=>{const t=punica.kernel?.AI?.sessions;return t?t.list(e?.workspaceId):[]}}),t.registerCommand(Ue.SESSION_RENAME,{title:"AI: Rename Session…",description:"Rename an AI conversation session.",execute:e=>{const t=punica.kernel?.AI?.sessions,n=e?.sessionId,r=e?.title;return!(!t||!n||"string"!=typeof r)&&t.rename(String(n),r)}}),t.registerCommand(Ue.SESSION_ARCHIVE,{title:"AI: Archive Session…",description:"Archive (or unarchive) an AI conversation session.",execute:e=>{const t=punica.kernel?.AI?.sessions,n=e?.sessionId;return!(!t||!n)&&t.archive(String(n),e?.archived)}}),t.registerCommand(Ue.SESSION_DELETE,{title:"AI: Delete Session…",description:"Delete an AI conversation session and its history.",execute:e=>{const t=punica.kernel?.AI?.sessions,n="string"==typeof e?e:e?.sessionId;return!(!t||!n)&&t.delete(String(n))}}),t.registerCommand(Ue.SHOW_LAST_TRACE,{title:"AI: Show Last Run Trace",description:"Print last run trace to console (temporary).",execute:()=>{const t=e.getLastRun();console.log("[AI] lastRun\n"+Le(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+Le(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Ue.SUMMARIZE,{title:"AI: Summarize…",description:"Summarize a given text snippet (no capability invocation).",execute:async(e,t)=>{const n=String(e?.text??"").trim();if(!n)return;if(!punica.kernel?.Events?.manager)return;const r=t?.__punica?.correlationId??punica.kernel.Events.manager.createCorrelationId(),i=t?.__punica?.traceId??r,s=t?.__punica?.spanId??punica.kernel.Events.manager.createCorrelationId(),o=t?.__punica?.source??"kernel:ai",a=e?.source;Ge("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:Ke(n),source:a}});try{const e={correlationId:r,messages:[{role:"system",content:"You are a helpful assistant. Summarize the provided text concisely. Prefer bullet points when appropriate. Keep it clear and accurate."},{role:"user",content:n}]},t=punica.runtime.capabilities?.gateway;if(!t&&!punica.runtime?.llm)return;const c=t?await t.call("llm.chat",e,{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"ai:commands"},origin:{kind:"ai",id:"command-summary"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat(e),l=String(c?.text??"").trim(),u=punica.kernel.Events.manager.createCorrelationId();Ge("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:Ke(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),Ge("ai.summaryGenerated","result",r,i,punica.kernel.Events.manager.createCorrelationId(),u,o,{summary:l,usage:c?.usage,modelId:c?.modelId,provider:c?.provider,source:a})}catch(e){Ge("ai.response","error",r,i,punica.kernel.Events.manager.createCorrelationId(),s,o,{kind:"summarize",error:String(e?.message??e)})}}})}({runLastPlan:e=>this.runLastPlan(e),runAgent:e=>this.runAgent(e),getLastPlan:()=>this.getLastPlan(),approvePending:(e,t)=>this.approvePending(e,t),dismissPending:e=>this.dismissPending(e),getPendingApprovals:()=>this.getPendingApprovals(),getLastRun:()=>this.#C,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#M){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#N=e;for(const t of this.#M.values())t.cancelRequested=e,e&&t.controller.abort()}}})}getLastPlan(){return this.#x}getPendingApprovals(){return e=this.#T,Array.from(e.values()).sort((e,t)=>e.timestampMs-t.timestampMs);var e}approvePending(e,t){return function(e,t,n){const r=n.get(e);return!!r&&(punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason},t,{decidedBy:"user",workspaceId:r.workspaceId}),n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.approvalRecorded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r,scope:t}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"approved"}}),!0)}(e,t,this.#T)}dismissPending(e){return function(e,t){const n=t.get(e);return!!n&&(t.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalDismissed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:n}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"dismissed"}}),!0)}(e,this.#T)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#x=e);const t=await pe(this.#x,this.#C,()=>this.#N,e=>{this.#x=e});return this.#C=t,this.#N=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#M.set(t,n);try{return await Re(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#M.delete(t)}}},at=new class{#D;create(e){const t=Xe(),n={sessionId:nt("sess"),title:e?.title?.trim()||et,createdAtMs:tt(),updatedAtMs:tt(),messageCount:0,tokenEstimate:0};e?.workspaceId&&(n.workspaceId=e.workspaceId);const r={version:1,meta:n,transcript:[]};t.writeSession(r);const i=t.readIndex();return i.push(n),this.#P(i,n),t.writeIndex(i),rt("ai.sessionCreated",n),{...n}}list(e){const t=Xe().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return Xe().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#O(e,e=>{e.title=n});return!!r&&(rt("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#O(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(rt("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=Xe(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[i]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),rt("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=Xe(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||nt("msg"),createdAtMs:e.createdAtMs||tt(),content:e.content.length>16e3?e.content.slice(0,16e3)+"…":e.content};return n?.runId&&!t.runId&&(t.runId=n.runId),t});i.transcript.push(...s),i.transcript.length>200&&i.transcript.splice(0,i.transcript.length-200);const o=i.meta;if(o.messageCount=i.transcript.length,o.updatedAtMs=tt(),n?.runId&&(o.lastRunId=n.runId),o.tokenEstimate=i.transcript.reduce((e,t)=>e+function(e){return Math.ceil(e.length/4)}(t.content),0),o.title===et){const e=i.transcript.find(e=>"user"===e.role);e&&(o.title=function(e){const t=e.replace(/\s+/g," ").trim();return t?t.length>48?t.slice(0,47)+"…":t:et}(e.content))}r.writeSession(i),this.#R(o),rt("ai.sessionUpdated",o,{appendedCount:s.length,runId:n?.runId});const a=this.#D;a?.shouldCompact(i)&&Promise.resolve().then(()=>a.compact(i)).then(t=>{const n=Xe().readSession(e);n&&(n.contextView=t,Xe().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=Xe().readSession(e);if(!t)return[];const n=t.contextView;if(n){const e=[];return n.summaryText&&e.push({role:"system",content:`[conversation summary]\n${n.summaryText}`}),e.push(...it(n.messages).map(st)),e}return it(t.transcript.slice(-40)).map(st)}setCompactor(e){this.#D=e}recordUsage(e,t){const n=this.#O(e,e=>{const n=e.usage??{inputTokens:0,outputTokens:0,totalTokens:0,cacheReadTokens:0,runCount:0};n.inputTokens+=t.inputTokens,n.outputTokens+=t.outputTokens,n.totalTokens+=t.totalTokens,n.cacheReadTokens+=t.cacheReadTokens??0,"number"==typeof t.totalCost&&(n.totalCostUsd=(n.totalCostUsd??0)+t.totalCost),n.runCount+=1,n.lastRunAtMs=tt(),e.usage=n});return!!n&&(rt("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#O(e,t){const n=Xe(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=tt(),n.writeSession(r),this.#R(r.meta),{...r.meta}}#R(e){const t=Xe(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#P(e,t){const n=Xe(),r=e=>e.workspaceId===t.workspaceId;let i=e.filter(r);for(;i.length>50;){const s=i.filter(e=>e.sessionId!==t.sessionId).sort((e,t)=>{const n=e.archived?0:1,r=t.archived?0:1;return n!==r?n-r:e.updatedAtMs-t.updatedAtMs})[0];if(!s)break;const o=e.findIndex(e=>e.sessionId===s.sessionId);o>=0&&e.splice(o,1),n.deleteSession(s.sessionId),rt("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};at.setCompactor(function(){const e=ge.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=we([{role:"system",content:""},...n.map(e=>({role:e.role,content:e.content,...e.name?{name:e.name}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolCalls?{toolCalls:e.toolCalls}:{}}))],e.keepLastTurnsVerbatim);return{messages:n.map((e,t)=>t+1<r&&"tool"===e.role&&!e.content.startsWith(ye)?{...e,content:be(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());var ct={manager:ot,sessions:at},lt=Object.freeze({__proto__:null,default:ct,manager:ot,sessions:at});const ut=new class{#L=new Map;#$=new Map;#j=new Map;#F;registerProductOriginResolver(e){this.#F=e}#B(e){try{const t=punica.extensions?.manager;if(t){if(t.getExtension(e))return!0;const n=t.getAllExtensions();if(Array.isArray(n))return n.some(t=>t.name===e||t.id===e)}return!0}catch{return!0}}register(e,t){if(!e.id)throw new Error("Instruction class must have an id");if(!e.role)throw new Error("Instruction class must have a role");if(!e.systemPrompt)throw new Error("Instruction class must have a systemPrompt");if(this.#L.has(e.id)){const n=this.#L.get(e.id),r=n?.originExtension||this.#j.get(e.id),i=t||e.originExtension;if(!r||!i||r!==i)throw new Error(`Instruction class ID collision: "${e.id}" is already registered by a different extension. Each product extension must use namespaced IDs (e.g., "ivy.node.generator", "ivy.agent.generator").`)}!t&&e.productId&&this.#F&&(t=this.#F(e.productId)),t&&(e.originExtension=t,this.#j.set(e.id,t)),e.capability||(e.capability=function(e){if(e.capability)return e.capability;const t={id:e.id,title:e.role.charAt(0).toUpperCase()+e.role.slice(1),description:`LLM instruction class: ${e.role}`,version:"1.0.0",tags:["llm","instruction-class",e.role]};return t.inputs={schema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",enum:[e.id],description:"Instruction class identifier"},userPrompt:{type:"string",description:"User prompt/query"},context:{type:"object",properties:{workspaceId:{type:"string"},filePath:{type:"string"},previousOutputs:{type:"object"},capabilities:{type:"array"}}},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"}}}}}},e.outputSchema?t.outputs={schema:e.outputSchema,kind:"direct"}:t.outputs={schema:{type:"object",properties:{text:{type:"string"},structured:{type:"object"}}},kind:"direct"},e.riskLevel?t.policy={risk:e.riskLevel,approval:"high"===e.riskLevel?"step":"plan"}:t.policy={risk:"medium",approval:"step"},t.sideEffects=["llm-invocation"],"json_object"===e.responseFormat&&t.sideEffects.push("structured-output"),t}(e)),this.#L.set(e.id,e),this.#$.set(e.id,e.capability)}unregister(e){this.#L.delete(e),this.#$.delete(e),this.#j.delete(e)}unregisterByOrigin(e){const t=[];this.#j.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>this.unregister(e))}get(e){return this.#L.get(e)}list(e=!1){const t=Array.from(this.#L.values());return e?t.filter(e=>{const t=e.originExtension||this.#j.get(e.id);return!t||this.#B(t)}):t}listSummaries(e=!1){return this.list(e).map(e=>({id:e.id,role:e.role,originExtension:e.originExtension||this.#j.get(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0}))}has(e){return this.#L.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#j.get(e);return!n||this.#B(n)}getCapability(e){return this.#$.get(e)}listCapabilities(){return Array.from(this.#$.values())}};async function dt(e){const{primaryModelId:t,count:n,exclude:r}=e,i=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{return await e.listInstalled()}catch{return null}}();if(!i||!Array.isArray(i.installed)||0===i.installed.length)return t?[t]:[];const s=new Set(i.installed.map(e=>e.id)),o=[],a=e=>{e&&s.has(e)&&(function(e,t){return!(!t||0===t.length)&&t.includes(e)}(e,r)||o.includes(e)||o.push(e))};if(a(t),o.length<n)for(const e of i.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function pt(e,t){let n=e.riskLevel;if(!n){const r=await async function(e,t){if("risk-assessor"===e.id)return{riskLevel:"medium"};const n=ut.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,i=[];i.push("Assess the risk level for this task:"),i.push(""),i.push(`Instruction Class: ${e.id}`),i.push(`Role: ${e.role}`),i.push(""),i.push("User Prompt:"),i.push(t.userPrompt),i.push(""),i.push("Context:"),i.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),i.push(`- File Path: ${r?.filePath??"N/A"}`),i.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),i.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),i.push(""),i.push("Consider:"),i.push("- Is this production code?"),i.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),i.push("- Is it a critical business function?"),i.push("- Does it handle sensitive data?"),i.push("- Is it a simple utility or a complex system?"),i.push(""),i.push('Respond with ONLY one word: "low", "medium", or "high".');const s=i.join("\n");try{const e=punica.runtime.capabilities?.gateway,t=e?await e.call("llm.chat",{messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20},{sessionId:"internal",workspaceId:void 0,actor:{type:"extension",extensionName:"kernel:policy"},origin:{kind:"command",id:"risk-assessment"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat({messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20}),r=String(t.text??"").toLowerCase();return/\bhigh\b/.test(r)?{riskLevel:"high"}:/\bmedium\b/.test(r)?{riskLevel:"medium"}:/\blow\b/.test(r)?{riskLevel:"low"}:{riskLevel:"medium"}}catch{return{riskLevel:"medium"}}}(e,t);n=r.riskLevel}if(n||(n="medium"),"high"===n){const t=e.expertModelId,r=e.expertModelIds;let i=[];return i=r&&r.length>0?r.slice():await dt({primaryModelId:t,count:3}),{strategy:i.length>1?"multi":"single",modelIds:i.length?i:[t].filter(Boolean),riskLevel:n,reason:"High risk detected via LLM-based assessment"}}let r=e.expertModelId??null;return r||(r=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{const t=await e.listInstalled();if(t.activeModelId)return t.activeModelId;const n=t.installed[0];return n?n.id:null}catch{return null}}()),{strategy:"single",modelIds:r?[r]:[],riskLevel:n,reason:"Low/medium risk, single expert sufficient"}}function ht(e){const t=[];return e.capabilities&&e.capabilities.length>0&&t.push(`Available capabilities:\n${JSON.stringify(e.capabilities,null,2)}`),e.previousOutputs&&t.push(`Previous outputs:\n${JSON.stringify(e.previousOutputs,null,2)}`),e.filePath&&t.push(`Current file: ${e.filePath}`),e.workspaceId&&t.push(`Workspace ID: ${e.workspaceId}`),t.length>0?t.join("\n\n"):void 0}function ft(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function mt(){const e=globalThis;return e.punica?.runtime?.fs}function gt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const yt={type:"ai",id:"llm:context"},bt={kind:"ai",id:"context-builder"};async function wt(e){if(e.filePath)try{const t=ft(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:yt,origin:bt,trace:{traceId:gt()},policy:{mode:"execute"}}):await(mt()?.readFile?.(e.filePath));if(!n)return;const r=5e3,i=n.length>r?n.slice(0,r)+"\n... (truncated)":n;return`File content (${e.filePath}):\n\`\`\`\n${i}\n\`\`\``}catch{return}}async function vt(e){try{const t=ft(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:yt,origin:bt,trace:{traceId:gt()},policy:{mode:"execute"}}):await(mt()?.getFileTree?.());if(!n||!Array.isArray(n)||0===n.length)return;const r=n.filter(e=>!e.isDirectory).length,i=n.filter(e=>e.isDirectory).length;return`Workspace structure: ${r} files, ${i} directories\nTop-level items: ${n.filter(e=>{const t=String(e.path??"");return!t.includes("/")||2===t.split("/").length}).slice(0,20).map(e=>{const t=String(e.name??"");if(t)return t;return String(e.path??"").split("/").pop()??""}).join(", ")}`}catch{return}}function kt(){const e=globalThis;return e.punica?.shell?.ContentTabs}function It(){return"undefined"==typeof document?void 0:document}function Et(){const e=It();if(!e)return;const t=e.getElementById("content-tabs-panels");if(!t)return;const n=Array.from(t.children);for(const e of n){const t=e.__codeEditorInstance;if(t)return t}}function At(e){try{const t=kt();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Et();if(!n)return;const r=n.getSelection?.(),i=n.getModel?.();if(!r||!i||r.isEmpty())return;const s=i.getValueInRange(r),o=String(s??"").trim();if(!o)return;const a=2e3,c=o.length>a?o.slice(0,a)+"\n... (truncated)":o,l=r.startLineNumber;return`Selected code (lines ${l}-${r.endLineNumber}):\n\`\`\`\n${c}\n\`\`\``}catch{return}}function St(){try{const e=kt();if(!e)return;const t=[],n=e.getActivePath?.()??null,r=e.getActiveViewType?.()??null;if(n&&(t.push(`Active file: ${n}`),r&&t.push(`View type: ${r}`)),n)try{const e=Et();if(e){const n=e.getPosition?.(),r=e.getModel?.();if(n&&r){const e=n.lineNumber,i=n.column,s=r.getOffsetAt(n);t.push(`Cursor position: Line ${e}, Column ${i} (offset: ${s})`)}}}catch{}try{const e=It();if(e){const n=e.querySelector('[id*="content-tabs"]');if(n){const e=n.querySelectorAll('[role="tab"]');e.length>1&&t.push(`Open files: ${e.length} tabs`)}}}catch{}return t.length>0?`Editor State:\n${t.join("\n")}`:void 0}catch{return}}function _t(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const xt={type:"ai",id:"llm:context"},Ct={kind:"ai",id:"context-builder"};async function Tt(e){const t=function(){const e=globalThis;return e.punica?.runtime?.vcs}();if(!t)return;const n=[];if(t.status)try{const r=function(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}(),i=r?await r.call("vcs.status",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:xt,origin:Ct,trace:{traceId:_t()},policy:{mode:"execute"}}):await t.status();if(i){const e=[];i.current&&(e.push(`Branch: ${i.current}`),i.tracking&&e.push(`Tracking: ${i.tracking}`),i.ahead&&i.ahead>0&&e.push(`Ahead: ${i.ahead}`),i.behind&&i.behind>0&&e.push(`Behind: ${i.behind}`));const t=i.modified??[],r=i.staged??[],s=i.created??[],o=i.deleted??[],a=i.renamed??[],c=(t,n,r)=>{if(0===n.length)return;const i=n.slice(0,r).join(", "),s=n.length>r?"...":"";e.push(`${t} (${n.length}): ${i}${s}`)};c("Staged",r,5),c("Modified",t,5),c("Created",s,3),c("Deleted",o,3),c("Renamed",a,3),e.length>0&&n.push(`Git Status:\n${e.join("\n")}`)}}catch{}if(t.logs&&e.filePath)try{const e=await t.logs({limit:5});if(e&&Array.isArray(e)&&e.length>0){const t=e.slice(0,5).map(e=>{const t=e.hash?e.hash.substring(0,7):"unknown",n=e.date?new Date(e.date).toLocaleDateString():"",r=e.authorName??"",i=(e.message??"").split("\n")[0].substring(0,60);return` ${t} ${n} ${r?`(${r})`:""}: ${i}${i.length>=60?"...":""}`}).join("\n");n.push(`Recent Commits:\n${t}`)}}catch{}if(t.branches)try{const e=await t.branches();if(e&&Array.isArray(e)&&e.length>0){const t=e.find(e=>e.current),r=e.filter(e=>!e.current).slice(0,5),i=[];t?.name&&i.push(`Current: ${t.name}`),r.length>0&&i.push(`Other branches: ${r.map(e=>e.name).filter(Boolean).join(", ")}`),i.length>0&&n.push(`Branches:\n${i.join("\n")}`)}}catch{}return n.length>0?n.join("\n\n"):void 0}async function Nt(){const e=function(){const e=globalThis;return e.punica?.kernel?.Tasks?.manager}();if(!e)return;const t=[];try{const n=await(e.listRuns?.({status:["running","pending"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown";return` ${e.label??e.definitionId??"Unknown"} (${t})`}).join("\n");t.push(`Active Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listDefinitions?.());if(n&&n.length>0){const e=n.slice(0,10).map(e=>{const t=e.kind??"unknown",n=e.group?` [${e.group}]`:"";return` ${e.label??e.id??"Unknown"} (${t})${n}`}).join("\n");t.push(`Available Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listRuns?.({status:["success","failed","cancelled"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown",n=e.label??e.definitionId??"Unknown",r=null!=e.exitCode?` (exit: ${e.exitCode})`:"",i=e.startedAt?new Date(e.startedAt).toLocaleDateString():"";return` ${n}: ${t}${r}${i?` (${i})`:""}`}).join("\n");t.push(`Recent Task History:\n${e}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}async function Mt(e){if(!e.workspaceId)return;if(!function(){const e=globalThis;return e.punica?.runtime?.resources}())return;const t=[];try{const e=await(function(){const e=globalThis;return e.punica?.runtime?.datasets}()?.list?.());if(e&&e.length>0){const n=e.slice(0,10).map(e=>{const t=e.name??e.ref.id??"Unnamed",n=e.ref.provider??"";var r;return` ${t}${n?` [${n}]`:""}${"number"==typeof e.stats?.bytes?` (${r=e.stats.bytes,r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(2)} KB`:r<1073741824?`${(r/1048576).toFixed(2)} MB`:`${(r/1073741824).toFixed(2)} GB`})`:""}`}).join("\n");t.push(`Datasets (${e.length}):\n${n}`)}}catch{}try{const e=function(){const e=globalThis;return e.punica?.runtime?.compute?.registry?.listProviders?.()??[]}();if(e.length>0){const n=e.slice(0,10).map(e=>{const t=e.label??e.id??"Unnamed",n=e.kind??"",r=e.description??"";return` ${t}${n?` [${n}]`:""}${r?` - ${r}`:""}`}).join("\n");t.push(`Compute Providers (${e.length}):\n${n}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}const Dt="problems.getDiagnostics";function Pt(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Commands?.manager}();if(!t)return;const n=t.getAllCommands?.()??[];if(!n.some(e=>e.id===Dt))return;let r;try{r=t.executeCommand?.(Dt)}catch{return}if(!r||!Array.isArray(r)||0===r.length)return;const i=e.filePath?r.filter(t=>t.file===e.filePath):r;if(0===i.length)return;const s=i.slice(0,10).map(e=>{const t=e.file?`${e.file}:${e.line??0}:${e.column??0}`:`${e.line??0}:${e.column??0}`;return` ${(e.severity??"error").toUpperCase()} ${t}${e.source?`[${e.source}]`:""}${e.code?`(${e.code})`:""}: ${e.message??""}`}).join("\n"),o=i.length;return`Diagnostics (${o} ${1===o?"issue":"issues"}):\n${s}${o>10?`\n ... and ${o-10} more`:""}`}catch{return}}function Ot(e,t){switch(e){case"tenant":return t.workspaceId??"(unknown)";case"user":return t.userId??"(unknown)";case"capability":return t.capabilityId??"(unknown)";case"provider":return t.provider}}const Rt=new class{#q;#z=[];constructor(e){this.#q=Math.max(1,e?.maxRecords??1e4)}record(e){this.#z.push(e),this.#z.length>this.#q&&this.#z.splice(0,this.#z.length-this.#q)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,i=new Map;let s=0,o=0,a=0,c=0,l=0;for(const e of this.#z){if(e.timestamp<n||e.timestamp>r)continue;const u=Ot(t,e),d=i.get(u)??{cost:0,calls:0,promptTokens:0,completionTokens:0,cachedPromptTokens:0};d.cost+=e.totalCost,d.calls+=1,d.promptTokens+=e.promptTokens,d.completionTokens+=e.completionTokens,d.cachedPromptTokens+=e.cachedPromptTokens??0,i.set(u,d),s+=e.totalCost,o+=1,a+=e.promptTokens,c+=e.completionTokens,l+=e.cachedPromptTokens??0}const u=Array.from(i.entries()).map(([e,t])=>({key:e,cost:t.cost,calls:t.calls,promptTokens:t.promptTokens,completionTokens:t.completionTokens,cachedPromptTokens:t.cachedPromptTokens})).sort((e,t)=>t.cost-e.cost);return{scope:t,totalCost:s,totalCalls:o,totalPromptTokens:a,totalCompletionTokens:c,totalCachedPromptTokens:l,byKey:u}}clear(){this.#z.length=0}};async function Lt(e,n){const r=ut;if(!r)return{ok:!1,error:"Instruction class registry not available",metadata:{instructionClass:e.instructionClass,role:"unknown"}};if(!(r.isAvailable?r.isAvailable(e.instructionClass):r.has(e.instructionClass))){const t=r.get(e.instructionClass);return t?{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_ORIGIN_EXTENSION_INACTIVE",error:`Instruction class "${e.instructionClass}" is registered but its origin extension is not active`,metadata:{instructionClass:e.instructionClass,role:t.role,originExtension:t.originExtension,productId:t.productId}}:{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}}}const i=r.get(e.instructionClass);if(!i)return{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}};try{const r=await async function(e){return e?(await Promise.all([Promise.resolve(ht(e)),wt(e),Promise.resolve(At(e)),vt(e),Tt(e),Nt(),Promise.resolve(St()),Mt(e),Promise.resolve(Pt(e))])).filter(e=>void 0!==e&&e.length>0).join("\n\n"):""}(e.context),s=r?`${r}\n\n${e.userPrompt}`:e.userPrompt,o=await pt(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,correlationId:n?.correlationId??punica.kernel.Events.manager.createCorrelationId()},c=!0===e.options?.stream?"llm.chatStream":"llm.chat";let l,u,d=0;const p=await t();if("single"===o.strategy||o.modelIds.length<=1){const t=o.modelIds[0],n=Date.now();try{const r=punica.kernel.Events.manager;l=await punica.runtime.capabilities.gateway.call(c,{...a,modelId:t},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-n}catch(t){if(!(o.modelIds.length>1)||e.options?.skipFallback)throw t;{let n=t;for(const t of o.modelIds.slice(1))try{const r=Date.now(),s=punica.kernel.Events.manager;try{s.publishEvent({name:"llm.fallback",envelope:{id:s.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,fromModelId:o.modelIds[0],toModelId:t,reason:n?.message??"unknown"}})}catch{}l=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??s.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??s.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-r;break}catch(e){n=e;continue}if(!l)throw n}}}else{const t=Date.now(),n=punica.kernel.Events.manager,r=o.modelIds.map(async t=>{const r=Date.now(),s=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??n.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??n.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),o=Date.now()-r;let c;if(i.outputSchema&&"json_object"===i.responseFormat)try{c=JSON.parse(s.text)}catch{}return{res:s,expert:{modelId:s.modelId??t,text:s.text,structured:c,usage:s.usage,latencyMs:o}}}),s=await Promise.all(r);u=s.map(e=>e.expert);const c=function(e,t){if(!e.length)throw new Error("aggregateBestOfN called with no results");if("json_object"===t.responseFormat){const t=e.filter(e=>void 0!==e.structured);if(t.length>0)return t.reduce((e,t)=>t.latencyMs<e.latencyMs?t:e)}return e.reduce((e,t)=>{const n=e.text.length-e.latencyMs/1e3+.1*(e.usage?.outputTokens??0);return t.text.length-t.latencyMs/1e3+.1*(t.usage?.outputTokens??0)>n?t:e})}(u,i);l={text:c.text,modelId:c.modelId,provider:s.find(e=>e.expert.modelId===c.modelId)?.res.provider,usage:c.usage},d=Date.now()-t}let h;if(i.outputSchema&&"json_object"===i.responseFormat)try{h=JSON.parse(l.text)}catch(e){return{ok:!1,error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}const f={ok:!0,text:l.text,structured:h,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId,tokensUsed:l.usage?.totalTokens,inputTokens:l.usage?.inputTokens,outputTokens:l.usage?.outputTokens,latencyMs:d,modelId:l.modelId,provider:l.provider}};try{const e=l.usage?.inputTokens??0,t=l.usage?.outputTokens??0,n=l.usage?.cacheReadInputTokens??0,r=String(l.provider??"unknown"),s=String(l.modelId??"unknown"),o=0,c={provider:r,model:s,promptTokens:e,completionTokens:t,totalCost:o,latencyMs:d};Rt.record({capabilityId:i.id,provider:r,model:s,promptTokens:e,completionTokens:t,...n>0?{cachedPromptTokens:n}:{},totalCost:o,latencyMs:d,timestamp:Date.now(),workspaceId:p}),punica.kernel.Events.manager.publishEvent({name:"llm.call",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,workspaceId:p,meta:c}})}catch{}return f}catch(e){return{ok:!1,error:`LLM invocation failed: ${e?.message??String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}}async function $t(e){return Lt({instructionClass:"planner",userPrompt:`Generate a Workflow (ivy.workflow/v0.1) workflow from this query:\n${e.query}\n\nThe Workflow should have:\n- apiVersion: "ivy.workflow/v0.1"\n- kind: "Workflow"\n- capability: { id, version, title, description, inputs, outputs }\n- graph: { entryNodeId, nodes[], edges[] }\n- Nodes should use ref: { kind: "ivyNode" | "workflow" | "flowInput" | "flowOutput", id?, version? }\n- Edges should use fromPath/toPath for property mapping\n`,context:{capabilities:e.capabilities}})}async function jt(e){return Lt({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function Ft(e){return Lt({instructionClass:"validator",userPrompt:e.language?`Validate this ${e.language} code:\n\n${e.code}`:`Validate this code:\n\n${e.code}`,context:e.context})}async function Bt(e){return Lt({instructionClass:"reviewer",userPrompt:e.language?`Review this ${e.language} code:\n\n${e.code}`:`Review this code:\n\n${e.code}`,context:e.context})}async function qt(e){let t="";e.requirements?t+=`Requirements:\n${e.requirements}\n\n`:t+="Optimize and improve this Workflow:\n\n",t+=`Current Workflow:\n${JSON.stringify(e.workflow,null,2)}\n\n`,e.requirements?(t+="Please edit this Workflow according to the requirements above. ",t+="Maintain DAG structure, preserve all node.ref and node.data, ",t+='ensure all IDs remain valid, and maintain apiVersion="ivy.workflow/v0.1" and kind="Workflow".\n'):(t+="Please optimize this Workflow: ",t+="- Improve parallelization opportunities\n",t+="- Remove redundant nodes/edges\n",t+="- Improve node labels\n",t+="- Maintain DAG structure (no cycles)\n",t+="- Preserve all functionality\n",t+='- Maintain apiVersion="ivy.workflow/v0.1" and kind="Workflow"\n');return await Lt({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function zt(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function Ut(e,t){const n=zt(e).split("/").filter(Boolean),r=zt(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function Vt(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function Wt(e,t){const n=zt(e).split("/").filter(Boolean),r=zt(t).split("/").filter(Boolean);let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;const s=n.length-i,o=r.slice(i);return[...Array(s).fill(".."),...o].join("/")}async function Kt(e,t){const n=[];let r=0;const i=1048576;if("0.1"!==e.specVersion)throw new Error(`Unsupported CodegenBundle version: ${e.specVersion}`);if(!e.files||!Array.isArray(e.files))throw new Error("CodegenBundle must have a files array");if(0===e.files.length)throw new Error("CodegenBundle files array cannot be empty");if(e.files.length>50)throw new Error(`CodegenBundle exceeds max files limit: ${e.files.length} > 50`);let s=0;const o=/^(?!\/)(?!.*\.\.)([a-zA-Z0-9._-]+\/)*[a-zA-Z0-9._-]+$/;for(const r of e.files){if(!o.test(r.path)){n.push({path:r.path,error:"Invalid path: must be relative, no absolute paths, no .."});continue}if("delete"===r.action){if(void 0!==r.content){n.push({path:r.path,error:"Delete action cannot have content"});continue}}else if("create"===r.action||"update"===r.action){if(!r.content){n.push({path:r.path,error:`${r.action} action requires content`});continue}s+=r.content.length}const e=Wt(t,Ut(t,zt(r.path)));(e.startsWith("..")||Vt(e))&&n.push({path:r.path,error:"Path traversal detected"})}if(s>i)throw new Error(`CodegenBundle exceeds max total size: ${s} > 1048576 bytes`);for(const t of e.files)if(!n.some(e=>e.path===t.path))try{const e=zt(t.path);if("create"===t.action){const n=e.split("/");if(n.length>1){const e=n.slice(0,-1).join("/");try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFolder(e)}catch{}}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFileWithContent(e,t.content),r++}else if("update"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{n.push({path:t.path,error:"File does not exist for update"});continue}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.updateFileContent(e,t.content),r++}else if("delete"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{continue}await punica.runtime.fs.deleteFile(e),r++}}catch(e){n.push({path:t.path,error:e?.message??String(e)})}return{applied:r,errors:n}}const Gt={type:"object",additionalProperties:!1,required:["specVersion","files"],properties:{specVersion:{type:"string",const:"0.1"},summary:{type:"string",maxLength:500},files:{type:"array",minItems:1,maxItems:50,items:{type:"object",additionalProperties:!1,required:["path","action"],properties:{path:{type:"string",minLength:1,maxLength:500,pattern:"^(?!/)(?!.*\\.\\.)([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+$"},action:{type:"string",enum:["create","update","delete"]},content:{type:"string",maxLength:1e6},encoding:{type:"string",enum:["utf-8"],default:"utf-8"}}}}}};const Ht=new class{api;constructor(){this.api={instructionClassRegistry:ut,invoke:Lt,plan:$t,generateCode:jt,validator:Ft,reviewer:Bt,editWorkflow:qt,listInstructionClasses:e=>ut.listSummaries(e)}}};var Yt={manager:Ht};const Jt={Commands:r,History:s,TimeServer:o,Tasks:d,Events:V,Notifications:H,Policy:ue,AI:lt,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:Gt,applyCodegenBundle:Kt,default:Yt,manager:Ht})};const Zt={manager:new class{#U=new Map;#V=new Map;#W=null;#K=null;#G;#H;#Y;#J(){const e=punica.shell.Layout.manager,t=e.getSlot("activityBar")??e.getSlot("primarySidebar"),n=t?.content;this.#G=document.createElement("punica-row"),this.#H=document.createElement("punica-col"),this.#Y=document.createElement("punica-col"),this.#G.setAttribute("direction","column"),this.#G.setAttribute("alignitems","stretch"),this.#G.setAttribute("justifycontent","space-between"),this.#G.style.height="100%",this.#G.appendChild(this.#H),this.#G.appendChild(this.#Y),n?.appendChild(this.#G)}constructor(){}setActiveByViewId(e){if(e){for(const t of this.#U.values())if(t.viewId===e)return void this.#Z(t.id);for(const t of this.#V.values())if(t.viewId===e)return void this.#Z(t.id)}else this.#Z(null)}#Q(e,t){const n=globalThis,r=()=>{const r=n.punica?.shell?.Views?.manager;return r?.reveal?.(e,{kind:"user-gesture",id:`activity-bar:${t}`})},i=n.punica?.runtime?.capabilities?.gateway;if(!i?.call)return void Promise.resolve(r()).catch(t=>{console.error("[ActivityBar] Failed to reveal view",e,t)});const s=n.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`activity-bar-${Date.now()}`;i.call("shell.revealView",{viewId:e},{sessionId:"default",actor:{type:"user"},origin:{kind:"command",id:`activity-bar:${t}`},trace:{traceId:o},policy:{mode:"execute"}}).catch(e=>(console.warn("[ActivityBar] shell.revealView failed, falling back to direct reveal:",e),Promise.resolve(r()))).catch(t=>{console.error("[ActivityBar] Failed to reveal view",e,t)})}#Z(e){this.#W=e;const t=punica.shell.Layout.manager,n=t.getSlot("primarySidebar")?.content;e?(this.#K=null,n&&n.classList.remove("primarySidebar-hidden")):n&&n.classList.add("primarySidebar-hidden"),this.#X()}syncContentTool(e){const t=e?this.#ee(e):void 0;this.#K=t?.id??null,this.#X()}#ee(e){for(const t of this.#V.values())if(t.contentViewType===e)return t;for(const t of this.#U.values())if(t.contentViewType===e)return t}#X(){if(!this.#G)return;const e="extension-is-active",t=this.#K??this.#W;if(this.#G.querySelectorAll(".extension").forEach(t=>t.classList.remove(e)),!t)return;const n=this.#G.querySelector("#"+t);n&&n.classList.add(e)}addItem(e){this.#G||this.#J();const t=punica.shell.Layout.manager,n=document.createElement("punica-button");n.setAttribute("id",e.id),n.setAttribute("rounded",""),n.setAttribute("color","primary"),n.setAttribute("variant","text"),n.setAttribute("size","medium"),n.setAttribute("style","margin-bottom: 4px;"),n.setAttribute("title",e.title),n.onclick=()=>{const n=globalThis.punica?.shell?.Views?.manager,r=!!e.viewId&&!!n?.getPlacement?.(e.viewId),i=()=>{if(e.command)try{punica.kernel.Commands.manager.executeCommand(e.command)}catch(t){console.error("[ActivityBar] Failed to execute command for item",e.id,e.command,t)}};if(!(r||!!e.viewId)){return e.contentViewType&&(this.#K=e.id,this.#X()),void i()}if(this.#W===e.id)return r&&n.hide(e.viewId,{kind:"user-gesture",id:`activity-bar:${e.id}`}),void this.#Z(null);if(this.#Z(e.id),r)this.#Q(e.viewId,e.id);else{try{t.ensureViewHost("primarySidebar",e.viewId)}catch(t){console.error("[ActivityBar] Failed to show primary view for item",e.id,e.viewId,t)}i()}},n.innerHTML=`<punica-icon size="xlarge">${e.icon}</punica-icon>`,n.className="extension";const r="primary"===e.alignment,i=r?this.#H:this.#Y;(r?this.#U:this.#V).set(e.id,e);const s=i.querySelector("#"+e.id);s?i.replaceChild(n,s):i.appendChild(n);(this.#K??this.#W)===e.id&&n.classList.add("extension-is-active")}removeItem(e){if(this.#U.has(e)){const t=this.#H.querySelector("#"+e);t&&(this.#H.removeChild(t),this.#U.delete(e))}else if(this.#V.has(e)){const t=this.#Y.querySelector("#"+e);t&&(this.#Y.removeChild(t),this.#V.delete(e))}}}};const Qt={manager:new class{#U=new Map;#V=new Map;#G;#H;#Y;#J(){const e=window.punica?.shell?.Layout.manager,t=e.getSlot("statusbar"),n=t?.content;this.#G=document.createElement("div"),this.#G.className="status-bar-inner",this.#H=document.createElement("div"),this.#H.className="status-bar-group status-bar-group-primary",this.#Y=document.createElement("div"),this.#Y.className="status-bar-group status-bar-group-secondary",this.#G.appendChild(this.#H),this.#G.appendChild(this.#Y),n?.appendChild(this.#G)}constructor(){}addItem(e){this.#G||this.#J();const t=document.createElement("button");t.type="button",t.id=e.id,t.title=e.title,t.className="status-bar-action";const n=e.command??e.capability;t.onclick=()=>{if(n)try{punica.kernel.Commands.manager.executeCommand(n)}catch(t){console.error("[Statusbar] Failed to execute command for item",e.id,n,t)}};const r=[];e.icon&&r.push(`<punica-icon size="small">${e.icon}</punica-icon>`),e.label&&r.push(`<span class="status-bar-label">${e.label}</span>`),t.innerHTML=r.join(""),"primary"===e.alignment?(this.#U.set(e.id,e),this.#H.appendChild(t)):(this.#V.set(e.id,e),this.#Y.appendChild(t))}removeItem(e){if(this.#U.has(e)){const t=this.#H.querySelector("#"+e);t&&(this.#H.removeChild(t),this.#U.delete(e))}else if(this.#V.has(e)){const t=this.#Y.querySelector("#"+e);t&&(this.#Y.removeChild(t),this.#V.delete(e))}}}};function Xt(e,t){const n=document.createElement("punica-typography");if(n.textContent=e,t?.variant&&n.setAttribute("variant",t.variant),t?.color&&n.setAttribute("color",t.color),"bold"===t?.fontWeight&&n.setAttribute("fontweight","bold"),t?.attrs)for(const[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);return t?.style&&("string"==typeof t.style?n.setAttribute("style",t.style):Object.assign(n.style,t.style)),t?.className&&(n.className=t.className),n}const en={createElement:function(e,t){const n=document.createElement(e);if(t?.attrs)for(const[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);return t?.text&&(n.textContent=t.text),t?.children&&t.children.forEach(e=>n.appendChild(e)),t?.style&&("string"==typeof t.style?n.setAttribute("style",t.style):Object.assign(n.style,t.style)),t?.className&&(n.className=t.className),n},createButton:function(e,t,n){const r=document.createElement("punica-button");if(e.includes("<")||e.includes("<")?r.innerHTML=e:r.textContent=e,!1!==n?.rounded&&r.setAttribute("rounded",""),r.setAttribute("size",n?.size??"small"),r.setAttribute("variant",n?.variant??"outlined"),n?.color&&r.setAttribute("color",n.color),n?.disabled&&r.setAttribute("disabled",""),n?.fullwidth&&r.setAttribute("fullwidth",""),n?.icon){const e=document.createElement("punica-icon");e.setAttribute("slot","startIcon");const t=document.createElement("i");t.className=n.icon,e.appendChild(t),r.appendChild(e)}return n?.disabled||r.addEventListener("click",t),r},createIconButton:function(e,t,n){const r=document.createElement("punica-icon-button");if(r.setAttribute("size",n?.size??"x-small"),n?.variant&&r.setAttribute("variant",n.variant),n?.title&&r.setAttribute("title",n.title),n?.disabled&&r.setAttribute("disabled",""),n?.attrs)for(const[e,t]of Object.entries(n.attrs))r.setAttribute(e,t);return r.innerHTML=`<i class="${e}"></i>`,n?.disabled||r.addEventListener("click",t),r},createTypography:Xt,createChip:function(e,t){const n=document.createElement("punica-chip");return n.textContent=e,n.setAttribute("size",t?.size??"small"),n.setAttribute("variant",t?.variant??"filled"),t?.color&&n.setAttribute("color",t.color),n},createBox:function(e){const t=document.createElement("punica-box");if(e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createRow:function(e){const t=document.createElement("punica-row");if(e?.spacing&&t.setAttribute("spacing",e.spacing),e?.alignItems&&t.setAttribute("alignitems",e.alignItems),e?.wrap&&t.setAttribute("wrap",e.wrap),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createCol:function(e){const t=document.createElement("punica-col");if(void 0!==e?.xs&&t.setAttribute("xs",String(e.xs)),void 0!==e?.sm&&t.setAttribute("sm",String(e.sm)),void 0!==e?.md&&t.setAttribute("md",String(e.md)),void 0!==e?.lg&&t.setAttribute("lg",String(e.lg)),void 0!==e?.xl&&t.setAttribute("xl",String(e.xl)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createInput:function(e){const t=document.createElement("punica-input");if(void 0!==e?.value&&(t.value=e.value),e?.placeholder&&t.setAttribute("placeholder",e.placeholder),e?.type&&t.setAttribute("type",e.type),e?.size&&t.setAttribute("size",e.size),e?.fullwidth&&t.setAttribute("fullwidth",""),e?.rounded&&t.setAttribute("rounded",""),e?.disabled&&t.setAttribute("disabled",""),e?.id&&t.setAttribute("id",e.id),void 0!==e?.min&&t.setAttribute("min",String(e.min)),void 0!==e?.max&&t.setAttribute("max",String(e.max)),void 0!==e?.step&&t.setAttribute("step",String(e.step)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onInput&&t.addEventListener("input",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onInput(n)}),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onChange(n)}),t},createSelect:function(e){const t=document.createElement("punica-select");if(void 0!==e?.value&&(t.value=e.value),e?.size&&t.setAttribute("size",e.size),e?.fullwidth&&t.setAttribute("fullwidth",""),e?.rounded&&t.setAttribute("rounded",""),e?.disabled&&t.setAttribute("disabled",""),e?.minimumTargetWidth&&t.setAttribute("minimumtargetwidth",""),e?.id&&t.setAttribute("id",e.id),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onChange(n)}),t},createSelectItem:function(e){const t=document.createElement("punica-select-item");if(t.setAttribute("value",e.value),e.text&&(t.textContent=e.text),e.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t},createCheckbox:function(e){const t=document.createElement("punica-checkbox");if(void 0!==e?.checked&&(t.checked=e.checked),e?.disabled&&t.setAttribute("disabled",""),e?.id&&t.setAttribute("id",e.id),e?.label&&t.setAttribute("label",e.label),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.checked??t?.target?.checked??!1;e.onChange(n)}),t},createIcon:function(e){const t=document.createElement("punica-icon");if(e?.iconClass){const n=document.createElement("i");n.className=e.iconClass,t.appendChild(n)}else e?.innerHTML&&(t.innerHTML=e.innerHTML);if(e?.slot&&t.setAttribute("slot",e.slot),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createTextarea:function(e){const t=document.createElement("punica-textarea");if(void 0!==e?.value&&(t.value=e.value),e?.placeholder&&t.setAttribute("placeholder",e.placeholder),e?.rows&&t.setAttribute("rows",String(e.rows)),e?.cols&&t.setAttribute("cols",String(e.cols)),e?.size&&t.setAttribute("size",e.size),e?.fullwidth&&t.setAttribute("fullwidth",""),e?.rounded&&t.setAttribute("rounded",""),e?.disabled&&t.setAttribute("disabled",""),e?.id&&t.setAttribute("id",e.id),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.onInput&&t.addEventListener("input",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onInput(n)}),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.value??"";e.onChange(n)}),t},createDivider:function(e){const t=document.createElement("punica-divider");if(e?.orientation&&t.setAttribute("orientation",e.orientation),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createListView:function(e){const t=document.createElement("punica-list-view");if(e?.enableDivider&&t.setAttribute("enabledivider",""),e?.spacing&&t.setAttribute("spacing",e.spacing),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createListViewItem:function(e){const t=document.createElement("punica-list-view-item");if(e?.label)if("string"==typeof e.label){const n=document.createElement("punica-typography");n.setAttribute("slot","label"),n.textContent=e.label,t.appendChild(n)}else e.label.getAttribute("slot")||e.label.setAttribute("slot","label"),t.appendChild(e.label);if(e?.content)if("string"==typeof e.content){const n=document.createElement("div");n.setAttribute("slot","content"),n.textContent=e.content,t.appendChild(n)}else e.content.getAttribute("slot")||e.content.setAttribute("slot","content"),t.appendChild(e.content);if(e?.endAdornment&&(e.endAdornment.getAttribute("slot")||e.endAdornment.setAttribute("slot","endAdornment"),t.appendChild(e.endAdornment)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),t},createPaper:function(e){const t=document.createElement("punica-paper");if(void 0!==e?.elevation&&t.setAttribute("elevation",String(e.elevation)),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createTab:function(e){const t=document.createElement("punica-tab");if(e?.value&&t.setAttribute("value",e.value),e?.orientation&&t.setAttribute("orientation",e.orientation),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.onChange&&t.addEventListener("change",t=>{const n=t?.detail?.value??t?.target?.getAttribute("value")??"";e.onChange(n)}),t},createTabItem:function(e){const t=document.createElement("punica-tab-item");if(t.setAttribute("value",e.value),e.text&&(t.textContent=e.text),e.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t},createTabPanel:function(e){const t=document.createElement("punica-tab-panel");if(t.setAttribute("value",e.value),e.selectedValue&&t.setAttribute("selectedvalue",e.selectedValue),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createBadge:function(e){const t=document.createElement("punica-badge");if(e?.text&&(t.textContent=e.text),e?.variant&&t.setAttribute("variant",e.variant),e?.color&&t.setAttribute("color",e.color),e?.size&&t.setAttribute("size",e.size),e?.title&&t.setAttribute("title",e.title),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t},createMenu:function(e){const t=document.createElement("punica-menu");if(e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t},createMenuItem:function(e){const t=document.createElement("punica-menu-item");if(e?.text){const n=Xt(e.text);t.appendChild(n)}if(e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.onClick&&t.addEventListener("click",e.onClick),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),e?.children&&e.children.forEach(e=>t.appendChild(e)),t},createLink:function(e,t){const n=document.createElement("a");if(n.href=t.href,n.textContent=e,t.target&&(n.target=t.target),t.rel&&(n.rel=t.rel),t.download&&(n.download=t.download),t.attrs)for(const[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);return t.children&&t.children.forEach(e=>n.appendChild(e)),t.style&&("string"==typeof t.style?n.setAttribute("style",t.style):Object.assign(n.style,t.style)),t.className&&(n.className=t.className),n},createToolbar:function(e){const t=document.createElement("punica-toolbar");if(e?.variant&&t.setAttribute("variant",e.variant),e?.disableGutters&&t.setAttribute("disablegutters",""),e?.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return e?.children&&e.children.forEach(e=>t.appendChild(e)),e?.style&&("string"==typeof e.style?t.setAttribute("style",e.style):Object.assign(t.style,e.style)),e?.className&&(t.className=e.className),t}};const tn={light:{id:"light",name:"Light",variables:{"--background-main":"#ffffff","--background-paper":"#f0f0f0","--background-navbar":"#0969da","--background-tabbar":"#e1e4e8","--background-backdrop":"rgba(0, 0, 0, 0.25)","--text-primary":"#24292f","--text-secondary":"#57606a","--text-placeholder":"#8c959f","--text-navbar":"#ffffff","--text-tabbar":"#0969da","--icon-navbar":"#ffffff","--icon-tabbar-active":"#0969da","--icon-tabbar-inactive":"#656d76","--primary-light":"#58a6ff","--primary-main":"#0969da","--primary-dark":"#0550ae","--error-light":"#ffebe9","--error-main":"#cf222e","--error-dark":"#a40e26","--warning-light":"#fff8c5","--warning-main":"#9a6700","--warning-dark":"#7d4e00","--success-light":"#dafbe1","--success-main":"#1a7f37","--success-dark":"#116329","--info-light":"#ddf4ff","--info-main":"#0969da","--info-dark":"#0550ae","--neutral-light":"#d1d9e0","--neutral-main":"#e9e9e9","--neutral-dark":"#8c959f","--disabled":"#33353a","--highlight":"#ddf4ff","--white":"#ffffff","--black":"#000000","--divider":"#d1d9e0","--focus-ring":"#0969da","--root-border-radius":"8px","--root-padding":"16px"}},dark:{id:"dark",name:"Dark",variables:{"--background-main":"#131416","--background-paper":"#2a2d33","--background-navbar":"#0969da","--background-tabbar":"#232529","--background-backdrop":"rgba(0, 0, 0, 0.5)","--text-primary":"#f5f7fa","--text-secondary":"#c0c4cc","--text-placeholder":"#9aa0a6","--text-navbar":"#ffffff","--text-tabbar":"#0a84ff","--icon-navbar":"#ffffff","--icon-tabbar-active":"#0a84ff","--icon-tabbar-inactive":"#6b6e76","--primary-light":"#66b3ff","--primary-main":"#0a84ff","--primary-dark":"#0056b3","--error-light":"#f8d7da","--error-main":"#ff453a","--error-dark":"#c41c12","--warning-light":"#ffe28a","--warning-main":"#ffd60a","--warning-dark":"#c9a400","--success-light":"#48e09e","--success-main":"#30d158","--success-dark":"#228c3f","--info-light":"#4ac8ff","--info-main":"#64d2ff","--info-dark":"#0a84ff","--neutral-light":"#45484e","--neutral-main":"#35383f","--neutral-dark":"#25272b","--disabled":"#33353a","--highlight":"#52a8ff","--white":"#ffffff","--black":"#000000","--divider":"#3a3d44","--focus-ring":"#52a8ff","--root-border-radius":"8px","--root-padding":"16px"}}};const nn=new class{currentProfileId=null;listeners=new Set;async loadProfile(e){const t=tn[e];if(!t)return void console.warn(`[Theme] Profile not found: ${e}`);const n=document.documentElement;if(Object.entries(t.variables).forEach(([e,t])=>{n.style.setProperty(e,t)}),this.currentProfileId=e,this.listeners.forEach(t=>t(e)),"undefined"!=typeof punica&&punica.extensions?.settings?.manager)try{await punica.extensions.settings.manager.set("system","theme.profile",e,"global")}catch(e){console.error("[Theme] Failed to save profile to settings:",e)}}getCurrentProfile(){return this.currentProfileId}getProfiles(){return{...tn}}getProfile(e){return tn[e]}registerProfile(e){tn[e.id]=e}onDidChangeProfile(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDefaultImmediate(){const e=tn.dark;if(!e)return void console.warn("[Theme] Default dark profile not found");const t=document.documentElement;Object.entries(e.variables).forEach(([e,n])=>{t.style.setProperty(e,n)}),this.currentProfileId="dark"}async initialize(){if("undefined"!=typeof punica&&punica.extensions?.settings?.manager)try{await punica.extensions.settings.manager.load();const e=punica.extensions.settings.manager.get("system","theme.profile");e&&"string"==typeof e&&tn[e]?await this.loadProfile(e):await this.loadProfile("dark")}catch(e){console.error("[Theme] Failed to initialize from settings:",e),await this.loadProfile("dark")}else await this.loadProfile("dark")}};async function rn(e){return new Promise(t=>{const{title:n,message:r,html:i,buttons:s=[{label:"OK",variant:"filled",action:"ok"}],footerHtml:o,modal:a=!0,width:c,height:l,icon:u,tone:d,onMount:p}=e,h=`punica-dialog-${Date.now()}`,f=document.querySelector(`#${h}`);f?.remove();const m=document.createElement("punica-dialog");m.id=h,m.setAttribute("rounded",""),a&&m.setAttribute("modal","");const g=[`width: ${c||"440px"}`];l&&g.push(`height: ${l}`);const y=` style="${g.join("; ")}"`,b=d?`var(--${d}-main)`:"",w=u||(d?{info:"fa-circle-info",warning:"fa-triangle-exclamation",error:"fa-circle-exclamation",success:"fa-circle-check"}[d]:""),v=w&&b?`<span style="flex:0 0 auto; width:34px; height:34px; display:inline-flex; align-items:center; justify-content:center; border-radius:50%; background: color-mix(in srgb, ${b} 16%, transparent); color:${b}; font-size:16px;"><i class="fa-duotone fa-solid ${w}"></i></span>`:"",k=i||(r?`<punica-typography style="color: var(--text-secondary); line-height: 1.6;">${r}</punica-typography>`:"");m.innerHTML=`\n <punica-dialog-header>\n <punica-box style="display:flex; align-items:center; gap:12px;">\n ${v}\n <punica-typography fontweight="bold" style="color: var(--text-primary); font-size: 16px;">${n}</punica-typography>\n </punica-box>\n </punica-dialog-header>\n <punica-dialog-content${y}>\n <punica-box style="display:flex; flex-direction: column; gap: 10px; padding: 4px 2px 8px;">\n ${k}\n </punica-box>\n </punica-dialog-content>\n <punica-dialog-footer>\n ${o||`\n <punica-box style="display:flex; width:100%; box-sizing:border-box; gap: 8px; justify-content: flex-end; padding-top: 14px; border-top: 1px solid var(--divider);">\n ${s.map((e,t)=>`<punica-button id="${`${h}-btn-${t}`}" variant="${e.variant||"outlined"}" color="${e.color||"primary"}" size="small" rounded>${e.label}</punica-button>`).join("")}\n </punica-box>\n `}\n </punica-dialog-footer>\n `,document.body.appendChild(m),queueMicrotask(()=>{try{m.setAttribute("open","true"),m.open=!0,p?.(m)}catch{}});const I=e=>{try{m.remove()}catch{}t(e)};s.forEach((e,t)=>{const n=`${h}-btn-${t}`,r=m.querySelector(`#${n}`);r?.addEventListener("click",()=>{I(e.action||e.label.toLowerCase())})}),m.addEventListener?.("close",()=>{I(void 0)})})}async function sn(e){const{title:t,message:n,variant:r="info",buttonLabel:i="OK"}=e,s=t||("success"===r?"Success":"warning"===r?"Warning":"error"===r?"Error":"Information");await rn({title:s,message:n,tone:r,buttons:[{label:i,variant:"filled",color:"error"===r?"error":"primary",action:"ok"}]})}const on={showInformationMessage:async function(e,...t){return 0===t.length?void await sn({message:e,variant:"info",title:"Information"}):await rn({title:"Information",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showWarningMessage:async function(e,...t){return 0===t.length?void await sn({message:e,variant:"warning",title:"Warning"}):await rn({title:"Warning",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showErrorMessage:async function(e,...t){return 0===t.length?void await sn({message:e,variant:"error",title:"Error"}):await rn({title:"Error",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showDialog:rn,showConfirm:async function(e){const{title:t="Confirm",message:n,confirmLabel:r="OK",cancelLabel:i="Cancel",variant:s="info"}=e;return"confirm"===await rn({title:t,message:n,tone:s,buttons:[{label:i,variant:"text",action:"cancel"},{label:r,variant:"filled",color:"error"===s?"error":"primary",action:"confirm"}]})},showAlert:sn,showPrompt:async function(e){return new Promise(t=>{const{title:n="Prompt",message:r,placeholder:i="",defaultValue:s="",confirmLabel:o="OK",cancelLabel:a="Cancel",type:c="text"}=e,l=`${`punica-prompt-${Date.now()}`}-input`;rn({title:n,html:`\n <punica-box style="display:flex; flex-direction: column; gap: 10px;">\n <punica-typography>${r}</punica-typography>\n <punica-input \n id="${l}" \n type="${c}" \n placeholder="${i}" \n value="${s}"\n rounded>\n </punica-input>\n </punica-box>\n `,buttons:[{label:a,variant:"outlined",action:"cancel"},{label:o,variant:"filled",action:"confirm"}]}).then(e=>{if("confirm"===e){const e=document.querySelector(`#${l}`),n=e?.value??e?.getAttribute?.("value")??"";t(n||void 0)}else t(void 0)})})},showToast:function(e){const{title:t="",message:n="",variant:r="neutral",duration:i=1e3,dismissible:s=!0,placement:o="top-right"}=e,a=function(){let e=document.querySelector("punica-toaster");return e||(e=document.createElement("punica-toaster"),document.body.appendChild(e)),e}().shadowRoot;if(!a){if(window.Toast?.show)return window.Toast.show(e);throw new Error("punica-toaster shadow root not available")}const c=a.querySelector(`.region.${o}`)||a.querySelector(".region.top-right");if(!c)throw new Error(`Toast region not found: ${o}`);const l=document.createElement("punica-toast");return l.setAttribute("variant",r),t&&l.setAttribute("title",t),n&&l.setAttribute("message",n),i>0&&l.setAttribute("duration",String(i)),l.setAttribute("dismissible",String(s)),l.setAttribute("enter-from",o.startsWith("top")?"top":"bottom"),c.prepend(l),l},showChangesPreview:async function(e){const{title:t,summary:n,files:r,onConfirm:i,onCancel:s}=e,o=`changes-preview-files-${Date.now()}`,a=`changes-preview-content-${Date.now()}`,c=`changes-preview-selected-${Date.now()}`;let l=0;const u=()=>{const e=document.querySelector(`#${c}`);e&&r[l]&&(e.textContent=r[l].path)},d=e=>{e.innerHTML="",r.forEach((t,n)=>{const r=en.createBadge({text:t.action,variant:"filled",color:"delete"===t.action?"error":"create"===t.action?"success":"primary",size:"small"}),i=en.createListViewItem({label:t.path,content:t.action,endAdornment:r});n===l&&(i.style.backgroundColor="rgba(255, 255, 255, 0.1)"),i.style.cursor="pointer",i.addEventListener("click",()=>{l=n,d(e),p(document.getElementById(a)),u()}),e.appendChild(i)})},p=e=>{const t=r[l];if(e.innerHTML="","delete"===t.action){const n=en.createTypography(`This file will be deleted: ${t.path}`,{variant:"body"});return void e.appendChild(n)}if(!t.content){const t=en.createTypography("No content preview available",{variant:"body"});return void e.appendChild(t)}const n=en.createBox({style:{width:"100%",height:"400px",border:"1px solid rgba(255, 255, 255, 0.1)",borderRadius:"4px",overflow:"hidden"}});e.appendChild(n);const i=window.monaco||globalThis.monaco;if(i?.editor)try{const r=f(t.path),s=i.editor.create(n,{value:t.content||"",language:r,theme:"vs-dark",readOnly:!0,minimap:{enabled:!1},fontSize:13,fontLigatures:!0,automaticLayout:!0,scrollBeyondLastLine:!1});e.__monacoEditor=s}catch(e){h(n,t.content||"")}else h(n,t.content||"")},h=(e,t)=>{const n=document.createElement("pre");n.style.cssText="margin: 0; padding: 10px; overflow: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap; word-wrap: break-word;",n.textContent=t,e.innerHTML="",e.appendChild(n)},f=e=>{const t=e.split(".").pop()?.toLowerCase();return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",json:"json",md:"markdown",html:"html",css:"css",yaml:"yaml",yml:"yaml"}[t||""]||"plaintext"},m=`\n <punica-box style="display: flex; flex-direction: column; gap: 12px; min-width: 800px; max-width: 1200px; max-height: 80vh;">\n ${n?`<punica-typography>${n}</punica-typography>`:""}\n <punica-box style="display: flex; gap: 12px; flex: 1; min-height: 0;">\n <punica-box style="flex: 0 0 300px; display: flex; flex-direction: column; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 4px; overflow: hidden;">\n <punica-box style="padding: 8px; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">\n <punica-typography fontweight="bold">Files (${r.length})</punica-typography>\n </punica-box>\n <punica-box id="${o}" style="flex: 1; overflow-y: auto; padding: 4px;"></punica-box>\n </punica-box>\n <punica-box style="flex: 1; display: flex; flex-direction: column; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 4px; overflow: hidden; min-width: 0;">\n <punica-box style="padding: 8px; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">\n <punica-typography fontweight="bold" id="${c}">${r[0]?.path||""}</punica-typography>\n </punica-box>\n <punica-box id="${a}" style="flex: 1; overflow: auto; padding: 0;"></punica-box>\n </punica-box>\n </punica-box>\n </punica-box>\n `;return new Promise(e=>{punica.shell.View.showDialog({title:t,html:m,buttons:[{label:"Cancel",variant:"outlined",action:"cancel"},{label:"Apply Changes",variant:"filled",color:"primary",action:"confirm"}],width:"90vw",onMount:e=>{const t=e.querySelector(`#${o}`),n=e.querySelector(`#${a}`);e.querySelector(`#${c}`),t&&d(t),n&&p(n),u()}}).then(async t=>{const n=document.querySelector('[id^="punica-dialog-"]');if(n){const e=n.querySelector(`#${a}`);if(e&&e.__monacoEditor)try{e.__monacoEditor.dispose()}catch{}}if("confirm"===t)try{await i(),e("confirm")}catch(t){await punica.shell.View.showAlert({title:"Error",message:`Failed to apply changes: ${t instanceof Error?t.message:String(t)}`,variant:"error"}),e(void 0)}else s?.(),e("cancel"===t?"cancel":void 0)})})},Helpers:en,Theme:{manager:nn,profiles:tn}};function an(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!t?.publishEvent||!t?.createCorrelationId)&&(t.publishEvent({name:e.name,envelope:{id:t.createCorrelationId(),correlationId:e.correlationId,traceId:e.traceId,timestampMs:Date.now(),source:e.source??"shell:profile",kind:e.kind??"info"},payload:e.payload}),!0)}catch{return!1}}function cn(){return globalThis.punica?.shell?.Layout?.manager}function ln(){return globalThis.punica?.shell?.ActivityBar?.manager}const un={manager:new class{#te=new Map;#ne=new Map;#re=new Map;#ie=new Map;registerPlacement(e){if(!e?.viewId||!e.slot)return;const t=this.#te.get(e.viewId);t&&t.extensionName!==e.extensionName&&console.warn(`[Views] Placement collision for view "${e.viewId}" between "${t.extensionName}" and "${e.extensionName}". Keeping the last registered.`),this.#te.set(e.viewId,e),an({name:"shell.view.registered",source:"shell:views",payload:{viewId:e.viewId,slot:e.slot,extensionName:e.extensionName}})}registerProvider(e,t,n){return this.#te.has(e)||console.warn(`[Views] Provider registered for "${e}" but no placement is declared in any manifest.`+(n?` (extension: ${n})`:"")),this.#ne.set(e,t),{dispose:()=>{this.#ne.get(e)===t&&this.#ne.delete(e)}}}getPlacement(e){return this.#te.get(e)}hasProvider(e){return this.#ne.has(e)}getState(e){if(!this.#te.has(e)&&!this.#ne.has(e))return;const t=this.#te.get(e);return t&&this.#ie.get(t.slot)===e?"visible":this.#re.has(e)?"materialized":"registered"}getVisibleView(e){return this.#ie.get(e)}listViews(){return Array.from(this.#te.values()).map(e=>({viewId:e.viewId,slot:e.slot,extensionName:e.extensionName,title:e.title,state:this.getState(e.viewId)??"registered"}))}async reveal(e,t,n){const r=this.#te.get(e);if(!r)throw new Error(`[Views] Cannot reveal "${e}": no placement is registered for this view.`);if(!this.#ne.has(e)){const t=globalThis.punica?.extensions?.manager;t?.activate&&await t.activate(r.extensionName,{reason:"view",trigger:e,presentation:"interactive"})}const i=cn();if(!i)throw new Error("[Views] Layout manager unavailable — cannot reveal.");const s=i.materializeViewHost(r.slot,e),o=this.#ne.get(e),a="contentSidebar"===r.slot;if(o&&(a||!this.#re.has(e))){if(a){const t=this.#re.get(e);try{t?.dispose()}catch(t){console.warn(`[Views] provider dispose failed for "${e}":`,t)}}const t=await o.render(s);this.#re.set(e,t&&"function"==typeof t.dispose?t:null)}if(i.showView(r.slot,e),i.setSlotCollapsed?.(r.slot,!1),this.#ie.set(r.slot,e),"panel"===r.slot&&(globalThis.punica?.shell?.PanelTabs)?.activateTabVisual?.(e),"primarySidebar"===r.slot)try{ln()?.setActiveByViewId?.(e)}catch{}if(!o&&r.fallbackCommand)try{(globalThis.punica?.kernel?.Commands?.manager)?.executeCommand?.(r.fallbackCommand)}catch(t){console.warn(`[Views] fallback command "${r.fallbackCommand}" for view "${e}" failed:`,t)}an({name:"shell.view.revealed",source:"shell:views",payload:{viewId:e,slot:r.slot,extensionName:r.extensionName,source:t?.kind??"host",sourceId:t?.id,focus:n?.focus??!1}})}hide(e,t){const n=this.#te.get(e);if(!n)return;if(this.#ie.get(n.slot)!==e)return;const r=cn();if("contentSidebar"===n.slot?this.#se(n.slot):(r?.hideSlotViews(n.slot),r?.setSlotCollapsed?.(n.slot,!0)),this.#ie.delete(n.slot),"primarySidebar"===n.slot)try{ln()?.setActiveByViewId?.(null)}catch{}an({name:"shell.view.hidden",source:"shell:views",payload:{viewId:e,slot:n.slot,source:t?.kind??"host",sourceId:t?.id}})}notifySlotReset(e){this.#se(e);const t=this.#ie.get(e);void 0!==t&&(this.#ie.delete(e),an({name:"shell.view.hidden",source:"shell:views",payload:{viewId:t,slot:e,source:"host",sourceId:"slot-reset"}}))}#se(e){const t=cn();for(const n of this.#te.values()){if(n.slot!==e)continue;const r=this.#re.get(n.viewId);try{r?.dispose()}catch(e){console.warn(`[Views] provider dispose failed for "${n.viewId}":`,e)}this.#re.delete(n.viewId),t?.removeViewHost?.(e,n.viewId)}}unmountByExtension(e){for(const t of this.#te.values()){if(t.extensionName!==e)continue;const n=t.viewId;this.#ie.get(t.slot)===n&&this.hide(n,{kind:"host",id:"deactivate"});const r=this.#re.get(n);try{r?.dispose()}catch(e){console.warn(`[Views] provider dispose failed for "${n}":`,e)}this.#re.delete(n),this.#ne.delete(n);const i=cn();i?.removeViewHost?.(t.slot,n)}}}};const dn={manager:new class{#oe=[];#ae(e,t){return e.length===t.length&&e.every((e,n)=>e.key.toLowerCase()===t[n].key.toLowerCase()&&!!e.ctrlKey==!!t[n].ctrlKey&&!!e.shiftKey==!!t[n].shiftKey&&!!e.altKey==!!t[n].altKey&&!!e.metaKey==!!t[n].metaKey)}#ce(e,t){return t.every(t=>!!t.ctrlKey===e.ctrlKey&&!!t.shiftKey===e.shiftKey&&!!t.altKey===e.altKey&&!!t.metaKey===e.metaKey&&e.key.toLowerCase()===t.key.toLowerCase())}constructor(){document.addEventListener("keydown",this.handleKeyEvent.bind(this))}#le(e){switch(e){case"editorTextFocus":return this.#ue();case"fileExplorerFocus":return this.#de("primarySidebar","file-explorer-sidebar");default:return}}#ue(){const e="undefined"!=typeof document?document.activeElement:null;if(!e)return!1;const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||(!!e.isContentEditable||!!e.closest?.(".monaco-editor, .cm-editor"))}#de(e,t){if("undefined"==typeof document)return!1;if((punica.shell.Views?.manager?.getVisibleView?.(e)??null)!==t)return!1;const n=document.getElementById(e),r=document.activeElement;return!!(n&&r&&n.contains(r))}#pe(e){const t=e.when;return!t||t.split("&&").map(e=>e.trim()).filter(e=>e.length>0).every(e=>this.#he(e))}#he(e){const t=e.indexOf("==");if(-1!==t){const n=e.slice(0,t).trim(),r=e.slice(t+2).trim().replace(/^['"]|['"]$/g,"");if("view"===n){return(punica.shell.ContentTabs?.getActiveViewType?.()??null)===r}return!1}if(e.startsWith("!")){const t=this.#le(e.slice(1).trim());return void 0!==t&&!t}return!0===this.#le(e)}registerShortcut(e){const t=this.#oe.find(t=>this.#ae(t.keys,e.keys)&&(t.when??"")===(e.when??""));t?console.warn(`[KeyboardShortcuts] Ignoring duplicate binding for command "${e.command}"; "${t.command}" already owns this chord${e.when?` (when: ${e.when})`:""}.`):this.#oe.push(e)}unregisterShortcut(e){this.#oe=this.#oe.filter(t=>!this.#ae(t.keys,e))}handleKeyEvent(e){if(e.repeat)return;const t=this.#oe.find(t=>this.#ce(e,t.keys)&&this.#pe(t));t&&(e.preventDefault(),punica.kernel.Commands.manager.executeCommand(t.command))}}};let pn=0;function hn(){return pn>0}async function fn(e){pn++;try{return await e()}finally{pn>0&&pn--}}const mn={id:"classic-editor",title:"Classic Editor",root:{type:"row",sizes:[70,30],children:[{type:"column",sizes:[80,20],children:[{type:"slot",id:"content",role:"content"},{type:"slot",id:"panel",role:"panel"}]},{type:"slot",id:"secondarySidebar",role:"secondarySidebar"}]}},gn={id:"welcome",title:"Welcome",root:{type:"row",sizes:[100],children:[{type:"column",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]}]}},yn={type:"row",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]};const bn={manager:new class{#fe;#me=new Map;#ge=new Map;#ye;#be=new Map;constructor(){this.#fe=document.createElement("div"),this.#fe.id="punica-editor",this.#ye=mn}applyProfile(e){if(this.#ye=e,this.#me.clear(),this.#ge.clear(),this.#be.clear(),this.#fe.innerHTML="",this.#fe.classList.remove("layout-welcome","layout-classic"),this.#fe.classList.add("welcome"===e.id?"layout-welcome":"layout-classic"),"welcome"!==e.id){const e=document.createElement("div");e.id="activityBar",this.#fe.appendChild(e),this.#me.set("activityBar",{id:"activityBar",role:"activityBar",content:e})}const t=document.createElement("div");if(t.id="mainContent",t.style.height="100%",t.style.width="100%",t.style.display="flex",this.#fe.appendChild(t),"welcome"!==e.id){const e=document.createElement("div");e.id="primarySidebar",this.#fe.appendChild(e),this.#me.set("primarySidebar",{id:"primarySidebar",role:"primarySidebar",content:e});const t=document.createElement("div");t.id="contentSidebar",this.#fe.appendChild(t),this.#me.set("contentSidebar",{id:"contentSidebar",role:"overlay",content:t})}const n=document.createElement("div");n.id="statusbar",this.#fe.appendChild(n),this.#me.set("statusbar",{id:"statusbar",role:"statusbar",content:n}),this.#we(e.root,t,!0)}getActiveProfile(){return this.#ye}getSlot(e){return this.#me.get(e)}materializeViewHost(e,t){const n=this.#me.get(e);if(!n)throw new Error(`Layout slot "${e}" not found in active profile`);let r=this.#ge.get(e);r||(r=new Map,this.#ge.set(e,r));let i=n.content;if("panel"===e){const e=n.content.querySelector("#panel-views-root");e&&(i=e)}let s=r.get(t);return s?s.parentElement||i.appendChild(s):(s=document.createElement("div"),s.dataset.viewId=t,s.style.height="100%",s.style.width="100%",s.style.display="none",i.appendChild(s),r.set(t,s)),s}showView(e,t){if("primarySidebar"===e){const e=this.#me.get("contentSidebar");if(e){const t=this.#ge.get("contentSidebar");t&&(t.forEach(e=>{e.parentElement&&e.parentElement.removeChild(e)}),t.clear()),e.content.innerHTML="";try{punica.shell?.Views?.manager?.notifySlotReset?.("contentSidebar")}catch{}}}const n=this.#me.get(e);if(!n)throw new Error(`Layout slot "${e}" not found in active profile`);const r=this.#ge.get(e);if(r?.forEach((e,n)=>{e.style.display=n===t?"block":"none"}),n.content.style.display="block","primarySidebar"===e)try{punica.shell.ActivityBar.manager.setActiveByViewId?.(t)}catch(e){console.warn("[Layout] Failed to sync ActivityBar selection:",e)}}hideSlotViews(e){const t=this.#ge.get(e);t?.forEach(e=>{e.style.display="none"})}#ve(e){const t=this.#me.get(e);if(!t)return;const n=t.content.closest("punica-split");if(!n)return;let r=t.content;for(;r&&r.parentElement!==n;)r=r.parentElement;if(!r)return;const i=Array.from(n.children).filter(e=>1===e.nodeType),s=i.indexOf(r);return s<0?void 0:{split:n,index:s,count:i.length}}isSlotCollapsed(e){return this.#be.has(e)}setSlotCollapsed(e,t){const n=this.#ve(e);if(!n)return;const{split:r,index:i,count:s}=n;if("function"==typeof r.setSizes)if(t){if(this.#be.has(e))return;const t=(r.getSizes?.()??[]).slice();if(t.length!==s||s<2)return;this.#be.set(e,t);const n=t.reduce((e,t,n)=>n===i?e:e+t,0),o=t.map((e,t)=>t===i?0:n>0?e/n*100:100/(s-1));r.setSizes(o)}else{const t=this.#be.get(e);this.#be.delete(e),t&&t.length===s&&r.setSizes(t)}}removeViewHost(e,t){const n=this.#ge.get(e),r=n?.get(t);r&&(r.parentElement&&r.parentElement.removeChild(r),n?.delete(t))}ensureViewHost(e,t){const n=this.materializeViewHost(e,t);return hn()?(an({name:"shell.view.revealBlocked",source:"shell:views",kind:"warn",payload:{viewId:t,slot:e,api:"Layout.ensureViewHost"}}),console.warn(`[Shell] UI mutation during headless activation blocked: ensureViewHost("${e}", "${t}"). Register a ViewProvider (context.ui.registerViewProvider) and reveal via the shell.revealView capability instead.`),n):(this.showView(e,t),n)}#we(e,t,n){if("slot"===e.type){const n=document.createElement("div");n.style.height="100%",n.style.width="100%",n.style.overflow="hidden",t.appendChild(n);const r={id:e.id,role:e.role,content:n};return void this.#me.set(e.id,r)}const r="row"===e.type,i=document.createElement("punica-split");i.style.height="100%",i.style.width="100%",i.setAttribute("orientation",r?"horizontal":"vertical"),e.sizes&&e.sizes.length&&i.setAttribute("sizes",e.sizes.join(",")),t.appendChild(i);const s=e.children.length;for(let t=0;t<s;t++){const n=document.createElement("div");n.style.height="100%",n.style.width="100%",i.appendChild(n),this.#we(e.children[t],n,!1)}}applyApplicationProfile(e){const t=new Set(e.shell.activeModules),n=t.has("shell.activityBar"),r=t.has("shell.view"),i=t.has("shell.statusbar"),s=e.shell.layout,o=s?.id??e.identity.id,a=s?.root??yn;if(this.#ye={id:o,title:e.identity.name,root:a},this.#me.clear(),this.#ge.clear(),this.#be.clear(),this.#fe.innerHTML="",this.#fe.classList.remove("layout-welcome","layout-classic"),this.#fe.classList.add(n?"layout-classic":"layout-welcome"),this.#fe.dataset.profileId=e.identity.id,n){const e=document.createElement("div");e.id="activityBar",this.#fe.appendChild(e),this.#me.set("activityBar",{id:"activityBar",role:"activityBar",content:e})}const c=document.createElement("div");if(c.id="mainContent",c.style.height="100%",c.style.width="100%",c.style.display="flex",this.#fe.appendChild(c),r){const e=document.createElement("div");e.id="primarySidebar",this.#fe.appendChild(e),this.#me.set("primarySidebar",{id:"primarySidebar",role:"primarySidebar",content:e});const t=document.createElement("div");t.id="contentSidebar",this.#fe.appendChild(t),this.#me.set("contentSidebar",{id:"contentSidebar",role:"overlay",content:t})}if(i){const e=document.createElement("div");e.id="statusbar",this.#fe.appendChild(e),this.#me.set("statusbar",{id:"statusbar",role:"statusbar",content:e})}this.#we(a,c,!0)}render(e){try{const e=window,t=e.punica?.Runtime?.runtime??e.punica?.runtime,n=t?.lifecyclePhase,r="noWorkspace"===n?gn:mn;this.#fe.childElementCount&&this.#ye.id===r.id||this.applyProfile(r)}catch{this.#fe.childElementCount||this.applyProfile(this.#ye)}e.appendChild(this.#fe)}}};const wn=new class{#ke=!1;#Ie=null;#Ee=null;#Ae=new Map;#Se=null;#_e(){if(this.#ke)return;const e=punica.shell.Layout.manager.getSlot("content"),t=e?.content;if(!t)return void console.warn("[ContentTabs] content host not found");t.innerHTML="";const n=document.createElement("punica-box");n.id="content-tabs-root",n.style.height="100%",n.style.display="flex",n.style.flexDirection="column";const r=document.createElement("punica-box");r.style.height="40px",r.style.display="flex",r.style.alignItems="center";const i=document.createElement("punica-tab");i.setAttribute("orientation","horizontal"),i.style.width="100%",i.style.height="100%",i.style.backgroundColor="var(--background-paper)",i.addEventListener("change",e=>{const t=e?.detail?.value;t&&this.#xe(t)}),r.appendChild(i);const s=document.createElement("punica-box");s.id="content-tabs-panels",s.style.flex="1",s.style.height="calc(100% - 40px)",n.appendChild(r),n.appendChild(s);const o=document.createElement("punica-context-menu");o.id="content-tabs-menu",o.setAttribute("target","#content-tabs-root");const a=document.createElement("punica-context-menu-item");a.setAttribute("label","Close"),a.setAttribute("value","close"),o.appendChild(a);const c=document.createElement("punica-context-menu-item");c.setAttribute("label","Close Others"),c.setAttribute("value","closeOthers"),o.appendChild(c);const l=document.createElement("punica-context-menu-item");l.setAttribute("label","Close All"),l.setAttribute("value","closeAll"),o.appendChild(l),o.addEventListener("punica-context-menu-select",e=>{const t=e?.detail?.value;if(!t)return;const n=this.#Se||this.#Ie&&this.#Ie.getAttribute("value")||"";switch(t){case"close":n&&this.closeById(n);break;case"closeOthers":n&&this.closeOthersById(n);break;case"closeAll":this.closeAll()}this.#Se=null}),n.appendChild(o),t.appendChild(n),this.#Ie=i,this.#Ee=s,this.#ke=!0}#xe(e){if(!this.#Ie||!this.#Ee)return;this.#Ie.setAttribute("value",e);this.#Ie.querySelectorAll("punica-tab-item").forEach(t=>{const n=t.getAttribute("value");t.style.backgroundColor=n===e?"var(--background-main)":""});this.#Ee.querySelectorAll("punica-tab-panel").forEach(t=>{t.setAttribute("selectedvalue",e)});try{const t=window,n=t?.punica?.kernel?.Commands?.manager;n&&"function"==typeof n.executeCommand&&n.executeCommand("file-explorer.revealFile",e)}catch(e){console.warn("[ContentTabs] Failed to notify file-explorer",e)}this.#Ce(e)}#Ce(e){try{const t=e?Array.from(this.#Ae.values()).find(t=>t.id===e):void 0;punica.shell.ActivityBar.manager.syncContentTool?.(t?.viewType??null)}catch{}}open(e){if(this.#_e(),!this.#Ie||!this.#Ee)return null;const t=this.#Ae.get(e.path);if(t)return this.#xe(t.id),t.container;const n=e.path,r=e.title??e.path.split("/").pop()??e.path,i=document.createElement("punica-tab-item");i.setAttribute("value",n),i.className="content-file-type",i.style.maxWidth="200px",i.style.flex="0 0 auto",i.style.padding="var(--spacing-8) var(--spacing-4) var(--spacing-8) var(--spacing-12)";const s=document.createElement("punica-row");s.setAttribute("alignitems","center"),s.setAttribute("wrap","nowrap"),s.setAttribute("spacing","0.5"),s.style.maxWidth="200px";const o=document.createElement("punica-col"),a=document.createElement("punica-typography");a.setAttribute("truncate","1"),a.style.maxWidth="150px",a.setAttribute("title",e.path),a.textContent=r,o.appendChild(a);const c=document.createElement("punica-col"),l=document.createElement("punica-icon-button");l.setAttribute("size","small"),l.setAttribute("title","Close"),l.innerHTML="<i class='fa-duotone fa-solid fa-xmark'></i>",l.addEventListener("click",t=>{t.stopPropagation(),this.close(e.path)}),c.appendChild(l),s.appendChild(o),s.appendChild(c),i.appendChild(s),i.addEventListener("contextmenu",()=>{this.#Se=n,this.#xe(n)}),this.#Ie.appendChild(i);const u=document.createElement("punica-tab-panel");u.setAttribute("value",n),u.setAttribute("selectedvalue",n),u.style.height="100%",u.style.width="100%",u.style.boxSizing="border-box";const d=document.createElement("div");d.style.height="100%",d.style.width="100%",d.style.boxSizing="border-box",u.appendChild(d),this.#Ee.appendChild(u);const p={id:n,path:e.path,title:r,viewType:e.viewType,tabElement:i,labelElement:a,container:d,panel:u,dirty:!1};return this.#Ae.set(e.path,p),this.#xe(n),d}async close(e){const t=this.#Ae.get(e);t&&await this.#Te(t)&&this.#Ne(t)}async closeById(e){const t=Array.from(this.#Ae.values()).find(t=>t.id===e);t&&await this.#Te(t)&&this.#Ne(t)}async closeOthers(e){const t=this.#Ae.get(e);t&&await this.closeOthersById(t.id)}async closeOthersById(e){const t=Array.from(this.#Ae.values()).filter(t=>t.id!==e);for(const e of t){if(!await this.#Te(e))return;this.#Ne(e)}this.#xe(e)}async closeAll(){const e=Array.from(this.#Ae.values());for(const t of e){if(!await this.#Te(t))return;this.#Ne(t)}}#Ne(e){if(!this.#Ie||!this.#Ee)return;e.tabElement.parentElement===this.#Ie&&this.#Ie.removeChild(e.tabElement),e.panel.parentElement===this.#Ee&&this.#Ee.removeChild(e.panel),this.#Ae.delete(e.path);const t=Array.from(this.#Ae.values());if(t.length>0){const e=t[t.length-1];this.#xe(e.id)}else this.#Ie.removeAttribute("value"),this.#Ce(null)}async#Te(e){if(!e.dirty)return!0;this.#xe(e.id);const t=e.title||e.path.split("/").pop()||e.path,n=await punica.shell.View.showDialog({title:"Unsaved changes",message:`"${t}" has unsaved changes. Do you want to save before closing?`,tone:"warning",buttons:[{label:"Cancel",variant:"text",action:"cancel"},{label:"Don't Save",variant:"outlined",action:"discard"},{label:"Save",variant:"filled",color:"primary",action:"save"}]});if("save"===n)try{const e=punica?.kernel?.Commands?.manager;return e&&"function"==typeof e.executeCommand&&await e.executeCommand("editor.saveActiveFile"),!0}catch(e){return await punica.shell.View.showAlert({title:"Save failed",message:`Could not save "${t}". The tab was left open.`,variant:"error"}),console.warn("[ContentTabs] save before close failed",e),!1}return"discard"===n}setDirty(e,t){const n=this.#Ae.get(e);if(!n)return;n.dirty=t;const r=n.title||n.path.split("/").pop()||n.path;n.labelElement.textContent=t?`${r} •`:r}getActivePath(){if(!this.#Ie)return null;const e=this.#Ie.getAttribute("value");if(!e)return null;const t=Array.from(this.#Ae.values()).find(t=>t.id===e);return t?.path??null}getActiveViewType(){if(!this.#Ie)return null;const e=this.#Ie.getAttribute("value");if(!e)return null;const t=Array.from(this.#Ae.values()).find(t=>t.id===e);return t?.viewType??null}};const vn=new class{#ke=!1;#Me=null;#Ie=null;#De=null;#Pe=null;#Oe=null;#Re=null;#Le=!1;#$e=new Set;#je=new Map;#W=null;#_e(){if(this.#ke)return;const e=punica.shell.Layout.manager.getSlot("panel"),t=e?.content;if(!t)return void console.warn("[PanelTabs] panel host not found");t.innerHTML="";const n=document.createElement("punica-box");n.id="panel-tabs-root",n.style.height="100%",n.style.display="flex",n.style.flexDirection="column";const r=document.createElement("punica-box");r.style.height="32px",r.style.display="flex",r.style.alignItems="center",r.style.backgroundColor="var(--background-paper)";const i=document.createElement("punica-tab");i.setAttribute("orientation","horizontal"),i.style.flex="1 1 auto",i.style.minWidth="0",i.style.overflow="hidden",i.style.height="100%",i.style.backgroundColor="var(--background-paper)",i.addEventListener("change",e=>{const t=e?.detail?.value;t&&this.#Fe(t,"panel-tab")});const s=document.createElement("punica-icon-button");s.id="panel-tab-overflow-btn",s.setAttribute("size","x-small"),s.setAttribute("title","More tabs"),s.setAttribute("aria-label","More tabs"),s.style.flex="0 0 auto",s.style.display="none",s.innerHTML='<i class="fa-solid fa-ellipsis"></i>',s.addEventListener("click",()=>{this.#Be()});const o=document.createElement("punica-box");o.id="panel-toolbar-area",o.style.flex="0 0 auto",o.style.display="flex",o.style.alignItems="center",o.style.padding="0 var(--spacing-8)",r.appendChild(i),r.appendChild(s),r.appendChild(o);const a=document.createElement("punica-menu");a.id="panel-tab-overflow-menu",a.addEventListener("close",()=>{a.removeAttribute("open")}),a.addEventListener("menu-item-click",e=>{const t=e?.detail?.data;t&&(e.stopPropagation?.(),a.removeAttribute("open"),this.#Fe(t,"panel-tab-overflow"))});const c=document.createElement("div");if(c.id="panel-views-root",c.style.flex="1",c.style.height="calc(100% - 32px)",n.appendChild(r),n.appendChild(c),n.appendChild(a),t.appendChild(n),"undefined"!=typeof ResizeObserver){new ResizeObserver(()=>{this.#qe()}).observe(r)}this.#Me=n,this.#Ie=i,this.#De=o,this.#Pe=s,this.#Oe=a,this.#ke=!0}#Fe(e,t){const n=globalThis.punica?.shell?.Views?.manager;if(n?.getPlacement?.(e))return n.reveal(e,{kind:"user-gesture",id:`${t}:${e}`}).catch(t=>{console.warn("[PanelTabs] reveal failed for tab",e,t)}),void this.activateTabVisual(e);this.setActive(e)}open(e){if(this.#_e(),!this.#Ie)return;if(this.#je.get(e.id))return void(!1===e.autoActivate||this.#W===e.id||this.#ze(e.id,"PanelTabs.open")||this.setActive(e.id));const t=document.createElement("punica-tab-item");t.setAttribute("value",e.id),t.style.maxWidth="160px",t.style.flex="0 0 auto",t.style.padding="var(--spacing-6) var(--spacing-8)";const n=document.createElement("punica-row");if(n.setAttribute("alignitems","center"),n.setAttribute("wrap","nowrap"),n.setAttribute("spacing","0.5"),e.iconClass){const t=document.createElement("punica-col"),r=document.createElement("punica-icon"),i=document.createElement("i");i.className=e.iconClass,r.appendChild(i),t.appendChild(r),n.appendChild(t)}const r=document.createElement("punica-col"),i=document.createElement("punica-typography");i.setAttribute("truncate","1"),i.textContent=e.title,r.appendChild(i),n.appendChild(r),t.appendChild(n);const s=e.order??1e3,o=Array.from(this.#je.values()).sort((e,t)=>e.order-t.order).find(e=>e.order>s);o?this.#Ie.insertBefore(t,o.tabElement):this.#Ie.appendChild(t);const a={id:e.id,title:e.title,commandId:e.commandId,iconClass:e.iconClass,order:s,tabElement:t,toolbar:e.toolbar,toolbarEl:null};e.toolbar?.length&&this.#De&&(a.toolbarEl=this.#Ue(e.id,e.toolbar),this.#De.appendChild(a.toolbarEl)),this.#je.set(e.id,a),this.#qe();const c=e.autoActivate;this.#W||!1===c||this.#ze(e.id,"PanelTabs.open")||this.setActive(e.id)}#Ue(e,t){const n=document.createElement("div");n.dataset.viewId=e,n.style.display="none",n.style.alignItems="center",n.style.gap="var(--spacing-4)";for(const e of t){if(!e?.command)continue;const t=document.createElement("punica-icon-button");t.setAttribute("size","x-small"),t.setAttribute("title",e.title??e.command),t.setAttribute("aria-label",e.title??e.command),t.dataset.actionId=e.id,t.style.flex="0 0 auto",t.innerHTML=e.icon??"",t.addEventListener("click",()=>{try{const t=window,n=t?.punica?.kernel?.Commands?.manager;n&&"function"==typeof n.executeCommand&&n.executeCommand(e.command)}catch(t){console.warn("[PanelTabs] Failed to execute toolbar command",e.command,t)}}),n.appendChild(t)}return n}#ze(e,t){return!!hn()&&(an({name:"shell.view.revealBlocked",source:"shell:views",kind:"warn",payload:{viewId:e,slot:"panel",api:t}}),console.warn(`[Shell] UI mutation during headless activation blocked: ${t}("${e}"). Declare the tab without autoActivate and reveal via the shell.revealView capability instead.`),!0)}activateTabVisual(e){if(!this.#Ie)return;if(!this.#je.get(e))return;this.#W=e,this.#Ie.setAttribute("value",e);this.#Ie.querySelectorAll("punica-tab-item").forEach(t=>{const n=t.getAttribute("value");t.style.backgroundColor=n===e?"var(--background-main)":""}),this.#je.forEach(t=>{t.toolbarEl&&(t.toolbarEl.style.display=t.id===e?"flex":"none")}),this.recomputeOverflow()}close(e){if(!this.#Ie)return;const t=this.#je.get(e);if(t&&(t.tabElement.parentElement===this.#Ie&&this.#Ie.removeChild(t.tabElement),t.toolbarEl&&(t.toolbarEl.remove(),t.toolbarEl=null),this.#$e.delete(e),this.#je.delete(e),this.#qe(),this.#W===e)){const e=Array.from(this.#je.values()).sort((e,t)=>e.order-t.order);this.#W=null,e.length>0?this.setActive(e[0].id):this.#Ie.removeAttribute("value")}}closeAll(){this.#Ie&&Array.from(this.#je.keys()).forEach(e=>this.close(e))}setActive(e){if(!this.#Ie)return;const t=this.#je.get(e);if(t&&!this.#ze(e,"PanelTabs.setActive")&&(this.activateTabVisual(e),t.commandId))try{const e=window,n=e?.punica?.kernel?.Commands?.manager;n&&"function"==typeof n.executeCommand&&n.executeCommand(t.commandId)}catch(e){console.warn("[PanelTabs] Failed to execute command",t.commandId,e)}}getActiveId(){return this.#W}#qe(){if(this.#Le)return;this.#Le=!0;const e=()=>{this.#Le=!1,this.recomputeOverflow()};"function"==typeof requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,0)}recomputeOverflow(){const e=this.#Ie;if(!e)return;const t=Array.from(e.querySelectorAll("punica-tab-item"));if(t.forEach(e=>{e.style.display=""}),0===t.length)return this.#$e.clear(),void this.#Ve(!1);const n=e.clientWidth;if(n<=0)return this.#$e.clear(),void this.#Ve(!1);const r=t.map(e=>e.offsetWidth);if(r.reduce((e,t)=>e+t,0)<=n)return this.#$e.clear(),void this.#Ve(!1);const i=n-this.#We(),s=t.findIndex(e=>e.getAttribute("value")===this.#W);let o=s>=0?r[s]:0;const a=new Set;let c=!0;t.forEach((e,t)=>{if(t===s)return;if(c&&o+r[t]<=i)return void(o+=r[t]);c=!1,e.style.display="none";const n=e.getAttribute("value");n&&a.add(n)}),this.#$e=a,this.#Ve(a.size>0)}#Ve(e){const t=this.#Pe;t&&(t.style.display=e?"inline-flex":"none",e||this.#Oe?.removeAttribute("open"))}#We(){if(null!=this.#Re)return this.#Re;const e=this.#Pe;if(!e)return 28;const t=e.style.display;e.style.display="inline-flex";const n=e.offsetWidth||28;return e.style.display=t,this.#Re=n,n}#Be(){const e=this.#Oe,t=this.#Pe,n=this.#Ie;if(!e||!t||!n||0===this.#$e.size)return;e.innerHTML="",n.querySelectorAll("punica-tab-item").forEach(t=>{const n=t.getAttribute("value");if(!n||!this.#$e.has(n))return;const r=this.#je.get(n);if(!r)return;const i=document.createElement("punica-menu-item");i.setAttribute("data-item",n),i.setAttribute("aria-label",r.title);const s=document.createElement("punica-typography");s.textContent=r.title,i.appendChild(s),e.appendChild(i)});const r=t.getBoundingClientRect();e.setAttribute("top",String(r.top)),e.setAttribute("left",String(r.left)),e.setAttribute("width",String(r.width)),e.setAttribute("height",String(r.height)),e.setAttribute("bottom",String(r.bottom)),e.setAttribute("placement","bottom"),e.setAttribute("open","true")}};function kn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function In(e){return"string"==typeof e}function En(e){return"string"==typeof e&&e.trim().length>0}function An(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const Sn=new Set(["shell.activityBar","shell.statusbar","shell.view","shell.views","shell.keyboardShortcuts","shell.layout","shell.contentTabs","shell.panelTabs","flow.shell"]),_n=new Set(["light","dark","auto"]),xn=new Set(["compact","comfortable"]),Cn=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const Tn=new class{validate(e){const t=[];if(!kn(e))return{valid:!1,errors:["ApplicationProfile must be an object"]};if("1"!==e.schemaVersion&&t.push(`schemaVersion must be '1', got: ${JSON.stringify(e.schemaVersion)}`),kn(e.identity)?(En(e.identity.id)||t.push("identity.id must be a non-empty string"),En(e.identity.name)||t.push("identity.name must be a non-empty string"),En(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),kn(e.shell)?(Array.isArray(e.shell.activeModules)?e.shell.activeModules.forEach((e,n)=>{In(e)&&Sn.has(e)||t.push(`shell.activeModules[${n}] is not a valid ShellModuleId: ${JSON.stringify(e)}`)}):t.push("shell.activeModules must be an array"),void 0!==e.shell.layout&&(kn(e.shell.layout)?(En(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),kn(e.shell.layout.root)||t.push("shell.layout.root must be an object")):t.push("shell.layout must be an object when provided"))):t.push("shell must be an object"),kn(e.theme)?(_n.has(e.theme.mode)||t.push(`theme.mode must be one of 'light'|'dark'|'auto', got: ${JSON.stringify(e.theme.mode)}`),void 0===e.theme.density||xn.has(e.theme.density)||t.push(`theme.density must be 'compact' or 'comfortable', got: ${JSON.stringify(e.theme.density)}`)):t.push("theme must be an object"),kn(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||An(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||An(e.capabilities.deniedIds)||t.push("capabilities.deniedIds must be string[] when provided"),void 0!==e.capabilities.allowedOrigins&&(Array.isArray(e.capabilities.allowedOrigins)?e.capabilities.allowedOrigins.forEach((e,n)=>{In(e)&&Cn.has(e)||t.push(`capabilities.allowedOrigins[${n}] must be a valid CapabilityOrigin, got: ${JSON.stringify(e)}`)}):t.push("capabilities.allowedOrigins must be an array when provided"))}else t.push("capabilities must be an object");return t.length>0?{valid:!1,errors:t}:{valid:!0,profile:e}}};class Nn{#Ke=new Map;#W;register(e){if(this.#Ke.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#Ke.set(e.identity.id,e),void 0===this.#W&&(this.#W=e.identity.id)}get(e){return this.#Ke.get(e)}getActive(){if(void 0===this.#W||!this.#Ke.has(this.#W))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#Ke.get(this.#W)}setActive(e){if(!this.#Ke.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#W=e}switchProfile(e){if(!this.#Ke.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#W=e,an({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Ke.has(e)}list(){return Array.from(this.#Ke.values())}}const Mn={manager:new class{registry=new Nn;get validator(){return Tn}loadProfile(e){if("string"==typeof e){if(this.registry.has(e))return void this.registry.setActive(e);let t;try{t=JSON.parse(e)}catch{throw new Error(`loadProfile: '${e}' is not a registered profile id and could not be parsed as JSON`)}return void this.#Ge(t)}this.#Ge(e)}#Ge(e){const t=this.validator.validate(e);if(!t.valid)throw an({name:"shell.profile.load_failed",payload:{errors:t.errors}}),new Error(`ApplicationProfile validation failed:\n ${t.errors.join("\n ")}`);this.registry.has(t.profile.identity.id)||this.registry.register(t.profile),this.registry.setActive(t.profile.identity.id),an({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}},Dn={};function Pn(e,t){"string"!=typeof t&&(t=Pn.defaultChars);const n=function(e){let t=Dn[e];if(t)return t;t=Dn[e]=[];for(let e=0;e<128;e++){const n=String.fromCharCode(e);t.push(n)}for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t[r]="%"+("0"+r.toString(16).toUpperCase()).slice(-2)}return t}(t);return e.replace(/(%[a-f0-9]{2})+/gi,function(e){let t="";for(let r=0,i=e.length;r<i;r+=3){const s=parseInt(e.slice(r+1,r+3),16);if(s<128)t+=n[s];else{if(192==(224&s)&&r+3<i){const n=parseInt(e.slice(r+4,r+6),16);if(128==(192&n)){const e=s<<6&1984|63&n;t+=e<128?"��":String.fromCharCode(e),r+=3;continue}}if(224==(240&s)&&r+6<i){const n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16);if(128==(192&n)&&128==(192&i)){const e=s<<12&61440|n<<6&4032|63&i;t+=e<2048||e>=55296&&e<=57343?"���":String.fromCharCode(e),r+=6;continue}}if(240==(248&s)&&r+9<i){const n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16),o=parseInt(e.slice(r+10,r+12),16);if(128==(192&n)&&128==(192&i)&&128==(192&o)){let e=s<<18&1835008|n<<12&258048|i<<6&4032|63&o;e<65536||e>1114111?t+="����":(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(1023&e))),r+=9;continue}}t+="�"}}return t})}Pn.defaultChars=";/?:@&=+$,#",Pn.componentChars="";const On={};function Rn(e,t,n){"string"!=typeof t&&(n=t,t=Rn.defaultChars),void 0===n&&(n=!0);const r=function(e){let t=On[e];if(t)return t;t=On[e]=[];for(let e=0;e<128;e++){const n=String.fromCharCode(e);/^[0-9a-z]$/i.test(n)?t.push(n):t.push("%"+("0"+e.toString(16).toUpperCase()).slice(-2))}for(let n=0;n<e.length;n++)t[e.charCodeAt(n)]=e[n];return t}(t);let i="";for(let t=0,s=e.length;t<s;t++){const o=e.charCodeAt(t);if(n&&37===o&&t+2<s&&/^[0-9a-f]{2}$/i.test(e.slice(t+1,t+3)))i+=e.slice(t,t+3),t+=2;else if(o<128)i+=r[o];else if(o>=55296&&o<=57343){if(o>=55296&&o<=56319&&t+1<s){const n=e.charCodeAt(t+1);if(n>=56320&&n<=57343){i+=encodeURIComponent(e[t]+e[t+1]),t++;continue}}i+="%EF%BF%BD"}else i+=encodeURIComponent(e[t])}return i}function Ln(e){let t="";return t+=e.protocol||"",t+=e.slashes?"//":"",t+=e.auth?e.auth+"@":"",e.hostname&&-1!==e.hostname.indexOf(":")?t+="["+e.hostname+"]":t+=e.hostname||"",t+=e.port?":"+e.port:"",t+=e.pathname||"",t+=e.search||"",t+=e.hash||"",t}function $n(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}Rn.defaultChars=";/?:@&=+$,-_.!~*'()#",Rn.componentChars="-_.!~*'()";const jn=/^([a-z0-9.+-]+:)/i,Fn=/:[0-9]*$/,Bn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,qn=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),zn=["'"].concat(qn),Un=["%","/","?",";","#"].concat(zn),Vn=["/","?","#"],Wn=/^[+a-z0-9A-Z_-]{0,63}$/,Kn=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,Gn={javascript:!0,"javascript:":!0},Hn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function Yn(e,t){if(e&&e instanceof $n)return e;const n=new $n;return n.parse(e,t),n}$n.prototype.parse=function(e,t){let n,r,i,s=e;if(s=s.trim(),!t&&1===e.split("#").length){const e=Bn.exec(s);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=jn.exec(s);if(o&&(o=o[0],n=o.toLowerCase(),this.protocol=o,s=s.substr(o.length)),(t||o||s.match(/^\/\/[^@\/]+@[^@\/]+/))&&(i="//"===s.substr(0,2),!i||o&&Gn[o]||(s=s.substr(2),this.slashes=!0)),!Gn[o]&&(i||o&&!Hn[o])){let e,t,n=-1;for(let e=0;e<Vn.length;e++)r=s.indexOf(Vn[e]),-1!==r&&(-1===n||r<n)&&(n=r);t=-1===n?s.lastIndexOf("@"):s.lastIndexOf("@",n),-1!==t&&(e=s.slice(0,t),s=s.slice(t+1),this.auth=e),n=-1;for(let e=0;e<Un.length;e++)r=s.indexOf(Un[e]),-1!==r&&(-1===n||r<n)&&(n=r);-1===n&&(n=s.length),":"===s[n-1]&&n--;const i=s.slice(0,n);s=s.slice(n),this.parseHost(i),this.hostname=this.hostname||"";const o="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!o){const e=this.hostname.split(/\./);for(let t=0,n=e.length;t<n;t++){const n=e[t];if(n&&!n.match(Wn)){let r="";for(let e=0,t=n.length;e<t;e++)n.charCodeAt(e)>127?r+="x":r+=n[e];if(!r.match(Wn)){const r=e.slice(0,t),i=e.slice(t+1),o=n.match(Kn);o&&(r.push(o[1]),i.unshift(o[2])),i.length&&(s=i.join(".")+s),this.hostname=r.join(".");break}}}}this.hostname.length>255&&(this.hostname=""),o&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}const a=s.indexOf("#");-1!==a&&(this.hash=s.substr(a),s=s.slice(0,a));const c=s.indexOf("?");return-1!==c&&(this.search=s.substr(c),s=s.slice(0,c)),s&&(this.pathname=s),Hn[n]&&this.hostname&&!this.pathname&&(this.pathname=""),this},$n.prototype.parseHost=function(e){let t=Fn.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var Jn,Zn=Object.freeze({__proto__:null,decode:Pn,encode:Rn,format:Ln,parse:Yn}),Qn=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,Xn=/[\0-\x1F\x7F-\x9F]/,er=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,tr=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,nr=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,rr=Object.freeze({__proto__:null,Any:Qn,Cc:Xn,Cf:/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,P:er,S:tr,Z:nr}),ir=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏઑඡ༉༦ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲϏϢϸontourIntegraìȹoɴ\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲy;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱còJTabcdfgorstרׯؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ߂ߐĀiyޱrc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣসে্ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४ĀnrࢃgleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpwਖਛgȀLRlr৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼અઋp;椅y;䐜Ādl੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑඞcy;䐊cute;䅃ƀaeyહાron;䅇dil;䅅;䐝ƀgswે૰ativeƀMTV૨ediumSpace;怋hiĀcn૦ëeryThiîtedĀGLଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷreak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪௫ఄ಄ದൡඅ櫬Āoungruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater;EFGLSTஶஷ扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨setĀ;Eೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂෛ෧ขภยา฿ไlig;䅒cute耻Ó䃓Āiyීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲcr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬืde耻Õ䃕es;樷ml耻Ö䃖erĀBP๋Āar๐๓r;怾acĀek๚;揞et;掴arenthesis;揜ҀacfhilorsງຊຏຒດຝະrtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ檻cedesȀ;EST່້扺qual;檯lantEqual;扼ilde;找me;怳Ādpuct;戏ortionĀ;aȥl;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL憒ar;懥eftArrow;懄eiling;按oǵ\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄቕቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHcቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗ĀeiቻDzኀ\0ኇefore;戴a;䎘ĀcnኘkSpace;쀀 Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtèa;䎖r;愨pf;愤cr;쀀𝒵ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒;Eaeiopᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;eᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;eᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰᝃᝈ០៦ᠹᡐᜍ᥈ᥰot;櫭ĀcrᛶkȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;tbrk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯᝳ;䎲;愶een;扬r;쀀𝔟gcostuvwឍឝឳេ៕៛ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀakoᠦᠵĀcn៲ᠣkƀlst֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ;敛;敘;攘;攔;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģbar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;elƀ;bhᥨᥩᥫ䁜;槅sub;柈ŬᥴlĀ;e怢t»pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭒\0᯽\0ᰌƀcprᦲute;䄇̀;abcdsᦿᧀᧄ᧕᧙戩nd;橄rcup;橉Āau᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r;Ecefms᩠ᩢᩫ᪤᪪旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ\0\0aĀ;t䀬;䁀ƀ;fl戁îᅠeĀmxent»eóɍǧ\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯delprvw᭠᭬᭷ᮂᮬᯔarrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;pᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰻᰿ᱝᱩᱵᲞᲬᲷᴍᵻᶑᶫᶻ᷆᷍ròar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂᳖᳜᳠mƀ;oș᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄĀDoḆᴴoôĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»ṺƀaeiἒἚls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧\0耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₥₰₴⃰℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽ƀ;qsؾٌlanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqrⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0proør;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼ròòΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonóquigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roøurĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨íistĀ;sடr;쀀𝔫ȀEest⩦⩹⩼ƀ;qs⩭ƀ;qs⩴lanôií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast⭕⭚⭟lleìl;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖchimpqu⮽⯍⯙⬄⯤⯯Ȁ;cerല⯆ഷ⯉uå;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭ååഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñĀ;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;cⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācrir;榿;쀀𝔬ͯ\0\0\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕⶥⶨrò᪀Āirⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔǒr;榷rp;榹;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ\0\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ脀¶;l䂶leìЃɩ\0\0m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳ᤈ⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t⾴ïrel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⋢⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔ABHabcdefhilmnoprstuxけさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstwガクシスゼゾダッデナp;極Ā;fゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ìâヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘rrowĀ;tㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowóarpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓ròaòՑ;怏oustĀ;a㈞掱che»mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì耻䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;qኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫwar;椪lig耻ß䃟㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rëƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproøim»ኬsðኞĀas㚺㚮ðrn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈadempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xôheadĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roðtré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜtré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),sr=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));const or=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),ar=null!==(Jn=String.fromCodePoint)&&void 0!==Jn?Jn:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t};var cr;!function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"}(cr||(cr={}));var lr,ur,dr;function pr(e){return e>=cr.ZERO&&e<=cr.NINE}function hr(e){return e>=cr.UPPER_A&&e<=cr.UPPER_F||e>=cr.LOWER_A&&e<=cr.LOWER_F}function fr(e){return e===cr.EQUALS||function(e){return e>=cr.UPPER_A&&e<=cr.UPPER_Z||e>=cr.LOWER_A&&e<=cr.LOWER_Z||pr(e)}(e)}!function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"}(lr||(lr={})),function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"}(ur||(ur={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(dr||(dr={}));class mr{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=ur.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=dr.Strict}startEntity(e){this.decodeMode=e,this.state=ur.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case ur.EntityStart:return e.charCodeAt(t)===cr.NUM?(this.state=ur.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=ur.NamedEntity,this.stateNamedEntity(e,t));case ur.NumericStart:return this.stateNumericStart(e,t);case ur.NumericDecimal:return this.stateNumericDecimal(e,t);case ur.NumericHex:return this.stateNumericHex(e,t);case ur.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===cr.LOWER_X?(this.state=ur.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=ur.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const i=n-t;this.result=this.result*Math.pow(r,i)+parseInt(e.substr(t,i),r),this.consumed+=i}}stateNumericHex(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!pr(r)&&!hr(r))return this.addToNumericResult(e,n,t,16),this.emitNumericEntity(r,3);t+=1}return this.addToNumericResult(e,n,t,16),-1}stateNumericDecimal(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!pr(r))return this.addToNumericResult(e,n,t,10),this.emitNumericEntity(r,2);t+=1}return this.addToNumericResult(e,n,t,10),-1}emitNumericEntity(e,t){var n;if(this.consumed<=t)return null===(n=this.errors)||void 0===n||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===cr.SEMI)this.consumed+=1;else if(this.decodeMode===dr.Strict)return 0;return this.emitCodePoint(function(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=or.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==cr.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],i=(r&lr.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const s=e.charCodeAt(t);if(this.treeIndex=yr(n,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return 0===this.result||this.decodeMode===dr.Attribute&&(0===i||fr(s))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],i=(r&lr.VALUE_LENGTH)>>14,0!==i){if(s===cr.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==dr.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&lr.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~lr.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case ur.NamedEntity:return 0===this.result||this.decodeMode===dr.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case ur.NumericDecimal:return this.emitNumericEntity(0,2);case ur.NumericHex:return this.emitNumericEntity(0,3);case ur.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case ur.EntityStart:return 0}}}function gr(e){let t="";const n=new mr(e,e=>t+=ar(e));return function(e,r){let i=0,s=0;for(;(s=e.indexOf("&",s))>=0;){t+=e.slice(i,s),n.startEntity(r);const o=n.write(e,s+1);if(o<0){i=s+n.end();break}i=s+o,s=0===o?i+1:i}const o=t+e.slice(i);return t="",o}}function yr(e,t,n,r){const i=(t&lr.BRANCH_LENGTH)>>7,s=t&lr.JUMP_TABLE;if(0===i)return 0!==s&&r===s?n:-1;if(s){const t=r-s;return t<0||t>=i?-1:e[n+t]-1}let o=n,a=o+i-1;for(;o<=a;){const t=o+a>>>1,n=e[t];if(n<r)o=t+1;else{if(!(n>r))return e[t+i];a=t-1}}return-1}const br=gr(ir);function wr(e){return"[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}gr(sr);const vr=Object.prototype.hasOwnProperty;function kr(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach(function(n){e[n]=t[n]})}}),e}function Ir(e,t,n){return[].concat(e.slice(0,t),n,e.slice(t+1))}function Er(e){return!(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(!!(65535&~e&&65534!=(65535&e))&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function Ar(e){if(e>65535){const t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}const Sr=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,_r=new RegExp(Sr.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),xr=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function Cr(e,t){if(35===t.charCodeAt(0)&&xr.test(t)){const n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Er(n)?Ar(n):e}const n=function(e,t=dr.Legacy){return br(e,t)}(e);return n!==e?n:e}function Tr(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(_r,function(e,t,n){return t||Cr(e,n)})}const Nr=/[&<>"]/,Mr=/[&<>"]/g,Dr={"&":"&","<":"<",">":">",'"':"""};function Pr(e){return Dr[e]}function Or(e){return Nr.test(e)?e.replace(Mr,Pr):e}const Rr=/[.?*+^$[\]\\(){}|-]/g;function Lr(e){switch(e){case 9:case 32:return!0}return!1}function $r(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1}function jr(e){return er.test(e)||tr.test(e)}function Fr(e){return jr(Ar(e))}function Br(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function qr(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}function zr(e){return 32===e||9===e||10===e||13===e}function Ur(e){let t=0;for(;t<e.length&&zr(e.charCodeAt(t));t++);let n=e.length-1;for(;n>=t&&zr(e.charCodeAt(n));n--);return e.slice(t,n+1)}const Vr={mdurl:Zn,ucmicro:rr};var Wr=Object.freeze({__proto__:null,arrayReplaceAt:Ir,asciiTrim:Ur,assign:kr,escapeHtml:Or,escapeRE:function(e){return e.replace(Rr,"\\$&")},fromCodePoint:Ar,has:function(e,t){return vr.call(e,t)},isMdAsciiPunct:Br,isPunctChar:jr,isPunctCharCode:Fr,isSpace:Lr,isString:wr,isValidEntityCode:Er,isWhiteSpace:$r,lib:Vr,normalizeReference:qr,unescapeAll:Tr,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(Sr,"$1")}});var Kr=Object.freeze({__proto__:null,parseLinkDestination:function(e,t,n){let r,i=t;const s={ok:!1,pos:0,str:""};if(60===e.charCodeAt(i)){for(i++;i<n;){if(r=e.charCodeAt(i),10===r)return s;if(60===r)return s;if(62===r)return s.pos=i+1,s.str=Tr(e.slice(t+1,i)),s.ok=!0,s;92===r&&i+1<n?i+=2:i++}return s}let o=0;for(;i<n&&(r=e.charCodeAt(i),32!==r)&&!(r<32||127===r);)if(92===r&&i+1<n){if(32===e.charCodeAt(i+1))break;i+=2}else{if(40===r&&(o++,o>32))return s;if(41===r){if(0===o)break;o--}i++}return t===i||0!==o||(s.str=Tr(e.slice(t,i)),s.pos=i,s.ok=!0),s},parseLinkLabel:function(e,t,n){let r,i,s,o;const a=e.posMax,c=e.pos;for(e.pos=t+1,r=1;e.pos<a;){if(s=e.src.charCodeAt(e.pos),93===s&&(r--,0===r)){i=!0;break}if(o=e.pos,e.md.inline.skipToken(e),91===s)if(o===e.pos-1)r++;else if(n)return e.pos=c,-1}let l=-1;return i&&(l=e.pos),e.pos=c,l},parseLinkTitle:function(e,t,n,r){let i,s=t;const o={ok:!1,can_continue:!1,pos:0,str:"",marker:0};if(r)o.str=r.str,o.marker=r.marker;else{if(s>=n)return o;let r=e.charCodeAt(s);if(34!==r&&39!==r&&40!==r)return o;t++,s++,40===r&&(r=41),o.marker=r}for(;s<n;){if(i=e.charCodeAt(s),i===o.marker)return o.pos=s+1,o.str+=Tr(e.slice(t,s)),o.ok=!0,o;if(40===i&&41===o.marker)return o;92===i&&s+1<n&&s++,s++}return o.can_continue=!0,o.str+=Tr(e.slice(t,s)),o}});const Gr={};function Hr(){this.rules=kr({},Gr)}function Yr(){this.__rules__=[],this.__cache__=null}function Jr(e,t,n){this.type=e,this.tag=t,this.attrs=null,this.map=null,this.nesting=n,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}function Zr(e,t,n){this.src=e,this.env=n,this.tokens=[],this.inlineMode=!1,this.md=t}Gr.code_inline=function(e,t,n,r,i){const s=e[t];return"<code"+i.renderAttrs(s)+">"+Or(s.content)+"</code>"},Gr.code_block=function(e,t,n,r,i){const s=e[t];return"<pre"+i.renderAttrs(s)+"><code>"+Or(e[t].content)+"</code></pre>\n"},Gr.fence=function(e,t,n,r,i){const s=e[t],o=s.info?Tr(s.info).trim():"";let a,c="",l="";if(o){const e=o.split(/(\s+)/g);c=e[0],l=e.slice(2).join("")}if(a=n.highlight&&n.highlight(s.content,c,l)||Or(s.content),0===a.indexOf("<pre"))return a+"\n";if(o){const e=s.attrIndex("class"),t=s.attrs?s.attrs.slice():[];e<0?t.push(["class",n.langPrefix+c]):(t[e]=t[e].slice(),t[e][1]+=" "+n.langPrefix+c);const r={attrs:t};return`<pre><code${i.renderAttrs(r)}>${a}</code></pre>\n`}return`<pre><code${i.renderAttrs(s)}>${a}</code></pre>\n`},Gr.image=function(e,t,n,r,i){const s=e[t];return s.attrs[s.attrIndex("alt")][1]=i.renderInlineAsText(s.children,n,r),i.renderToken(e,t,n)},Gr.hardbreak=function(e,t,n){return n.xhtmlOut?"<br />\n":"<br>\n"},Gr.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"<br />\n":"<br>\n":"\n"},Gr.text=function(e,t){return Or(e[t].content)},Gr.html_block=function(e,t){return e[t].content},Gr.html_inline=function(e,t){return e[t].content},Hr.prototype.renderAttrs=function(e){let t,n,r;if(!e.attrs)return"";for(r="",t=0,n=e.attrs.length;t<n;t++)r+=" "+Or(e.attrs[t][0])+'="'+Or(e.attrs[t][1])+'"';return r},Hr.prototype.renderToken=function(e,t,n){const r=e[t];let i="";if(r.hidden)return"";r.block&&-1!==r.nesting&&t&&e[t-1].hidden&&(i+="\n"),i+=(-1===r.nesting?"</":"<")+r.tag,i+=this.renderAttrs(r),0===r.nesting&&n.xhtmlOut&&(i+=" /");let s=!1;if(r.block&&(s=!0,1===r.nesting&&t+1<e.length)){const n=e[t+1];("inline"===n.type||n.hidden||-1===n.nesting&&n.tag===r.tag)&&(s=!1)}return i+=s?">\n":">",i},Hr.prototype.renderInline=function(e,t,n){let r="";const i=this.rules;for(let s=0,o=e.length;s<o;s++){const o=e[s].type;void 0!==i[o]?r+=i[o](e,s,t,n,this):r+=this.renderToken(e,s,t)}return r},Hr.prototype.renderInlineAsText=function(e,t,n){let r="";for(let i=0,s=e.length;i<s;i++)switch(e[i].type){case"text":case"html_inline":case"html_block":r+=e[i].content;break;case"image":r+=this.renderInlineAsText(e[i].children,t,n);break;case"softbreak":case"hardbreak":r+="\n"}return r},Hr.prototype.render=function(e,t,n){let r="";const i=this.rules;for(let s=0,o=e.length;s<o;s++){const o=e[s].type;"inline"===o?r+=this.renderInline(e[s].children,t,n):void 0!==i[o]?r+=i[o](e,s,t,n,this):r+=this.renderToken(e,s,t,n)}return r},Yr.prototype.__find__=function(e){for(let t=0;t<this.__rules__.length;t++)if(this.__rules__[t].name===e)return t;return-1},Yr.prototype.__compile__=function(){const e=this,t=[""];e.__rules__.forEach(function(e){e.enabled&&e.alt.forEach(function(e){t.indexOf(e)<0&&t.push(e)})}),e.__cache__={},t.forEach(function(t){e.__cache__[t]=[],e.__rules__.forEach(function(n){n.enabled&&(t&&n.alt.indexOf(t)<0||e.__cache__[t].push(n.fn))})})},Yr.prototype.at=function(e,t,n){const r=this.__find__(e),i=n||{};if(-1===r)throw new Error("Parser rule not found: "+e);this.__rules__[r].fn=t,this.__rules__[r].alt=i.alt||[],this.__cache__=null},Yr.prototype.before=function(e,t,n,r){const i=this.__find__(e),s=r||{};if(-1===i)throw new Error("Parser rule not found: "+e);this.__rules__.splice(i,0,{name:t,enabled:!0,fn:n,alt:s.alt||[]}),this.__cache__=null},Yr.prototype.after=function(e,t,n,r){const i=this.__find__(e),s=r||{};if(-1===i)throw new Error("Parser rule not found: "+e);this.__rules__.splice(i+1,0,{name:t,enabled:!0,fn:n,alt:s.alt||[]}),this.__cache__=null},Yr.prototype.push=function(e,t,n){const r=n||{};this.__rules__.push({name:e,enabled:!0,fn:t,alt:r.alt||[]}),this.__cache__=null},Yr.prototype.enable=function(e,t){Array.isArray(e)||(e=[e]);const n=[];return e.forEach(function(e){const r=this.__find__(e);if(r<0){if(t)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[r].enabled=!0,n.push(e)},this),this.__cache__=null,n},Yr.prototype.enableOnly=function(e,t){Array.isArray(e)||(e=[e]),this.__rules__.forEach(function(e){e.enabled=!1}),this.enable(e,t)},Yr.prototype.disable=function(e,t){Array.isArray(e)||(e=[e]);const n=[];return e.forEach(function(e){const r=this.__find__(e);if(r<0){if(t)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[r].enabled=!1,n.push(e)},this),this.__cache__=null,n},Yr.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},Jr.prototype.attrIndex=function(e){if(!this.attrs)return-1;const t=this.attrs;for(let n=0,r=t.length;n<r;n++)if(t[n][0]===e)return n;return-1},Jr.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]},Jr.prototype.attrSet=function(e,t){const n=this.attrIndex(e),r=[e,t];n<0?this.attrPush(r):this.attrs[n]=r},Jr.prototype.attrGet=function(e){const t=this.attrIndex(e);let n=null;return t>=0&&(n=this.attrs[t][1]),n},Jr.prototype.attrJoin=function(e,t){const n=this.attrIndex(e);n<0?this.attrPush([e,t]):this.attrs[n][1]=this.attrs[n][1]+" "+t},Zr.prototype.Token=Jr;const Qr=/\r\n?|\n/g,Xr=/\0/g;function ei(e){return/^<a[>\s]/i.test(e)}function ti(e){return/^<\/a\s*>/i.test(e)}const ni=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,ri=/\((c|tm|r)\)/i,ii=/\((c|tm|r)\)/gi,si={c:"©",r:"®",tm:"™"};function oi(e,t){return si[t.toLowerCase()]}function ai(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||(r.content=r.content.replace(ii,oi)),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++}}function ci(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||ni.test(r.content)&&(r.content=r.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/gm,"$1—").replace(/(^|\s)--(?=\s|$)/gm,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,"$1–")),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++}}const li=/['"]/,ui=/['"]/g;function di(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function pi(e,t){let n;const r=[],i={};for(let s=0;s<e.length;s++){const o=e[s],a=e[s].level;for(n=r.length-1;n>=0&&!(r[n].level<=a);n--);if(r.length=n+1,"text"!==o.type)continue;const c=o.content;let l=0;const u=c.length;e:for(;l<u;){ui.lastIndex=l;const o=ui.exec(c);if(!o)break;let d=!0,p=!0;l=o.index+1;const h="'"===o[0];let f=32;if(o.index-1>=0)f=c.charCodeAt(o.index-1);else for(n=s-1;n>=0&&("softbreak"!==e[n].type&&"hardbreak"!==e[n].type);n--)if(e[n].content){f=e[n].content.charCodeAt(e[n].content.length-1);break}let m=32;if(l<u)m=c.charCodeAt(l);else for(n=s+1;n<e.length&&("softbreak"!==e[n].type&&"hardbreak"!==e[n].type);n++)if(e[n].content){m=e[n].content.charCodeAt(0);break}const g=Br(f)||Fr(f),y=Br(m)||Fr(m),b=$r(f),w=$r(m);if(w?d=!1:y&&(b||g||(d=!1)),b?p=!1:g&&(w||y||(p=!1)),34===m&&'"'===o[0]&&f>=48&&f<=57&&(p=d=!1),d&&p&&(d=g,p=y),d||p){if(p)for(n=r.length-1;n>=0;n--){let e=r[n];if(r[n].level<a)break;if(e.single===h&&r[n].level===a){let a,c;e=r[n],h?(a=t.md.options.quotes[2],c=t.md.options.quotes[3]):(a=t.md.options.quotes[0],c=t.md.options.quotes[1]),di(i,s,o.index,c),di(i,e.token,e.pos,a),r.length=n;continue e}}d?r.push({token:s,pos:o.index,single:h,level:a}):p&&h&&di(i,s,o.index,"’")}else h&&di(i,s,o.index,"’")}}Object.keys(i).forEach(function(t){e[t].content=function(e,t){let n="",r=0;t.sort((e,t)=>e.pos-t.pos);for(let i=0;i<t.length;i++){const s=t[i];n+=e.slice(r,s.pos)+s.ch,r=s.pos+1}return n+e.slice(r)}(e[t].content,i[t])})}const hi=[["normalize",function(e){let t;t=e.src.replace(Qr,"\n"),t=t.replace(Xr,"�"),e.src=t}],["block",function(e){let t;e.inlineMode?(t=new e.Token("inline","",0),t.content=e.src,t.map=[0,1],t.children=[],e.tokens.push(t)):e.md.block.parse(e.src,e.md,e.env,e.tokens)}],["inline",function(e){const t=e.tokens;for(let n=0,r=t.length;n<r;n++){const r=t[n];"inline"===r.type&&e.md.inline.parse(r.content,e.md,e.env,r.children)}}],["linkify",function(e){const t=e.tokens;if(e.md.options.linkify)for(let n=0,r=t.length;n<r;n++){if("inline"!==t[n].type||!e.md.linkify.pretest(t[n].content))continue;let r=t[n].children,i=0;for(let s=r.length-1;s>=0;s--){const o=r[s];if("link_close"!==o.type){if("html_inline"===o.type&&(ei(o.content)&&i>0&&i--,ti(o.content)&&i++),!(i>0)&&"text"===o.type&&e.md.linkify.test(o.content)){const i=o.content;let a=e.md.linkify.match(i);const c=[];let l=o.level,u=0;a.length>0&&0===a[0].index&&s>0&&"text_special"===r[s-1].type&&(a=a.slice(1));for(let t=0;t<a.length;t++){const n=a[t].url,r=e.md.normalizeLink(n);if(!e.md.validateLink(r))continue;let s=a[t].text;s=a[t].schema?"mailto:"!==a[t].schema||/^mailto:/i.test(s)?e.md.normalizeLinkText(s):e.md.normalizeLinkText("mailto:"+s).replace(/^mailto:/,""):e.md.normalizeLinkText("http://"+s).replace(/^http:\/\//,"");const o=a[t].index;if(o>u){const t=new e.Token("text","",0);t.content=i.slice(u,o),t.level=l,c.push(t)}const d=new e.Token("link_open","a",1);d.attrs=[["href",r]],d.level=l++,d.markup="linkify",d.info="auto",c.push(d);const p=new e.Token("text","",0);p.content=s,p.level=l,c.push(p);const h=new e.Token("link_close","a",-1);h.level=--l,h.markup="linkify",h.info="auto",c.push(h),u=a[t].lastIndex}if(u<i.length){const t=new e.Token("text","",0);t.content=i.slice(u),t.level=l,c.push(t)}t[n].children=r=Ir(r,s,c)}}else for(s--;r[s].level!==o.level&&"link_open"!==r[s].type;)s--}}}],["replacements",function(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&(ri.test(e.tokens[t].content)&&ai(e.tokens[t].children),ni.test(e.tokens[t].content)&&ci(e.tokens[t].children))}],["smartquotes",function(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&li.test(e.tokens[t].content)&&pi(e.tokens[t].children,e)}],["text_join",function(e){let t,n;const r=e.tokens,i=r.length;for(let e=0;e<i;e++){if("inline"!==r[e].type)continue;const i=r[e].children,s=i.length;for(t=0;t<s;t++)"text_special"===i[t].type&&(i[t].type="text");for(t=n=0;t<s;t++)"text"===i[t].type&&t+1<s&&"text"===i[t+1].type?i[t+1].content=i[t].content+i[t+1].content:(t!==n&&(i[n]=i[t]),n++);t!==n&&(i.length=n)}}]];function fi(){this.ruler=new Yr;for(let e=0;e<hi.length;e++)this.ruler.push(hi[e][0],hi[e][1])}function mi(e,t,n,r){this.src=e,this.md=t,this.env=n,this.tokens=r,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0;const i=this.src;for(let e=0,t=0,n=0,r=0,s=i.length,o=!1;t<s;t++){const a=i.charCodeAt(t);if(!o){if(Lr(a)){n++,9===a?r+=4-r%4:r++;continue}o=!0}10!==a&&t!==s-1||(10!==a&&t++,this.bMarks.push(e),this.eMarks.push(t),this.tShift.push(n),this.sCount.push(r),this.bsCount.push(0),o=!1,n=0,r=0,e=t+1)}this.bMarks.push(i.length),this.eMarks.push(i.length),this.tShift.push(0),this.sCount.push(0),this.bsCount.push(0),this.lineMax=this.bMarks.length-1}fi.prototype.process=function(e){const t=this.ruler.getRules("");for(let n=0,r=t.length;n<r;n++)t[n](e)},fi.prototype.State=Zr,mi.prototype.push=function(e,t,n){const r=new Jr(e,t,n);return r.block=!0,n<0&&this.level--,r.level=this.level,n>0&&this.level++,this.tokens.push(r),r},mi.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},mi.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},mi.prototype.skipSpaces=function(e){for(let t=this.src.length;e<t;e++){if(!Lr(this.src.charCodeAt(e)))break}return e},mi.prototype.skipSpacesBack=function(e,t){if(e<=t)return e;for(;e>t;)if(!Lr(this.src.charCodeAt(--e)))return e+1;return e},mi.prototype.skipChars=function(e,t){for(let n=this.src.length;e<n&&this.src.charCodeAt(e)===t;e++);return e},mi.prototype.skipCharsBack=function(e,t,n){if(e<=n)return e;for(;e>n;)if(t!==this.src.charCodeAt(--e))return e+1;return e},mi.prototype.getLines=function(e,t,n,r){if(e>=t)return"";const i=new Array(t-e);for(let s=0,o=e;o<t;o++,s++){let e=0;const a=this.bMarks[o];let c,l=a;for(c=o+1<t||r?this.eMarks[o]+1:this.eMarks[o];l<c&&e<n;){const t=this.src.charCodeAt(l);if(Lr(t))9===t?e+=4-(e+this.bsCount[o])%4:e++;else{if(!(l-a<this.tShift[o]))break;e++}l++}i[s]=e>n?new Array(e-n+1).join(" ")+this.src.slice(l,c):this.src.slice(l,c)}return i.join("")},mi.prototype.Token=Jr;function gi(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function yi(e){const t=[],n=e.length;let r=0,i=e.charCodeAt(r),s=!1,o=0,a="";for(;r<n;)124===i&&(s?(a+=e.substring(o,r-1),o=r):(t.push(a+e.substring(o,r)),a="",o=r+1)),s=92===i,r++,i=e.charCodeAt(r);return t.push(a+e.substring(o)),t}function bi(e,t){const n=e.eMarks[t];let r=e.bMarks[t]+e.tShift[t];const i=e.src.charCodeAt(r++);if(42!==i&&45!==i&&43!==i)return-1;if(r<n){if(!Lr(e.src.charCodeAt(r)))return-1}return r}function wi(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];let i=n;if(i+1>=r)return-1;let s=e.src.charCodeAt(i++);if(s<48||s>57)return-1;for(;;){if(i>=r)return-1;if(s=e.src.charCodeAt(i++),!(s>=48&&s<=57)){if(41===s||46===s)break;return-1}if(i-n>=10)return-1}return i<r&&(s=e.src.charCodeAt(i),!Lr(s))?-1:i}const vi="<[A-Za-z][A-Za-z0-9\\-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^\"'=<>`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",ki="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",Ii=new RegExp("^(?:"+vi+"|"+ki+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|<![A-Za-z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)"),Ei=new RegExp("^(?:"+vi+"|"+ki+")"),Ai=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^<!--/,/-->/,!0],[/^<\?/,/\?>/,!0],[/^<![A-Z]/,/>/,!0],[/^<!\[CDATA\[/,/\]\]>/,!0],[new RegExp("^</?("+["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"].join("|")+")(?=(\\s|/?>|$))","i"),/^$/,!0],[new RegExp(Ei.source+"\\s*$"),/^$/,!1]];const Si=[["table",function(e,t,n,r){if(t+2>n)return!1;let i=t+1;if(e.sCount[i]<e.blkIndent)return!1;if(e.sCount[i]-e.blkIndent>=4)return!1;let s=e.bMarks[i]+e.tShift[i];if(s>=e.eMarks[i])return!1;const o=e.src.charCodeAt(s++);if(124!==o&&45!==o&&58!==o)return!1;if(s>=e.eMarks[i])return!1;const a=e.src.charCodeAt(s++);if(124!==a&&45!==a&&58!==a&&!Lr(a))return!1;if(45===o&&Lr(a))return!1;for(;s<e.eMarks[i];){const t=e.src.charCodeAt(s);if(124!==t&&45!==t&&58!==t&&!Lr(t))return!1;s++}let c=gi(e,t+1),l=c.split("|");const u=[];for(let e=0;e<l.length;e++){const t=l[e].trim();if(!t){if(0===e||e===l.length-1)continue;return!1}if(!/^:?-+:?$/.test(t))return!1;58===t.charCodeAt(t.length-1)?u.push(58===t.charCodeAt(0)?"center":"right"):58===t.charCodeAt(0)?u.push("left"):u.push("")}if(c=gi(e,t).trim(),-1===c.indexOf("|"))return!1;if(e.sCount[t]-e.blkIndent>=4)return!1;l=yi(c),l.length&&""===l[0]&&l.shift(),l.length&&""===l[l.length-1]&&l.pop();const d=l.length;if(0===d||d!==u.length)return!1;if(r)return!0;const p=e.parentType;e.parentType="table";const h=e.md.block.ruler.getRules("blockquote"),f=[t,0];e.push("table_open","table",1).map=f,e.push("thead_open","thead",1).map=[t,t+1],e.push("tr_open","tr",1).map=[t,t+1];for(let t=0;t<l.length;t++){const n=e.push("th_open","th",1);u[t]&&(n.attrs=[["style","text-align:"+u[t]]]);const r=e.push("inline","",0);r.content=l[t].trim(),r.children=[],e.push("th_close","th",-1)}let m;e.push("tr_close","tr",-1),e.push("thead_close","thead",-1);let g=0;for(i=t+2;i<n&&!(e.sCount[i]<e.blkIndent);i++){let r=!1;for(let t=0,s=h.length;t<s;t++)if(h[t](e,i,n,!0)){r=!0;break}if(r)break;if(c=gi(e,i).trim(),!c)break;if(e.sCount[i]-e.blkIndent>=4)break;if(l=yi(c),l.length&&""===l[0]&&l.shift(),l.length&&""===l[l.length-1]&&l.pop(),g+=d-l.length,g>65536)break;if(i===t+2){e.push("tbody_open","tbody",1).map=m=[t+2,0]}e.push("tr_open","tr",1).map=[i,i+1];for(let t=0;t<d;t++){const n=e.push("td_open","td",1);u[t]&&(n.attrs=[["style","text-align:"+u[t]]]);const r=e.push("inline","",0);r.content=l[t]?l[t].trim():"",r.children=[],e.push("td_close","td",-1)}e.push("tr_close","tr",-1)}return m&&(e.push("tbody_close","tbody",-1),m[1]=i),e.push("table_close","table",-1),f[1]=i,e.parentType=p,e.line=i,!0},["paragraph","reference"]],["code",function(e,t,n){if(e.sCount[t]-e.blkIndent<4)return!1;let r=t+1,i=r;for(;r<n;)if(e.isEmpty(r))r++;else{if(!(e.sCount[r]-e.blkIndent>=4))break;r++,i=r}e.line=i;const s=e.push("code_block","code",0);return s.content=e.getLines(t,i,4+e.blkIndent,!1)+"\n",s.map=[t,e.line],!0}],["fence",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;if(i+3>s)return!1;const o=e.src.charCodeAt(i);if(126!==o&&96!==o)return!1;let a=i;i=e.skipChars(i,o);let c=i-a;if(c<3)return!1;const l=e.src.slice(a,i),u=e.src.slice(i,s);if(96===o&&u.indexOf(String.fromCharCode(o))>=0)return!1;if(r)return!0;let d=t,p=!1;for(;(d++,!(d>=n))&&(i=a=e.bMarks[d]+e.tShift[d],s=e.eMarks[d],!(i<s&&e.sCount[d]<e.blkIndent));)if(e.src.charCodeAt(i)===o&&!(e.sCount[d]-e.blkIndent>=4||(i=e.skipChars(i,o),i-a<c||(i=e.skipSpaces(i),i<s)))){p=!0;break}c=e.sCount[t],e.line=d+(p?1:0);const h=e.push("fence","code",0);return h.info=u,h.content=e.getLines(t+1,d,c,!0),h.markup=l,h.map=[t,e.line],!0},["paragraph","reference","blockquote","list"]],["blockquote",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];const o=e.lineMax;if(e.sCount[t]-e.blkIndent>=4)return!1;if(62!==e.src.charCodeAt(i))return!1;if(r)return!0;const a=[],c=[],l=[],u=[],d=e.md.block.ruler.getRules("blockquote"),p=e.parentType;e.parentType="blockquote";let h,f=!1;for(h=t;h<n;h++){const t=e.sCount[h]<e.blkIndent;if(i=e.bMarks[h]+e.tShift[h],s=e.eMarks[h],i>=s)break;if(62===e.src.charCodeAt(i++)&&!t){let t,n,r=e.sCount[h]+1;32===e.src.charCodeAt(i)?(i++,r++,n=!1,t=!0):9===e.src.charCodeAt(i)?(t=!0,(e.bsCount[h]+r)%4==3?(i++,r++,n=!1):n=!0):t=!1;let o=r;for(a.push(e.bMarks[h]),e.bMarks[h]=i;i<s;){const t=e.src.charCodeAt(i);if(!Lr(t))break;9===t?o+=4-(o+e.bsCount[h]+(n?1:0))%4:o++,i++}f=i>=s,c.push(e.bsCount[h]),e.bsCount[h]=e.sCount[h]+1+(t?1:0),l.push(e.sCount[h]),e.sCount[h]=o-r,u.push(e.tShift[h]),e.tShift[h]=i-e.bMarks[h];continue}if(f)break;let r=!1;for(let t=0,i=d.length;t<i;t++)if(d[t](e,h,n,!0)){r=!0;break}if(r){e.lineMax=h,0!==e.blkIndent&&(a.push(e.bMarks[h]),c.push(e.bsCount[h]),u.push(e.tShift[h]),l.push(e.sCount[h]),e.sCount[h]-=e.blkIndent);break}a.push(e.bMarks[h]),c.push(e.bsCount[h]),u.push(e.tShift[h]),l.push(e.sCount[h]),e.sCount[h]=-1}const m=e.blkIndent;e.blkIndent=0;const g=e.push("blockquote_open","blockquote",1);g.markup=">";const y=[t,0];g.map=y,e.md.block.tokenize(e,t,h),e.push("blockquote_close","blockquote",-1).markup=">",e.lineMax=o,e.parentType=p,y[1]=e.line;for(let n=0;n<u.length;n++)e.bMarks[n+t]=a[n],e.tShift[n+t]=u[n],e.sCount[n+t]=l[n],e.bsCount[n+t]=c[n];return e.blkIndent=m,!0},["paragraph","reference","blockquote","list"]],["hr",function(e,t,n,r){const i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let s=e.bMarks[t]+e.tShift[t];const o=e.src.charCodeAt(s++);if(42!==o&&45!==o&&95!==o)return!1;let a=1;for(;s<i;){const t=e.src.charCodeAt(s++);if(t!==o&&!Lr(t))return!1;t===o&&a++}if(a<3)return!1;if(r)return!0;e.line=t+1;const c=e.push("hr","hr",0);return c.map=[t,e.line],c.markup=Array(a+1).join(String.fromCharCode(o)),!0},["paragraph","reference","blockquote","list"]],["list",function(e,t,n,r){let i,s,o,a,c=t,l=!0;if(e.sCount[c]-e.blkIndent>=4)return!1;if(e.listIndent>=0&&e.sCount[c]-e.listIndent>=4&&e.sCount[c]<e.blkIndent)return!1;let u,d,p,h=!1;if(r&&"paragraph"===e.parentType&&e.sCount[c]>=e.blkIndent&&(h=!0),(p=wi(e,c))>=0){if(u=!0,o=e.bMarks[c]+e.tShift[c],d=Number(e.src.slice(o,p-1)),h&&1!==d)return!1}else{if(!((p=bi(e,c))>=0))return!1;u=!1}if(h&&e.skipSpaces(p)>=e.eMarks[c])return!1;if(r)return!0;const f=e.src.charCodeAt(p-1),m=e.tokens.length;u?(a=e.push("ordered_list_open","ol",1),1!==d&&(a.attrs=[["start",d]])):a=e.push("bullet_list_open","ul",1);const g=[c,0];a.map=g,a.markup=String.fromCharCode(f);let y=!1;const b=e.md.block.ruler.getRules("list"),w=e.parentType;for(e.parentType="list";c<n;){s=p,i=e.eMarks[c];const t=e.sCount[c]+p-(e.bMarks[c]+e.tShift[c]);let r=t;for(;s<i;){const t=e.src.charCodeAt(s);if(9===t)r+=4-(r+e.bsCount[c])%4;else{if(32!==t)break;r++}s++}const d=s;let h;h=d>=i?1:r-t,h>4&&(h=1);const m=t+h;a=e.push("list_item_open","li",1),a.markup=String.fromCharCode(f);const g=[c,0];a.map=g,u&&(a.info=e.src.slice(o,p-1));const w=e.tight,v=e.tShift[c],k=e.sCount[c],I=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=m,e.tight=!0,e.tShift[c]=d-e.bMarks[c],e.sCount[c]=r,d>=i&&e.isEmpty(c+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,c,n,!0),e.tight&&!y||(l=!1),y=e.line-c>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=I,e.tShift[c]=v,e.sCount[c]=k,e.tight=w,a=e.push("list_item_close","li",-1),a.markup=String.fromCharCode(f),c=e.line,g[1]=c,c>=n)break;if(e.sCount[c]<e.blkIndent)break;if(e.sCount[c]-e.blkIndent>=4)break;let E=!1;for(let t=0,r=b.length;t<r;t++)if(b[t](e,c,n,!0)){E=!0;break}if(E)break;if(u){if(p=wi(e,c),p<0)break;o=e.bMarks[c]+e.tShift[c]}else if(p=bi(e,c),p<0)break;if(f!==e.src.charCodeAt(p-1))break}return a=u?e.push("ordered_list_close","ol",-1):e.push("bullet_list_close","ul",-1),a.markup=String.fromCharCode(f),g[1]=c,e.line=c,e.parentType=w,l&&function(e,t){const n=e.level+2;for(let r=t+2,i=e.tokens.length-2;r<i;r++)e.tokens[r].level===n&&"paragraph_open"===e.tokens[r].type&&(e.tokens[r+2].hidden=!0,e.tokens[r].hidden=!0,r+=2)}(e,m),!0},["paragraph","reference","blockquote"]],["reference",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t],o=t+1;if(e.sCount[t]-e.blkIndent>=4)return!1;if(91!==e.src.charCodeAt(i))return!1;function a(t){const n=e.lineMax;if(t>=n||e.isEmpty(t))return null;let r=!1;if(e.sCount[t]-e.blkIndent>3&&(r=!0),e.sCount[t]<0&&(r=!0),!r){const r=e.md.block.ruler.getRules("reference"),i=e.parentType;e.parentType="reference";let s=!1;for(let i=0,o=r.length;i<o;i++)if(r[i](e,t,n,!0)){s=!0;break}if(e.parentType=i,s)return null}const i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];return e.src.slice(i,s+1)}let c=e.src.slice(i,s+1);s=c.length;let l=-1;for(i=1;i<s;i++){const e=c.charCodeAt(i);if(91===e)return!1;if(93===e){l=i;break}if(10===e){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}else if(92===e&&(i++,i<s&&10===c.charCodeAt(i))){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}}if(l<0||58!==c.charCodeAt(l+1))return!1;for(i=l+2;i<s;i++){const e=c.charCodeAt(i);if(10===e){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}else if(!Lr(e))break}const u=e.md.helpers.parseLinkDestination(c,i,s);if(!u.ok)return!1;const d=e.md.normalizeLink(u.str);if(!e.md.validateLink(d))return!1;i=u.pos;const p=i,h=o,f=i;for(;i<s;i++){const e=c.charCodeAt(i);if(10===e){const e=a(o);null!==e&&(c+=e,s=c.length,o++)}else if(!Lr(e))break}let m,g=e.md.helpers.parseLinkTitle(c,i,s);for(;g.can_continue;){const t=a(o);if(null===t)break;c+=t,i=s,s=c.length,o++,g=e.md.helpers.parseLinkTitle(c,i,s,g)}for(i<s&&f!==i&&g.ok?(m=g.str,i=g.pos):(m="",i=p,o=h);i<s;){if(!Lr(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i)&&m)for(m="",i=p,o=h;i<s;){if(!Lr(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i))return!1;const y=qr(c.slice(1,l));return!!y&&(r||(void 0===e.env.references&&(e.env.references={}),void 0===e.env.references[y]&&(e.env.references[y]={title:m,href:d}),e.line=o),!0)}],["html_block",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;if(!e.md.options.html)return!1;if(60!==e.src.charCodeAt(i))return!1;let o=e.src.slice(i,s),a=0;for(;a<Ai.length&&!Ai[a][0].test(o);a++);if(a===Ai.length)return!1;if(r)return Ai[a][2];let c=t+1;const l=Ai[a][1].test("");if(!Ai[a][1].test(o))for(;c<n&&(!(e.sCount[c]<e.blkIndent)||!l&&e.isEmpty(c));c++)if(i=e.bMarks[c]+e.tShift[c],s=e.eMarks[c],o=e.src.slice(i,s),Ai[a][1].test(o)){0!==o.length&&c++;break}e.line=c;const u=e.push("html_block","",0);return u.map=[t,c],u.content=e.getLines(t,c,e.blkIndent,!0),!0},["paragraph","reference","blockquote"]],["heading",function(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],s=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let o=e.src.charCodeAt(i);if(35!==o||i>=s)return!1;let a=1;for(o=e.src.charCodeAt(++i);35===o&&i<s&&a<=6;)a++,o=e.src.charCodeAt(++i);if(a>6||i<s&&!Lr(o))return!1;if(r)return!0;s=e.skipSpacesBack(s,i);const c=e.skipCharsBack(s,35,i);c>i&&Lr(e.src.charCodeAt(c-1))&&(s=c),e.line=t+1;const l=e.push("heading_open","h"+String(a),1);l.markup="########".slice(0,a),l.map=[t,e.line];const u=e.push("inline","",0);return u.content=Ur(e.src.slice(i,s)),u.map=[t,e.line],u.children=[],e.push("heading_close","h"+String(a),-1).markup="########".slice(0,a),!0},["paragraph","reference","blockquote"]],["lheading",function(e,t,n){const r=e.md.block.ruler.getRules("paragraph");if(e.sCount[t]-e.blkIndent>=4)return!1;const i=e.parentType;e.parentType="paragraph";let s,o=0,a=t+1;for(;a<n&&!e.isEmpty(a);a++){if(e.sCount[a]-e.blkIndent>3)continue;if(e.sCount[a]>=e.blkIndent){let t=e.bMarks[a]+e.tShift[a];const n=e.eMarks[a];if(t<n&&(s=e.src.charCodeAt(t),(45===s||61===s)&&(t=e.skipChars(t,s),t=e.skipSpaces(t),t>=n))){o=61===s?1:2;break}}if(e.sCount[a]<0)continue;let t=!1;for(let i=0,s=r.length;i<s;i++)if(r[i](e,a,n,!0)){t=!0;break}if(t)break}if(!o)return e.parentType=i,!1;const c=Ur(e.getLines(t,a,e.blkIndent,!1));e.line=a+1;const l=e.push("heading_open","h"+String(o),1);l.markup=String.fromCharCode(s),l.map=[t,e.line];const u=e.push("inline","",0);return u.content=c,u.map=[t,e.line-1],u.children=[],e.push("heading_close","h"+String(o),-1).markup=String.fromCharCode(s),e.parentType=i,!0}],["paragraph",function(e,t,n){const r=e.md.block.ruler.getRules("paragraph"),i=e.parentType;let s=t+1;for(e.parentType="paragraph";s<n&&!e.isEmpty(s);s++){if(e.sCount[s]-e.blkIndent>3)continue;if(e.sCount[s]<0)continue;let t=!1;for(let i=0,o=r.length;i<o;i++)if(r[i](e,s,n,!0)){t=!0;break}if(t)break}const o=Ur(e.getLines(t,s,e.blkIndent,!1));e.line=s,e.push("paragraph_open","p",1).map=[t,e.line];const a=e.push("inline","",0);return a.content=o,a.map=[t,e.line],a.children=[],e.push("paragraph_close","p",-1),e.parentType=i,!0}]];function _i(){this.ruler=new Yr;for(let e=0;e<Si.length;e++)this.ruler.push(Si[e][0],Si[e][1],{alt:(Si[e][2]||[]).slice()})}function xi(e,t,n,r){this.src=e,this.env=n,this.md=t,this.tokens=r,this.tokens_meta=Array(r.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}function Ci(e){switch(e){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}_i.prototype.tokenize=function(e,t,n){const r=this.ruler.getRules(""),i=r.length,s=e.md.options.maxNesting;let o=t,a=!1;for(;o<n&&(e.line=o=e.skipEmptyLines(o),!(o>=n))&&!(e.sCount[o]<e.blkIndent);){if(e.level>=s){e.line=n;break}const t=e.line;let c=!1;for(let s=0;s<i;s++)if(c=r[s](e,o,n,!1),c){if(t>=e.line)throw new Error("block rule didn't increment state.line");break}if(!c)throw new Error("none of the block rules matched");e.tight=!a,e.isEmpty(e.line-1)&&(a=!0),o=e.line,o<n&&e.isEmpty(o)&&(a=!0,o++,e.line=o)}},_i.prototype.parse=function(e,t,n,r){if(!e)return;const i=new this.State(e,t,n,r);this.tokenize(i,i.line,i.lineMax)},_i.prototype.State=mi,xi.prototype.pushPending=function(){const e=new Jr("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},xi.prototype.push=function(e,t,n){this.pending&&this.pushPending();const r=new Jr(e,t,n);let i=null;return n<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),r.level=this.level,n>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],i={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(r),this.tokens_meta.push(i),r},xi.prototype.scanDelims=function(e,t){const n=this.posMax,r=this.src.charCodeAt(e);let i;if(0===e)i=32;else if(1===e)i=this.src.charCodeAt(0),55296==(63488&i)&&(i=65533);else if(i=this.src.charCodeAt(e-1),56320==(64512&i)){const t=this.src.charCodeAt(e-2);i=55296==(64512&t)?65536+(t-55296<<10)+(i-56320):65533}else 55296==(64512&i)&&(i=65533);let s=e;for(;s<n&&this.src.charCodeAt(s)===r;)s++;const o=s-e;let a=s<n?this.src.charCodeAt(s):32;if(55296==(64512&a)){const e=this.src.charCodeAt(s+1);a=56320==(64512&e)?65536+(a-55296<<10)+(e-56320):65533}else 56320==(64512&a)&&(a=65533);const c=Br(i)||Fr(i),l=Br(a)||Fr(a),u=$r(i),d=$r(a),p=!d&&(!l||u||c),h=!u&&(!c||d||l);return{can_open:p&&(t||!h||c),can_close:h&&(t||!p||l),length:o}},xi.prototype.Token=Jr;const Ti=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;const Ni=[];for(let e=0;e<256;e++)Ni.push(0);function Mi(e,t){let n;const r=[],i=t.length;for(let s=0;s<i;s++){const i=t[s];if(126!==i.marker)continue;if(-1===i.end)continue;const o=t[i.end];n=e.tokens[i.token],n.type="s_open",n.tag="s",n.nesting=1,n.markup="~~",n.content="",n=e.tokens[o.token],n.type="s_close",n.tag="s",n.nesting=-1,n.markup="~~",n.content="","text"===e.tokens[o.token-1].type&&"~"===e.tokens[o.token-1].content&&r.push(o.token-1)}for(;r.length;){const t=r.pop();let i=t+1;for(;i<e.tokens.length&&"s_close"===e.tokens[i].type;)i++;i--,t!==i&&(n=e.tokens[i],e.tokens[i]=e.tokens[t],e.tokens[t]=n)}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(e){Ni[e.charCodeAt(0)]=1});var Di={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return!1;if(126!==r)return!1;const i=e.scanDelims(e.pos,!0);let s=i.length;const o=String.fromCharCode(r);if(s<2)return!1;let a;s%2&&(a=e.push("text","",0),a.content=o,s--);for(let t=0;t<s;t+=2)a=e.push("text","",0),a.content=o+o,e.delimiters.push({marker:r,length:0,token:e.tokens.length-1,end:-1,open:i.can_open,close:i.can_close});return e.pos+=i.length,!0},postProcess:function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Mi(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Mi(e,t[r].delimiters)}};function Pi(e,t){for(let n=t.length-1;n>=0;n--){const r=t[n];if(95!==r.marker&&42!==r.marker)continue;if(-1===r.end)continue;const i=t[r.end],s=n>0&&t[n-1].end===r.end+1&&t[n-1].marker===r.marker&&t[n-1].token===r.token-1&&t[r.end+1].token===i.token+1,o=String.fromCharCode(r.marker),a=e.tokens[r.token];a.type=s?"strong_open":"em_open",a.tag=s?"strong":"em",a.nesting=1,a.markup=s?o+o:o,a.content="";const c=e.tokens[i.token];c.type=s?"strong_close":"em_close",c.tag=s?"strong":"em",c.nesting=-1,c.markup=s?o+o:o,c.content="",s&&(e.tokens[t[n-1].token].content="",e.tokens[t[r.end+1].token].content="",n--)}}var Oi={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return!1;if(95!==r&&42!==r)return!1;const i=e.scanDelims(e.pos,42===r);for(let t=0;t<i.length;t++){e.push("text","",0).content=String.fromCharCode(r),e.delimiters.push({marker:r,length:i.length,token:e.tokens.length-1,end:-1,open:i.can_open,close:i.can_close})}return e.pos+=i.length,!0},postProcess:function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Pi(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Pi(e,t[r].delimiters)}};const Ri=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,Li=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;const $i=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,ji=/^&([a-z][a-z0-9]{1,31});/i;function Fi(e){const t={},n=e.length;if(!n)return;let r=0,i=-2;const s=[];for(let o=0;o<n;o++){const n=e[o];if(s.push(0),e[r].marker===n.marker&&i===n.token-1||(r=o),i=n.token,n.length=n.length||0,!n.close)continue;t.hasOwnProperty(n.marker)||(t[n.marker]=[-1,-1,-1,-1,-1,-1]);const a=t[n.marker][(n.open?3:0)+n.length%3];let c=r-s[r]-1,l=c;for(;c>a;c-=s[c]+1){const t=e[c];if(t.marker===n.marker&&(t.open&&t.end<0)){let r=!1;if((t.close||n.open)&&(t.length+n.length)%3==0&&(t.length%3==0&&n.length%3==0||(r=!0)),!r){const r=c>0&&!e[c-1].open?s[c-1]+1:0;s[o]=o-c+r,s[c]=r,n.open=!1,t.end=o,t.close=!1,l=-1,i=-2;break}}}-1!==l&&(t[n.marker][(n.open?3:0)+(n.length||0)%3]=l)}}const Bi=[["text",function(e,t){let n=e.pos;for(;n<e.posMax&&!Ci(e.src.charCodeAt(n));)n++;return n!==e.pos&&(t||(e.pending+=e.src.slice(e.pos,n)),e.pos=n,!0)}],["linkify",function(e,t){if(!e.md.options.linkify)return!1;if(e.linkLevel>0)return!1;const n=e.pos;if(n+3>e.posMax)return!1;if(58!==e.src.charCodeAt(n))return!1;if(47!==e.src.charCodeAt(n+1))return!1;if(47!==e.src.charCodeAt(n+2))return!1;const r=e.pending.match(Ti);if(!r)return!1;const i=r[1],s=e.md.linkify.matchAtStart(e.src.slice(n-i.length));if(!s)return!1;let o=s.url;if(o.length<=i.length)return!1;let a=o.length;for(;a>0&&42===o.charCodeAt(a-1);)a--;a!==o.length&&(o=o.slice(0,a));const c=e.md.normalizeLink(o);if(!e.md.validateLink(c))return!1;if(!t){e.pending=e.pending.slice(0,-i.length);const t=e.push("link_open","a",1);t.attrs=[["href",c]],t.markup="linkify",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(o);const n=e.push("link_close","a",-1);n.markup="linkify",n.info="auto"}return e.pos+=o.length-i.length,!0}],["newline",function(e,t){let n=e.pos;if(10!==e.src.charCodeAt(n))return!1;const r=e.pending.length-1,i=e.posMax;if(!t)if(r>=0&&32===e.pending.charCodeAt(r))if(r>=1&&32===e.pending.charCodeAt(r-1)){let t=r-1;for(;t>=1&&32===e.pending.charCodeAt(t-1);)t--;e.pending=e.pending.slice(0,t),e.push("hardbreak","br",0)}else e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0);else e.push("softbreak","br",0);for(n++;n<i&&Lr(e.src.charCodeAt(n));)n++;return e.pos=n,!0}],["escape",function(e,t){let n=e.pos;const r=e.posMax;if(92!==e.src.charCodeAt(n))return!1;if(n++,n>=r)return!1;let i=e.src.charCodeAt(n);if(10===i){for(t||e.push("hardbreak","br",0),n++;n<r&&(i=e.src.charCodeAt(n),Lr(i));)n++;return e.pos=n,!0}if(32===i){if(!t){const t=e.push("text_special","",0);t.content="\\",t.markup="\\",t.info="escape"}return e.pos=n,!0}let s=e.src[n];if(i>=55296&&i<=56319&&n+1<r){const t=e.src.charCodeAt(n+1);t>=56320&&t<=57343&&(s+=e.src[n+1],n++)}const o="\\"+s;if(!t){const t=e.push("text_special","",0);i<256&&0!==Ni[i]?t.content=s:t.content=o,t.markup=o,t.info="escape"}return e.pos=n+1,!0}],["backticks",function(e,t){let n=e.pos;if(96!==e.src.charCodeAt(n))return!1;const r=n;n++;const i=e.posMax;for(;n<i&&96===e.src.charCodeAt(n);)n++;const s=e.src.slice(r,n),o=s.length;if(e.backticksScanned&&(e.backticks[o]||0)<=r)return t||(e.pending+=s),e.pos+=o,!0;let a,c=n;for(;-1!==(a=e.src.indexOf("`",c));){for(c=a+1;c<i&&96===e.src.charCodeAt(c);)c++;const r=c-a;if(r===o){if(!t){const t=e.push("code_inline","code",0);t.markup=s,t.content=e.src.slice(n,a).replace(/\n/g," ").replace(/^ (.+) $/,"$1")}return e.pos=c,!0}e.backticks[r]=a}return e.backticksScanned=!0,t||(e.pending+=s),e.pos+=o,!0}],["strikethrough",Di.tokenize],["emphasis",Oi.tokenize],["link",function(e,t){let n,r,i,s,o="",a="",c=e.pos,l=!0;if(91!==e.src.charCodeAt(e.pos))return!1;const u=e.pos,d=e.posMax,p=e.pos+1,h=e.md.helpers.parseLinkLabel(e,e.pos,!0);if(h<0)return!1;let f=h+1;if(f<d&&40===e.src.charCodeAt(f)){for(l=!1,f++;f<d&&(n=e.src.charCodeAt(f),Lr(n)||10===n);f++);if(f>=d)return!1;if(c=f,i=e.md.helpers.parseLinkDestination(e.src,f,e.posMax),i.ok){for(o=e.md.normalizeLink(i.str),e.md.validateLink(o)?f=i.pos:o="",c=f;f<d&&(n=e.src.charCodeAt(f),Lr(n)||10===n);f++);if(i=e.md.helpers.parseLinkTitle(e.src,f,e.posMax),f<d&&c!==f&&i.ok)for(a=i.str,f=i.pos;f<d&&(n=e.src.charCodeAt(f),Lr(n)||10===n);f++);}(f>=d||41!==e.src.charCodeAt(f))&&(l=!0),f++}if(l){if(void 0===e.env.references)return!1;if(f<d&&91===e.src.charCodeAt(f)?(c=f+1,f=e.md.helpers.parseLinkLabel(e,f),f>=0?r=e.src.slice(c,f++):f=h+1):f=h+1,r||(r=e.src.slice(p,h)),s=e.env.references[qr(r)],!s)return e.pos=u,!1;o=s.href,a=s.title}if(!t){e.pos=p,e.posMax=h;const t=[["href",o]];e.push("link_open","a",1).attrs=t,a&&t.push(["title",a]),e.linkLevel++,e.md.inline.tokenize(e),e.linkLevel--,e.push("link_close","a",-1)}return e.pos=f,e.posMax=d,!0}],["image",function(e,t){let n,r,i,s,o,a,c,l,u="";const d=e.pos,p=e.posMax;if(33!==e.src.charCodeAt(e.pos))return!1;if(91!==e.src.charCodeAt(e.pos+1))return!1;const h=e.pos+2,f=e.md.helpers.parseLinkLabel(e,e.pos+1,!1);if(f<0)return!1;if(s=f+1,s<p&&40===e.src.charCodeAt(s)){for(s++;s<p&&(n=e.src.charCodeAt(s),Lr(n)||10===n);s++);if(s>=p)return!1;for(l=s,a=e.md.helpers.parseLinkDestination(e.src,s,e.posMax),a.ok&&(u=e.md.normalizeLink(a.str),e.md.validateLink(u)?s=a.pos:u=""),l=s;s<p&&(n=e.src.charCodeAt(s),Lr(n)||10===n);s++);if(a=e.md.helpers.parseLinkTitle(e.src,s,e.posMax),s<p&&l!==s&&a.ok)for(c=a.str,s=a.pos;s<p&&(n=e.src.charCodeAt(s),Lr(n)||10===n);s++);else c="";if(s>=p||41!==e.src.charCodeAt(s))return e.pos=d,!1;s++}else{if(void 0===e.env.references)return!1;if(s<p&&91===e.src.charCodeAt(s)?(l=s+1,s=e.md.helpers.parseLinkLabel(e,s),s>=0?i=e.src.slice(l,s++):s=f+1):s=f+1,i||(i=e.src.slice(h,f)),o=e.env.references[qr(i)],!o)return e.pos=d,!1;u=o.href,c=o.title}if(!t){r=e.src.slice(h,f);const t=[];e.md.inline.parse(r,e.md,e.env,t);const n=e.push("image","img",0),i=[["src",u],["alt",""]];n.attrs=i,n.children=t,n.content=r,c&&i.push(["title",c])}return e.pos=s,e.posMax=p,!0}],["autolink",function(e,t){let n=e.pos;if(60!==e.src.charCodeAt(n))return!1;const r=e.pos,i=e.posMax;for(;;){if(++n>=i)return!1;const t=e.src.charCodeAt(n);if(60===t)return!1;if(62===t)break}const s=e.src.slice(r+1,n);if(Li.test(s)){const n=e.md.normalizeLink(s);if(!e.md.validateLink(n))return!1;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(s);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto"}return e.pos+=s.length+2,!0}if(Ri.test(s)){const n=e.md.normalizeLink("mailto:"+s);if(!e.md.validateLink(n))return!1;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(s);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto"}return e.pos+=s.length+2,!0}return!1}],["html_inline",function(e,t){if(!e.md.options.html)return!1;const n=e.posMax,r=e.pos;if(60!==e.src.charCodeAt(r)||r+2>=n)return!1;const i=e.src.charCodeAt(r+1);if(33!==i&&63!==i&&47!==i&&!function(e){const t=32|e;return t>=97&&t<=122}(i))return!1;const s=e.src.slice(r).match(Ii);if(!s)return!1;if(!t){const t=e.push("html_inline","",0);t.content=s[0],o=t.content,/^<a[>\s]/i.test(o)&&e.linkLevel++,function(e){return/^<\/a\s*>/i.test(e)}(t.content)&&e.linkLevel--}var o;return e.pos+=s[0].length,!0}],["entity",function(e,t){const n=e.pos,r=e.posMax;if(38!==e.src.charCodeAt(n))return!1;if(n+1>=r)return!1;if(35===e.src.charCodeAt(n+1)){const r=e.src.slice(n).match($i);if(r){if(!t){const t="x"===r[1][0].toLowerCase()?parseInt(r[1].slice(1),16):parseInt(r[1],10),n=e.push("text_special","",0);n.content=Er(t)?Ar(t):Ar(65533),n.markup=r[0],n.info="entity"}return e.pos+=r[0].length,!0}}else{const r=e.src.slice(n).match(ji);if(r){const n=(i=r[0],br(i,dr.Strict));if(n!==r[0]){if(!t){const t=e.push("text_special","",0);t.content=n,t.markup=r[0],t.info="entity"}return e.pos+=r[0].length,!0}}}var i;return!1}]],qi=[["balance_pairs",function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Fi(e.delimiters);for(let e=0;e<n;e++)t[e]&&t[e].delimiters&&Fi(t[e].delimiters)}],["strikethrough",Di.postProcess],["emphasis",Oi.postProcess],["fragments_join",function(e){let t,n,r=0;const i=e.tokens,s=e.tokens.length;for(t=n=0;t<s;t++)i[t].nesting<0&&r--,i[t].level=r,i[t].nesting>0&&r++,"text"===i[t].type&&t+1<s&&"text"===i[t+1].type?i[t+1].content=i[t].content+i[t+1].content:(t!==n&&(i[n]=i[t]),n++);t!==n&&(i.length=n)}]];function zi(){this.ruler=new Yr;for(let e=0;e<Bi.length;e++)this.ruler.push(Bi[e][0],Bi[e][1]);this.ruler2=new Yr;for(let e=0;e<qi.length;e++)this.ruler2.push(qi[e][0],qi[e][1])}function Ui(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(n){e[n]=t[n]})}),e}function Vi(e){return Object.prototype.toString.call(e)}function Wi(e){return"[object Function]"===Vi(e)}function Ki(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}zi.prototype.skipToken=function(e){const t=e.pos,n=this.ruler.getRules(""),r=n.length,i=e.md.options.maxNesting,s=e.cache;if(void 0!==s[t])return void(e.pos=s[t]);let o=!1;if(e.level<i){for(let i=0;i<r;i++)if(e.level++,o=n[i](e,!0),e.level--,o){if(t>=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;o||e.pos++,s[t]=e.pos},zi.prototype.tokenize=function(e){const t=this.ruler.getRules(""),n=t.length,r=e.posMax,i=e.md.options.maxNesting;for(;e.pos<r;){const s=e.pos;let o=!1;if(e.level<i)for(let r=0;r<n;r++)if(o=t[r](e,!1),o){if(s>=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(o){if(e.pos>=r)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},zi.prototype.parse=function(e,t,n,r){const i=new this.State(e,t,n,r);this.tokenize(i);const s=this.ruler2.getRules(""),o=s.length;for(let e=0;e<o;e++)s[e](i)},zi.prototype.State=xi;const Gi={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};const Hi={"http:":{validate:function(e,t,n){const r=e.slice(t);return n.re.http||(n.re.http=new RegExp(`^\\/\\/${n.re.src_auth}${n.re.src_host_port_strict}${n.re.src_path}`,"i")),n.re.http.test(r)?r.match(n.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(e,t,n){const r=e.slice(t);return n.re.no_http||(n.re.no_http=new RegExp("^"+n.re.src_auth+`(?:localhost|(?:(?:${n.re.src_domain})\\.)+${n.re.src_domain_root})`+n.re.src_port+n.re.src_host_terminator+n.re.src_path,"i")),n.re.no_http.test(r)?t>=3&&":"===e[t-3]||t>=3&&"/"===e[t-3]?0:r.match(n.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,n){const r=e.slice(t);return n.re.mailto||(n.re.mailto=new RegExp(`^${n.re.src_email_name}@${n.re.src_host_strict}`,"i")),n.re.mailto.test(r)?r.match(n.re.mailto)[0].length:0}}},Yi="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function Ji(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=Qn.source,t.src_Cc=Xn.source,t.src_Z=nr.source,t.src_P=er.source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|");const n="[><|]";return t.src_pseudo_letter=`(?:(?!${n}|${t.src_ZPCc})${t.src_Any})`,t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth=`(?:(?:(?!${t.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`,t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator=`(?=$|${n}|${t.src_ZPCc})(?!${e["---"]?"-(?!--)|":"-|"}_|:\\d|\\.-|\\.(?!$|${t.src_ZPCc}))`,t.src_path=`(?:[/?#](?:(?!${t.src_ZCc}|${n}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${t.src_ZCc}|\\]).)*\\]|\\((?:(?!${t.src_ZCc}|[)]).)*\\)|\\{(?:(?!${t.src_ZCc}|[}]).)*\\}|\\"(?:(?!${t.src_ZCc}|["]).)+\\"|\\'(?:(?!${t.src_ZCc}|[']).)+\\'|\\'(?=${t.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${t.src_ZCc}|[.]|$)|`+(e["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+`,(?!${t.src_ZCc}|$)|`+`;(?!${t.src_ZCc}|$)|`+`\\!+(?!${t.src_ZCc}|[!]|$)|`+`\\?(?!${t.src_ZCc}|[?]|$))+|\\/)?`,t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+`${t.src_pseudo_letter}{1,63})`,t.src_domain="(?:"+t.src_xn+"|"+`(?:${t.src_pseudo_letter})|`+`(?:${t.src_pseudo_letter}(?:-|${t.src_pseudo_letter}){0,61}${t.src_pseudo_letter}))`,t.src_host=`(?:(?:(?:(?:${t.src_domain})\\.)*${t.src_domain}))`,t.tpl_host_fuzzy="(?:"+t.src_ip4+"|"+`(?:(?:(?:${t.src_domain})\\.)+(?:%TLDS%)))`,t.tpl_host_no_ip_fuzzy=`(?:(?:(?:${t.src_domain})\\.)+(?:%TLDS%))`,t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test=`localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${t.src_ZPCc}|>|$))`,t.tpl_email_fuzzy=`(^|${n}|"|\\(|${t.src_ZCc})(${t.src_email_name}@${t.tpl_host_fuzzy_strict})`,t.tpl_link_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${t.src_ZPCc}))((?![$+<=>^\`||])${t.tpl_host_port_fuzzy_strict}${t.src_path})`,t.tpl_link_no_ip_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${t.src_ZPCc}))((?![$+<=>^\`||])${t.tpl_host_port_no_ip_fuzzy_strict}${t.src_path})`,t}(e.__opts__),n=e.__tlds__.slice();function r(e){return e.replace("%TLDS%",t.src_tlds)}e.onCompile(),e.__tlds_replaced__||n.push("a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"),n.push(t.src_xn),t.src_tlds=n.join("|"),t.email_fuzzy=RegExp(r(t.tpl_email_fuzzy),"i"),t.email_fuzzy_global=RegExp(r(t.tpl_email_fuzzy),"ig"),t.link_fuzzy=RegExp(r(t.tpl_link_fuzzy),"i"),t.link_fuzzy_global=RegExp(r(t.tpl_link_fuzzy),"ig"),t.link_no_ip_fuzzy=RegExp(r(t.tpl_link_no_ip_fuzzy),"i"),t.link_no_ip_fuzzy_global=RegExp(r(t.tpl_link_no_ip_fuzzy),"ig"),t.host_fuzzy_test=RegExp(r(t.tpl_host_fuzzy_test),"i");const i=[];function s(e,t){throw new Error(`(LinkifyIt) Invalid schema "${e}": ${t}`)}e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){const n=e.__schemas__[t];if(null===n)return;const r={validate:null,link:null};if(e.__compiled__[t]=r,"[object Object]"===Vi(n))return!function(e){return"[object RegExp]"===Vi(e)}(n.validate)?Wi(n.validate)?r.validate=n.validate:s(t,n):r.validate=function(e){return function(t,n){const r=t.slice(n);return e.test(r)?r.match(e)[0].length:0}}(n.validate),void(Wi(n.normalize)?r.normalize=n.normalize:n.normalize?s(t,n):r.normalize=function(e,t){t.normalize(e)});!function(e){return"[object String]"===Vi(e)}(n)?s(t,n):i.push(t)}),i.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize)}),e.__compiled__[""]={validate:null,normalize:function(e,t){t.normalize(e)}};const o=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(Ki).join("|");e.re.schema_test=RegExp(`(^|(?!_)(?:[><|]|${t.src_ZPCc}))(${o})`,"i"),e.re.schema_search=RegExp(`(^|(?!_)(?:[><|]|${t.src_ZPCc}))(${o})`,"ig"),e.re.schema_at_start=RegExp(`^${e.re.schema_search.source}`,"i"),e.re.pretest=RegExp(`(${e.re.schema_test.source})|(${e.re.host_fuzzy_test.source})|@`,"i")}function Zi(e,t,n,r){const i=e.slice(n,r);this.schema=t.toLowerCase(),this.index=n,this.lastIndex=r,this.raw=i,this.text=i,this.url=i}function Qi(e,t){if(!(this instanceof Qi))return new Qi(e,t);var n;t||(n=e,Object.keys(n||{}).reduce(function(e,t){return e||Gi.hasOwnProperty(t)},!1)&&(t=e,e={})),this.__opts__=Ui({},Gi,t),this.__schemas__=Ui({},Hi,e),this.__compiled__={},this.__tlds__=Yi,this.__tlds_replaced__=!1,this.re={},Ji(this)}Qi.prototype.add=function(e,t){return this.__schemas__[e]=t,Ji(this),this},Qi.prototype.set=function(e){return this.__opts__=Ui(this.__opts__,e),this},Qi.prototype.test=function(e){if(!e.length)return!1;let t,n;if(this.re.schema_test.test(e))for(n=this.re.schema_search,n.lastIndex=0;null!==(t=n.exec(e));)if(this.testSchemaAt(e,t[2],n.lastIndex))return!0;return!!(this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&e.search(this.re.host_fuzzy_test)>=0&&null!==e.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy))||!!(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&e.indexOf("@")>=0&&null!==e.match(this.re.email_fuzzy))},Qi.prototype.pretest=function(e){return this.re.pretest.test(e)},Qi.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},Qi.prototype.match=function(e){const t=[],n=[],r=[],i=[];let s,o,a;function c(e,t){return e?t?e.index!==t.index?e.index<t.index?e:t:e.lastIndex>=t.lastIndex?e:t:e:t}if(!e.length)return null;if(this.re.schema_test.test(e))for(a=this.re.schema_search,a.lastIndex=0;null!==(s=a.exec(e));)o=this.testSchemaAt(e,s[2],a.lastIndex),o&&n.push({schema:s[2],index:s.index+s[1].length,lastIndex:s.index+s[0].length+o});if(this.__opts__.fuzzyLink&&this.__compiled__["http:"])for(a=this.__opts__.fuzzyIP?this.re.link_fuzzy_global:this.re.link_no_ip_fuzzy_global,a.lastIndex=0;null!==(s=a.exec(e));)r.push({schema:"",index:s.index+s[1].length,lastIndex:s.index+s[0].length});if(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"])for(a=this.re.email_fuzzy_global,a.lastIndex=0;null!==(s=a.exec(e));)i.push({schema:"mailto:",index:s.index+s[1].length,lastIndex:s.index+s[0].length});const l=[0,0,0];let u=0;for(;;){const s=[n[l[0]],i[l[1]],r[l[2]]],o=c(c(s[0],s[1]),s[2]);if(!o)break;if(o===s[0]?l[0]++:o===s[1]?l[1]++:l[2]++,o.index<u)continue;const a=new Zi(e,o.schema,o.index,o.lastIndex);this.__compiled__[a.schema].normalize(a,this),t.push(a),u=o.lastIndex}return t.length?t:null},Qi.prototype.matchAtStart=function(e){if(!e.length)return null;const t=this.re.schema_at_start.exec(e);if(!t)return null;const n=this.testSchemaAt(e,t[2],t[0].length);if(!n)return null;const r=new Zi(e,t[2],t.index+t[1].length,t.index+t[0].length+n);return this.__compiled__[r.schema].normalize(r,this),r},Qi.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,n){return e!==n[t-1]}).reverse(),Ji(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,Ji(this),this)},Qi.prototype.normalize=function(e){e.schema||(e.url=`http://${e.url}`),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url=`mailto:${e.url}`)},Qi.prototype.onCompile=function(){};const Xi=2147483647,es=36,ts=/^xn--/,ns=/[^\0-\x7F]/,rs=/[\x2E\u3002\uFF0E\uFF61]/g,is={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},ss=Math.floor,os=String.fromCharCode;function as(e){throw new RangeError(is[e])}function cs(e,t){const n=e.split("@");let r="";n.length>1&&(r=n[0]+"@",e=n[1]);const i=function(e,t){const n=[];let r=e.length;for(;r--;)n[r]=t(e[r]);return n}((e=e.replace(rs,".")).split("."),t).join(".");return r+i}function ls(e){const t=[];let n=0;const r=e.length;for(;n<r;){const i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<r){const r=e.charCodeAt(n++);56320==(64512&r)?t.push(((1023&i)<<10)+(1023&r)+65536):(t.push(i),n--)}else t.push(i)}return t}const us=function(e){return e>=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:es},ds=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},ps=function(e,t,n){let r=0;for(e=n?ss(e/700):e>>1,e+=ss(e/t);e>455;r+=es)e=ss(e/35);return ss(r+36*e/(e+38))},hs=function(e){const t=[],n=e.length;let r=0,i=128,s=72,o=e.lastIndexOf("-");o<0&&(o=0);for(let n=0;n<o;++n)e.charCodeAt(n)>=128&&as("not-basic"),t.push(e.charCodeAt(n));for(let a=o>0?o+1:0;a<n;){const o=r;for(let t=1,i=es;;i+=es){a>=n&&as("invalid-input");const o=us(e.charCodeAt(a++));o>=es&&as("invalid-input"),o>ss((Xi-r)/t)&&as("overflow"),r+=o*t;const c=i<=s?1:i>=s+26?26:i-s;if(o<c)break;const l=es-c;t>ss(Xi/l)&&as("overflow"),t*=l}const c=t.length+1;s=ps(r-o,c,0==o),ss(r/c)>Xi-i&&as("overflow"),i+=ss(r/c),r%=c,t.splice(r++,0,i)}return String.fromCodePoint(...t)},fs=function(e){const t=[],n=(e=ls(e)).length;let r=128,i=0,s=72;for(const n of e)n<128&&t.push(os(n));const o=t.length;let a=o;for(o&&t.push("-");a<n;){let n=Xi;for(const t of e)t>=r&&t<n&&(n=t);const c=a+1;n-r>ss((Xi-i)/c)&&as("overflow"),i+=(n-r)*c,r=n;for(const n of e)if(n<r&&++i>Xi&&as("overflow"),n===r){let e=i;for(let n=es;;n+=es){const r=n<=s?1:n>=s+26?26:n-s;if(e<r)break;const i=e-r,o=es-r;t.push(os(ds(r+i%o,0))),e=ss(i/o)}t.push(os(ds(e,0))),s=ps(i,c,a===o),i=0,++a}++i,++r}return t.join("")},ms=function(e){return cs(e,function(e){return ns.test(e)?"xn--"+fs(e):e})},gs=function(e){return cs(e,function(e){return ts.test(e)?hs(e.slice(4).toLowerCase()):e})};const ys={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}},zero:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","fragments_join"]}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","fragments_join"]}}}},bs=/^(vbscript|javascript|file|data):/,ws=/^data:image\/(gif|png|jpeg|webp);/;function vs(e){const t=e.trim().toLowerCase();return!bs.test(t)||ws.test(t)}const ks=["http:","https:","mailto:"];function Is(e){const t=Yn(e,!0);if(t.hostname&&(!t.protocol||ks.indexOf(t.protocol)>=0))try{t.hostname=ms(t.hostname)}catch(e){}return Rn(Ln(t))}function Es(e){const t=Yn(e,!0);if(t.hostname&&(!t.protocol||ks.indexOf(t.protocol)>=0))try{t.hostname=gs(t.hostname)}catch(e){}return Pn(Ln(t),Pn.defaultChars+"%")}function As(e,t){if(!(this instanceof As))return new As(e,t);t||wr(e)||(t=e||{},e="default"),this.inline=new zi,this.block=new _i,this.core=new fi,this.renderer=new Hr,this.linkify=new Qi,this.validateLink=vs,this.normalizeLink=Is,this.normalizeLinkText=Es,this.utils=Wr,this.helpers=kr({},Kr),this.options={},this.configure(e),t&&this.set(t)}function Ss(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _s,xs;function Cs(){if(xs)return _s;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],i=typeof r;"object"!==i&&"function"!==i||Object.isFrozen(r)||e(r)}),t}xs=1;class t{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...t){const n=Object.create(null);for(const t in e)n[t]=e[t];return t.forEach(function(e){for(const t in e)n[t]=e[t]}),n}const i=e=>!!e.scope;class s{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=n(e)}openNode(e){if(!i(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){i(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const o=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class a{constructor(){this.rootNode=o(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=o({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{a._collapse(e)}))}}class c extends a{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new s(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function l(e){return e?"string"==typeof e?e:e.source:null}function u(e){return h("(?=",e,")")}function d(e){return h("(?:",e,")*")}function p(e){return h("(?:",e,")?")}function h(...e){return e.map(e=>l(e)).join("")}function f(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>l(e)).join("|")+")"}function m(e){return new RegExp(e.toString()+"|").exec("").length-1}const g=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function y(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=l(e),i="";for(;r.length>0;){const e=g.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+String(Number(e[1])+t):(i+=e[0],"("===e[0]&&n++)}return i}).map(e=>`(${e})`).join(t)}const b="[a-zA-Z]\\w*",w="[a-zA-Z_]\\w*",v="\\b\\d+(\\.\\d+)?",k="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",I="\\b(0b[01]+)",E={begin:"\\\\[\\s\\S]",relevance:0},A={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[E]},S={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[E]},_=function(e,t,n={}){const i=r({scope:"comment",begin:e,end:t,contains:[]},n);i.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const s=f("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return i.contains.push({begin:h(/[ ]+/,"(",s,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i},x=_("//","$"),C=_("/\\*","\\*/"),T=_("#","$"),N={scope:"number",begin:v,relevance:0},M={scope:"number",begin:k,relevance:0},D={scope:"number",begin:I,relevance:0},P={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[E,{begin:/\[/,end:/\]/,relevance:0,contains:[E]}]},O={scope:"title",begin:b,relevance:0},R={scope:"title",begin:w,relevance:0},L={begin:"\\.\\s*"+w,relevance:0};var $=Object.freeze({__proto__:null,APOS_STRING_MODE:A,BACKSLASH_ESCAPE:E,BINARY_NUMBER_MODE:D,BINARY_NUMBER_RE:I,COMMENT:_,C_BLOCK_COMMENT_MODE:C,C_LINE_COMMENT_MODE:x,C_NUMBER_MODE:M,C_NUMBER_RE:k,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:T,IDENT_RE:b,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:L,NUMBER_MODE:N,NUMBER_RE:v,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:S,REGEXP_MODE:P,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=h(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:O,UNDERSCORE_IDENT_RE:w,UNDERSCORE_TITLE_MODE:R});function j(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function F(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function B(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=j,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function q(e,t){Array.isArray(e.illegal)&&(e.illegal=f(...e.illegal))}function z(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function U(e,t){void 0===e.relevance&&(e.relevance=1)}const V=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=h(n.beforeMatch,u(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},W=["of","and","for","in","not","or","if","then","parent","list","value"];function K(e,t,n="keyword"){const r=Object.create(null);return"string"==typeof e?i(n,e.split(" ")):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,K(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,G(n[0],n[1])]})}}function G(e,t){return t?Number(t):function(e){return W.includes(e.toLowerCase())}(e)?0:1}const H={},Y=e=>{console.error(e)},J=(e,...t)=>{console.log(`WARN: ${e}`,...t)},Z=(e,t)=>{H[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),H[`${e}/${t}`]=!0)},Q=new Error;function X(e,t,{key:n}){let r=0;const i=e[n],s={},o={};for(let e=1;e<=t.length;e++)o[e+r]=i[e],s[e+r]=!0,r+=m(t[e-1]);e[n]=o,e[n]._emit=s,e[n]._multi=!0}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw Y("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),Q;if("object"!=typeof e.beginScope||null===e.beginScope)throw Y("beginScope must be object"),Q;X(e,e.begin,{key:"beginScope"}),e.begin=y(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw Y("skip, excludeEnd, returnEnd not compatible with endScope: {}"),Q;if("object"!=typeof e.endScope||null===e.endScope)throw Y("endScope must be object"),Q;X(e,e.end,{key:"endScope"}),e.end=y(e.end,{joinWith:""})}}(e)}function te(e){function t(t,n){return new RegExp(l(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=m(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(y(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class i{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(s,o){const a=s;if(s.isCompiled)return a;[F,z,ee,V].forEach(e=>e(s,o)),e.compilerExtensions.forEach(e=>e(s,o)),s.__beforeBegin=null,[B,q,U].forEach(e=>e(s,o)),s.isCompiled=!0;let c=null;return"object"==typeof s.keywords&&s.keywords.$pattern&&(s.keywords=Object.assign({},s.keywords),c=s.keywords.$pattern,delete s.keywords.$pattern),c=c||/\w+/,s.keywords&&(s.keywords=K(s.keywords,e.case_insensitive)),a.keywordPatternRe=t(c,!0),o&&(s.begin||(s.begin=/\B|\b/),a.beginRe=t(a.begin),s.end||s.endsWithParent||(s.end=/\B|\b/),s.end&&(a.endRe=t(a.end)),a.terminatorEnd=l(a.end)||"",s.endsWithParent&&o.terminatorEnd&&(a.terminatorEnd+=(s.end?"|":"")+o.terminatorEnd)),s.illegal&&(a.illegalRe=t(s.illegal)),s.contains||(s.contains=[]),s.contains=[].concat(...s.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?s:e)})),s.contains.forEach(function(e){n(e,a)}),s.starts&&n(s.starts,o),a.matcher=function(e){const t=new i;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(a),a}(e)}function ne(e){return!!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const ie=n,se=r,oe=Symbol("nomatch"),ae=function(n){const r=Object.create(null),i=Object.create(null),s=[];let o=!0;const a="Could not find the language '{}', did you forget to load/include a language module?",l={disableAutodetect:!0,name:"Plain text",contains:[]};let m={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:c};function g(e){return m.noHighlightRe.test(e)}function y(e,t,n){let r="",i="";"object"==typeof t?(r=e,n=t.ignoreIllegals,i=t.language):(Z("10.7.0","highlight(lang, code, ...args) has been deprecated."),Z("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),i=e,r=t),void 0===n&&(n=!0);const s={code:r,language:i};_("before:highlight",s);const o=s.result?s.result:b(s.language,s.code,n);return o.code=s.code,_("after:highlight",o),o}function b(e,n,i,s){const c=Object.create(null);function l(e,t){return e.keywords[t]}function u(){if(!x.keywords)return void T.addText(N);let e=0;x.keywordPatternRe.lastIndex=0;let t=x.keywordPatternRe.exec(N),n="";for(;t;){n+=N.substring(e,t.index);const r=A.case_insensitive?t[0].toLowerCase():t[0],i=l(x,r);if(i){const[e,s]=i;if(T.addText(n),n="",c[r]=(c[r]||0)+1,c[r]<=7&&(M+=s),e.startsWith("_"))n+=t[0];else{const n=A.classNameAliases[e]||e;p(t[0],n)}}else n+=t[0];e=x.keywordPatternRe.lastIndex,t=x.keywordPatternRe.exec(N)}n+=N.substring(e),T.addText(n)}function d(){null!=x.subLanguage?function(){if(""===N)return;let e=null;if("string"==typeof x.subLanguage){if(!r[x.subLanguage])return void T.addText(N);e=b(x.subLanguage,N,!0,C[x.subLanguage]),C[x.subLanguage]=e._top}else e=w(N,x.subLanguage.length?x.subLanguage:null);x.relevance>0&&(M+=e.relevance),T.__addSublanguage(e._emitter,e.language)}():u(),N=""}function p(e,t){""!==e&&(T.startScope(t),T.addText(e),T.endScope())}function h(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=A.classNameAliases[e[n]]||e[n],i=t[n];r?p(i,r):(N=i,u(),N=""),n++}}function f(e,t){return e.scope&&"string"==typeof e.scope&&T.openNode(A.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(p(N,A.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),N=""):e.beginScope._multi&&(h(e.beginScope,t),N="")),x=Object.create(e,{parent:{value:x}}),x}function g(e,n,r){let i=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(i){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return g(e.parent,n,r)}function y(e){return 0===x.matcher.regexIndex?(N+=e[0],1):(O=!0,0)}function v(e){const t=e[0],r=n.substring(e.index),i=g(x,e,r);if(!i)return oe;const s=x;x.endScope&&x.endScope._wrap?(d(),p(t,x.endScope._wrap)):x.endScope&&x.endScope._multi?(d(),h(x.endScope,e)):s.skip?N+=t:(s.returnEnd||s.excludeEnd||(N+=t),d(),s.excludeEnd&&(N=t));do{x.scope&&T.closeNode(),x.skip||x.subLanguage||(M+=x.relevance),x=x.parent}while(x!==i.parent);return i.starts&&f(i.starts,e),s.returnEnd?0:t.length}let k={};function I(r,s){const a=s&&s[0];if(N+=r,null==a)return d(),0;if("begin"===k.type&&"end"===s.type&&k.index===s.index&&""===a){if(N+=n.slice(s.index,s.index+1),!o){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=k.rule,t}return 1}if(k=s,"begin"===s.type)return function(e){const n=e[0],r=e.rule,i=new t(r),s=[r.__beforeBegin,r["on:begin"]];for(const t of s)if(t&&(t(e,i),i.isMatchIgnored))return y(n);return r.skip?N+=n:(r.excludeBegin&&(N+=n),d(),r.returnBegin||r.excludeBegin||(N=n)),f(r,e),r.returnBegin?0:n.length}(s);if("illegal"===s.type&&!i){const e=new Error('Illegal lexeme "'+a+'" for mode "'+(x.scope||"<unnamed>")+'"');throw e.mode=x,e}if("end"===s.type){const e=v(s);if(e!==oe)return e}if("illegal"===s.type&&""===a)return N+="\n",1;if(P>1e5&&P>3*s.index){throw new Error("potential infinite loop, way more iterations than matches")}return N+=a,a.length}const A=E(e);if(!A)throw Y(a.replace("{}",e)),new Error('Unknown language: "'+e+'"');const S=te(A);let _="",x=s||S;const C={},T=new m.__emitter(m);!function(){const e=[];for(let t=x;t!==A;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>T.openNode(e))}();let N="",M=0,D=0,P=0,O=!1;try{if(A.__emitTokens)A.__emitTokens(n,T);else{for(x.matcher.considerAll();;){P++,O?O=!1:x.matcher.considerAll(),x.matcher.lastIndex=D;const e=x.matcher.exec(n);if(!e)break;const t=I(n.substring(D,e.index),e);D=e.index+t}I(n.substring(D))}return T.finalize(),_=T.toHTML(),{language:e,value:_,relevance:M,illegal:!1,_emitter:T,_top:x}}catch(t){if(t.message&&t.message.includes("Illegal"))return{language:e,value:ie(n),illegal:!0,relevance:0,_illegalBy:{message:t.message,index:D,context:n.slice(D-100,D+100),mode:t.mode,resultSoFar:_},_emitter:T};if(o)return{language:e,value:ie(n),illegal:!1,relevance:0,errorRaised:t,_emitter:T,_top:x};throw t}}function w(e,t){t=t||m.languages||Object.keys(r);const n=function(e){const t={value:ie(e),illegal:!1,relevance:0,_top:l,_emitter:new m.__emitter(m)};return t._emitter.addText(e),t}(e),i=t.filter(E).filter(S).map(t=>b(t,e,!1));i.unshift(n);const s=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(E(e.language).supersetOf===t.language)return 1;if(E(t.language).supersetOf===e.language)return-1}return 0}),[o,a]=s,c=o;return c.secondBest=a,c}function v(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=m.languageDetectRe.exec(t);if(n){const t=E(n[1]);return t||(J(a.replace("{}",n[1])),J("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>g(e)||E(e))}(e);if(g(n))return;if(_("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(m.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),m.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,s=n?y(r,{language:n,ignoreIllegals:!0}):w(r);e.innerHTML=s.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&i[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`)}(e,n,s.language),e.result={language:s.language,re:s.relevance,relevance:s.relevance},s.secondBest&&(e.secondBest={language:s.secondBest.language,relevance:s.secondBest.relevance}),_("after:highlightElement",{el:e,result:s,text:r})}let k=!1;function I(){if("loading"===document.readyState)return k||window.addEventListener("DOMContentLoaded",function(){I()},!1),void(k=!0);document.querySelectorAll(m.cssSelector).forEach(v)}function E(e){return e=(e||"").toLowerCase(),r[e]||r[i[e]]}function A(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function S(e){const t=E(e);return t&&!t.disableAutodetect}function _(e,t){const n=e;s.forEach(function(e){e[n]&&e[n](t)})}Object.assign(n,{highlight:y,highlightAuto:w,highlightAll:I,highlightElement:v,highlightBlock:function(e){return Z("10.7.0","highlightBlock will be removed entirely in v12.0"),Z("10.7.0","Please use highlightElement now."),v(e)},configure:function(e){m=se(m,e)},initHighlighting:()=>{I(),Z("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){I(),Z("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(e,t){let i=null;try{i=t(n)}catch(t){if(Y("Language definition for '{}' could not be registered.".replace("{}",e)),!o)throw t;Y(t),i=l}i.name||(i.name=e),r[e]=i,i.rawDefinition=t.bind(null,n),i.aliases&&A(i.aliases,{languageName:e})},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(i))i[t]===e&&delete i[t]},listLanguages:function(){return Object.keys(r)},getLanguage:E,registerAliases:A,autoDetection:S,inherit:se,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),s.push(e)},removePlugin:function(e){const t=s.indexOf(e);-1!==t&&s.splice(t,1)}}),n.debugMode=function(){o=!1},n.safeMode=function(){o=!0},n.versionString="11.11.1",n.regex={concat:h,lookahead:u,either:f,optional:p,anyNumberOfTimes:d};for(const t in $)"object"==typeof $[t]&&e($[t]);return Object.assign(n,$),n},ce=ae({});return ce.newInstance=()=>ae({}),_s=ce,ce.HighlightJS=ce,ce.default=ce,_s}As.prototype.set=function(e){return kr(this.options,e),this},As.prototype.configure=function(e){const t=this;if(wr(e)){const t=e;if(!(e=ys[t]))throw new Error('Wrong `markdown-it` preset "'+t+'", check name')}if(!e)throw new Error("Wrong `markdown-it` preset, can't be empty");return e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach(function(n){e.components[n].rules&&t[n].ruler.enableOnly(e.components[n].rules),e.components[n].rules2&&t[n].ruler2.enableOnly(e.components[n].rules2)}),this},As.prototype.enable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.enable(e,!0))},this),n=n.concat(this.inline.ruler2.enable(e,!0));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+r);return this},As.prototype.disable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.disable(e,!0))},this),n=n.concat(this.inline.ruler2.disable(e,!0));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+r);return this},As.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},As.prototype.parse=function(e,t){if("string"!=typeof e)throw new Error("Input data should be a String");const n=new this.core.State(e,this,t);return this.core.process(n),n.tokens},As.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},As.prototype.parseInline=function(e,t){const n=new this.core.State(e,this,t);return n.inlineMode=!0,this.core.process(n),n.tokens},As.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var Ts=Ss(Cs());const Ns="[A-Za-z$_][0-9A-Za-z$_]*",Ms=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Ds=["true","false","null","undefined","NaN","Infinity"],Ps=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Os=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Rs=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ls=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],$s=[].concat(Rs,Ps,Os);const js="[A-Za-z$_][0-9A-Za-z$_]*",Fs=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Bs=["true","false","null","undefined","NaN","Infinity"],qs=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],zs=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Us=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Vs=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Ws=[].concat(Us,qs,zs);function Ks(e){const t=e.regex,n=js,r="<>",i="</>",s={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const s=e.input.substring(n);((i=s.match(/^\s*=/))||(i=s.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},o={$pattern:js,keyword:Fs,literal:Bs,built_in:Ws,"variable.language":Vs},a="[0-9](_?[0-9])*",c=`\\.(${a})`,l="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",u={className:"number",variants:[{begin:`(\\b(${l})((${c})|\\.)?|(${c}))[eE][+-]?(${a})\\b`},{begin:`\\b(${l})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},h={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},f={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},m={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},g={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},y=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,{match:/\$\d+/},u];d.contains=y.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(y)});const b=[].concat(g,d.contains),w=b.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(b)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w},k={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...qs,...zs]}},E={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/};const A={match:t.concat(/\b/,function(e){return t.concat("(?!",e.join("|"),")")}([...Us,"super","import"].map(e=>`${e}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},S={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},_={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},x="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",C={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(x)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:w,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,g,{match:/\$\d+/},u,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},C,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[g,e.REGEXP_MODE,{className:"function",begin:x,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:s.begin,"on:begin":s.isTrulyOpeningTag,end:s.end}],subLanguage:"xml",contains:[{begin:s.begin,end:s.end,skip:!0,contains:["self"]}]}]},E,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},S,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},A,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},k,_,{match:/\$[(.]/}]}}const Gs=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Hs=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),Ys=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Js=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Zs=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();Ts.registerLanguage("javascript",function(e){const t=e.regex,n=Ns,r="<>",i="</>",s={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const s=e.input.substring(n);((i=s.match(/^\s*=/))||(i=s.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},o={$pattern:Ns,keyword:Ms,literal:Ds,built_in:$s,"variable.language":Ls},a="[0-9](_?[0-9])*",c=`\\.(${a})`,l="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",u={className:"number",variants:[{begin:`(\\b(${l})((${c})|\\.)?|(${c}))[eE][+-]?(${a})\\b`},{begin:`\\b(${l})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},h={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},f={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},m={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},g={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},y=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,{match:/\$\d+/},u];d.contains=y.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(y)});const b=[].concat(g,d.contains),w=b.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(b)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w},k={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...Ps,...Os]}},E={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/},A={match:t.concat(/\b/,function(e){return t.concat("(?!",e.join("|"),")")}([...Rs,"super","import"].map(e=>`${e}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},S={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},_={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},x="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",C={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(x)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:w,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,h,f,m,g,{match:/\$\d+/},u,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},C,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[g,e.REGEXP_MODE,{className:"function",begin:x,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:w}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:s.begin,"on:begin":s.isTrulyOpeningTag,end:s.end}],subLanguage:"xml",contains:[{begin:s.begin,end:s.end,skip:!0,contains:["self"]}]}]},E,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},S,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},A,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},k,_,{match:/\$[(.]/}]}}),Ts.registerLanguage("typescript",function(e){const t=e.regex,n=Ks(e),r=js,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],s={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[n.exports.CLASS_REFERENCE]},a={$pattern:js,keyword:Fs.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:Bs,built_in:Ws.concat(i),"variable.language":Vs},c={className:"meta",begin:"@"+r},l=(e,t,n)=>{const r=e.contains.findIndex(e=>e.label===t);if(-1===r)throw new Error("can not find mode to replace");e.contains.splice(r,1,n)};Object.assign(n.keywords,a),n.exports.PARAMS_CONTAINS.push(c);const u=n.contains.find(e=>"attr"===e.scope),d=Object.assign({},u,{match:t.concat(r,t.lookahead(/\s*\?:/))});return n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,u,d]),n.contains=n.contains.concat([c,s,o,d]),l(n,"shebang",e.SHEBANG()),l(n,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/}),n.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}),Ts.registerLanguage("python",function(e){const t=e.regex,n=/[\p{XID_Start}_]\p{XID_Continue}*/u,r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},s={className:"meta",begin:/^(>>>|\.\.\.) /},o={className:"subst",begin:/\{/,end:/\}/,keywords:i,illegal:/#/},a={begin:/\{\{/,relevance:0},c={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,s],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,s],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,s,a,o]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,s,a,o]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,a,o]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,a,o]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l="[0-9](_?[0-9])*",u=`(\\b(${l}))?\\.(${l})|\\b(${l})\\.`,d=`\\b|${r.join("|")}`,p={className:"number",relevance:0,variants:[{begin:`(\\b(${l})|(${u}))[eE][+-]?(${l})[jJ]?(?=${d})`},{begin:`(${u})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${l})[jJ](?=${d})`}]},h={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},f={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:["self",s,p,c,e.HASH_COMMENT_MODE]}]};return o.contains=[c,p,s],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[s,p,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},c,h,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[f]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[p,f,c]}]}}),Ts.registerLanguage("json",function(e){const t=["true","false","null"],n={scope:"literal",beginKeywords:t.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,n,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}),Ts.registerLanguage("yaml",function(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(r,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),s={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},o={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},a={begin:/\{/,end:/\}/,contains:[o],illegal:"\\n",relevance:0},c={begin:"\\[",end:"\\]",contains:[o],illegal:"\\n",relevance:0},l=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},s,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},a,c,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},r],u=[...l];return u.pop(),u.push(i),o.contains=u,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:l}}),Ts.registerLanguage("bash",function(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const i={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},s=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},a={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(a);const c={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},l=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),u={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[l,e.SHEBANG(),u,c,s,o,{match:/(\/[a-z._-]+)+/},a,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},n]}}),Ts.registerLanguage("xml",function(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},s=e.inherit(i,{begin:/\(/,end:/\)/}),o=e.inherit(e.APOS_STRING_MODE,{className:"string"}),a=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[r]},{begin:/'/,end:/'/,contains:[r]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[i,a,o,s,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,s,a,o]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[a]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:c}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}),Ts.registerLanguage("css",function(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+Ys.join("|")+")"},{begin:":(:)?("+Js.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Zs.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:Hs.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Gs.join("|")+")\\b"}]}}),Ts.registerLanguage("sql",function(e){const t=e.regex,n=e.COMMENT("--","$"),r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],i=r,s=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!r.includes(e)),o={match:t.concat(/\b/,t.either(...i),/\s*\(/),relevance:0,keywords:{built_in:i}};function a(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const c={scope:"keyword",match:a(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:n}={}){const r=n;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}(s,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:a(["double precision","large object","with timezone","without timezone"])},c,o,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}),Ts.registerLanguage("markdown",function(e){const t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},n={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},r={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},s=e.inherit(r,{contains:[]}),o=e.inherit(i,{contains:[]});r.contains.push(o),i.contains.push(s);let a=[t,n];return[r,i,s,o].forEach(e=>{e.contains=e.contains.concat(a)}),a=a.concat(r,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:a},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:a}]}]},t,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},r,i,{className:"quote",begin:"^>\\s+",contains:a,end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},n,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}),Ts.registerLanguage("diff",function(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}});const Qs={js:"javascript",jsx:"javascript",mjs:"javascript",ts:"typescript",tsx:"typescript",py:"python",yml:"yaml",sh:"bash",shell:"bash",zsh:"bash",html:"xml",htm:"xml",md:"markdown"};function Xs(e){const t=new As({html:!1,linkify:!0,breaks:!0,highlight:e?(e,t)=>{const n=function(e){const t=(e||"").trim().toLowerCase();if(!t)return;const n=Qs[t]??t;return Ts.getLanguage(n)?n:void 0}(t);if(n)try{return Ts.highlight(e,{language:n,ignoreIllegals:!0}).value}catch{}return""}:void 0});return t}const eo=Xs(!0),to=Xs(!1);const no={ActivityBar:Zt,Statusbar:Qt,View:on,Views:un,KeyboardShortcuts:dn,Layout:bn,ContentTabs:wn,PanelTabs:vn,Profile:Mn,Markdown:{render:function(e,t){return(!1===t?.highlight?to:eo).render(String(e??""))},css:"\n.pnc-md { font-size: 14px; line-height: 1.65; word-break: break-word; }\n.pnc-md p { margin: 0 0 8px; }\n.pnc-md p:last-child { margin-bottom: 0; }\n.pnc-md h1, .pnc-md h2, .pnc-md h3,\n.pnc-md h4, .pnc-md h5, .pnc-md h6 {\n margin: 14px 0 6px;\n line-height: 1.3;\n font-weight: 600;\n}\n.pnc-md h1 { font-size: 1.4em; }\n.pnc-md h2 { font-size: 1.25em; }\n.pnc-md h3 { font-size: 1.12em; }\n.pnc-md h4 { font-size: 1em; }\n.pnc-md h5, .pnc-md h6 { font-size: 0.92em; color: var(--text-secondary, #9aa0a6); }\n.pnc-md ul, .pnc-md ol { margin: 0 0 8px; padding-left: 22px; }\n.pnc-md li { margin: 2px 0; }\n.pnc-md li:last-child { margin-bottom: 0; }\n.pnc-md a { color: var(--primary-main, #6ea8fe); text-decoration: underline; }\n.pnc-md blockquote {\n margin: 6px 0;\n padding: 2px 0 2px 12px;\n border-left: 3px solid var(--neutral-main, rgba(127, 127, 127, 0.35));\n color: var(--text-secondary, #9aa0a6);\n}\n.pnc-md table {\n border-collapse: collapse;\n margin: 8px 0;\n font-size: 13px;\n display: block;\n overflow-x: auto;\n}\n.pnc-md th, .pnc-md td {\n border: 1px solid var(--neutral-main, rgba(127, 127, 127, 0.3));\n padding: 4px 8px;\n text-align: left;\n}\n.pnc-md th { background: rgba(127, 127, 127, 0.12); font-weight: 600; }\n\n/* Inline code */\n.pnc-md code {\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n font-size: 0.92em;\n padding: 1px 5px;\n border-radius: 5px;\n background: rgba(127, 127, 127, 0.16);\n}\n\n/* Fenced code block — fixed dark surface (One Dark), independent of app theme */\n.pnc-md pre {\n margin: 6px 0 10px;\n border-radius: 8px;\n overflow: hidden;\n background: #282c34;\n border: 1px solid rgba(127, 127, 127, 0.28);\n}\n.pnc-md pre code {\n display: block;\n padding: 12px 14px;\n overflow-x: auto;\n background: none;\n border-radius: 0;\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n font-size: 12.5px;\n line-height: 1.55;\n color: #abb2bf;\n white-space: pre;\n}\n\n/* Code-block chrome (extension-added): top bar with language + copy button */\n.pnc-md-code { position: relative; }\n.pnc-md-code__bar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 4px 10px;\n background: #21252b;\n border-bottom: 1px solid rgba(127, 127, 127, 0.28);\n font-size: 11px;\n}\n.pnc-md-code__lang {\n color: #7f848e;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.pnc-md-code__copy {\n border: none;\n background: transparent;\n color: #abb2bf;\n cursor: pointer;\n font-size: 11px;\n padding: 2px 6px;\n border-radius: 4px;\n}\n.pnc-md-code__copy:hover { background: rgba(127, 127, 127, 0.2); }\n.pnc-md-code__copy--done { color: #98c379; }\n\n/* highlight.js — One Dark palette (matches the editor's code coloring) */\n.hljs-comment, .hljs-quote { color: #5c6370; font-style: italic; }\n.hljs-keyword, .hljs-selector-tag, .hljs-literal,\n.hljs-doctag, .hljs-name { color: #c678dd; }\n.hljs-built_in, .hljs-class .hljs-title, .hljs-title.class_,\n.hljs-attr, .hljs-attribute { color: #e5c07b; }\n.hljs-string, .hljs-symbol, .hljs-bullet,\n.hljs-addition, .hljs-regexp { color: #98c379; }\n.hljs-number, .hljs-meta .hljs-number { color: #d19a66; }\n.hljs-title, .hljs-title.function_, .hljs-section { color: #61afef; }\n.hljs-variable, .hljs-template-variable, .hljs-tag,\n.hljs-selector-id, .hljs-selector-class { color: #e06c75; }\n.hljs-meta, .hljs-comment .hljs-doctag { color: #56b6c2; }\n.hljs-deletion { color: #e06c75; }\n.hljs-emphasis { font-style: italic; }\n.hljs-strong { font-weight: 600; }\n"}};function ro(e,t){switch(e.mode){case"extension":return function(e,t){const n=t.path.split(".").pop();return!(!n||!1===t.path.endsWith(`.${n}`))&&n.toLowerCase()===e.toLowerCase()}(e.pattern,t);case"mime":return function(e,t){if(!t.mimeType)return!1;const n=e.toLowerCase(),r=t.mimeType.toLowerCase();if(n.endsWith("/*")){const e=n.slice(0,-2);return r.startsWith(e+"/")}return r===n}(e.pattern,t);case"glob":return function(e,t){const n="__DOUBLE_STAR_PLACEHOLDER__",r="__SINGLE_STAR_PLACEHOLDER__",i=e.replace(/\*\*/g,n).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),".*").replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"[^/]*");return new RegExp(`^${i}$`,"i").test(t.path)}(e.pattern,t);default:return!1}}const io=new class{#He=[];register(e){this.#He=this.#He.filter(t=>t.id!==e.id),this.#He.push({priority:0,...e}),this.#He.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#He=this.#He.filter(t=>t.id!==e)}clear(){this.#He=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#He){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>ro(t,e)))return console.log("[Runtime.FileOpeners] resolve",e.path,"→",n.id,"(",n.command,")"),{opener:n,command:n.command}}else t.push(n)}if(t.length>0){const n=t[0];return console.log("[Runtime.FileOpeners] resolve (fallback)",e.path,"→",n.id,"(",n.command,")"),{opener:n,command:n.command}}return console.warn("[Runtime.FileOpeners] resolve: no opener for",e.path),null}resolveAll(e){return this.#He.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>ro(t,e))}).map(e=>({opener:e,command:e.command}))}};let so,oo,ao,co,lo,uo;function po(){if(so)return so;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return so=punica.runtime.resources,so}function ho(){if(oo)return oo;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return oo=e,oo}function fo(){if(co)return co;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return co=e,co}function mo(){if(lo)return lo;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function go(){if(uo)return uo;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return uo=e,uo}function yo(e){let t,n;return{get(){if(void 0!==t)return t;const n=e.resolveHostFallback?.();if(void 0!==n)return t=n,t;throw new Error(e.noProviderMessage)},set(e){t=e,n=void 0},hasProvider:()=>void 0!==t,lastProviderId:()=>n,trackProviderId(e){const t=n;return n=e,{previous:t,changed:void 0!==t&&void 0!==e&&t!==e}}}}function bo(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!t?.publishEvent||!t?.createCorrelationId)&&(t.publishEvent({name:e.name,envelope:{id:t.createCorrelationId(),correlationId:e.correlationId,timestampMs:Date.now(),source:e.source,kind:e.kind??"info"},payload:e.payload}),!0)}catch{return!1}}const wo=yo({label:"Runtime.workspace",noProviderMessage:"[Runtime.workspace] No Workspace provider registered. Host must attach punica.runtime.workspace",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.workspace}});function vo(){return wo.get()}function ko(e){wo.set(e),e&&bo({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Io(e,t,n){try{const r=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!r?.publishEvent||!r?.createCorrelationId)&&(r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:t}),!0)}catch{return!1}}const Eo=Symbol("punica.llm.gatewayGovernedAi");let Ao,So,_o;function xo(){if(Ao)return Ao;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return Ao=punica.runtime.llm,Ao}function Co(e){if(Ao=e,So=void 0,_o=void 0,!e)return;const t=e;Io("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class To{providers=new Map;runtimes=new Map;registerProvider(e){if(!e.id)throw new Error("Provider must have an id");this.providers.set(e.id,e)}registerLanguageRuntime(e){if(!e.language)throw new Error("Language runtime must have a language");this.runtimes.set(e.language,e)}getProvider(e){return this.providers.get(e)}getLanguageRuntime(e){return this.runtimes.get(e)}listProviders(){return Array.from(this.providers.values())}}let No=null;function Mo(){return No||(No=new To),No}class Do{registry;constructor(e){this.registry=e}selectProvider(e){const t=e.provider?.id??"local",n=this.registry.getProvider(t);if(!n)throw new Error(`Compute provider not found: ${t}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return n}selectLanguageRuntime(e){const t=this.registry.getLanguageRuntime(e);if(!t)throw new Error(`Language runtime not found for language: ${e}. Available languages: ${Array.from(this.registry.runtimes.keys()).join(", ")}`);return t}resolveKernelSpec(e,t){return e.kernelspec?e.kernelspec:t.resolveKernelSpec?t.resolveKernelSpec(e):void 0}}class Po{providerSession;id;providerId;language;kernelspec;languageRuntime;constructor(e,t,n,r,i,s){this.providerSession=e,this.id=t,this.providerId=n,this.language=r,this.kernelspec=i,this.languageRuntime=s}run(e,t){const n=t?.runId??function(e="id"){const t=globalThis;if(t.crypto?.randomUUID)return`${e}_${t.crypto.randomUUID()}`;const n=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${n}`}("run"),r={id:this.id,providerId:this.providerId,language:this.language,kernelspec:this.kernelspec},i=this.languageRuntime.prepare(e,r);return this.providerSession.run(i,n,t)}async interrupt(){return this.providerSession.interrupt()}async restart(){return this.providerSession.restart()}async close(){return this.providerSession.close()}}const Oo={language:"python",resolveKernelSpec:e=>"python3",prepare(e,t){if("jeg"===t.providerId||void 0!==t.kernelspec)return{kind:"jupyter",code:e.code??"",kernelspec:t.kernelspec??"python3",env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata};return{kind:"process",command:["python","-u","-c",e.code??""],env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata}}},Ro={language:"node",resolveKernelSpec(e){},prepare(e,t){if("jeg"===t.providerId&&void 0!==t.kernelspec)return{kind:"jupyter",code:e.code??"",kernelspec:t.kernelspec,env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata};return{kind:"process",command:["node","-e",e.code??""],env:e.env,cwd:e.cwd,timeoutMs:e.resources?.timeoutMs,meta:e.metadata}}},Lo={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},$o={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},jo={language:"scala",resolveKernelSpec:e=>"spark-scala",prepare(e,t){throw new Error("Scala execution is not yet supported. Use Python or Node.js for now.")}};function Fo(e="id"){const t=globalThis;if(t.crypto?.randomUUID)return`${e}_${t.crypto.randomUUID()}`;const n=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${n}`}class Bo{registry;router;constructor(e,t){this.registry=e,this.router=t}async open(e){const t=this.router.selectProvider(e),n=this.router.selectLanguageRuntime(e.language),r=this.router.resolveKernelSpec(e,n),i=await t.openSession({...e,kernelspec:r}),s=Fo("session");return new Po(i,s,t.id,e.language,r,n)}}class qo{providers=new Map;registerProvider(e){if(!e.id)throw new Error("Dataset provider must have an id");this.providers.set(e.id,e)}getProvider(e){return this.providers.get(e)}listProviders(){return Array.from(this.providers.values())}}let zo=null;function Uo(){return zo||(zo=new qo),zo}class Vo{registry;constructor(e){this.registry=e}selectProvider(e){const t=this.registry.getProvider(e.provider);if(!t)throw new Error(`Dataset provider not found: ${e.provider}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return t}}class Wo{providers=new Map;registerProvider(e){if(!e.id)throw new Error("Model provider must have an id");this.providers.set(e.id,e)}getProvider(e){return this.providers.get(e)}listProviders(){return Array.from(this.providers.values())}}let Ko=null;function Go(){return Ko||(Ko=new Wo),Ko}class Ho{registry;constructor(e){this.registry=e}selectProvider(e){const t=this.registry.getProvider(e.provider);if(!t)throw new Error(`Model provider not found: ${e.provider}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return t}}class Yo{#Ye=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#Ye.set(e.id,e)}get(e){return this.#Ye.get(e)}list(){return Array.from(this.#Ye.values())}select(e){return this.list().find(t=>t.canRun(e))}}let Jo=null;function Zo(){return Jo||(Jo=new Yo),Jo}function Qo(e,t){const n=Math.min(e.length,t.length);let r=0,i=0,s=0;for(let o=0;o<n;o++)r+=e[o]*t[o],i+=e[o]*e[o],s+=t[o]*t[o];return 0===i||0===s?0:r/(Math.sqrt(i)*Math.sqrt(s))}const Xo="default";class ea{#Je=new Map;#Ze(e){const t=e||Xo;let n=this.#Je.get(t);return n||(n=new Map,this.#Je.set(t,n)),n}upsert(e,t=Xo){const n=this.#Ze(t);for(const t of e){if(!t||"string"!=typeof t.id)throw new Error("VectorRecord requires a string id.");n.set(t.id,t)}}query(e,t=10,n=Xo){const r=this.#Ze(n),i=[];for(const t of r.values())i.push({id:t.id,score:Qo(e,t.vector),text:t.text,metadata:t.metadata});return i.sort((e,t)=>t.score-e.score),i.slice(0,Math.max(0,t))}delete(e,t=Xo){const n=this.#Ze(t);for(const t of e)n.delete(t)}clear(e=Xo){this.#Je.delete(e||Xo)}count(e=Xo){return this.#Ze(e).size}export(e=Xo){return Array.from(this.#Ze(e).values())}import(e,t=Xo){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#Je.set(t||Xo,n)}}const ta=".punica/vectors";class na{#b=new ea;#Qe=new Set;#Xe(){try{return punica.runtime?.fs}catch{return}}#et(e){return`${ta}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#tt(e){const t=e||"default";if(this.#Qe.has(t))return;this.#Qe.add(t);const n=this.#Xe();if(n?.readFile)try{const e=await n.readFile(this.#et(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#b.import(r.records,t)}catch{}}async#nt(e){const t=this.#Xe();if(t)try{if(t.mkdir)try{await t.mkdir(ta)}catch{}const n={version:1,records:this.#b.export(e)},r=this.#et(e),i=JSON.stringify(n);try{await t.updateFileContent(r,i)}catch{await t.createFileWithContent(r,i)}}catch(e){console.warn("[Runtime.vectors] Failed to persist collection:",e)}}async upsert(e,t){const n=t?.collection??"default";await this.#tt(n),this.#b.upsert(e,n),await this.#nt(n)}async query(e){const t=e.collection??"default";return await this.#tt(t),this.#b.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#tt(n),this.#b.delete(e,n),await this.#nt(n)}async clear(e){const t=e?.collection??"default";await this.#tt(t),this.#b.clear(t),await this.#nt(t)}async count(e){const t=e?.collection??"default";return await this.#tt(t),this.#b.count(t)}}let ra,ia,sa;function oa(){return ra||(ia||(ia=new na),ia)}function aa(){if(!sa)throw new Error("[Runtime.host] No host data-dir provider is registered. This surface is only available on hosts with a real filesystem (e.g. Electron); a browser host does not provide a data directory.");return sa}var ca;!function(e){e.CAPABILITY_SPEC_INVALID="CAPABILITY_SPEC_INVALID",e.CAPABILITY_ALREADY_REGISTERED="CAPABILITY_ALREADY_REGISTERED",e.CAPABILITY_NOT_FOUND="CAPABILITY_NOT_FOUND",e.CAPABILITY_PROVIDER_MISSING="CAPABILITY_PROVIDER_MISSING",e.CAPABILITY_HANDLER_MISSING="CAPABILITY_HANDLER_MISSING",e.EXTENSION_ACTIVATION_FAILED="EXTENSION_ACTIVATION_FAILED",e.CAPABILITY_INPUT_INVALID="CAPABILITY_INPUT_INVALID",e.CAPABILITY_PATH_TRAVERSAL_DENIED="CAPABILITY_PATH_TRAVERSAL_DENIED",e.CAPABILITY_ENCRYPTION_REQUIRED="CAPABILITY_ENCRYPTION_REQUIRED",e.CAPABILITY_NOT_IN_PROFILE="CAPABILITY_NOT_IN_PROFILE",e.CAPABILITY_DENIED="CAPABILITY_DENIED",e.CAPABILITY_APPROVAL_REQUIRED="CAPABILITY_APPROVAL_REQUIRED",e.CAPABILITY_RATE_LIMITED="CAPABILITY_RATE_LIMITED",e.CAPABILITY_IDEMPOTENCY_KEY_MISSING="CAPABILITY_IDEMPOTENCY_KEY_MISSING",e.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED="CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED",e.CAPABILITY_CIRCUIT_OPEN="CAPABILITY_CIRCUIT_OPEN",e.CAPABILITY_TIMEOUT="CAPABILITY_TIMEOUT",e.CAPABILITY_PROVIDER_ERROR="CAPABILITY_PROVIDER_ERROR"}(ca||(ca={}));class la extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const ua=new class{#rt=new Map;#ne=new Map;registerCapability(e){if(!e.name)throw new la(ca.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" must have a version`,{capability:e.name});if(!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(e.version))throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" version "${e.version}" is not valid semver (expected MAJOR.MINOR.PATCH, e.g. "1.0.0")`,{capability:e.name,version:e.version});if(this.#rt.has(e.name))throw new la(ca.CAPABILITY_ALREADY_REGISTERED,`Capability "${e.name}" is already registered`,{capability:e.name});const t=function(e){const t=[];if(!e)return{ok:!0,errors:t};if(void 0!==e.timeoutMs&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)&&t.push(`timeoutMs must be a positive finite number, got ${e.timeoutMs}`),void 0!==e.retries&&(!Number.isInteger(e.retries)||e.retries<0)&&t.push(`retries must be a non-negative integer, got ${e.retries}`),void 0!==e.retryBackoffMs&&(!Number.isFinite(e.retryBackoffMs)||e.retryBackoffMs<=0)&&t.push(`retryBackoffMs must be a positive finite number, got ${e.retryBackoffMs}`),void 0!==e.rateLimit){const{perSecond:n}=e.rateLimit;(!Number.isFinite(n)||n<=0)&&t.push(`rateLimit.perSecond must be a positive finite number, got ${n}`)}if(void 0!==e.concurrency){const{key:n,max:r}=e.concurrency;"string"==typeof n&&0!==n.trim().length||t.push(`concurrency.key must be a non-empty string, got ${JSON.stringify(n)}`),(!Number.isInteger(r)||r<=0)&&t.push(`concurrency.max must be a positive integer, got ${r}`)}if(void 0!==e.circuitBreaker){const{failureThreshold:n,cooldownMs:r}=e.circuitBreaker;void 0!==n&&(!Number.isInteger(n)||n<=0)&&t.push(`circuitBreaker.failureThreshold must be a positive integer, got ${n}`),void 0!==r&&(!Number.isFinite(r)||r<=0)&&t.push(`circuitBreaker.cooldownMs must be a positive finite number, got ${r}`)}return{ok:0===t.length,errors:t}}(e.defaults);if(!t.ok)throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" has invalid middleware config: ${t.errors.join("; ")}`,{capability:e.name,errors:t.errors});if(e.requires&&e.requires.length>0){if(e.requires.includes(e.name))throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot require itself`,{capability:e.name,cycle:[e.name,e.name]});for(const t of e.requires){const n=this.#it(t,e.name);if(n)throw new la(ca.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#rt.set(e.name,e);try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.({name:"capability.registered",envelope:{id:`cap-reg-${e.name}-${Date.now()}`,correlationId:`cap-reg-${e.name}`,timestampMs:Date.now(),source:"runtime:capabilities:registry",kind:"info"},payload:{capability:e.name,version:e.version,origin:"core",risk:e.risk,sideEffect:e.sideEffect,deprecated:e.deprecated??null}})}catch{}}#it(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#rt.get(e);if(!r?.requires)return null;for(const i of r.requires){const r=this.#it(i,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#rt.has(e.name))throw new la(ca.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ne.set(e.name,e)}getSpec(e){return this.#rt.get(e)}getProvider(e){return this.#ne.get(e)}hasCapability(e){return this.#rt.has(e)}hasProvider(e){return this.#ne.has(e)}listCapabilities(){return Array.from(this.#rt.keys())}getAllSpecs(){return Array.from(this.#rt.values())}clear(){this.#rt.clear(),this.#ne.clear()}};function da(e){const t={id:e.name,title:e.name,version:e.version,policy:{risk:e.policy?.risk??e.risk,approval:e.policy?.approval??(r=e.risk,"high"===r?"step":"plan")},sideEffects:(n=e.sideEffect,"none"===n?[]:[n])};var n,r;return void 0!==e.inputSchema&&(t.inputs={schema:e.inputSchema}),void 0!==e.outputSchema&&(t.outputs={schema:e.outputSchema,kind:"direct"}),e.defaults&&(t.execution=function(e){const t={};void 0!==e.timeoutMs&&(t.timeoutMs=e.timeoutMs);void 0===e.retries&&void 0===e.retryBackoffMs||(t.retry={},void 0!==e.retries&&(t.retry.maxAttempts=e.retries),void 0!==e.retryBackoffMs&&(t.retry.initialDelayMs=e.retryBackoffMs));e.rateLimit&&(t.rateLimit={perSecond:e.rateLimit.perSecond});e.concurrency&&(t.concurrency={key:e.concurrency.key,max:e.concurrency.max});void 0!==e.idempotency&&(t.idempotency=e.idempotency);return t}(e.defaults)),e.deprecated&&(t.deprecated={...e.deprecated}),e.requires&&e.requires.length>0&&(t.requires=[...e.requires]),e.permissions&&e.permissions.length>0&&(t["x-permissions"]=[...e.permissions]),e.secretBearing&&(t["x-secretBearing"]=!0),t}function pa(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:ha(e.sideEffects),risk:e.policy?.risk??"low",permissions:n,inputSchema:e.inputs?.schema,outputSchema:e.outputs?.schema};return e.execution&&(r.defaults=function(e){const t={};void 0!==e.timeoutMs&&(t.timeoutMs=e.timeoutMs);void 0!==e.retry?.maxAttempts&&(t.retries=e.retry.maxAttempts);void 0!==e.retry?.initialDelayMs&&(t.retryBackoffMs=e.retry.initialDelayMs);void 0!==e.rateLimit?.perSecond&&(t.rateLimit={perSecond:e.rateLimit.perSecond});e.concurrency&&(t.concurrency={key:e.concurrency.key,max:e.concurrency.max});void 0!==e.idempotency&&(t.idempotency=e.idempotency);return t}(e.execution)),!0===t["x-secretBearing"]&&(r.secretBearing=!0),e.deprecated&&(r.deprecated={...e.deprecated}),Array.isArray(e.requires)&&e.requires.length>0&&(r.requires=[...e.requires]),e.policy&&(r.policy={...e.policy}),r}function ha(e){if(!e||0===e.length)return"none";const t=["none","read","write","network"];for(const n of e)if(t.includes(n))return n;return"none"}const fa=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function ma(){const e=globalThis;return e.punica?.extensions?.manager}function ga(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function ya(){const e=globalThis;return e.punica?.flow?.registry}function ba(){const e=globalThis;return e.punica?.flow?.agents}function wa(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const va={core:function(e){const t=ua.getSpec(e);if(t)return{origin:"core",definition:da(t)}},extension:function(e){const t=ma();if(!t)return;const n=t.getCapability(e);if(!n)return;const r=t.listCapabilities().find(t=>t.id===e);return{origin:"extension",definition:n,metadata:r?.extensionName?{extensionName:r.extensionName}:void 0}},"instruction-class":function(e){const t=ga();if(!t)return;const n=t.getCapability(e);if(!n)return;const r=t.get(e);return{origin:"instruction-class",definition:n,metadata:r?.productId?{productId:r.productId}:void 0}},"ivy-node":function(e){const t=ya();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-node",definition:r,metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},"ivy-agent":function(e){const t=ba();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-agent",definition:r,metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},mcp:function(e){const t=wa();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},ka={core:function(){return ua.getAllSpecs().map(e=>({origin:"core",definition:da(e)}))},extension:function(){const e=ma();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=ga();return e?e.listCapabilities().map(t=>{const n=e.get(t.id);return{origin:"instruction-class",definition:t,metadata:n?.productId?{productId:n.productId}:void 0}}):[]},"ivy-node":function(){const e=ya();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-node",definition:e,metadata:{packageRoot:n.manifestPath}})}return t},"ivy-agent":function(){const e=ba();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-agent",definition:e,metadata:{packageRoot:n.manifestPath}})}return t},mcp:function(){const e=wa();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Ia={getCapability(e){for(const t of fa){const n=va[t](e);if(n)return n}},listCapabilities(e){const t=(n=e?.origin,void 0===n?void 0:new Set(Array.isArray(n)?n:[n]));var n;const r=new Set,i=[];for(const e of fa)if(!t||t.has(e))for(const t of ka[e]()){const e=t.definition.id;r.has(e)||(r.add(e),i.push(t))}return i},hasCapability(e){return void 0!==this.getCapability(e)}};function Ea(e,t,n){switch(e){case"mcp":return function(e,t){const{mcpServerId:n,mcpToolName:r}=t;return{name:e.id,async execute(t,i){const s=globalThis.punica?.runtime?.mcp;if(!s?.callTool)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`MCP runtime is not initialized — cannot invoke "${e.id}". Ensure McpModule has started before calling MCP capabilities.`,{capability:e.id,origin:"mcp"});if(!n||!r)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`MCP capability "${e.id}" is missing serverId or toolName metadata`,{capability:e.id,origin:"mcp"});return await s.callTool(n,r,t??{})}}}(t,n??{});case"instruction-class":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.kernel?.llm?.api;if(!r?.invokeLlmCapability)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`LLM kernel API is not initialized — cannot invoke instruction-class capability "${e.id}".`,{capability:e.id,origin:"instruction-class"});const i=null!==t&&"object"==typeof t?t:{},s="string"==typeof i.instructionClass?i.instructionClass:e.id,o="string"==typeof i.userPrompt?i.userPrompt:"string"==typeof i.prompt?i.prompt:JSON.stringify(t);return await r.invokeLlmCapability({instructionClass:s,userPrompt:o,context:i.context??{}})}}}(t);case"ivy-node":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.runner;if(!r?.run)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Flow runner is not initialized — cannot invoke ivy-node capability "${e.id}". Ensure the flow module has started before calling IvyNode capabilities.`,{capability:e.id,origin:"ivy-node"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i});return s?.output??null}}}(t);case"ivy-agent":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.agents;if(!r?.run)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Agent registry is not initialized — cannot invoke ivy-agent capability "${e.id}". Ensure the flow module has started before calling IvyAgent capabilities.`,{capability:e.id,origin:"ivy-agent"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i});return s?.output??null}}}(t);case"extension":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.extensions?.manager;if(!r?.executeCapability)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Extension manager is not initialized — cannot invoke extension capability "${e.id}".`,{capability:e.id,origin:"extension"});return await r.executeCapability(e.id,t,n)}}}(t);case"core":throw new la(ca.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Aa={recordSpan:()=>{}};function Sa(e){try{Aa.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function _a(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,o={capability:i,"actor.type":s.actor.type,"origin.kind":s.origin.kind};s.actor.extensionName&&(o["actor.extension"]=s.actor.extensionName),s.origin.extension&&(o["origin.extension"]=s.origin.extension),s.workspaceId&&(o["workspace.id"]=s.workspaceId),r.tags={...r.tags,...o};try{const e=await t();return r.durationMs=Date.now()-r.startTimeMs,Sa({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"success",attributes:{...r.tags}}),e}catch(e){r.error=e instanceof Error?e:new Error(String(e)),r.durationMs=Date.now()-r.startTimeMs;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.failed",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,spanId:s.trace.parentSpanId??n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"error"},payload:{invocationId:n.invocationId,capability:i,error:r.error.message,durationMs:r.durationMs}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.failed event:",e)}throw Sa({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"error",errorCode:e instanceof la?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function xa(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(xa);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=xa(r);return t}return e}const Ca=new WeakMap;function Ta(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s}=n;if(!0===r.spec.secretBearing||i.startsWith("secrets."))r.redactedInput=xa(s);else{const e=function(e){const t=Ca.get(e);if(t)return t;const n=y(e.inputSchema);return Ca.set(e,n),n}(r.spec);r.redactedInput=e.length>0?b(s,e):s}return await t()}}function Na(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function Ma(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Na(t))}const Da=new class{validate(e,t){const n=[];if(!e||"object"!=typeof e)return{ok:!0,errors:n};const r=e,i=r.type;if(i&&(Ma(i,t)||n.push(`Expected type "${i}", got "${Na(t)}"`)),"object"===i&&t&&"object"==typeof t&&!Array.isArray(t)){const e=t,i=r.required,s=r.properties;if(Array.isArray(i))for(const t of i)t in e&&void 0!==e[t]||n.push(`Missing required field: "${t}"`);if(s)for(const[t,r]of Object.entries(e)){if(void 0===r)continue;const e=s[t];if(!e)continue;const i=e.type;i&&(Ma(i,r)||n.push(`Field "${t}": expected type "${i}", got "${Na(r)}"`))}}return{ok:0===n.length,errors:n}}};let Pa=Da;function Oa(){return Pa}function Ra(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=Oa().validate(s,i);if(!o.ok)throw new la(ca.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const La=yo({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function $a(){return La.get()}const ja=["path","oldPath","newPath","src","dst","target","linkPath"];function Fa(e,t){if(e.includes("\0"))return{ok:!1,reason:"null byte in path"};if(/(%2e|\.)(?:%2e|\.)/i.test(e)&&/%2e/i.test(e))return{ok:!1,reason:"URL-encoded traversal segment"};if(/^[A-Za-z]:[\\/]?/.test(e))return{ok:!1,reason:"drive-relative path"};if(e.startsWith("\\\\"))return{ok:!1,reason:"UNC path"};const n=e.replace(/\\/g,"/"),r=n.startsWith("/"),i=n.split("/").filter(e=>""!==e&&"."!==e),s=[];for(const e of i)if(".."===e){if(0===s.length)return{ok:!1,reason:"traversal above root"};s.pop()}else s.push(e);let o=(r?"/":"")+s.join("/");if(""===o&&(o=r?"/":"."),t&&r){const e=function(e){let t=e.replace(/\\/g,"/");t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1));return t}(t);if("/"===e);else if(o!==e&&!o.startsWith(`${e}/`))return{ok:!1,reason:"path is outside the workspace root"}}return{ok:!0,canonical:o}}function Ba(){try{return $a().cwd}catch{return}}function qa(){return async(e,t)=>{const{input:n}=e.req;if("object"!=typeof n||null===n)return await t();const r=n;let i,s=!1;for(const e of ja){const t=r[e];if("string"!=typeof t)continue;s||(i=Ba(),s=!0);const n=Fa(t,i);if(!n.ok)throw new la(ca.CAPABILITY_PATH_TRAVERSAL_DENIED,`Path traversal denied on field "${e}": ${n.reason}`,{field:e,reason:n.reason,value:t,...void 0!==i?{cwd:i}:{}})}return await t()}}const za="encrypted-at-rest";function Ua(){return async(e,t)=>{const n=e.state.spec;if("sensitive"!==(n.dataClassification??"internal"))return t();if(!(r=n.name).startsWith("fs.")&&!r.startsWith("workspace."))return t();var r;const i=function(){try{return $a()}catch{return}}();if(!i)throw new la(ca.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires an encryption-at-rest-capable FileSystemProvider, but no provider is registered`,{capability:n.name,required:za,reason:"provider not registered"});if(!i.capabilities?.has(za))throw new la(ca.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${za}" capability flag`,{capability:n.name,required:za,reason:"capability not advertised"});return bo({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:za}}),t()}}function Va(e,t,n,r,i){try{const s=globalThis.punica?.kernel?.Events?.manager;if(!s||"function"!=typeof s.publishEvent)return;s.publishEvent({name:"capability.denied_by_profile",source:"runtime:capabilities:middleware:profileBudget",kind:"warn",correlationId:i,payload:{invocationId:i,capability:e,profile:t,reason:n,origin:r??"unknown"}})}catch{}}function Wa(){return async(e,t)=>{const n=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()}catch{return}}();if(!n)return t();const{allowedIds:r,deniedIds:i,allowedOrigins:s}=n.capabilities;if("*"===r&&!i?.length&&!s?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(s&&s.length>0){const e=Ia.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw Va(o,c,"origin-not-allowed",t,a),new la(ca.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" origin "${t??"unknown"}" is not in profile "${c}" allowedOrigins`,{capability:o,profile:c,reason:"origin-not-allowed",origin:t??"unknown"})}if(i&&i.includes(o))throw Va(o,c,"in-denylist",void 0,a),new la(ca.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is explicitly denied by profile "${c}"`,{capability:o,profile:c,reason:"in-denylist"});if("*"!==r){const e=function(e){return"*"===e?"*":new Set(e)}(r);if("*"!==e&&!e.has(o))throw Va(o,c,"not-in-allowlist",void 0,a),new la(ca.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Ka={alg:"HS256",typ:"PUNICA-APPROVAL"};class Ga extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function Ha(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return("undefined"!=typeof btoa?btoa(t):globalThis.Buffer.from(e).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ya(e){const t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4);if("undefined"!=typeof atob){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}const n=globalThis.Buffer.from(t,"base64");return new Uint8Array(n)}function Ja(e){return(new TextEncoder).encode(e)}function Za(e){return Ha(Ja(JSON.stringify(e)))}function Qa(e){return JSON.parse((t=Ya(e),(new TextDecoder).decode(t)));var t}function Xa(){const e=globalThis.crypto?.subtle;if(!e)throw new Error("[ApprovalToken] crypto.subtle is unavailable. Host must inject a custom signer/verifier or run in an environment with Web Crypto (browser, Node 18+).");return e}function ec(){const e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("[ApprovalToken] crypto.getRandomValues unavailable.");const t=new Uint8Array(32);return e.getRandomValues(t),t}class tc{#st;#ot;constructor(e){e?.secret instanceof Uint8Array?this.#st=e.secret:this.#st="string"==typeof e?.secret?Ja(e.secret):ec()}async sign(e){const t=await this.#at(),n=Za(Ka),r=Za(e),i=Ja(`${n}.${r}`),s=await Xa().sign("HMAC",t,i);return`${n}.${r}.${Ha(new Uint8Array(s))}`}getSecret(){return this.#st}async#at(){return this.#ot||(this.#ot=await Xa().importKey("raw",this.#st,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#ot}}class nc{#st;#ot;#ct=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#st=e.secret:this.#st="string"==typeof e?.secret?Ja(e.secret):ec()}async verify(e){const t=e.split(".");if(3!==t.length)throw new Ga("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=Qa(n)}catch{throw new Ga("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new Ga("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=Qa(r)}catch{throw new Ga("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#at(),c=Ja(`${n}.${r}`);let l;try{l=Ya(i)}catch{throw new Ga("MALFORMED","Token signature is not valid base64url")}const u=Xa();if(!await u.verify("HMAC",a,l,c))throw new Ga("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new Ga("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new Ga("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#ct.add(e)}isRevoked(e){return this.#ct.has(e)}async#at(){return this.#ot||(this.#ot=await Xa().importKey("raw",this.#st,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#ot}}let rc;function ic(){return rc||(rc=function(){const e=new tc,t=new nc({secret:e.getSecret()});return{signer:e,verifier:t}}()),rc}const sc=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function oc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=globalThis.punica?.kernel?.Policy?.manager;if(!a){const e=o.policy??{},a=e.risk??o.risk??"low",c=e.approval??"none",l="high"===a||"step"===c||"plan"===c,u=!0===globalThis.punica?.kernel?.Policy?.failClosed,d=u&&l;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"policy.manager.missing",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:d?"error":"warning"},payload:{capability:i,risk:a,approval:c,actor:s.actor,decision:d?"deny":"allow",failClosed:u}})}catch{}if(console.warn(`[CapabilityGateway] Policy manager not available for "${i}" (risk=${a}, approval=${c}); `+(d?"DENYING (fail-closed)":"allowing (fail-open)")+"."),d)throw new la(ca.CAPABILITY_DENIED,`Policy manager unavailable and capability "${i}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:i,reason:"policy-manager-missing",risk:a,approval:c});return r.policyDecision={allowed:!0,requiresApproval:!1,reason:"policy-manager-missing (fail-open)"},await t()}const c=o.policy??{},l=c.risk??o.risk??"low",u=c.approval??"none";let d=!1,p="";if("ai"===s.actor.type){"approval"===sc({capabilityId:i,risk:o.risk,sideEffect:o.sideEffect})&&(d=!0,p=`agent-mode policy: ${o.sideEffect}/${o.risk}`)}"high"===o.risk&&(d=!0,p="High risk capability"),"step"!==u&&"plan"!==u||(d=!0,p=`Capability requires ${u} approval`);const h={kind:"capability",id:i,risk:l,approval:u,reason:o.description??o.title??`Capability: ${i}`},f=a.evaluate(h,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});if(r.policyDecision={allowed:f.allowed,requiresApproval:f.requiresApproval||d,approvalToken:s.policy.approvalToken,reason:f.reason||p},d||f.requiresApproval)if(s.policy.approvalToken)try{await ic().verifier.verify(s.policy.approvalToken)}catch(e){if(e instanceof Ga){try{const t=globalThis.punica?.kernel?.Events?.manager;t&&t.publishEvent({name:"token.invalid",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:"error"},payload:{capability:i,tokenError:e.code,actor:s.actor}})}catch{}throw new la(ca.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:i,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!(a.hasApproval(h,"always",{workspaceId:s.workspaceId})||a.hasApproval(h,"workspace",{workspaceId:s.workspaceId})||a.hasApproval(h,"once",{workspaceId:s.workspaceId}))){a.requestApproval(h,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:i,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}throw new la(ca.CAPABILITY_APPROVAL_REQUIRED,`Approval required: ${p}`,{capability:i,reason:p})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:s.workspaceId};if(!(a.hasApproval(h,"always",e)||a.hasApproval(h,"workspace",e))&&"function"==typeof a.revokeApproval)try{a.revokeApproval({kind:h.kind,id:h.id,scope:"once"})}catch{}}}if(!f.allowed&&!d&&"suggest"!==f.mode)throw new la(ca.CAPABILITY_DENIED,f.reason??"Policy denied execution",{capability:i,decision:f});return await t()}}const ac=new class{#f=new Map;#lt;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#lt=t<=0?1:t}get(e,t){const n=this.#ut(e,t),r=this.#f.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#f.delete(n),this.#f.set(n,r),r;this.#f.delete(n)}}set(e){const t=this.#ut(e.capabilityId,e.key);for(this.#f.delete(t),this.#f.set(t,e);this.#f.size>this.#lt;){const e=this.#f.keys().next().value;if(void 0===e)break;this.#f.delete(e)}}delete(e,t){return this.#f.delete(this.#ut(e,t))}clear(){this.#f.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#f)r.expiresAtMs<=e&&(this.#f.delete(n),t++);return t}size(){return this.#f.size}#ut(e,t){return`${e}|${t}`}};let cc=ac;function lc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s,idempotencyKey:o}=n,a=r.spec.defaults?.idempotency??"none";if("none"===a)return t();if("required"===a&&!o)throw new la(ca.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=cc,l=function(e){const t=JSON.stringify(e??null);let n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}(s),u=c.get(i,o);if(u){if(u.inputHash!==l)throw function(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}({name:"idempotency.replay_blocked",envelope:{id:n.invocationId,correlationId:n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:idempotency",kind:"error"},payload:{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs,actor:n.ctx.actor}}),new la(ca.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED,`Capability "${i}" idempotencyKey "${o}" was previously used with a different input`,{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs});return r.output=u.response,r.tags["idempotency.hit"]="true",u.response}const d=await t(),p=Date.now();return c.set({key:o,capabilityId:i,inputHash:l,response:d,createdAtMs:p,expiresAtMs:p+864e5}),r.tags["idempotency.cached"]="true",d}}const uc=new class{#dt=new Map;getBucket(e,t){let n=this.#dt.get(e);return n||(n={tokens:t,lastRefillMs:Date.now(),perSecond:t,maxTokens:t},this.#dt.set(e,n)),n}consumeToken(e,t){const n=this.getBucket(e,t),r=Date.now(),i=(r-n.lastRefillMs)/1e3*t;return n.tokens=Math.min(n.maxTokens,n.tokens+i),n.lastRefillMs=r,n.tokens>=1&&(n.tokens-=1,!0)}};function dc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=o.defaults?.rateLimit;if(!a||!a.perSecond)return await t();const c=function(e,t,n){const r=[e,t];return n&&r.push(n),r.join(":")}(i,s.actor.type,s.actor.extensionName??s.origin.extension);if(!uc.consumeToken(c,a.perSecond))throw new la(ca.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const pc=new class{#pt=new Map;getSemaphore(e,t){let n=this.#pt.get(e);return n||(n={count:0,max:t,queue:[]},this.#pt.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e){const t=this.#pt.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function hc(){return async(e,t)=>{const{req:n,state:r}=e,{ctx:i}=n,{spec:s}=r,o=s.defaults?.concurrency;if(!o||!o.key||!o.max)return await t();const a=function(e,t){let n=e;return n=n.replace(/\{workspaceId\}/g,t.workspaceId??""),n=n.replace(/\{tenantId\}/g,t.tenantId??""),n=n.replace(/\{extension\}/g,t.extension??""),n=n.replace(/\{actorType\}/g,t.actorType??""),n}(o.key,{workspaceId:i.workspaceId,tenantId:i.tenantId,extension:i.actor.extensionName??i.origin.extension,actorType:i.actor.type});try{await pc.acquire(a,o.max)}catch(e){throw new la(ca.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{pc.release(a)}}}const fc=new class{#ht=new Map;getBreaker(e){let t=this.#ht.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#ht.set(e,t)),t}};function mc(){return async(e,t)=>{const{req:n,state:r}=e,{name:i}=n,s=r.spec.defaults?.circuitBreaker;if(!s)return await t();const o=s.failureThreshold??3,a=s.cooldownMs??6e4,c=fc.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new la(ca.CAPABILITY_CIRCUIT_OPEN,`Circuit breaker open for "${i}"`,{capability:i,openedAtMs:c.openedAtMs,cooldownMs:a,remainingMs:a-(l-c.openedAtMs)});try{const e=await t();return c.consecutiveFailures=0,c.status="closed",e}catch(e){c.consecutiveFailures++;throw("half-open"===c.status||c.consecutiveFailures>=o)&&(c.status="open",c.openedAtMs=l),e}}}function gc(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return["timeout","network","connection","temporary","retry","rate limit","503","502","504"].some(e=>t.includes(e))}async function yc(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new la(ca.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),s])}finally{void 0!==i&&clearTimeout(i)}}function bc(e){return{invocationId:e.invocationId,capability:e.capability,actor:e.actor,origin:e.origin,capabilityOrigin:e.capabilityOrigin,workspace:e.workspaceId,policyDecision:e.policyDecision?{allowed:e.policyDecision.allowed,requiresApproval:e.policyDecision.requiresApproval,reason:e.policyDecision.reason}:void 0,input:e.redactedInput,output:e.redactedOutput,duration:e.durationMs,error:e.error?{message:e.error.message,name:e.error.name}:void 0,timestamp:e.timestamp}}async function wc(e){try{if(function(e){const t=globalThis.punica?.kernel?.Events?.manager;if(!t||"function"!=typeof t.publishEvent||"function"!=typeof t.createCorrelationId)return!1;try{return t.publishEvent({name:"capability.audited",envelope:{id:t.createCorrelationId(),correlationId:e.invocationId,timestampMs:e.timestamp,source:"runtime:capabilities:gateway",kind:e.error?"error":"info"},payload:bc(e)}),!0}catch{return!1}}(e))return;if(await async function(e){const t=globalThis.punica?.kernel?.History?.auditWriter;if(!t||"function"!=typeof t.write)return!1;try{return await t.write(bc(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=$a()}catch{return!1}try{const n=".punica/audit";await t.createFolder(n).catch(()=>{});const r=`${n}/${e.invocationId}.json`;return await t.createFileWithContent(r,JSON.stringify(bc(e),null,2)),!0}catch{return!1}}(e))return;console.warn("[CapabilityGateway] Audit record dropped (no event manager / audit writer / FS provider available):",e.invocationId)}catch(e){console.warn("[CapabilityGateway] Failed to write audit record:",e)}}const vc=new WeakMap;function kc(e,t){if(!0===t.secretBearing)return Ic(e);const n=function(e){const t=vc.get(e);if(t)return t;const n=y(e.outputSchema);return vc.set(e,n),n}(t);return n.length>0?b(e,n):e}function Ic(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ic);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ic(r);return t}return e}function Ec(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a="object"==typeof n.input&&null!==n.input&&"path"in n.input&&"string"==typeof n.input.path&&/^\.punica\/audit\//.test(n.input.path);let c,l;try{c=await t(),r.output=c}catch(e){throw l=e instanceof Error?e:new Error(String(e)),r.error=l,e}finally{const e=globalThis.punica?.runtime,t=!e||"bootstrapping"===e.lifecyclePhase||"noWorkspace"===e.lifecyclePhase;if(!a&&!t){const e=kc(r.output,o);await wc({invocationId:n.invocationId,capability:i,actor:s.actor,origin:s.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:s.workspaceId,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Ac=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Sc(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const _c=new class{async call(e,t,n,r){const i=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let s=ua.getSpec(e),o=s?ua.getProvider(e):void 0,a="core";if(!s){const t=Ia.getCapability(e);if(!t)throw Sc({name:"capability.unknown_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:n.actor}}),new la(ca.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,s=pa(t.definition),o=Ea(t.origin,t.definition,t.metadata)}if(!o)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(s.requires)for(const t of s.requires)if(!ua.hasCapability(t))throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});s.deprecated&&Sc({name:"capability.deprecated_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:a,since:s.deprecated.since,reason:s.deprecated.reason,replacement:s.deprecated.replacement,actor:n.actor}});const c={req:{invocationId:i,name:e,input:t,ctx:n,idempotencyKey:r},state:{spec:s,capabilityOrigin:a,startTimeMs:Date.now(),tags:{}}},l=this.#ft(o);try{return await this.#mt(l,c)}catch(e){if(e instanceof la)throw e;throw new la(ca.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#ft(e){const t={auditTrail:Ec,traceMetrics:_a,redaction:Ta,validateInput:Ra,pathTraversalGuard:qa,encryptionRouting:Ua,profileBudget:Wa,policyGate:oc,idempotency:lc,rateLimit:dc,concurrency:hc,circuitBreaker:mc,timeoutRetry:()=>function(e){return async(t,n)=>{const{req:r,state:i}=t,{input:s,idempotencyKey:o}=r,{spec:a}=i,c=a.defaults?.timeoutMs??3e4,l=a.defaults?.retries??0,u=a.defaults?.retryBackoffMs??1e3,d="write"!==a.sideEffect||Boolean(o);let p=null,h=0;for(;h<=l;){h++;try{const n=await yc(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),h<=l&&d&&gc(p)){const e=u*Math.pow(2,h-1);await new Promise(t=>setTimeout(t,e));continue}throw i.error=p,p}}throw i.error=p??new Error("Execution failed"),i.error}}(e)};return Ac.map(e=>t[e]())}#mt(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const i=e[n];return n++,await i(t,r)};return r()}};function xc(e,t){const n=$a(),r=n[t];if("function"!=typeof r)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires FileSystemProvider.${String(t)}() but the registered provider does not expose it`,{capability:e,method:String(t)});return r.bind(n)}function Cc(e,t,n){const r=$a();if(!r.capabilities?.has(n))throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires the FileSystemProvider to advertise the "${n}" capability flag, but it does not`,{capability:e,method:String(t),requiredProviderCapability:n});const i=r[t];if("function"!=typeof i)throw new la(ca.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires FileSystemProvider.${String(t)}() but the registered provider does not expose it`,{capability:e,method:String(t),requiredProviderCapability:n});return i.bind(r)}class Tc{name="fs.readFile";async execute(e,t){const n=$a();return await n.readFile(e.path)}}class Nc{name="fs.writeFile";async execute(e,t){const n=$a();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class Mc{name="fs.listFiles";async execute(e,t){const n=$a();return await n.getFileTree()}}class Dc{name="fs.stat";async execute(e,t){return await xc("fs.stat","stat")(e.path)}}class Pc{name="fs.exists";async execute(e,t){return await xc("fs.exists","exists")(e.path)}}class Oc{name="fs.copy";async execute(e,t){await xc("fs.copy","copy")(e.src,e.dst)}}class Rc{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await xc("fs.mkdir","mkdir")(e.path,n)}}class Lc{name="fs.history";async execute(e,t){return await Cc("fs.history","history","versioning")(e.path)}}class $c{name="fs.readAtVersion";async execute(e,t){return await Cc("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class jc{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await xc("fs.list","list")(e.path,n)}}const Fc=yo({label:"Runtime.secrets",noProviderMessage:"[Runtime.secrets] No Secrets provider registered. Host must call punica.runtime.setSecretsProvider() before using Secrets API",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.secrets??function(){const e=new Map,t=new Map;return{set(n,r){const i=String(n??"").trim();if(!i)throw new Error("[Runtime.secrets] Secret name is required");const s=Date.now();if(t.has(i)){const e=t.get(i);t.set(i,{...e,updatedAtMs:s})}else t.set(i,{createdAtMs:s,updatedAtMs:s});e.set(i,String(r??""))},get(t){const n=String(t??"").trim();return n&&e.has(n)?e.get(n):null},delete(n){const r=String(n??"").trim();return!!r&&(t.delete(r),e.delete(r))},list(){const e=[];for(const[n,r]of t.entries())e.push({name:n,createdAtMs:r.createdAtMs,updatedAtMs:r.updatedAtMs});return e.sort((e,t)=>e.name.localeCompare(t.name)),e}}}()}});function Bc(){return Fc.get()}function qc(e){Fc.set(e),e&&bo({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class zc{name="secrets.get";async execute(e,t){return Bc().get(e.name)}}class Uc{name="secrets.set";async execute(e,t){Bc().set(e.name,e.value)}}function Vc(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Eo]=!0,n}class Wc{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=Vc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class Kc{name="llm.chatStream";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=globalThis.punica?.kernel?.Events?.manager,i=t.sessionId??t.trace?.traceId,s=e=>{if(r)try{r.publishEvent({name:"llm.chunk",envelope:{id:r.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"progress"},payload:{capabilityId:this.name,chunk:e}})}catch{}},o=Vc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);if("function"!=typeof n.chatStream){const e=await n.chat(o);return s({type:"done",response:e}),e}let a="",c="";const l=[];let u;for await(const e of n.chatStream(o)){if(t.signal?.aborted)break;switch(s(e),e.type){case"content":a+=e.text;break;case"thinking":c+=e.text;break;case"tool_call":l.push(e.toolCall);break;case"done":u=e.response;break;case"error":throw new Error(`[llm.chatStream] ${e.error.code}: ${e.error.message}`)}}const d={text:a||u?.text||"",modelId:u?.modelId,provider:u?.provider,usage:u?.usage,meta:u?.meta};return l.length>0&&(d.toolCalls=l),c&&(d.thinking=c),d}}class Gc{name="llm.invoke";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.invoke(e,{correlationId:t.sessionId??t.trace?.traceId})}}class Hc{name="llm.plan";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.plan(e)}}class Yc{name="search.query";async execute(e,t){const n=globalThis.punica?.runtime?.search;if(!n)throw new Error("Search provider not available");return await n.query({q:e.q,limit:e.limit})}}class Jc{name="vcs.status";async execute(e,t){const n=globalThis.punica?.runtime?.vcs;if(!n)throw new Error("VCS provider not available");return await n.status()}}class Zc{name="vcs.commit";async execute(e,t){const n=globalThis.punica?.runtime?.vcs;if(!n)throw new Error("VCS provider not available");return await n.commit({message:e.message,all:e.all})}}class Qc{name="workspace.readFile";async execute(e,t){const n=$a();return await n.readFile(e.path)}}class Xc{name="workspace.writeFile";async execute(e,t){const n=$a();await n.createFileWithContent(e.path,e.content)}}class el{name="workspace.listFiles";async execute(e,t){const n=$a(),r=await n.getFileTree(),i=[],s=e=>{for(const t of e??[])i.push({path:t.path,name:t.name,isDirectory:t.isDirectory}),t.isDirectory&&Array.isArray(t.children)&&t.children.length&&s(t.children)};return s(r??[]),{entries:i}}}class tl{name="terminals.create";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");return await n.create(e.title?{title:e.title}:void 0)}}class nl{name="terminals.send";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");n.write(e.id,e.text)}}class rl{name="tasks.runCommand";async execute(e,t){const n=globalThis.punica?.runtime?.tasks;if(!n)throw new Error("Tasks provider not available");return await n.run(e)}}class il{name="flow.migrate";async execute(e,t){const n=globalThis.punica,r=n?.flow?.primitives?.migrations;if(!r||"function"!=typeof r.migrate)throw new Error("[FlowMigrateProvider] Migration registry is not available — substrate bootstrap incomplete");return r.migrate(e)}}class sl{name="flow.runSubflow";async execute(e,t){const n=globalThis.punica,r=n?.flow?.engine?.manager;if(!r||"function"!=typeof r.runSubflow)throw new Error("[FlowRunSubflowProvider] Flow engine is not available — substrate bootstrap incomplete");const i={...e,workspaceId:e.workspaceId??t.workspaceId,parentTraceId:e.parentTraceId??t.trace?.traceId};return r.runSubflow(i)}}const ol="capability.catalog";class al{name=ol;async execute(e,t){const n=e??{},r=Ia.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>cl(e,n));return{capabilities:r,count:r.length}}}function cl(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=ll(t.risk);if(0===n.length)return!1;const r=e.definition.policy?.risk;if(!r||!n.includes(r))return!1}if(void 0!==t.tags){const n=ll(t.tags);if(0===n.length)return!1;const r=e.definition.tags;if(!Array.isArray(r)||0===r.length)return!1;if(!n.some(e=>r.includes(e)))return!1}if(void 0!==t.sideEffects){const n=ll(t.sideEffects);if(0===n.length)return!1;const r=e.definition.sideEffects;if(!Array.isArray(r)||0===r.length)return!1;if(!n.some(e=>r.includes(e)))return!1}return!0}function ll(e){return Array.isArray(e)?e:[e]}const ul=["examples","$comment","default","title"];function dl(e,t){let n=String(e??"");if(n=n.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[`*_#>]/g,"").replace(/\s+/g," ").trim(),!n)return n;const r=n.match(/^.{12,}?[.!?](?=\s|$)/)?.[0];return r&&(n=r),n.length>t&&(n=n.slice(0,t-1).trimEnd()+"…"),n}const pl=["properties","patternProperties","definitions","$defs"];function hl(e){if(Array.isArray(e))return e.map(e=>hl(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!ul.includes(n))if("description"!==n||"string"!=typeof r){if(pl.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=hl(n);t[n]=e;continue}t[n]=hl(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const fl="capability.schemaExport";class ml{name=fl;async execute(e,t){const n=e??{},r=n.filter??{},i=Ia.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>cl(e,r)),s=n.mode??"full",o=i.map(e=>{const t=function(e){const t=e.definition,n={id:t.id,origin:e.origin,version:t.version,title:t.title};void 0!==t.description&&(n.description=t.description);void 0!==t.inputs?.schema&&(n.inputSchema=t.inputs.schema);void 0!==t.outputs?.schema&&(n.outputSchema=t.outputs.schema);t.policy&&(n.policy={risk:t.policy.risk,approval:t.policy.approval});t.tags&&t.tags.length>0&&(n.tags=[...t.tags]);t.sideEffects&&t.sideEffects.length>0&&(n.sideEffects=[...t.sideEffects]);const r=t.requires;r&&r.length>0&&(n.requires=[...r]);t.deprecated&&(n.deprecated={...t.deprecated});if(e.metadata){const t={};for(const[n,r]of Object.entries(e.metadata))void 0!==r&&(t[n]=r);Object.keys(t).length>0&&(n.metadata=t)}return n}(e);return"ai-tools"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=dl(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=hl(e.inputSchema));e.policy&&(t.policy={...e.policy});return t}(t):"summary"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=dl(e.description??e.title,100);n&&(t.description=n);return t}(t):t});return{schemaVersion:"v1",generatedAt:Date.now(),capabilities:o,count:o.length}}}async function gl(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return[];const i=Ia.listCapabilities();if(0===i.length)return[];const s=function(e,t){const n=wl(bl(e));return t.map(e=>({...e,score:vl(n,wl(bl(e.text)))}))}(r,i.map(e=>({id:e.definition.id,description:e.definition.description,text:yl(e.definition)}))),o=s.slice().sort((e,t)=>t.score-e.score).slice(0,Math.max(0,n)).map(e=>({id:e.id,score:e.score,description:e.description}));return Io("llm.recommendIntent",{intent:r,limit:n,path:"text-similarity",topIds:o.map(e=>e.id),topScore:o[0]?.score??0}),o}function yl(e){const t=[];return t.push(e.id),e.title&&t.push(e.title),e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(e.tags.join(" ")),t.join(" ")}function bl(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(e=>e.length>0)}function wl(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function vl(e,t){if(0===e.size||0===t.size)return 0;let n=0,r=0,i=0;for(const[,t]of e)r+=t*t;for(const[,e]of t)i+=e*e;for(const[r,i]of e){const e=t.get(r);void 0!==e&&(n+=i*e)}const s=Math.sqrt(r)*Math.sqrt(i);return 0===s?0:n/s}const kl="capability.recommend";class Il{name=kl;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await gl(r,"number"==typeof n.limit?{limit:n.limit}:void 0);return{recommendations:i.map(e=>({id:e.id,score:e.score,description:e.description})),path:"text-similarity",count:i.length}}}const El="capability.describe",Al="capability.search";function Sl(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class _l{name=El;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new ml).execute({mode:"ai-tools"},t)).capabilities.filter(e=>r.has(String(e.id))),s=new Set(i.map(e=>String(e.id)));return{tools:i,missing:n.filter(e=>!s.has(e))}}}class xl{name=Al;async execute(e,t){const n=e??{},r=String(n.query??"").trim(),i=Math.min(Math.max(1,Math.floor(n.limit??16)),50);if(!r)return{results:[],count:0};const s=Ia.listCapabilities(),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await gl(r,{limit:i});e.reduce((e,t)=>"number"==typeof t.score&&t.score>e?t.score:e,0)>1e-9&&(a=e.map(e=>String(e.id)).filter(e=>o.has(e)))}catch{}if(0===a.length){const e=r.toLowerCase().split(/\s+/).filter(Boolean);a=s.filter(t=>{const n=`${t.definition.id} ${t.definition.title??""} ${t.definition.description??""}`.toLowerCase();return e.some(e=>n.includes(e))}).map(e=>String(e.definition.id))}const c=a.slice(0,i).map(e=>{const t=o.get(e);return{id:e,description:dl(t?.description??t?.title??e,100),category:Sl(e)}});return{results:c,count:c.length}}}function Cl(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Tl(e,t){return{name:e,version:"1.0.0",sideEffect:e.endsWith(".list")||e.endsWith(".get")?"read":"write",risk:t.risk??"low",permissions:[],inputSchema:{type:"object",...t.required?{required:t.required}:{},properties:t.properties??{}},outputSchema:{type:"object",properties:t.outputProperties??{}},defaults:{timeoutMs:5e3}}}class Nl{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Cl().create(n)}}}class Ml{name="ai.session.list";async execute(e,t){const n=Cl().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Dl{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Cl().get(n)}}}class Pl{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Cl().rename(String(n?.sessionId??""),String(n?.title??""))}}}class Ol{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Cl().archive(String(n?.sessionId??""),n?.archived)}}}class Rl{name="ai.session.delete";async execute(e,t){return{ok:Cl().delete(String(e?.sessionId??""))}}}const Ll={id:"missing-title",severity:"error",check(e){const t=e.title;return"string"==typeof t&&t.trim().length>0?[]:[{ruleId:"missing-title",severity:"error",message:`Capability "${e.id}" has no title — title is required and shown in UI + LLM prompts`,capabilityId:String(e.id),path:"title",code:"CAP_NO_TITLE"}]}},$l={id:"weak-description",severity:"warning",check(e){const t=e.description,n="string"==typeof t?t.trim():"";if(n.length>=20)return[];const r=0===n.length?"has no description":`has a very short description ("${n}")`;return[{ruleId:"weak-description",severity:"warning",message:`Capability "${e.id}" ${r} — the agent reads this to decide when to call the tool; write 1-2 sentences (what it does, when to pick it, side effects)`,capabilityId:String(e.id),path:"description",code:"CAP_WEAK_DESC"}]}},jl=new Set(["low","medium","high"]),Fl={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&jl.has(t.risk)?[]:[{ruleId:"invalid-risk",severity:"error",message:`Capability "${e.id}" declares policy.risk "${String(t.risk)}" — must be one of low | medium | high`,capabilityId:String(e.id),path:"policy.risk",code:"CAP_BAD_RISK"}]:[]}},Bl=new Set(["none","plan","step"]),ql={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Bl.has(t.approval)?[]:[{ruleId:"invalid-approval",severity:"error",message:`Capability "${e.id}" declares policy.approval "${String(t.approval)}" — must be one of none | plan | step`,capabilityId:String(e.id),path:"policy.approval",code:"CAP_BAD_APPROVAL"}]:[]}};const zl={id:"untyped-inputs",severity:"warning",check(e){const t=e.inputs;return t&&"object"==typeof t?function(e){const t=e.schema;if(t&&"object"==typeof t){const e=t;if(void 0!==e.type||void 0!==e.properties)return!0}for(const[t,n]of Object.entries(e))if("schema"!==t&&n&&"object"==typeof n&&void 0!==n.type)return!0;return!1}(t)?[]:[{ruleId:"untyped-inputs",severity:"warning",message:`Capability "${e.id}" declares inputs without type information — the agent generates arguments from this; add a JSON Schema (inputs.schema) or per-field types`,capabilityId:String(e.id),path:"inputs",code:"CAP_UNTYPED_INPUTS"}]:[]}},Ul=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Vl={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Ul.test(t)?[]:[{ruleId:"id-naming",severity:"warning",message:`Capability id "${String(t)}" is not a dotted <namespace>.<action> name (e.g. "editor.openFile") — consistent ids project cleanly to MCP and group related tools`,capabilityId:String(t),path:"id",code:"CAP_ID_NAMING"}]}},Wl=new Set(["low","medium","high"]),Kl=["write","delete","remove","modify","destroy"],Gl=[Ll,$l,Fl,ql,zl,Vl,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Wl.has(t.risk))return[];const n=[];"high"===t.risk&&"none"===t.approval&&n.push({ruleId:"risk-approval-consistency",severity:"warning",message:`Capability "${e.id}" is risk: high but approval: none — a high-risk capability the agent can run unattended; consider approval plan or step`,capabilityId:String(e.id),path:"policy.approval",code:"CAP_RISK_APPROVAL"});const r=e.sideEffects;if("low"===t.risk&&Array.isArray(r)){const t=r.find(e=>"string"==typeof e&&Kl.some(t=>e.toLowerCase().includes(t)));t&&n.push({ruleId:"risk-approval-consistency",severity:"warning",message:`Capability "${e.id}" declares a mutating side effect ("${String(t)}") but risk: low — risk is likely under-declared (medium/high for workspace-changing work)`,capabilityId:String(e.id),path:"policy.risk",code:"CAP_RISK_APPROVAL"})}return n}}];const Hl=new class{#gt=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#gt.values())try{const r=n.check(e);r&&r.length>0&&t.push(...r)}catch(r){t.push({ruleId:n.id,severity:"info",message:`Lint rule "${n.id}" threw during analysis: ${String(r?.message??r)}`,capabilityId:String(e.id),code:"CAP_LINT_RULE_ERROR"})}return{ok:!t.some(e=>"error"===e.severity),issues:t}}lintAll(e){return e.map(e=>({id:String(e.id),...this.lint(e)}))}register(e){if(!e||"function"!=typeof e.check)throw new Error("CapabilityLinter.register: rule must have a check(def) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("CapabilityLinter.register: rule.id must be a non-empty string");this.#gt.set(e.id,e)}unregister(e){return this.#gt.delete(e)}list(){return Array.from(this.#gt.keys())}reset(){this.#gt.clear();for(const e of Gl)this.#gt.set(e.id,e)}},Yl="capability.lint";class Jl{name=Yl;async execute(e,t){const n=e??{},r=Ia.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=Hl.lintAll(r).map(e=>({id:e.id,ok:e.ok,issues:e.issues}));return{results:i,ok:i.every(e=>e.ok),count:i.length}}}const Zl={type:"object"};function Ql(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Xl(e){let t;return t=function(e){if(e instanceof la)return!0;if(!e||"object"!=typeof e)return!1;const t=e;return"CapabilityError"===t.name&&"string"==typeof t.code}(e)?`[${e.code}] ${e.message}`:e instanceof Error?e.message:Ql(e),{content:[{type:"text",text:t}],isError:!0}}const eu="capability.serveList",tu="capability.serveCall",nu=new Set([eu,tu]);class ru{name=eu;async execute(e,t){const n=(e??{}).filter??{},r=Ia.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!nu.has(e.definition.id)).filter(e=>cl(e,n)).map(e=>function(e,t){const n=t??e.id,r=e.sideEffects??[];return{name:n,description:e.description??e.title??n,inputSchema:e.inputs?.schema??Zl,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class iu{name=tu;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||nu.has(r)||!Ia.getCapability(r))return Xl(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:Ql(e)}],isError:!1}}(await _c.call(r,n.arguments??{},t))}catch(e){return Xl(e)}}}const su="shell.revealView",ou="shell.hideView",au="shell.listViews",cu="shell.toggleView",lu="shell.toggleSlot";function uu(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new la(ca.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:su});return e}function du(e){const t=e?.actor?.type;return"user"===t?{kind:"user-gesture",id:e.origin?.id}:"extension"===t?{kind:"extension",id:e.actor?.extensionName??e.origin?.id}:{kind:"capability",id:e?.trace?.traceId??e?.origin?.id}}class pu{name=su;async execute(e,t){const{viewId:n,focus:r}=e??{},i=uu();if(!i.getPlacement(n))throw new la(ca.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:su,viewId:n});return await i.reveal(n,du(t),{focus:r}),{viewId:n,revealed:!0}}}class hu{name=ou;async execute(e,t){const{viewId:n}=e??{};return uu().hide(n,du(t)),{viewId:n,hidden:!0}}}class fu{name=au;async execute(e,t){return{views:uu().listViews()}}}class mu{name=cu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=uu();if(!i.getPlacement(n))throw new la(ca.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:cu,viewId:n});return"visible"===i.getState(n)?(i.hide(n,du(t)),{viewId:n,visible:!1}):(await i.reveal(n,du(t),{focus:r}),{viewId:n,visible:!0})}}const gu=new Map;class yu{name=lu;async execute(e,t){const{slot:n,focus:r}=e??{},i=uu(),s=i.getVisibleView(n);if(s)return gu.set(n,s),i.hide(s,du(t)),{slot:n,visible:!1,viewId:s};const o=gu.get(n);let a=o&&i.getPlacement(o)?o:void 0;return a||(a=i.listViews().find(e=>e.slot===n)?.viewId),a?(await i.reveal(a,du(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}function bu(e){try{ua.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function wu(e){const{definition:t,origin:n,metadata:r}=e;return{id:t.id,origin:n,title:t.title,risk:t.policy?.risk,approval:t.policy?.approval,outputKind:t.outputs?.kind,resultEvent:t.outputs?.resultEvent,extensionName:r?.extensionName,productId:r?.productId,packageRoot:r?.packageRoot}}function vu(e){const{definition:t,origin:n,metadata:r}=e;console.group(`[${n}] ${t.id}`),console.dir({title:t.title,description:t.description,version:t.version,tags:t.tags,inputs:t.inputs,outputs:t.outputs,policy:t.policy,sideEffects:t.sideEffects,execution:t.execution,deprecated:t.deprecated,...r?{_metadata:r}:{}},{depth:null}),console.groupEnd()}async function ku(e){const t=globalThis.punica;if(!t)return void console.warn("[Punica] logTrinityCatalog: global `punica` is missing — call after initialize().");try{await(t.flow?.registry?.discover?.())}catch{}if(e?.id){const t=Ia.getCapability(e.id);return t?void vu(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Ia.listCapabilities(n),i=r.map(wu);if(console.log("[Punica] Trinity capability catalog",{count:i.length}),i.length>0){if(console.table(i),e?.verbose){console.log("[Punica] Full definitions (same fields as .punica/capabilities.yaml):");for(const e of r)vu(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Iu(e){return ku({...e,verbose:!0})}function Eu(e){switch(e){case"core":return"Core";case"extension":return"Extension";case"instruction-class":return"Instruction class";case"ivy-node":return"Ivy node";case"ivy-agent":return"Ivy agent";case"mcp":return"MCP";default:return String(e)}}function Au(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,i=t.policy?.risk??"—",s=function(e){const t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t);return n.trim()}(t.description??t.title??"")||"—";return`| ${n} | ${r} | ${i} | ${function(e){return e.replace(/\|/g,"\\|")}(s)} |`}function Su(e){return JSON.stringify(e,null,2)}const _u=new class{#je=new Map;get(e){return this.#je.get(e)}list(){return[...this.#je.values()]}register(e,t){for(const e of t)this.#je.set(e.definition.id,e),this.#yt(e.definition.id)}unregister(e){for(const[t,n]of this.#je)n.serverId===e&&(this.#je.delete(t),this.#bt(t))}hasServer(e){for(const t of this.#je.values())if(t.serverId===e)return!0;return!1}#yt(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.registered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}#bt(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.unregistered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}},xu=16384,Cu="runtime:mcp:client";function Tu(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Nu(e,t){if("string"==typeof e){if(t<12){const n=function(e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{return}}(e);if(void 0!==n)return Nu(n,t+1)}return e.length>1024?e.slice(0,1024)+"…[truncated]":e}if(Array.isArray(e)){const n=e.slice(0,50).map(e=>Nu(e,t+1));return e.length>50&&n.push(`…[${e.length-50} more items truncated]`),n}if(e&&"object"==typeof e){if(t>=12)return"…[truncated]";const n={};for(const[r,i]of Object.entries(e))n[r]=Nu(i,t+1);return n}return e}function Mu(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=xu)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Nu(e,0),null,2)??"null";if(r.length<=xu)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,xu)+"\n… [truncated]",bytes:n,truncated:!0}}function Du(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const Pu=new class{#wt=new Map;async connect(e){if(this.#wt.has(e.id))return this.#wt.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return Fu}),r=e.toolOverrides??await t(e.id),i="stdio"===e.kind?n(e.env):e.env,s="streamable-http"===e.kind||"sse"===e.kind?n(e.headers):e.headers,o={...e,env:i,headers:s,toolOverrides:r&&Object.keys(r).length?r:void 0},a=function(e,t){const n=(t,n,r)=>({direction:"outbound",serverId:e.serverId,serverName:e.serverName,transport:e.transport,method:n,toolName:Du(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Tu(),s=Mu(r??{});bo({name:"mcp.request",source:Cu,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:fe().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Tu(),s=Date.now(),o=Mu(r??{});bo({name:"mcp.request",source:Cu,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:fe().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=Mu(o??null);return bo({name:"mcp.response",source:Cu,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:fe().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw bo({name:"mcp.response",source:Cu,correlationId:i,kind:"error",payload:{...n(i,e,r),kind:"request",isError:!0,durationMs:Date.now()-s,errorMessage:t instanceof Error?t.message:String(t)}}),t}}}}({serverId:o.id,serverName:o.name,transport:o.kind},await async function(e){if("stdio"===e.kind){if(!e.command)throw new Error(`MCP server "${e.id}": stdio transport requires 'command'`);const{StdioTransport:t}=await Promise.resolve().then(function(){return zb});return new t(e.command,e.args??[],e.env??{})}if("streamable-http"===e.kind||"sse"===e.kind){if(!e.url)throw new Error(`MCP server "${e.id}": http transport requires 'url'`);const{StreamableHttpTransport:t}=await Promise.resolve().then(function(){return Ub});return new t(e.url,e.headers??{})}throw new Error(`MCP server "${e.id}": unknown transport kind "${e.kind}"`)}(o));await a.connect(),await a.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"punica-editor",version:"1.0.0"}}),a.notify("notifications/initialized",{});const c=await a.request("tools/list",{}),l=c?.tools??[],u=l.map(e=>{const t=o.toolOverrides?.[e.name]??{},n=function(e,t,n={}){const r=t._meta?.punica??{},i={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},s={timeoutMs:n.executionDefaults?.timeoutMs??r.executionDefaults?.timeoutMs??3e4,idempotency:n.executionDefaults?.idempotency??r.executionDefaults?.idempotency??"none"},o=["mcp",e],a=r.tags??[],c=n.tags??[],l=[...new Set([...o,...a,...c])],u=n.sideEffects??r.sideEffects??["mcp-invocation","network"];return{id:`mcp.${e}.${t.name}`,title:t.name,description:t.description??`MCP tool ${t.name} from server ${e}`,version:"1.0.0",inputs:{schema:t.inputSchema??{type:"object"}},outputs:{schema:{type:"object",properties:{content:{type:"array",items:{type:"object",properties:{type:{type:"string"},text:{type:"string"}}}},isError:{type:"boolean"}}},kind:"direct"},policy:i,sideEffects:u,executionDefaults:s,tags:l}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});_u.register(o.id,u),console.log(`[Punica] MCP server "${o.id}" connected — ${l.length} tool(s) registered as capabilities`);const d={serverId:o.id,transportKind:o.kind,tools:l,disconnect:async()=>{a.close(),_u.unregister(e.id),this.#wt.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#wt.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#wt.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#wt.values()].map(e=>e.handle)}listTools(e){return e?this.#wt.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#wt.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},Ou=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Ru(e){if(!e)return{};const t={},n=function(){const e=globalThis.process,t=e?.env;return t&&"object"==typeof t?t:void 0}(),r=void 0!==n;for(const[i,s]of Object.entries(e)){const e="string"==typeof s?s.match(Ou):null;if(e){const s=e[1];if(!r){console.warn(`[Punica] MCP env placeholder \${env.${s}} skipped — not in Node/Electron`);continue}const o=n[s];void 0!==o?t[i]=o:console.warn(`[Punica] MCP env placeholder \${env.${s}} — variable unset`)}else t[i]=s}return t}async function Lu(e){try{const t=globalThis,n=t.punica?.runtime?.fs,r=n?.readFile,i=n?.exists;if(!r)return{};if(i){const t=`.punica/mcp/${e}.yaml`;if(!await i(t))return{}}let s;try{s=await r(`.punica/mcp/${e}.yaml`,{encoding:"utf8"})}catch{return{}}if("string"!=typeof s||""===s.trim())return{};const{parse:o}=await Promise.resolve().then(function(){return qf}),a=o(s);return a?.tools&&"object"==typeof a.tools?a.tools:{}}catch(t){return console.warn(`[Punica] MCP overrides for "${e}" failed:`,t?.message??t),{}}}async function $u(){try{const e=globalThis,t=e.punica?.runtime?.fs,n=t?.readFile,r=t?.exists;if(!n)return[];if(r){if(!await r(".punica/mcp.yaml"))return[]}let i;try{i=await n(".punica/mcp.yaml",{encoding:"utf8"})}catch{return[]}const{parseYamlMcpConfig:s}=await Promise.resolve().then(function(){return Vb}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await Lu(e.id),n="stdio"===e.kind?Ru(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?Ru(e.headers):e.headers;return{...e,env:n,headers:r,toolOverrides:Object.keys(t).length?t:void 0}}(e)))}catch(e){return console.error("[Punica] MCP config load failed:",e?.message??e),[]}}function ju(e){if(!e||"object"!=typeof e)return[];const t=e;if(!Array.isArray(t.servers))return[];const n=[];for(const e of t.servers){if(!e||"object"!=typeof e)continue;const t=e;if("string"!=typeof t.id)continue;const r=t.transport??t.kind??"stdio";if("stdio"===r){const e="object"==typeof t.env&&null!==t.env?Ru(t.env):{};n.push({id:t.id,name:"string"==typeof t.name?t.name:void 0,kind:"stdio",command:"string"==typeof t.command?t.command:void 0,args:Array.isArray(t.args)?t.args:[],env:e})}else if("streamable-http"===r||"sse"===r){const e="object"==typeof t.headers&&null!==t.headers?Ru(t.headers):{};n.push({id:t.id,name:"string"==typeof t.name?t.name:void 0,kind:r,url:"string"==typeof t.url?t.url:void 0,headers:e})}}return n}var Fu=Object.freeze({__proto__:null,loadMcpConfig:$u,loadServerOverrides:Lu,parseStaticConfig:ju,resolveEnvPlaceholders:Ru});class Bu{name=je.MCP;version="1.0.0";dependencies=[$e.EVENTS,je.FS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){this.#vt=e.BOOTSTRAPPING;const n=await $u();this.#kt(n),this.#vt=e.BOOTSTRAPPED}async#kt(e){for(const t of e)try{await Pu.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#vt=e.STARTING,this.#vt=e.STARTED,console.log(`[Punica] MCP module started — ${_u.list().length} capability(ies) active`)}}const qu=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const zu={get capabilities(){return La.hasProvider()?La.get().capabilities:void 0},get cwd(){return La.hasProvider()?La.get().cwd:void 0},getFileTree:()=>La.get().getFileTree(),readFile:e=>La.get().readFile(e),readBytes:(e,t,n)=>{const r=La.get();if("function"!=typeof r.readBytes)throw new Error("[Runtime.fs] Provider does not implement readBytes()");return r.readBytes(e,t,n)},updateFileContent:(e,t)=>La.get().updateFileContent(e,t),createFolder:e=>La.get().createFolder(e),deleteFolder:e=>La.get().deleteFolder(e),deleteFile:(e,t)=>La.get().deleteFile(e,t),renameFile:(e,t)=>La.get().renameFile(e,t),renameFolder:(e,t)=>La.get().renameFolder(e,t),createFileWithContent:(e,t)=>La.get().createFileWithContent(e,t),list:(e,t)=>{const n=La.get();if("function"!=typeof n.list)throw new Error("[Runtime.fs] Provider does not implement list()");return n.list(e,t)},stat:e=>{const t=La.get();if("function"!=typeof t.stat)throw new Error("[Runtime.fs] Provider does not implement stat()");return t.stat(e)},mkdir:(e,t)=>{const n=La.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},Uu=function(e){return e||{query:e=>ho().query(e),startIndex:e=>{const t=ho();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(qu?.search),Vu=function(e){return e||{status:()=>go().status(),branches:()=>go().branches(),logs:e=>go().logs(e),init:e=>go().init(e),clone:e=>go().clone(e),commit:e=>go().commit(e),stage:e=>go().stage(e),unstage:e=>go().unstage(e),discard:e=>go().discard(e),reset:e=>go().reset(e),switchBranch:e=>go().switchBranch(e),createBranch:(e,t)=>go().createBranch(e,t),fetch:e=>go().fetch(e),pull:e=>go().pull(e),push:e=>go().push(e)}}(qu?.vcs),Wu=function(e){return e||{create:e=>fo().create(e),write:(e,t)=>fo().write(e,t),resize:(e,t,n)=>fo().resize(e,t,n),close:e=>fo().close(e),onData:(e,t)=>fo().onData(e,t),onExit:(e,t)=>fo().onExit(e,t),list:()=>fo().list()}}(qu?.terminals),Ku=function(e){return e||{start:e=>mo().start(e),send:(e,t)=>mo().send(e,t),onMessage:(e,t)=>mo().onMessage(e,t),onStderr:(e,t)=>mo().onStderr(e,t),onExit:(e,t)=>mo().onExit(e,t),stop:e=>mo().stop(e),list:()=>mo().list()}}(qu?.debug),Gu=function(e){return e||{run:e=>function(){if(ao)return ao;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return ao=e,ao}().run(e)}}(qu?.tasks),Hu=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&ko(e),{getCurrent:()=>wo.get().getCurrent(),list:()=>wo.get().list(),open:e=>wo.get().open(e),setEnvironment:(e,t)=>wo.get().setEnvironment(e,t),onDidChange:e=>wo.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(qu?.workspace),Yu=function(e){return e||{list:async e=>po().list(e),get:e=>po().get(e),register:e=>po().register(e),unregister:e=>po().unregister(e),onDidChange:e=>po().onDidChange(e)}}(qu?.resources),Ju=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&Co(e),t)return e;function n(e){if("remote"===e?.route)return!0;if("local"===e?.route)return!1;if(e?.providerId){const t=String(e.providerId).toLowerCase();if(t.startsWith("remote:"))return!0;if(t.startsWith("local:"))return!1}return!0}async function r(e,t,n){!function(e,t){(So&&So!==e||_o&&t&&_o!==t)&&F.publishEvent({name:"llm.providerChanged",envelope:{id:F.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:So,newProviderId:e,previousEndpoint:_o,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),So=e,t&&(_o=t)}(t,n);const r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch(e){return void console.error("[LLM Facade] Error accessing punica.runtime.workspace (gateRemoteRequest):",e?.message??e)}})(),i=e?.correlationId??F.createCorrelationId(),s=ce.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!s.allowed)throw s.requiresApproval&&ce.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:i}),F.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:F.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(s.reason??"[Policy] Remote LLM request denied");return F.publishEvent({name:"llm.remoteRequestSent",envelope:{id:F.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),{...e,correlationId:i,route:"remote",providerId:t}}const i={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",i=e?.providerId??"remote",s=xo(),o=!0===e?.[Eo];if(!o&&("remote"===t||n(e))){const t=e?.endpoint,n=await r(e,i,t);return await s.chat(n)}const a=await s.chat(e);if(!a)throw new Error("[LLM Facade] No response returned from LLM provider");const c=a?.provider;if(!o&&function(e){if(!e)return!1;const t=String(e).toLowerCase();return!t.startsWith("local:")&&"local"!==t&&"mock"!==t&&"ollama"!==t&&!t.startsWith("ollama-")&&"llama.cpp"!==t&&"llamacpp"!==t}(c)){const n=c&&"remote"!==c?c:i,r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch{return}})(),s=e?.correlationId??F.createCorrelationId(),o=ce.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw F.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:F.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"error"},payload:{providerId:n,route:t,workspaceId:r,messageCount:e.messages?.length??0,reason:"Policy gate bypassed via auto route"}}),o.requiresApproval&&ce.requestApproval({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r,correlationId:s}),new Error(o.reason??"[Policy] Remote LLM request denied (auto route bypass detected)");F.publishEvent({name:"llm.remoteRequestSent",envelope:{id:F.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:n,workspaceId:r,messageCount:e.messages?.length??0,retroactive:!0,route:t}})}return a},chatStream:async function*(e){if(e?.signal?.aborted)return;const t=e?.route??"auto",i=e?.providerId??"remote",s=xo();let o=e;if(!(!0===e?.[Eo])&&("remote"===t||n(e))){const t=e?.endpoint;o=await r(e,i,t)}if("function"!=typeof s.chatStream){const e=await s.chat(o);if(!e)throw new Error("[LLM Facade] No response returned from LLM provider");if(o?.signal?.aborted)return;"string"==typeof e.text&&e.text.length>0&&(yield{type:"content",text:e.text});for(const t of e.toolCalls??[])yield{type:"tool_call",toolCall:t};return void(yield{type:"done",response:e})}for await(const e of s.chatStream(o)){if(o?.signal?.aborted)return;yield e}},__punicaWrappedLlmFacade:!0};return i.manager=function(){const e=("undefined"!=typeof window?window.api:void 0)?.llm;if(!e)return;return{listModels:async t=>await(e.listModels?.(t)),listInstalled:async()=>await(e.listInstalled?.()),setActiveModel:async t=>{await(e.setActive?.({modelId:t??null}))},removeModel:async t=>{await(e.remove?.({modelId:t}))},downloadModel:async t=>{await(e.download?.({modelId:t}))},pickModelFile:async()=>await(e.pickModelFile?.()),importModelFile:async t=>{await(e.importModelFile?.(t))},localServerStatus:async()=>await(e.localServerStatus?.()),startLocalServer:async t=>await(e.startLocalServer?.(t)),stopLocalServer:async()=>{await(e.stopLocalServer?.())}}}(),i}(qu?.llm),Zu=function(e){if(e)return e;const t=Mo(),n=new Do(t),r=new Bo(t,n);t.registerLanguageRuntime(Oo),t.registerLanguageRuntime(Ro),t.registerLanguageRuntime(Lo),t.registerLanguageRuntime($o),t.registerLanguageRuntime(jo);const i=new Map;return{async*run(e,t){const n=t?.runId??Fo("run"),s=await r.open({language:e.language,provider:e.metadata?.provider,kernelspec:e.metadata?.kernelspec,env:e.env,cwd:e.cwd,resources:e.resources,metadata:e.metadata});i.set(n,s);try{for await(const n of s.run(e,t))yield n}finally{i.delete(n),await s.close()}},async cancel(e){const t=i.get(e);t&&(await t.interrupt(),i.delete(e))},session:r,registry:t}}(qu?.compute),Qu=function(e){if(e)return e;const t=Uo(),n=new Vo(t),r={resolve:async e=>n.selectProvider(e).resolve(e),mount:async(e,t)=>n.selectProvider(e).mount(e,t),async unmount(e){const n=e.match(/^punica:\/\/dataset\/([^/]+)\/(.+)$/);if(!n)throw new Error(`Invalid dataset URI format: ${e}`);const r=n[1],i=t.getProvider(r);if(!i)throw new Error(`Dataset provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Dataset provider not found: ${e.provider}`);return n.list({query:e.query,tags:e.tags})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({query:e?.query,tags:e?.tags});r.push(...n)}catch(e){console.warn(`Failed to list datasets from provider ${t.id}:`,e)}return r},registry:t};return r}(qu?.datasets),Xu=function(e){if(e)return e;const t=Go(),n=new Ho(t),r={resolve:async e=>n.selectProvider(e).resolve(e),mount:async(e,t)=>n.selectProvider(e).mount(e,t),async unmount(e){const n=e.match(/^punica:\/\/model\/([^/]+)\/(.+)$/);if(!n)throw new Error(`Invalid model endpoint format: ${e}`);const r=n[1],i=t.getProvider(r);if(!i)throw new Error(`Model provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Model provider not found: ${e.provider}`);return n.list({task:e.task,query:e.query})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({task:e?.task,query:e?.query});r.push(...n)}catch(e){console.warn(`Failed to list models from provider ${t.id}:`,e)}return r},registry:t};return r}(qu?.models),ed=function(e){if(e)return e;const t=Zo();return{registry:t,async start(e){const n=function(e){if(e.format&&"unknown"!==e.format)return e.format;const t=e.filePath?.trim().toLowerCase();if(t){if(t.endsWith(".gguf"))return"gguf";if(t.endsWith(".safetensors"))return"safetensors";if(t.endsWith(".onnx"))return"onnx"}return"unknown"}(e),r=n!==e.format?{...e,format:n}:e,i=t.select(r);if(!i){const e=t.list().map(e=>e.id);throw new Error(`No model runtime can run record "${r.id}" (format=${r.format??"unknown"}). Registered runtimes: [${e.join(", ")||"none"}].`)}return i.start(r)},async stop(e){const n=t.get(e.runtimeId);if(!n)throw new Error(`No model runtime registered for handle runtimeId="${e.runtimeId}".`);await n.stop(e)}}}(qu?.modelRuntimes),td=function(e){if(e)return e;const t=Zo();return{async infer(e){const n=e.handle?.runtimeId;if(!n)throw new Error("inference.infer requires a started runtime handle (req.handle from runtime.modelRuntimes.start).");const r=t.get(n);if(!r)throw new Error(`No model runtime registered for handle runtimeId="${n}".`);if("function"!=typeof r.infer)throw new Error(`Model runtime "${n}" does not support inference (no infer()). Task: ${e.task}.`);return r.infer(e)}}}(qu?.inference),nd=function(e){return e||{upsert:(e,t)=>oa().upsert(e,t),query:e=>oa().query(e),delete:(e,t)=>oa().delete(e,t),clear:e=>oa().clear(e),count:e=>oa().count(e)}}(qu?.vectors),rd=function(e){if(e)return e;function t(){const e=aa().servers;if(!e)throw new Error("[Runtime.host] No managed-process (servers) surface is registered. This is only available on hosts that can spawn processes (e.g. Electron); a browser host does not provide it.");return e}function n(){const e=aa().mcpServer;if(!e)throw new Error("[Runtime.host] No inbound MCP server surface is registered. This is only available on hosts that can open a local listener (e.g. Electron); a browser host does not provide it.");return e}const r={start:e=>n().start(e),stop:()=>n().stop(),status:()=>n().status(),onRequest:e=>n().onRequest(e),reply:(e,t)=>n().reply(e,t)};return{dataDir:()=>aa().dataDir(),dataFs:{list:(e,t)=>aa().dataFs.list(e,t),readFile:e=>aa().dataFs.readFile(e),stat:e=>aa().dataFs.stat(e),mkdir:(e,t)=>aa().dataFs.mkdir(e,t),deleteFile:e=>aa().dataFs.deleteFile(e),deleteFolder:e=>aa().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=aa().dataFs;return"function"!=typeof r.readBytes?Promise.reject(new Error("[Runtime.host] readBytes is not supported by this host (only hosts with a real filesystem, e.g. Electron, provide it).")):r.readBytes(e,t,n)},readStrided:(e,t)=>{const n=aa().dataFs;return"function"!=typeof n.readStrided?Promise.reject(new Error("[Runtime.host] readStrided is not supported by this host (only hosts with a real filesystem, e.g. Electron, provide it).")):n.readStrided(e,t)}},servers:{start:e=>t().start(e),stop:e=>t().stop(e),status:e=>t().status(e)},http:{requestJson:e=>function(){const e=aa().http;if(!e)throw new Error("[Runtime.host] No JSON-over-HTTP (http) surface is registered. This is only available on hosts with network access (e.g. Electron); a browser host does not provide it.");return e}().requestJson(e)},get mcpServer(){return sa?.mcpServer?r:void 0}}}(qu?.host),id=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&qc(e);return{set:(e,t)=>Fc.get().set(e,t),get:e=>Fc.get().get(e),delete:e=>Fc.get().delete(e),list:()=>Fc.get().list(),__punicaWrappedSecretsFacade:!0}}(qu?.secrets);console.log("[Runtime] Facades created"),function(){bu({name:"fs.readFile",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Tc),bu({name:"fs.writeFile",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),ua.registerProvider(new Nc),bu({name:"fs.listFiles",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Mc),bu({name:"fs.stat",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"object",required:["size","mtimeMs","ctimeMs","isDirectory","isSymlink"],properties:{size:{type:"number"},mtimeMs:{type:"number"},ctimeMs:{type:"number"},mode:{type:"number"},isDirectory:{type:"boolean"},isSymlink:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Dc),bu({name:"fs.exists",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"boolean"},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Pc),bu({name:"fs.copy",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["src","dst"],properties:{src:{type:"string"},dst:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),ua.registerProvider(new Oc),bu({name:"fs.mkdir",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),ua.registerProvider(new Rc),bu({name:"fs.list",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new jc),bu({name:"fs.history",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Lc),bu({name:"fs.readAtVersion",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path","versionId"],properties:{path:{type:"string"},versionId:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new $c),bu({name:"secrets.get",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"}}},outputSchema:{type:["string","null"]},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3}}),ua.registerProvider(new zc),bu({name:"secrets.set",version:"1.0.0",sideEffect:"write",risk:"high",permissions:[],inputSchema:{type:"object",required:["name","value"],properties:{name:{type:"string"},value:{type:"string"}}},outputSchema:{type:"null"},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3,idempotency:"required"}}),ua.registerProvider(new Uc),bu({name:"llm.chat",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),ua.registerProvider(new Wc),bu({name:"llm.chatStream",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),ua.registerProvider(new Kc),bu({name:"llm.plan",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["query"],properties:{query:{type:"string"},capabilities:{type:"array"}}},outputSchema:{type:"object",properties:{ok:{type:"boolean"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),ua.registerProvider(new Hc),bu({name:"llm.invoke",version:"1.0.0",sideEffect:"network",risk:"low",permissions:[],inputSchema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string"},userPrompt:{type:"string"},context:{type:"object"},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"},stream:{type:"boolean"},skipCache:{type:"boolean"},skipFallback:{type:"boolean"}}}}},outputSchema:{type:"object",properties:{ok:{type:"boolean"},result:{type:"string"},parsed:{}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),ua.registerProvider(new Gc),bu({name:"search.query",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["q"],properties:{q:{type:"string"},limit:{type:"number"}}},outputSchema:{type:"object",properties:{results:{type:"array"}}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Yc),bu({name:"vcs.status",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),ua.registerProvider(new Jc),bu({name:"vcs.commit",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["message"],properties:{message:{type:"string"},all:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),ua.registerProvider(new Zc),bu({name:"workspace.readFile",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new Qc),bu({name:"workspace.writeFile",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),ua.registerProvider(new Xc),bu({name:"workspace.listFiles",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object"}}}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new el),bu({name:"terminals.create",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",properties:{title:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),ua.registerProvider(new tl),bu({name:"terminals.send",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["id","text"],properties:{id:{type:"string"},text:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:5e3,idempotency:"optional"}}),ua.registerProvider(new nl),bu({name:"tasks.runCommand",version:"1.0.0",sideEffect:"write",risk:"high",permissions:[],inputSchema:{type:"object",required:["command"],properties:{command:{type:"string"},args:{type:"array"},cwd:{type:"string"},env:{type:"object"}}},outputSchema:{type:"object",properties:{exitCode:{type:["number","null"]},stdout:{type:"string"},stderr:{type:"string"}}},defaults:{timeoutMs:3e5,concurrency:{key:"workspace:{workspaceId}",max:3},idempotency:"required"}}),ua.registerProvider(new rl),bu({name:"flow.migrate",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["document","targetVersion"],properties:{document:{type:"object"},targetVersion:{type:"string"},policy:{type:"string",enum:["auto-migrate","warn","reject"]}}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),ua.registerProvider(new il),bu({name:"flow.runSubflow",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["spec"],properties:{spec:{type:"object"},workspaceId:{type:"string"},input:{},parentRunId:{type:"string"},parentTraceId:{type:"string"},parentDepth:{type:"number",minimum:0,maximum:8},filePathOrUri:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:3e5,idempotency:"optional"}}),ua.registerProvider(new sl),bu({name:ol,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{origin:{type:["string","array"]},extension:{type:"string"},tags:{type:["string","array"]},risk:{type:["string","array"]},sideEffects:{type:["string","array"]}}},outputSchema:{type:"object",required:["capabilities","count"],properties:{capabilities:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new al),bu({name:fl,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{version:{type:"string"},filter:{type:"object"},mode:{type:"string",enum:["full","ai-tools","summary"]}}},outputSchema:{type:"object",required:["schemaVersion","generatedAt","capabilities","count"],properties:{schemaVersion:{type:"string"},generatedAt:{type:"number"},capabilities:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new ml),bu({name:kl,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["intent"],properties:{intent:{type:"string"},limit:{type:"number"}}},outputSchema:{type:"object",required:["recommendations","path","count"],properties:{recommendations:{type:"array"},path:{type:"string"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new Il),bu({name:Al,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",description:"What you need to do, in natural language."},limit:{type:"number"}}},outputSchema:{type:"object",required:["results","count"],properties:{results:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new xl),bu({name:El,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},minItems:1,maxItems:16,description:"Capability ids to load full definitions for."}}},outputSchema:{type:"object",required:["tools","missing"],properties:{tools:{type:"array"},missing:{type:"array",items:{type:"string"}}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new _l);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Tl("ai.session.create",{properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),Tl("ai.session.list",{properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),Tl("ai.session.get",{required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),Tl("ai.session.rename",{required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),Tl("ai.session.archive",{required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),Tl("ai.session.delete",{risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())bu(e);for(const e of[new Nl,new Ml,new Dl,new Pl,new Ol,new Rl])ua.registerProvider(e);bu({name:Yl,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{capabilityId:{type:"string"}}},outputSchema:{type:"object",required:["results","ok","count"],properties:{results:{type:"array"},ok:{type:"boolean"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new Jl),bu({name:eu,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{filter:{type:"object"}}},outputSchema:{type:"object",required:["tools","count"],properties:{tools:{type:"array"},count:{type:"number"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new ru),bu({name:tu,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"},arguments:{type:"object"}}},outputSchema:{type:"object",required:["content"],properties:{content:{type:"array"},isError:{type:"boolean"}}},defaults:{timeoutMs:3e4}}),ua.registerProvider(new iu),bu({name:su,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["viewId","revealed"],properties:{viewId:{type:"string"},revealed:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new pu),bu({name:ou,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"}}},outputSchema:{type:"object",required:["viewId","hidden"],properties:{viewId:{type:"string"},hidden:{type:"boolean"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new hu),bu({name:au,version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",required:["views"],properties:{views:{type:"array"}}},defaults:{timeoutMs:5e3}}),ua.registerProvider(new fu),bu({name:cu,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["viewId","visible"],properties:{viewId:{type:"string"},visible:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new mu),bu({name:lu,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["slot"],properties:{slot:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["slot","visible"],properties:{slot:{type:"string"},visible:{type:"boolean"},viewId:{type:"string"}}},defaults:{timeoutMs:1e4}}),ua.registerProvider(new yu)}(),console.log("[Runtime] Capabilities registered");const sd={lifecyclePhase:qu?.lifecyclePhase??"bootstrapping",fs:zu,fileOpeners:qu?.fileOpeners??io,search:Uu,vcs:Vu,terminals:Wu,debug:Ku,tasks:Gu,workspace:Hu,resources:Yu,secrets:id,llm:Ju,compute:Zu,datasets:Qu,models:Xu,modelRuntimes:ed,inference:td,vectors:nd,host:rd,capabilities:{gateway:_c,unifiedRegistry:Ia,logTrinityCatalog:ku,docs:{formatCapabilityMarkdown:function(e){const t=e.definition,n=[];n.push(`# \`${t.id}\``),n.push(""),n.push(function(e){const t=e.definition,n=[];n.push(`**Origin:** ${e.origin}`),n.push(`**Version:** ${t.version}`);const r=t.policy?.risk??"—",i=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${i}`);const s=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";return n.push(`**Side effects:** ${s}`),n.join(" · ")}(e)),n.push("");const r=t.description??t.title;r&&r.length>0&&(n.push(r),n.push("")),void 0!==t.inputs?.schema&&(n.push("## Input schema"),n.push(""),n.push("```json"),n.push(Su(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Su(t.outputs.schema)),n.push("```"),n.push("")),t.tags&&t.tags.length>0&&(n.push("## Tags"),n.push(""),n.push(t.tags.join(", ")),n.push(""));const i=t.requires;if(i&&i.length>0){n.push("## Requires"),n.push("");for(const e of i)n.push(`- \`${e}\``);n.push("")}if(t.deprecated){n.push("## Deprecated"),n.push("");const e=[];e.push(`**Since:** ${t.deprecated.since}`),t.deprecated.reason&&e.push(`— ${t.deprecated.reason}`),n.push(e.join(" ")),t.deprecated.replacement&&(n.push(""),n.push(`**Replacement:** \`${t.deprecated.replacement}\``)),n.push("")}const s=function(e){const t=e.metadata;if(!t)return;const n=[];t.extensionName&&n.push(`- Extension: \`${t.extensionName}\``);t.productId&&n.push(`- Product: \`${t.productId}\``);t.packageRoot&&n.push(`- Manifest: \`${t.packageRoot}\``);return n.length>0?n.join("\n"):void 0}(e);for(s&&(n.push("## Source"),n.push(""),n.push(s),n.push(""));n.length>1&&""===n[n.length-1];)n.pop();return n.join("\n")+"\n"},formatCapabilitiesIndex:function(e){const t=[];t.push("# Capability Reference"),t.push(""),t.push("Auto-generated from the substrate's unified capability registry."),t.push("Run `npm run docs:capabilities` to regenerate — CI gates drift."),t.push("");const n=function(e){const t=new Map;for(const n of e){const e=t.get(n.origin)??[];e.push(n),t.set(n.origin,e)}for(const e of t.values())e.sort((e,t)=>e.definition.id.localeCompare(t.definition.id));return t}(e),r=["core","extension","instruction-class","ivy-node"];for(const e of r){const r=n.get(e);if(r&&0!==r.length){t.push(`## ${Eu(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(Au(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:_u,connect:e=>Pu.connect(e),disconnect:e=>Pu.disconnect(e),listServers:()=>Pu.listServers(),listTools:e=>Pu.listTools(e),callTool:(e,t,n)=>Pu.callTool(e,t,n)},setFsProvider:function(e){La.set(e),e&&bo({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:Co,setComputeProvider:function(e){Mo().registerProvider(e)},setComputeRuntime:function(e){Mo().registerLanguageRuntime(e)},setDatasetProvider:function(e){Uo().registerProvider(e)},setModelProvider:function(e){Go().registerProvider(e)},setModelRuntime:function(e){Zo().register(e)},setHostProvider:function(e){sa=e},setVectorsProvider:function(e){ra=e},setSearchProvider:function(e){oo=e},setWorkspaceProvider:ko,setTerminalProvider:function(e){co=e},setDebugProvider:function(e){lo=e},setVcsProvider:function(e){uo=e},setResourcesProvider:function(e){so=e},setTasksProvider:function(e){ao=e},setSecretsProvider:qc};class od{#It;constructor(e){this.#It=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#It);n?e(n):t(new Error("Extension not found"))})}}let ad=class{#Et;constructor(e){this.#Et=e}async execute(){return await this.#Et.execute()}},cd=class extends ad{constructor(e){super(e)}async execute(){return await super.execute()}},ld=class extends ad{constructor(e){super(e)}async execute(){try{const e=await super.execute(),t=`${e.moduleURL}${e.main}`,n=(await import(/* webpackIgnore: true */`${t}`)).default;return e.module=n,e}catch(e){if(e instanceof Error)throw e;throw new Error(String(e))}}},ud=class extends ad{constructor(e){super(e)}async execute(){return await super.execute()}};const dd=Symbol.for("yaml.alias"),pd=Symbol.for("yaml.document"),hd=Symbol.for("yaml.map"),fd=Symbol.for("yaml.pair"),md=Symbol.for("yaml.scalar"),gd=Symbol.for("yaml.seq"),yd=Symbol.for("yaml.node.type"),bd=e=>!!e&&"object"==typeof e&&e[yd]===dd,wd=e=>!!e&&"object"==typeof e&&e[yd]===pd,vd=e=>!!e&&"object"==typeof e&&e[yd]===hd,kd=e=>!!e&&"object"==typeof e&&e[yd]===fd,Id=e=>!!e&&"object"==typeof e&&e[yd]===md,Ed=e=>!!e&&"object"==typeof e&&e[yd]===gd;function Ad(e){if(e&&"object"==typeof e)switch(e[yd]){case hd:case gd:return!0}return!1}function Sd(e){if(e&&"object"==typeof e)switch(e[yd]){case dd:case hd:case md:case gd:return!0}return!1}const _d=Symbol("break visit"),xd=Symbol("skip children"),Cd=Symbol("remove node");function Td(e,t){const n=Pd(t);if(wd(e)){Nd(null,e.contents,n,Object.freeze([e]))===Cd&&(e.contents=null)}else Nd(null,e,n,Object.freeze([]))}function Nd(e,t,n,r){const i=Od(e,t,n,r);if(Sd(i)||kd(i))return Rd(e,r,i),Nd(e,i,n,r);if("symbol"!=typeof i)if(Ad(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Nd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===_d)return _d;i===Cd&&(t.items.splice(e,1),e-=1)}}}else if(kd(t)){r=Object.freeze(r.concat(t));const e=Nd("key",t.key,n,r);if(e===_d)return _d;e===Cd&&(t.key=null);const i=Nd("value",t.value,n,r);if(i===_d)return _d;i===Cd&&(t.value=null)}return i}async function Md(e,t){const n=Pd(t);if(wd(e)){await Dd(null,e.contents,n,Object.freeze([e]))===Cd&&(e.contents=null)}else await Dd(null,e,n,Object.freeze([]))}async function Dd(e,t,n,r){const i=await Od(e,t,n,r);if(Sd(i)||kd(i))return Rd(e,r,i),Dd(e,i,n,r);if("symbol"!=typeof i)if(Ad(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await Dd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===_d)return _d;i===Cd&&(t.items.splice(e,1),e-=1)}}}else if(kd(t)){r=Object.freeze(r.concat(t));const e=await Dd("key",t.key,n,r);if(e===_d)return _d;e===Cd&&(t.key=null);const i=await Dd("value",t.value,n,r);if(i===_d)return _d;i===Cd&&(t.value=null)}return i}function Pd(e){return"object"==typeof e&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Od(e,t,n,r){return"function"==typeof n?n(e,t,r):vd(t)?n.Map?.(e,t,r):Ed(t)?n.Seq?.(e,t,r):kd(t)?n.Pair?.(e,t,r):Id(t)?n.Scalar?.(e,t,r):bd(t)?n.Alias?.(e,t,r):void 0}function Rd(e,t,n){const r=t[t.length-1];if(Ad(r))r.items[e]=n;else if(kd(r))"key"===e?r.key=n:r.value=n;else{if(!wd(r)){const e=bd(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Td.BREAK=_d,Td.SKIP=xd,Td.REMOVE=Cd,Md.BREAK=_d,Md.SKIP=xd,Md.REMOVE=Cd;const Ld={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},$d=e=>e.replace(/[!,[\]{}]/g,e=>Ld[e]);class jd{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},jd.defaultYaml,e),this.tags=Object.assign({},jd.defaultTags,t)}clone(){const e=new jd(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new jd(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:jd.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},jd.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:jd.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},jd.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(2!==n.length&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[e,r]=n;return this.tags[e]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==n.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=n;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const n=e.slice(2,-1);return"!"===n||"!!"===n?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),n)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return"!"===n?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+$d(e.substring(n.length));return"!"===e[0]?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&Sd(e.contents)){const t={};Td(e.contents,(e,n)=>{Sd(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(const[i,s]of n)"!!"===i&&"tag:yaml.org,2002:"===s||e&&!r.some(e=>e.startsWith(s))||t.push(`%TAG ${i} ${s}`);return t.join("\n")}}function Fd(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);throw new Error(`Anchor must not contain whitespace or control characters: ${t}`)}return!0}function Bd(e){const t=new Set;return Td(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function qd(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function zd(e,t,n,r){if(r&&"object"==typeof r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){const n=r[t],i=zd(e,r,String(t),n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),i=zd(e,r,t,n);void 0===i?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(const t of Array.from(r)){const n=zd(e,r,t,t);void 0===n?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(const[t,n]of Object.entries(r)){const i=zd(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function Ud(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Ud(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Id(r=e)&&!Ad(r)||!r.anchor))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=e=>{i.res=e,delete n.onCreate};const s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}var r;return"bigint"!=typeof e||n?.keep?e:Number(e)}jd.defaultYaml={explicit:!1,version:"1.2"},jd.defaultTags={"!!":"tag:yaml.org,2002:"};class Vd{constructor(e){Object.defineProperty(this,yd,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!wd(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=Ud(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?zd(i,{"":o},"",o):o}}class Wd extends Vd{constructor(e){super(dd),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Td(e,{Node:(e,n)=>{if(n===this)return Td.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,s=this.resolve(r);if(!s){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(s);if(o||(Ud(s,null,t),o=n.get(s)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(i>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=Kd(r,s,n)),o.count*o.aliasCount>i)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return o.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(Fd(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${r} `}return r}}function Kd(e,t,n){if(bd(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Ad(t)){let r=0;for(const i of t.items){const t=Kd(e,i,n);t>r&&(r=t)}return r}if(kd(t)){const r=Kd(e,t.key,n),i=Kd(e,t.value,n);return Math.max(r,i)}return 1}const Gd=e=>!e||"function"!=typeof e&&"object"!=typeof e;class Hd extends Vd{constructor(e){super(md),this.value=e}toJSON(e,t){return t?.keep?this.value:Ud(this.value,e,t)}toString(){return String(this.value)}}Hd.BLOCK_FOLDED="BLOCK_FOLDED",Hd.BLOCK_LITERAL="BLOCK_LITERAL",Hd.PLAIN="PLAIN",Hd.QUOTE_DOUBLE="QUOTE_DOUBLE",Hd.QUOTE_SINGLE="QUOTE_SINGLE";function Yd(e,t,n){if(wd(e)&&(e=e.contents),Sd(e))return e;if(kd(e)){const t=n.schema[hd].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||"undefined"!=typeof BigInt&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n;let c;if(r&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=i(e)),new Wd(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t="tag:yaml.org,2002:"+t.slice(2));let l=function(e,t,n){if(t){const e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}(e,t,o.tags);if(!l){if(e&&"function"==typeof e.toJSON&&(e=e.toJSON()),!e||"object"!=typeof e){const t=new Hd(e);return c&&(c.node=t),t}l=e instanceof Map?o[hd]:Symbol.iterator in Object(e)?o[gd]:o[hd]}s&&(s(l),delete n.onTagObj);const u=l?.createNode?l.createNode(n.schema,e,n):"function"==typeof l?.nodeClass?.from?l.nodeClass.from(n.schema,e,n):new Hd(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Jd(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){const n=t[e];if("number"==typeof n&&Number.isInteger(n)&&n>=0){const e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Yd(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const Zd=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class Qd extends Vd{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>Sd(t)||kd(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Zd(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Ad(i))i.addIn(r,t);else{if(void 0!==i||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,Jd(this.schema,r,t))}}}deleteIn(e){const[t,...n]=e;if(0===n.length)return this.delete(t);const r=this.get(t,!0);if(Ad(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return 0===r.length?!t&&Id(i)?i.value:i:Ad(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!kd(t))return!1;const n=t.value;return null==n||e&&Id(n)&&null==n.value&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(0===n.length)return this.has(t);const r=this.get(t,!0);return!!Ad(r)&&r.hasIn(n)}setIn(e,t){const[n,...r]=e;if(0===r.length)this.set(n,t);else{const e=this.get(n,!0);if(Ad(e))e.setIn(r,t);else{if(void 0!==e||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,Jd(this.schema,r,t))}}}}Qd.maxFlowStringSingleLineLength=60;const Xd=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ep(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const tp=(e,t,n)=>e.endsWith("\n")?ep(n,t):n.includes("\n")?"\n"+ep(n,t):(e.endsWith(" ")?"":" ")+n,np="flow",rp="block",ip="quoted";function sp(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let d,p,h=i-t.length;"number"==typeof r&&(r>i-Math.max(2,s)?l.push(0):h=i-r);let f=!1,m=-1,g=-1,y=-1;n===rp&&(m=op(e,m,t.length),-1!==m&&(h=m+c));for(let r;r=e[m+=1];){if(n===ip&&"\\"===r){switch(g=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if("\n"===r)n===rp&&(m=op(e,m,t.length)),h=m+t.length+c,d=void 0;else{if(" "===r&&p&&" "!==p&&"\n"!==p&&"\t"!==p){const t=e[m+1];t&&" "!==t&&"\n"!==t&&"\t"!==t&&(d=m)}if(m>=h)if(d)l.push(d),h=d+c,d=void 0;else if(n===ip){for(;" "===p||"\t"===p;)p=r,r=e[m+=1],f=!0;const t=m>y+1?m-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,h=t+c,d=void 0}else f=!0}p=r}if(f&&a&&a(),0===l.length)return e;o&&o();let b=e.slice(0,l[0]);for(let r=0;r<l.length;++r){const i=l[r],s=l[r+1]||e.length;0===i?b=`\n${t}${e.slice(0,s)}`:(n===ip&&u[i]&&(b+=`${e[i]}\\`),b+=`\n${t}${e.slice(i+1,s)}`)}return b}function op(e,t,n){let r=t,i=t+1,s=e[i];for(;" "===s||"\t"===s;)if(t<i+n)s=e[++t];else{do{s=e[++t]}while(s&&"\n"!==s);r=t,i=t+1,s=e[i]}return r}const ap=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),cp=e=>/^(%|---|\.\.\.)/m.test(e);function lp(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(cp(e)?" ":"");let o="",a=0;for(let e=0,t=n[e];t;t=n[++e])if(" "===t&&"\\"===n[e+1]&&"n"===n[e+2]&&(o+=n.slice(a,e)+"\\ ",e+=1,a=e,t="\\"),"\\"===t)switch(n[e+1]){case"u":{o+=n.slice(a,e);const t=n.substr(e+2,4);switch(t){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===t.substr(0,2)?o+="\\x"+t.substr(2):o+=n.substr(e,6)}e+=5,a=e+1}break;case"n":if(r||'"'===n[e+2]||n.length<i)e+=1;else{for(o+=n.slice(a,e)+"\n\n";"\\"===n[e+2]&&"n"===n[e+3]&&'"'!==n[e+4];)o+="\n",e+=2;o+=s," "===n[e+2]&&(o+="\\"),e+=1,a=e+1}break;default:e+=1}return o=a?o+n.slice(a):n,r?o:sp(o,s,ip,ap(t,!1))}function up(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return lp(e,t);const n=t.indent||(cp(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:sp(r,n,np,ap(t,!1))}function dp(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=lp;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?up:i&&!t?lp:n?up:lp}return r(e,t)}let pp;try{pp=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{pp=/\n+(?!\n|$)/g}function hp({comment:e,type:t,value:n},r,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return dp(n,r);const l=r.indent||(r.forceBlockIndent||cp(n)?" ":""),u="literal"===o||"folded"!==o&&t!==Hd.BLOCK_FOLDED&&(t===Hd.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}(n,c,l.length));if(!n)return u?"|\n":">\n";let d,p;for(p=n.length;p>0;--p){const e=n[p-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let h=n.substring(p);const f=h.indexOf("\n");-1===f?d="-":n===h||f!==h.length-1?(d="+",s&&s()):d="",h&&(n=n.slice(0,-h.length),"\n"===h[h.length-1]&&(h=h.slice(0,-1)),h=h.replace(pp,`$&${l}`));let m,g=!1,y=-1;for(m=0;m<n.length;++m){const e=n[m];if(" "===e)g=!0;else{if("\n"!==e)break;y=m}}let b=n.substring(0,y<m?y+1:m);b&&(n=n.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let w=(u?"|":">")+(g?l?"2":"1":"")+d;if(e&&(w+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),u)return`${w}\n${l}${b}${n=n.replace(/\n+/g,`$&${l}`)}${h}`;return`${w}\n${l}${sp(`${b}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${h}`,l,rp,ap(r,!0))}`}function fp(e,t,n,r){const{implicitKey:i,inFlow:s}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Hd.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Hd.QUOTE_DOUBLE);const c=e=>{switch(e){case Hd.BLOCK_FOLDED:case Hd.BLOCK_LITERAL:return i||s?dp(o.value,t):hp(o,t,n,r);case Hd.QUOTE_DOUBLE:return lp(o.value,t);case Hd.QUOTE_SINGLE:return up(o.value,t);case Hd.PLAIN:return function(e,t,n,r){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&s.includes("\n")||u&&/[[\]{},]/.test(s))return dp(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?dp(s,t):hp(e,t,n,r);if(!a&&!u&&i!==Hd.PLAIN&&s.includes("\n"))return hp(e,t,n,r);if(cp(s)){if(""===c)return t.forceBlockIndent=!0,hp(e,t,n,r);if(a&&c===l)return dp(s,t)}const d=s.replace(/\n+/g,`$&\n${c}`);if(o){const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return dp(s,t)}return a?d:sp(d,c,np,ap(t,!1))}(o,t,n,r);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}function mp(e,t){const n=Object.assign({blockQuote:!0,commentString:Xd,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof n.indent?" ".repeat(n.indent):" ",inFlow:r,options:n}}function gp(e,t,n,r){if(kd(e))return e.toString(t,n,r);if(bd(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=Sd(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i||(i=function(e,t){if(t.tag){const n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(Id(t)){r=t.value;const i=e.filter(e=>e.identify?.(r));n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n)throw new Error(`Tag not resolved for ${r?.constructor?.name??typeof r} value`);return n}(t.doc.schema.tags,s));const o=function(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const i=[],s=(Id(e)||Ad(e))&&e.anchor;s&&Fd(s)&&(n.add(s),i.push(`&${s}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&i.push(r.directives.tagString(o)),i.join(" ")}(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof i.stringify?i.stringify(s,t,n,r):Id(s)?fp(s,t,n,r):s.toString(t,n,r);return o?Id(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function yp(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function bp(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&wp(n))if(r=bd(r)?r.resolve(e.doc):r,Ed(r))for(const n of r.items)vp(e,t,n);else if(Array.isArray(r))for(const n of r)vp(e,t,n);else vp(e,t,r);else{const i=Ud(n,"",e);if(t instanceof Map)t.set(i,Ud(r,i,e));else if(t instanceof Set)t.add(i);else{const s=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(Sd(e)&&n?.doc){const t=mp(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;const r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+'..."'),yp(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}(n,i,e),o=Ud(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const wp=e=>"<<"===e||Id(e)&&"<<"===e.value&&(!e.type||e.type===Hd.PLAIN);function vp(e,t,n){const r=e&&bd(n)?n.resolve(e.doc):n;if(!vd(r))throw new Error("Merge sources must be maps or map aliases");const i=r.toJSON(null,e,Map);for(const[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function kp(e,t,n){const r=Yd(e,void 0,n),i=Yd(t,void 0,n);return new Ip(r,i)}class Ip{constructor(e,t=null){Object.defineProperty(this,yd,{value:fd}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Sd(t)&&(t=t.clone(e)),Sd(n)&&(n=n.clone(e)),new Ip(t,n)}toJSON(e,t){return bp(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,r,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n;let p=Sd(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Ad(e)||!Sd(e)&&"object"==typeof e)throw new Error("With simple keys, collection cannot be used as a key value")}let h=!d&&(!e||p&&null==t&&!n.inFlow||Ad(e)||(Id(e)?e.type===Hd.BLOCK_FOLDED||e.type===Hd.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(d||!s),indent:a+c});let f,m,g,y=!1,b=!1,w=gp(e,n,()=>y=!0,()=>b=!0);if(!h&&!n.inFlow&&w.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||null==t)return y&&r&&r(),""===w?"?":h?`? ${w}`:w}else if(s&&!d||null==t&&h)return w=`? ${w}`,p&&!y?w+=tp(w,n.indent,l(p)):b&&i&&i(),w;y&&(p=null),h?(p&&(w+=tp(w,n.indent,l(p))),w=`? ${w}\n${a}:`):(w=`${w}:`,p&&(w+=tp(w,n.indent,l(p)))),Sd(t)?(f=!!t.spaceBefore,m=t.commentBefore,g=t.comment):(f=!1,m=null,g=null,t&&"object"==typeof t&&(t=o.createNode(t))),n.implicitKey=!1,h||p||!Id(t)||(n.indentAtStart=w.length+1),b=!1,u||!(c.length>=2)||n.inFlow||h||!Ed(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let v=!1;const k=gp(t,n,()=>v=!0,()=>b=!0);let I=" ";if(p||f||m)I=f?"\n":"",m&&(I+=`\n${ep(l(m),n.indent)}`),""!==k||n.inFlow?I+=`\n${n.indent}`:"\n"===I&&(I="\n\n");else if(!h&&Ad(t)){const e=k[0],r=k.indexOf("\n"),i=-1!==r,s=n.inFlow??t.flow??0===t.items.length;if(i||!s){let t=!1;if(i&&("&"===e||"!"===e)){let n=k.indexOf(" ");"&"===e&&-1!==n&&n<r&&"!"===k[n+1]&&(n=k.indexOf(" ",n+1)),(-1===n||r<n)&&(t=!0)}t||(I=`\n${n.indent}`)}}else""!==k&&"\n"!==k[0]||(I="");return w+=I+k,n.inFlow?v&&r&&r():g&&!v?w+=tp(w,n.indent,l(g)):b&&i&&i(),w}(this,e,t,n):JSON.stringify(this)}}function Ep(e,t,n){return(t.inFlow??e.flow?Sp:Ap)(e,t,n)}function Ap({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null});let d=!1;const p=[];for(let e=0;e<t.length;++e){const i=t[e];let o=null;if(Sd(i))!d&&i.spaceBefore&&p.push(""),_p(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(kd(i)){const e=Sd(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),_p(n,p,e.commentBefore,d))}d=!1;let a=gp(i,u,()=>o=null,()=>d=!0);o&&(a+=tp(a,s,l(o))),d&&o&&(d=!1),p.push(r+a)}let h;if(0===p.length)h=i.start+i.end;else{h=p[0];for(let e=1;e<p.length;++e){const t=p[e];h+=t?`\n${c}${t}`:"\n"}}return e?(h+="\n"+ep(l(e),c),a&&a()):d&&o&&o(),h}function Sp({items:e},t,{flowChars:n,itemIndent:r}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;r+=s;const c=Object.assign({},t,{indent:r,inFlow:!0,type:null});let l=!1,u=0;const d=[];for(let n=0;n<e.length;++n){const i=e[n];let s=null;if(Sd(i))i.spaceBefore&&d.push(""),_p(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(kd(i)){const e=Sd(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),_p(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Sd(i.value)?i.value:null;n?(n.comment&&(s=n.comment),n.commentBefore&&(l=!0)):null==i.value&&e?.comment&&(s=e.comment)}s&&(l=!0);let o=gp(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=tp(o,r,a(s))),!l&&(d.length>u||o.includes("\n"))&&(l=!0),d.push(o),u=d.length}const{start:p,end:h}=n;if(0===d.length)return p+h;if(!l){const e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=p;for(const t of d)e+=t?`\n${s}${i}${t}`:"\n";return`${e}\n${i}${h}`}return`${p}${o}${d.join(" ")}${o}${h}`}function _p({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=ep(t(r),e);n.push(i.trimStart())}}function xp(e,t){const n=Id(t)?t.value:t;for(const r of e)if(kd(r)){if(r.key===t||r.key===n)return r;if(Id(r.key)&&r.key.value===n)return r}}class Cp extends Qd{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(hd,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:i}=n,s=new this(e),o=(e,o)=>{if("function"==typeof i)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(void 0!==o||r)&&s.items.push(kp(e,o,n))};if(t instanceof Map)for(const[e,n]of t)o(e,n);else if(t&&"object"==typeof t)for(const e of Object.keys(t))o(e,t[e]);return"function"==typeof e.sortMapEntries&&s.items.sort(e.sortMapEntries),s}add(e,t){let n;n=kd(e)?e:e&&"object"==typeof e&&"key"in e?new Ip(e.key,e.value):new Ip(e,e?.value);const r=xp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Id(r.value)&&Gd(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const e=this.items.findIndex(e=>i(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=xp(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=xp(this.items,e),r=n?.value;return(!t&&Id(r)?r.value:r)??void 0}has(e){return!!xp(this.items,e)}set(e,t){this.add(new Ip(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const e of this.items)bp(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!kd(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ep(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Tp={collection:"map",default:!0,nodeClass:Cp,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(vd(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Cp.from(e,t,n)};class Np extends Qd{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(gd,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Mp(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Mp(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Id(r)?r.value:r}has(e){const t=Mp(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Mp(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Id(r)&&Gd(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const e of this.items)n.push(Ud(e,String(r++),t));return n}toString(e,t,n){return e?Ep(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let s of t){if("function"==typeof r){const n=t instanceof Set?s:String(e++);s=r.call(t,n,s)}i.items.push(Yd(s,void 0,n))}}return i}}function Mp(e){let t=Id(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const Dp={collection:"seq",default:!0,nodeClass:Np,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Ed(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Np.from(e,t,n)},Pp={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>fp(e,t=Object.assign({actualString:!0},t),n,r)},Op={identify:e=>null==e,createNode:()=>new Hd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Hd(null),stringify:({source:e},t)=>"string"==typeof e&&Op.test.test(e)?e:t.options.nullStr},Rp={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Hd("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Rp.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Lp({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const i="number"==typeof r?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(s)){let e=s.indexOf(".");e<0&&(e=s.length,s+=".");let n=t-(s.length-e-1);for(;n-- >0;)s+="0"}return s}const $p={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Lp},jp={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():Lp(e)}},Fp={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const t=new Hd(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Lp},Bp=e=>"bigint"==typeof e||Number.isInteger(e),qp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function zp(e,t,n){const{value:r}=e;return Bp(r)&&r>=0?n+r.toString(t):Lp(e)}const Up={identify:e=>Bp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>qp(e,2,8,n),stringify:e=>zp(e,8,"0o")},Vp={identify:Bp,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>qp(e,0,10,n),stringify:Lp},Wp={identify:e=>Bp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>qp(e,2,16,n),stringify:e=>zp(e,16,"0x")},Kp=[Tp,Dp,Pp,Op,Rp,Up,Vp,Wp,$p,jp,Fp];function Gp(e){return"bigint"==typeof e||Number.isInteger(e)}const Hp=({value:e})=>JSON.stringify(e),Yp=[Tp,Dp].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Hp},{identify:e=>null==e,createNode:()=>new Hd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Hp},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:Hp},{identify:Gp,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Gp(e)?e.toString():JSON.stringify(e)},{identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Hp}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),Jp={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if("function"==typeof Buffer)return Buffer.from(e,"base64");if("function"==typeof atob){const t=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,i,s){const o=n;let a;if("function"==typeof Buffer)a=o instanceof Buffer?o.toString("base64"):Buffer.from(o.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);a=btoa(e)}}if(t||(t=Hd.BLOCK_LITERAL),t!==Hd.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(a.length/e),i=new Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=a.substr(r,e);a=i.join(t===Hd.BLOCK_LITERAL?"\n":" ")}return fp({comment:e,type:t,value:a},r,i,s)}};function Zp(e,t){if(Ed(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!kd(r)){if(vd(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Ip(new Hd(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){const t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=kd(r)?r:new Ip(r)}}else t("Expected a sequence for this tag");return e}function Qp(e,t,n){const{replacer:r}=n,i=new Np(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){let o,a;if("function"==typeof r&&(e=r.call(t,String(s++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);o=e[0],a=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);o=t[0],a=e[o]}else o=e;i.items.push(kp(o,a,n))}return i}const Xp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zp,createNode:Qp};class eh extends Np{constructor(){super(),this.add=Cp.prototype.add.bind(this),this.delete=Cp.prototype.delete.bind(this),this.get=Cp.prototype.get.bind(this),this.has=Cp.prototype.has.bind(this),this.set=Cp.prototype.set.bind(this),this.tag=eh.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const e of this.items){let r,i;if(kd(e)?(r=Ud(e.key,"",t),i=Ud(e.value,r,t)):r=Ud(e,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,i)}return n}static from(e,t,n){const r=Qp(e,t,n),i=new this;return i.items=r.items,i}}eh.tag="tag:yaml.org,2002:omap";const th={collection:"seq",identify:e=>e instanceof Map,nodeClass:eh,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=Zp(e,t),r=[];for(const{key:e}of n.items)Id(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new eh,n)},createNode:(e,t,n)=>eh.from(e,t,n)};function nh({value:e,source:t},n){return t&&(e?rh:ih).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const rh={identify:e=>!0===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hd(!0),stringify:nh},ih={identify:e=>!1===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hd(!1),stringify:nh},sh={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Lp},oh={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():Lp(e)}},ah={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){const t=new Hd(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(-1!==n){const r=e.substring(n+1).replace(/_/g,"");"0"===r[r.length-1]&&(t.minFractionDigits=r.length)}return t},stringify:Lp},ch=e=>"bigint"==typeof e||Number.isInteger(e);function lh(e,t,n,{intAsBigInt:r}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const s=parseInt(e,n);return"-"===i?-1*s:s}function uh(e,t,n){const{value:r}=e;if(ch(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return Lp(e)}const dh={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>lh(e,2,2,n),stringify:e=>uh(e,2,"0b")},ph={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>lh(e,1,8,n),stringify:e=>uh(e,8,"0")},hh={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>lh(e,0,10,n),stringify:Lp},fh={identify:ch,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>lh(e,2,16,n),stringify:e=>uh(e,16,"0x")};class mh extends Cp{constructor(e){super(e),this.tag=mh.tag}add(e){let t;t=kd(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Ip(e.key,null):new Ip(e,null);xp(this.items,t.key)||this.items.push(t)}get(e,t){const n=xp(this.items,e);return!t&&kd(n)?Id(n.key)?n.key.value:n.key:n}set(e,t){if("boolean"!=typeof t)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof t);const n=xp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ip(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof r&&(e=r.call(t,e,e)),i.items.push(kp(e,null,n));return i}}mh.tag="tag:yaml.org,2002:set";const gh={collection:"map",identify:e=>e instanceof Set,nodeClass:mh,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>mh.from(e,t,n),resolve(e,t){if(vd(e)){if(e.hasAllNullValues(!0))return Object.assign(new mh,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function yh(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,i=e=>t?BigInt(e):Number(e),s=r.replace(/_/g,"").split(":").reduce((e,t)=>e*i(60)+i(t),i(0));return"-"===n?i(-1)*s:s}function bh(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Lp(e);let r="";t<0&&(r="-",t*=n(-1));const i=n(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),r+s.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const wh={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>yh(e,n),stringify:bh},vh={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>yh(e,!1),stringify:bh},kh={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){const t=e.match(kh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,i,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=yh(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")},Ih=[Tp,Dp,Pp,Op,rh,ih,dh,ph,hh,fh,sh,oh,ah,Jp,th,Xp,gh,wh,vh,kh],Eh=new Map([["core",Kp],["failsafe",[Tp,Dp,Pp]],["json",Yp],["yaml11",Ih],["yaml-1.1",Ih]]),Ah={binary:Jp,bool:Rp,float:Fp,floatExp:jp,floatNaN:$p,floatTime:vh,int:Vp,intHex:Wp,intOct:Up,intTime:wh,map:Tp,null:Op,omap:th,pairs:Xp,seq:Dp,set:gh,timestamp:kh},Sh={"tag:yaml.org,2002:binary":Jp,"tag:yaml.org,2002:omap":th,"tag:yaml.org,2002:pairs":Xp,"tag:yaml.org,2002:set":gh,"tag:yaml.org,2002:timestamp":kh};function _h(e,t){let n=Eh.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(Eh.keys()).filter(e=>"yaml11"!==e).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}n=[]}if(Array.isArray(e))for(const t of e)n=n.concat(t);else"function"==typeof e&&(n=e(n.slice()));return n.map(e=>{if("string"!=typeof e)return e;const t=Ah[e];if(t)return t;const n=Object.keys(Ah).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const xh=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Ch{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?_h(e,"compat"):e?_h(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Sh:{},this.tags=_h(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,hd,{value:Tp}),Object.defineProperty(this,md,{value:Pp}),Object.defineProperty(this,gd,{value:Dp}),this.sortMapEntries="function"==typeof s?s:!0===s?xh:null}clone(){const e=Object.create(Ch.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Th{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,yd,{value:pd});let r=null;"function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:s}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new jd({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Th.prototype,{[yd]:{value:pd}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Sd(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Nh(this.contents)&&this.contents.add(e)}addIn(e,t){Nh(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Bd(this);e.anchor=!t||n.has(t)?qd(t||"a",n):t}return new Wd(e.anchor)}createNode(e,t,n){let r;if("function"==typeof t)e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,n=t.filter(e).map(String);n.length>0&&(t=t.concat(n)),r=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:s,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=function(e,t){const n=[],r=new Map;let i=null;return{onAnchor:r=>{n.push(r),i||(i=Bd(e));const s=qd(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Id(t.node)&&!Ad(t.node)){const t=new Error("Failed to resolve repeated object (this should not happen)");throw t.source=e,t}t.node.anchor=t.anchor}},sourceObjects:r}}(this,s||"a"),h=Yd(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&Ad(h)&&(h.flow=!0),d(),h}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Ip(r,i)}delete(e){return!!Nh(this.contents)&&this.contents.delete(e)}deleteIn(e){return Zd(e)?null!=this.contents&&(this.contents=null,!0):!!Nh(this.contents)&&this.contents.deleteIn(e)}get(e,t){return Ad(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Zd(e)?!t&&Id(this.contents)?this.contents.value:this.contents:Ad(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!Ad(this.contents)&&this.contents.has(e)}hasIn(e){return Zd(e)?void 0!==this.contents:!!Ad(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=Jd(this.schema,[e],t):Nh(this.contents)&&this.contents.set(e,t)}setIn(e,t){Zd(e)?this.contents=t:null==this.contents?this.contents=Jd(this.schema,Array.from(e),t):Nh(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){let n;switch("number"==typeof e&&(e=String(e)),e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new jd({version:"1.1"}),n={merge:!0,resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new jd({version:e}),n={merge:!1,resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else{if(!n)throw new Error("With a null YAML version, the { schema: Schema } option is required");this.schema=new Ch(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},a=Ud(this.contents,t??"",o);if("function"==typeof i)for(const{count:e,res:t}of o.anchors.values())i(t,e);return"function"==typeof s?zd(s,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return function(e,t){const n=[];let r=!0===t.directives;if(!1!==t.directives&&e.directives){const t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");const i=mp(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(ep(t,""))}let o=!1,a=null;if(e.contents){if(Sd(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(ep(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=gp(e.contents,i,()=>a=null,t);a&&(c+=tp(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(gp(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(ep(t,""))):n.push(`... ${t}`)}else n.push("...");else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,"")),t&&(o&&!a||""===n[n.length-1]||n.push(""),n.push(ep(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Nh(e){if(Ad(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Mh extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Dh extends Mh{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ph extends Mh{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Oh=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){const e=Math.min(s-39,o.length-79);o="…"+o.substring(e),s-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+"…\n"),o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];t&&t.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-s)));const a=" ".repeat(s)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function Rh(e,{flow:t,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",p="",h=!1,f=!1,m=!1,g=null,y=null,b=null,w=null,v=null,k=null;for(const i of e)switch(m&&("space"!==i.type&&"newline"!==i.type&&"comma"!==i.type&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&"comment"!==i.type&&"newline"!==i.type&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),i.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!i.source.includes("\t")||(g=i),u=!0;break;case"comment":{u||s(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=i.source.substring(1)||" ";d?d+=p+e:d=e,p="",l=!1;break}case"newline":l?d?d+=i.source:c=!0:p+=i.source,l=!0,h=!0,(y||b)&&(f=!0),u=!0;break;case"anchor":y&&s(i,"MULTIPLE_ANCHORS","A node can have at most one anchor"),i.source.endsWith(":")&&s(i.offset+i.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=i,null===k&&(k=i.offset),l=!1,u=!1,m=!0;break;case"tag":b&&s(i,"MULTIPLE_TAGS","A node can have at most one tag"),b=i,null===k&&(k=i.offset),l=!1,u=!1,m=!0;break;case n:(y||b)&&s(i,"BAD_PROP_ORDER",`Anchors and tags must be after the ${i.source} indicator`),v&&s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.source} in ${t??"collection"}`),v=i,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){w&&s(i,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=i,l=!1,u=!1;break}default:s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.type} token`),l=!1,u=!1}const I=e[e.length-1],E=I?I.offset+I.source.length:i;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||"block-map"===r?.type||"block-seq"===r?.type)&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:v,spaceBefore:c,comment:d,hasNewline:h,hasNewlineAfterProp:f,anchor:y,tag:b,end:E,start:k??E}}function Lh(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes("\n"))return!0;if(e.end)for(const t of e.end)if("newline"===t.type)return!0;return!1;case"flow-collection":for(const t of e.items){for(const e of t.start)if("newline"===e.type)return!0;if(t.sep)for(const e of t.sep)if("newline"===e.type)return!0;if(Lh(t.key)||Lh(t.value))return!0}return!1;default:return!0}}function $h(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&Lh(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function jh(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Id(t)&&Id(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const Fh="All mapping items must start at the same column";function Bh(e,t,n,r){let i="";if(e){let s=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}const qh="Block collections are not allowed within flow collections",zh=e=>e&&("block-map"===e.type||"block-seq"===e.type);function Uh(e,t,n,r,i,s){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Cp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const s of r.items){const{start:l,key:u,sep:d,value:p}=s,h=Rh(l,{indicator:"explicit-key-ind",next:u??d?.[0],offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0}),f=!h.found;if(f){if(u&&("block-seq"===u.type?i(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&i(a,"BAD_INDENT",Fh)),!h.anchor&&!h.tag&&!d){c=h.end,h.comment&&(o.comment?o.comment+="\n"+h.comment:o.comment=h.comment);continue}(h.hasNewlineAfterProp||Lh(u))&&i(u??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&i(a,"BAD_INDENT",Fh);const m=h.end,g=u?e(n,u,h,i):t(n,m,l,null,h,i);n.schema.compat&&$h(r.indent,u,i),jh(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Rh(d??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){f&&("block-map"!==p?.type||y.hasNewline||i(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<y.found.offset-1024&&i(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const c=p?e(n,p,y,i):t(n,a,d,null,y,i);n.schema.compat&&$h(r.indent,p,i),a=c.range[2];const l=new Ip(g,c);n.options.keepSourceTokens&&(l.srcToken=s),o.items.push(l)}else{f&&i(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const e=new Ip(g);n.options.keepSourceTokens&&(e.srcToken=s),o.items.push(e)}}return c&&c<a&&i(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[r.offset,a,c??a],o}(e,t,n,r,s):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Np)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Rh(s,{indicator:"seq-item-ind",next:l,offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(!(u.anchor||u.tag||l)){c=u.end,u.comment&&(o.comment=u.comment);continue}l&&"block-seq"===l.type?i(u.end,"BAD_INDENT","All sequence items must start at the same column"):i(a,"MISSING_CHAR","Sequence item without - indicator")}const d=l?e(n,l,u,i):t(n,u.end,s,null,u,i);n.schema.compat&&$h(r.indent,l,i),a=d.range[2],o.items.push(d)}return o.range=[r.offset,a,c??a],o}(e,t,n,r,s):function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o="{"===r.start.source,a=o?"flow map":"flow sequence",c=new(s?.nodeClass??(o?Cp:Np))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1);let u=r.offset+r.start.source.length;for(let s=0;s<r.items.length;++s){const l=r.items[s],{start:d,key:p,sep:h,value:f}=l,m=Rh(d,{flow:a,indicator:"explicit-key-ind",next:p??h?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!m.found){if(!(m.anchor||m.tag||h||f)){0===s&&m.comma?i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):s<r.items.length-1&&i(m.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),m.comment&&(c.comment?c.comment+="\n"+m.comment:c.comment=m.comment),u=m.end;continue}!o&&n.options.strict&&Lh(p)&&i(p,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===s)m.comma&&i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||i(m.start,"MISSING_CHAR",`Missing , between ${a} items`),m.comment){let e="";e:for(const t of d)switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}if(e){let t=c.items[c.items.length-1];kd(t)&&(t=t.value??t.key),t.comment?t.comment+="\n"+e:t.comment=e,m.comment=m.comment.substring(e.length+1)}}if(o||h||m.found){const s=m.end,g=p?e(n,p,m,i):t(n,s,d,null,m,i);zh(p)&&i(g.range,"BLOCK_IN_FLOW",qh);const y=Rh(h??[],{flow:a,indicator:"map-value-ind",next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(y.found){if(!o&&!m.found&&n.options.strict){if(h)for(const e of h){if(e===y.found)break;if("newline"===e.type){i(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<y.found.offset-1024&&i(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else f&&("source"in f&&f.source&&":"===f.source[0]?i(f,"MISSING_CHAR",`Missing space after : in ${a}`):i(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const b=f?e(n,f,y,i):y.found?t(n,y.end,h,null,y,i):null;b?zh(f)&&i(b.range,"BLOCK_IN_FLOW",qh):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const w=new Ip(g,b);if(n.options.keepSourceTokens&&(w.srcToken=l),o){const e=c;jh(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(w)}else{const e=new Cp(n.schema);e.flow=!0,e.items.push(w),c.items.push(e)}u=b?b.range[2]:y.end}else{const r=f?e(n,f,m,i):t(n,m.end,h,null,m,i);c.items.push(r),u=r.range[2],zh(f)&&i(r.range,"BLOCK_IN_FLOW",qh)}}const d=o?"}":"]",[p,...h]=r.end;let f=u;if(p&&p.source===d)f=p.offset+p.source.length;else{const e=a[0].toUpperCase()+a.substring(1);i(u,l?"MISSING_CHAR":"BAD_INDENT",l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`),p&&1!==p.source.length&&h.unshift(p)}if(h.length>0){const e=Bh(h,f,n.options.strict,i);e.comment&&(c.comment?c.comment+="\n"+e.comment:c.comment=e.comment),c.range=[r.offset,f,e.offset]}else c.range=[r.offset,f,f];return c}(e,t,n,r,s),a=o.constructor;return"!"===i||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Vh(e,t,n){const r=t.offset,i=function({offset:e,props:t},n,r){if("block-scalar-header"!==t[0].type)return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=t[0],s=i[0];let o=0,a="",c=-1;for(let t=1;t<i.length;++t){const n=i[t];if(a||"-"!==n&&"+"!==n){const r=Number(n);!o&&r?o=r:-1===c&&(c=e+t)}else a=n}-1!==c&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":l=!0;case"newline":d+=i.source.length;break;case"comment":if(n&&!l){r(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=i.source.length,u=i.source.substring(1);break;case"error":r(i,"UNEXPECTED_TOKEN",i.message),d+=i.source.length;break;default:{r(i,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${i.type}`);const e=i.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:s,indent:o,chomp:a,comment:u,length:d}}(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};const s=">"===i.mode?Hd.BLOCK_FOLDED:Hd.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}(t.source):[];let a=o.length;for(let e=o.length-1;e>=0;--e){const t=o[e][1];if(""!==t&&"\r"!==t)break;a=e}if(0===a){const e="+"===i.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:s,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<a;++t){const[r,s]=o[t];if(""!==s&&"\r"!==s){if(r.length<c){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+r.length,"MISSING_CHAR",e)}if(0===i.indent&&(c=r.length),u=t,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===i.indent&&r.length>c&&(c=r.length),l+=r.length+s.length+1}for(let e=o.length-1;e>=a;--e)o[e][0].length>c&&(a=e+1);let d="",p="",h=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+"\n";for(let e=u;e<a;++e){let[t,r]=o[e];l+=t.length+r.length+1;const a="\r"===r[r.length-1];if(a&&(r=r.slice(0,-1)),r&&t.length<c){const e=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(l-r.length-(a?2:1),"BAD_INDENT",e),t=""}s===Hd.BLOCK_LITERAL?(d+=p+t.slice(c)+r,p="\n"):t.length>c||"\t"===r[0]?(" "===p?p="\n":h||"\n"!==p||(p="\n\n"),d+=p+t.slice(c)+r,p="\n",h=!0):""===r?"\n"===p?d+="\n":p="\n":(d+=p+r,p=" ",h=!1)}switch(i.chomp){case"-":break;case"+":for(let e=a;e<o.length;++e)d+="\n"+o[e][0].slice(c);"\n"!==d[d.length-1]&&(d+="\n");break;default:d+="\n"}const f=r+i.length+t.source.length;return{value:d,type:s,comment:i.comment,range:[r,f,f]}}function Wh(e,t,n){const{offset:r,type:i,source:s,end:o}=e;let a,c;const l=(e,t,i)=>n(r+e,t,i);switch(i){case"scalar":a=Hd.PLAIN,c=function(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":n=`block scalar indicator ${e[0]}`;break;case"@":case"`":n=`reserved character ${e[0]}`}n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return Kh(e)}(s,l);break;case"single-quoted-scalar":a=Hd.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Kh(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=Hd.QUOTE_DOUBLE,c=function(e,t){let n="";for(let r=1;r<e.length-1;++r){const i=e[r];if("\r"!==i||"\n"!==e[r+1])if("\n"===i){const{fold:t,offset:i}=Gh(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=Hh[i];if(s)n+=s;else if("\n"===i)for(i=e[r+1];" "===i||"\t"===i;)i=e[1+ ++r];else if("\r"===i&&"\n"===e[r+1])for(i=e[1+ ++r];" "===i||"\t"===i;)i=e[1+ ++r];else if("x"===i||"u"===i||"U"===i){const s={x:2,u:4,U:8}[i];n+=Yh(e,r+1,s,t),r+=s}else{const i=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),n+=i}}else if(" "===i||"\t"===i){const t=r;let s=e[r+1];for(;" "===s||"\t"===s;)s=e[1+ ++r];"\n"===s||"\r"===s&&"\n"===e[r+2]||(n+=r>t?e.slice(t,r+1):i)}else n+=i}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}const u=r+s.length,d=Bh(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Kh(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch(e){t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],s=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)""===r[1]?"\n"===s?i+=s:s="\n":(i+=s+r[1],s=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,r=a.exec(e),i+s+(r?.[1]??"")}function Gh(e,t){let n="",r=e[t+1];for(;!(" "!==r&&"\t"!==r&&"\n"!==r&&"\r"!==r||"\r"===r&&"\n"!==e[t+2]);)"\n"===r&&(n+="\n"),r=e[(t+=1)+1];return n||(n=" "),{fold:n,offset:t}}const Hh={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function Yh(e,t,n,r){const i=e.substr(t,n),s=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(s)){const i=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}return String.fromCodePoint(s)}function Jh(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?Vh(e,t,r):Wh(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,"TAG_RESOLVE_FAILED",e)):null,l=n&&c?function(e,t,n,r,i){if("!"===n)return e[md];const s=[];for(const t of e.tags)if(!t.collection&&t.tag===n){if(!t.default||!t.test)return t;s.push(t)}for(const e of s)if(e.test?.test(t))return e;const o=e.knownTags[n];if(o&&!o.collection)return e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o;return i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[md]}(e.schema,i,c,n,r):"scalar"===t.type?function({directives:e,schema:t},n,r,i){const s=t.tags.find(e=>e.default&&e.test?.test(n))||t[md];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[md];if(s.tag!==o.tag){i(r,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${e.tagString(s.tag)} or ${e.tagString(o.tag)}`,!0)}}return s}(e,i,t,r):e.schema[md];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Id(s)?s:new Hd(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new Hd(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Zh(e,t,n){if(t){null===n&&(n=t.length);for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];"space"===n?.type;)e+=n.source.length,n=t[++r];break}}return e}const Qh={composeNode:Xh,composeEmptyNode:ef};function Xh(e,t,n,r){const{spaceBefore:i,comment:s,anchor:o,tag:a}=n;let c,l=!0;switch(t.type){case"alias":c=function({options:e},{offset:t,source:n,end:r},i){const s=new Wd(n.substring(1));""===s.source&&i(t,"BAD_ALIAS","Alias cannot be an empty string");s.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=Bh(r,o,e.strict,i);s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment);return s}(e,t,r),(o||a)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Jh(e,t,a,r),o&&(c.anchor=o.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":c=function(e,t,n,r,i){const s=r?t.directives.tagName(r.source,e=>i(r,"TAG_RESOLVE_FAILED",e)):null,o="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!s||"!"===s||s===Cp.tagName&&"map"===o||s===Np.tagName&&"seq"===o||!o)return Uh(e,t,n,i,s);let a=t.schema.tags.find(e=>e.tag===s&&e.collection===o);if(!a){const c=t.schema.knownTags[s];if(!c||c.collection!==o)return c?.collection?i(r,"BAD_COLLECTION_TYPE",`${c.tag} used for ${o} collection, but expects ${c.collection}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),Uh(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=Uh(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Sd(l)?l:new Hd(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(Qh,e,t,a,r),o&&(c.anchor=o.source.substring(1));break;default:r(t,"UNEXPECTED_TOKEN","error"===t.type?t.message:`Unsupported token (type: ${t.type})`),c=ef(e,t.offset,void 0,null,n,r),l=!1}return o&&""===c.anchor&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),i&&(c.spaceBefore=!0),s&&("scalar"===t.type&&""===t.source?c.comment=s:c.commentBefore=s),e.options.keepSourceTokens&&l&&(c.srcToken=t),c}function ef(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=Jh(e,{type:"scalar",offset:Zh(t,n,r),indent:-1,source:""},a,l);return o&&(u.anchor=o.source.substring(1),""===u.anchor&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function tf(e){if("number"==typeof e)return[e,e+1];if(Array.isArray(e))return 2===e.length?e:[e[0],e[1]];const{offset:t,source:n}=e;return[t,t+("string"==typeof n?n.length:1)]}function nf(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){const s=e[i];switch(s[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(s.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[i+1]?.[0]&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}class rf{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=tf(e);r?this.warnings.push(new Ph(i,t,n)):this.errors.push(new Dh(i,t,n))},this.directives=new jd({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=nf(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Ad(i)&&!i.flow&&i.items.length>0){let e=i.items[0];kd(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:nf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=tf(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=function(e,t,{offset:n,start:r,value:i,end:s},o){const a=Object.assign({_directives:t},e),c=new Th(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rh(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!i||"block-map"!==i.type&&"block-seq"!==i.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Xh(l,i,u,o):ef(l,u.end,r,null,u,o);const d=c.contents.range[2],p=Bh(s,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[n,d,p.offset],c}(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Dh(tf(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const t="Unexpected doc-end without preceding document";this.errors.push(new Dh(tf(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=Bh(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Dh(tf(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const e=Object.assign({_directives:this.directives},this.options),n=new Th(void 0,e);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}}function sf(e,t){if(t)for(const n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function of(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{const r=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{const r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{const r="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}function af(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=af(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=cf(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=cf(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=cf(e);if(e.end)for(const n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(const n of e.end)t+=n.source;return t}}}function cf({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=af(t)),n)for(const e of n)i+=e.source;return r&&(i+=af(r)),i}const lf=Symbol("break visit"),uf=Symbol("skip children"),df=Symbol("remove item");function pf(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),hf(Object.freeze([]),e,t)}function hf(e,t,n){let r=n(t,e);if("symbol"==typeof r)return r;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let t=0;t<s.items.length;++t){const r=hf(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===lf)return lf;r===df&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}pf.BREAK=lf,pf.SKIP=uf,pf.REMOVE=df,pf.itemAtPath=(e,t)=>{let n=e;for(const[e,r]of t){const t=n?.[e];if(!t||!("items"in t))return;n=t.items[r]}return n},pf.parentCollection=(e,t)=>{const n=pf.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};const ff="\ufeff",mf="",gf="",yf="";function bf(e){switch(e){case ff:return"byte-order-mark";case mf:return"doc-mode";case gf:return"flow-error-end";case yf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}var wf=Object.freeze({__proto__:null,BOM:ff,DOCUMENT:mf,FLOW_END:gf,SCALAR:yf,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=fp({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:"\n"}];switch(a[0]){case"|":case">":{const e=a.indexOf("\n"),t=a.substring(0,e),n=a.substring(e+1)+"\n",i=[{type:"block-scalar-header",offset:s,indent:r,source:t}];return sf(i,c)||i.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:s,indent:r,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:c};default:return{type:"scalar",offset:s,indent:r,source:a,end:c}}},isCollection:e=>!!e&&"items"in e,isScalar:e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),prettyToken:function(e){switch(e){case ff:return"<BOM>";case mf:return"<DOC>";case gf:return"<FLOW_END>";case yf:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const r=(e,t,r)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new Dh([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Wh(e,t,r);case"block-scalar":return Vh({options:{strict:t}},e,r)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(r&&"number"==typeof a&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");o=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=fp({type:o,value:t},{implicitKey:i||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),i=t.substring(n+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=r,e.source=i}else{const{offset:t}=e,n="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:t,indent:n,source:r}];sf(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:s,source:i})}}(e,c);break;case'"':of(e,c,"double-quoted-scalar");break;case"'":of(e,c,"single-quoted-scalar");break;default:of(e,c,"scalar")}},stringify:e=>"type"in e?af(e):cf(e),tokenType:bf,visit:pf});function vf(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const kf=new Set("0123456789ABCDEFabcdef"),If=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ef=new Set(",[]{}"),Af=new Set(" ,[]{}\n\r\t"),Sf=e=>!e||Af.has(e);class _f{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if("string"!=typeof e)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;" "===t||"\t"===t;)t=this.buffer[++e];return!t||"#"===t||"\n"===t||"\r"===t&&"\n"===this.buffer[e+1]}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;" "===t;)t=this.buffer[++n+e];if("\r"===t){const t=this.buffer[n+e+1];if("\n"===t||!t&&!this.atEnd)return e+n+1}return"\n"===t||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if("-"===t||"."===t){const t=this.buffer.substr(e,3);if(("---"===t||"..."===t)&&vf(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return("number"!=typeof e||-1!==e&&e<this.pos)&&(e=this.buffer.indexOf("\n",this.pos),this.lineEndPos=e),-1===e?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[e-1]&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(null===e)return this.setNext("stream");if(e[0]===ff&&(yield*this.pushCount(1),e=e.substring(1)),"%"===e[0]){let t=e.length,n=e.indexOf("#");for(;-1!==n;){const r=e[n-1];if(" "===r||"\t"===r){t=n-1;break}n=e.indexOf("#",n+1)}for(;;){const n=e[t-1];if(" "!==n&&"\t"!==n)break;t-=1}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield mf,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if("-"===e||"."===e){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if("---"===e&&vf(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&vf(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!vf(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if(("-"===e||"?"===e||":"===e)&&vf(t)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(null===e)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Sf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=(yield*this.parseBlockScalarHeader()),t+=(yield*this.pushSpaces(!0)),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do{e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=(yield*this.pushSpaces(!0))}while(e+t>0);const r=this.getLine();if(null===r)return this.setNext("flow");if(-1!==n&&n<this.indentNext&&"#"!==r[0]||0===n&&(r.startsWith("---")||r.startsWith("..."))&&vf(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield gf,yield*this.parseLineStart()}let i=0;for(;","===r[i];)i+=(yield*this.pushCount(1)),i+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(i+=(yield*this.pushIndicators()),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Sf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||vf(e)||","===e)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if("'"===e)for(;-1!==t&&"'"===this.buffer[t+1];)t=this.buffer.indexOf("'",t+2);else for(;-1!==t;){let e=0;for(;"\\"===this.buffer[t-1-e];)e+=1;if(e%2==0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf("\n",this.pos);if(-1!==r){for(;-1!==r;){const e=this.continueScalar(r+1);if(-1===e)break;r=n.indexOf("\n",e)}-1!==r&&(t=r-("\r"===n[r-1]?2:1))}if(-1===t){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if("+"===t)this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if("-"!==t)break}return yield*this.pushUntil(e=>vf(e)||"#"===e)}*parseBlockScalar(){let e,t=this.pos-1,n=0;e:for(let r=this.pos;e=this.buffer[r];++r)switch(e){case" ":n+=1;break;case"\n":t=r,n=0;break;case"\r":{const e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if("\n"===e)break}default:break e}if(!e&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(t+1);if(-1===e)break;t=this.buffer.indexOf("\n",e)}while(-1!==t);if(-1===t){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(e=this.buffer[r];" "===e;)e=this.buffer[++r];if("\t"===e){for(;"\t"===e||" "===e||"\r"===e||"\n"===e;)e=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)for(;;){let e=t-1,r=this.buffer[e];"\r"===r&&(r=this.buffer[--e]);const i=e;for(;" "===r;)r=this.buffer[--e];if(!("\n"===r&&e>=this.pos&&e+1+n>i))break;t=e}return yield yf,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t,n=this.pos-1,r=this.pos-1;for(;t=this.buffer[++r];)if(":"===t){const t=this.buffer[r+1];if(vf(t)||e&&Ef.has(t))break;n=r}else if(vf(t)){let i=this.buffer[r+1];if("\r"===t&&("\n"===i?(r+=1,t="\n",i=this.buffer[r+1]):n=r),"#"===i||e&&Ef.has(i))break;if("\n"===t){const e=this.continueScalar(r+1);if(-1===e)break;r=Math.max(r,e-2)}}else{if(e&&Ef.has(t))break;n=r}return t||this.atEnd?(yield yf,yield*this.pushToIndex(n+1,!0),e?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Sf))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(vf(t)||e&&Ef.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,t=this.buffer[e];for(;!vf(t)&&">"!==t;)t=this.buffer[++e];return yield*this.pushToIndex(">"===t?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(If.has(t))t=this.buffer[++e];else{if("%"!==t||!kf.has(this.buffer[e+1])||!kf.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,n=this.pos-1;do{t=this.buffer[++n]}while(" "===t||e&&"\t"===t);const r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class xf{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(0===t)return{line:0,col:e};return{line:t,col:e-this.lineStarts[t-1]+1}}}}function Cf(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Tf(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Nf(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Mf(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Df(e){if(0===e.length)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;"space"===e[++t]?.type;);return e.splice(t,e.length)}function Pf(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Cf(t.start,"explicit-key-ind")||Cf(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Nf(t.value)?t.value.end?Array.prototype.push.apply(t.value.end,t.sep):t.value.end=t.sep:Array.prototype.push.apply(t.start,t.sep),delete t.sep)}class Of{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new _f,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=e.length);const t=bf(e);if(t)if("scalar"===t)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&" "===e[0]&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if("doc-end"!==this.type||e&&"doc-end"===e.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&Pf(t),e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const n=e.items[e.items.length-1];if(n.value)return e.items.push({start:[],key:t,sep:[]}),void(this.onKeyLine=!0);if(!n.sep)return Object.assign(n,{key:t,sep:[]}),void(this.onKeyLine=!n.explicitKey);n.value=t;break}case"block-seq":{const n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{const n=e.items[e.items.length-1];return void(!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]}))}default:yield*this.pop(),yield*this.pop(t)}if(!("document"!==e.type&&"block-map"!==e.type&&"block-seq"!==e.type||"block-map"!==t.type&&"block-seq"!==t.type)){const n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&-1===Tf(n.start)&&(0===t.indent||n.start.every(e=>"comment"!==e.type||e.indent<t.indent))&&("document"===e.type?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}else{const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}}*stream(){switch(this.type){case"directive-line":return void(yield{type:"directive",offset:this.offset,source:this.source});case"byte-order-mark":case"space":case"comment":case"newline":return void(yield this.sourceToken);case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};return"doc-start"===this.type&&e.start.push(this.sourceToken),void this.stack.push(e)}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":return void(-1!==Tf(e.start)?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken));case"anchor":case"tag":case"space":case"comment":case"newline":return void e.start.push(this.sourceToken)}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if("map-value-ind"===this.type){const t=Df(Mf(this.peek(2)));let n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let i=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const i=t.sep[r];switch(i.type){case"newline":n.push(r);break;case"space":break;case"comment":i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Cf(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Nf(t.key)&&!Cf(t.sep,"newline")){const e=Df(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Cf(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Df(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Cf(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0))}default:{const t=this.startBlockValue(e);if(t)return n&&"block-seq"!==t.type&&e.items.push({start:i}),void this.stack.push(t)}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||Cf(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken))}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t)return void this.stack.push(t)}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if("flow-error-end"===this.type){let e;do{yield*this.pop(),e=this.peek(1)}while(e&&"flow-collection"===e.type)}else if(0===e.end.length){switch(this.type){case"comma":case"explicit-key-ind":return void(!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken));case"map-value-ind":return void(!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]}));case"space":case"comment":case"newline":case"anchor":case"tag":return void(!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]}))}case"flow-map-end":case"flow-seq-end":return void e.end.push(this.sourceToken)}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const t=this.peek(2);if("block-map"===t.type&&("map-value-ind"===this.type&&t.indent===e.indent||"newline"===this.type&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if("map-value-ind"===this.type&&"flow-collection"!==t.type){const n=Df(Mf(t));Pf(e);const r=e.end.splice(1,e.end.length);r.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=Df(Mf(e));return t.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=Df(Mf(e));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return"comment"===this.type&&(!(this.indent<=t)&&e.every(e=>"newline"===e.type||"space"===e.type))}*documentEnd(e){"doc-mode"!==this.type&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}}function Rf(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new xf||null,prettyErrors:t}}function Lf(e,t={}){const{lineCounter:n,prettyErrors:r}=Rf(t),i=new Of(n?.addNewLine),s=new rf(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(Oh(e,n)),t.warnings.forEach(Oh(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function $f(e,t={}){const{lineCounter:n,prettyErrors:r}=Rf(t),i=new Of(n?.addNewLine),s=new rf(t);let o=null;for(const t of s.compose(i.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new Dh(t.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else o=t;return r&&n&&(o.errors.forEach(Oh(e,n)),o.warnings.forEach(Oh(e,n))),o}function jf(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=$f(e,n);if(!i)return null;if(i.warnings.forEach(e=>yp(i.options.logLevel,e)),i.errors.length>0){if("silent"!==i.options.logLevel)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function Ff(e,t,n){let r=null;if("function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t),"string"==typeof n&&(n=n.length),"number"==typeof n){const e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(void 0===e){const{keepUndefined:e}=n??t??{};if(!e)return}return new Th(e,r,n).toString(n)}var Bf=Object.freeze({__proto__:null,Alias:Wd,CST:wf,Composer:rf,Document:Th,Lexer:_f,LineCounter:xf,Pair:Ip,Parser:Of,Scalar:Hd,Schema:Ch,YAMLError:Mh,YAMLMap:Cp,YAMLParseError:Dh,YAMLSeq:Np,YAMLWarning:Ph,isAlias:bd,isCollection:Ad,isDocument:wd,isMap:vd,isNode:Sd,isPair:kd,isScalar:Id,isSeq:Ed,parse:jf,parseAllDocuments:Lf,parseDocument:$f,stringify:Ff,visit:Td,visitAsync:Md}),qf=Object.freeze({__proto__:null,Alias:Wd,CST:wf,Composer:rf,Document:Th,Lexer:_f,LineCounter:xf,Pair:Ip,Parser:Of,Scalar:Hd,Schema:Ch,YAMLError:Mh,YAMLMap:Cp,YAMLParseError:Dh,YAMLSeq:Np,YAMLWarning:Ph,default:Bf,isAlias:bd,isCollection:Ad,isDocument:wd,isMap:vd,isNode:Sd,isPair:kd,isScalar:Id,isSeq:Ed,parse:jf,parseAllDocuments:Lf,parseDocument:$f,stringify:Ff,visit:Td,visitAsync:Md});class zf{#At;constructor(e){this.#At=e}execute(){return new Promise((e,t)=>{const n=`${this.#At}.punica/config.yaml`;fetch(n,{method:"GET"}).then(e=>{if(!e.ok)throw new Error(`Failed to load extension config: ${n} (${e.status})`);return e.text()}).then(async t=>{const n=Bf.parse(t);if(n.moduleURL=this.#At,n.hasCapabilities){const e=`${this.#At}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=Bf.parse(await t.text());n.capabilities=e??{}}else console.warn(`[Extensions] ${n.name}: hasCapabilities is set but ${e} could not be loaded (${t.status}).`)}catch{n.capabilities={}}}const r=n.instructionClasses;if(Array.isArray(r)&&r.length>0){const e=await Promise.all(r.map(async e=>{const t=`${this.#At}.punica/instruction-classes/${e}`,n=await fetch(t,{method:"GET"});if(!n.ok)throw new Error(`Failed to load instruction class: ${t} (${n.status})`);return Bf.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Uf{#Et;constructor(e){this.#Et=e}async execute(){return await this.#Et.execute()}}class Vf{#n;#St;constructor(){this.#n=new Map,this.#St=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#St.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#St.has(t)||console.warn(`Unknown event type: ${t}`)}}class Wf{}class Kf extends Wf{#_t;constructor(e){super(),this.#_t=e}execute(){}}let Gf=class extends Uf{#xt;constructor(e){super(e),this.#xt=new Vf,this.#xt.register("onExtension",Kf),this.#xt.markKnown("onCommand"),this.#xt.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#xt.handleEvent(e)),e}},Hf=class extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,activationEvents:n}=e,r=e.capabilities,i=[];if(r&&"object"==typeof r)for(const[e,t]of Object.entries(r)){if(!e)continue;const n="string"==typeof t?.title?t.title:e,r="string"==typeof t?.description?t.description:void 0;i.push({id:e,title:n,description:r})}return i.length&&i.forEach(({id:t,title:i,description:s})=>{if(!t)return;const o=punica.kernel.Commands.manager,a=punica.extensions.manager,c=punica.kernel.Events.manager;if(n?.some(e=>e===`onCommand:${t}`||"onCommand"===e)??!1)return;const l=r?.[t],u=l?.outputs?.resultEvent,d=l?.outputs?.errorEvent;o.registerCommand(t,{title:i??t,description:s,execute:(...n)=>{const r=n.length?n[n.length-1]:void 0,i=r?.__punica?.correlationId;a.activate(e.name,{reason:"command",trigger:t}).then(()=>{u&&c.publishEvent({name:u,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"result"},payload:{ok:!0,dispatched:!0,capabilityId:t,activatedExtension:e.name}})}).catch(n=>{d&&c.publishEvent({name:d,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"error"},payload:{ok:!1,capabilityId:t,activatedExtension:e.name,error:String(n?.message??n)}})})}})}),e}};function Yf(e,t=function(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}()){const n=e.split("+").map(e=>e.trim().toLowerCase()),r={key:""};return n.forEach(e=>{switch(e){case"ctrl":case"control":r.ctrlKey=!0;break;case"shift":r.shiftKey=!0;break;case"alt":case"option":r.altKey=!0;break;case"meta":case"cmd":case"command":r.metaKey=!0;break;case"mod":case"cmdorctrl":t?r.metaKey=!0:r.ctrlKey=!0;break;default:r.key=e}}),r}let Jf=class extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(t){const{keybindings:e}=t;e&&e.forEach(e=>{if(!e.capability)return void console.warn(`[Keybindings] Missing capability for keybinding: ${e.key}`);const t=e.capability,n=e.key,r=e.when;punica.shell.KeyboardShortcuts.manager.registerShortcut({command:t,keys:[Yf(n)],when:r})})}return e}},Zf=class extends Uf{constructor(e){super(e)}async execute(){return await super.execute()}},Qf=class extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,name:n}=e;if(t&&t.fileOpeners){const e=t.fileOpeners,r=sd.fileOpeners;e.forEach((e,t)=>{if(!e.capability)return void console.warn(`[FileOpeners] Missing capability for file opener: ${e.id??t}`);const i=e.capability,s=e.id??`${n}:${i||"opener"}:${t.toString(10)}`;r.register({id:s,label:e.label,command:i,priority:e.priority,matches:e.matches})})}return e}};class Xf extends Uf{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(!t)return e;const{views:n}=t;if(!n)return e;const{activityBar:r,statusBar:i,primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c}=n;if(r){const e={...r};e.capability&&(e.command=e.capability),s&&!e.viewId&&(e.viewId=s.id),punica.shell.ActivityBar.manager.addItem(e)}if(i){const e={...i};e.capability&&(e.command=e.capability),punica.shell.Statusbar.manager.addItem(e)}return this.#Ct(e,{primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r}),e}#Ct(e,t){const n=punica.shell?.Views?.manager;if(!n?.registerPlacement)return;const{primarySidebar:r,secondarySidebar:i,contentSidebar:s,panel:o,activityBar:a}=t;if(r?.id&&n.registerPlacement({viewId:r.id,slot:"primarySidebar",extensionName:e.name,title:r.title??r.name,icon:r.icon,fallbackCommand:r.capability??a?.capability??a?.command}),i?.id&&n.registerPlacement({viewId:i.id,slot:"secondarySidebar",extensionName:e.name,title:i.title??i.name,icon:i.icon,fallbackCommand:i.capability}),s?.id&&n.registerPlacement({viewId:s.id,slot:"contentSidebar",extensionName:e.name,title:s.title??s.name,icon:s.icon,fallbackCommand:s.capability}),o?.id){n.registerPlacement({viewId:o.id,slot:"panel",extensionName:e.name,title:o.title??o.name,icon:o.icon,order:o.order,fallbackCommand:o.capability});const t=punica.shell?.PanelTabs;t?.open?.({id:o.id,title:o.title??o.name??o.id,commandId:o.capability??"",iconClass:o.icon,order:o.order,autoActivate:!1,toolbar:Array.isArray(o.toolbar)?o.toolbar:void 0})}}}const em=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#Tt(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#Tt(e))}getExtensionCapabilities(e){const t=punica.extensions.manager.getExtension(e);if(!t)return;const n=t.capabilities;return n?Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>{const n=t;return[e,Object.freeze({id:n.id??e,title:n.title,description:n.description,inputs:n.inputs?Object.freeze({schema:n.inputs.schema?Object.freeze(n.inputs.schema):void 0}):void 0,outputs:n.outputs?Object.freeze({schema:n.outputs.schema?Object.freeze(n.outputs.schema):void 0,kind:n.outputs.kind,resultEvent:n.outputs.resultEvent,errorEvent:n.outputs.errorEvent}):void 0,policy:n.policy?Object.freeze({risk:n.policy.risk,approval:n.policy.approval}):void 0,sideEffects:n.sideEffects?Object.freeze([...n.sideEffects]):void 0,requiredContext:n.requiredContext?Object.freeze([...n.requiredContext]):void 0,examples:n.examples?Object.freeze(n.examples.map(e=>Object.freeze({input:e.input,output:e.output,description:e.description}))):void 0,version:n.version,tags:n.tags?Object.freeze([...n.tags]):void 0})]}))):void 0}#Tt(e){const t=e.integrations?.configuration?{title:e.integrations.configuration.title,properties:Object.freeze(Object.fromEntries(Object.entries(e.integrations.configuration.properties??{}).map(([e,t])=>{const n=t,r={type:n.type,default:n.default,description:n.description};let i;return"string"===n.type&&"enum"in n&&Array.isArray(n.enum)&&(i=Object.freeze([...n.enum])),[e,Object.freeze({...r,enum:i})]})))}:void 0;return Object.freeze({name:e.name,displayName:e.displayName,description:e.description,version:e.version,configuration:t?Object.freeze(t):void 0,capabilities:this.getExtensionCapabilities(e.name)})}};const tm=new class{#Nt=".punica/settings.json";#Mt;#Dt=null;#Pt=null;#Ot=new Map;#Rt=null;#Qe=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Mt=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Mt="localStorage:punica.settings":this.#Mt="settings.json"}async load(){this.#Qe||(await this.#Lt(),await this.#$t(),this.#Qe=!0)}async#Lt(){try{if(this.#Mt.startsWith("localStorage:")){const e=this.#Mt.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#Pt=await this.#jt(e)}else this.#Pt={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Mt),t=JSON.parse(e);this.#Pt=await this.#jt(t)}catch{this.#Pt={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Pt={version:"1.0",extensions:{},system:{}}}}async#$t(){try{const e=await punica.runtime.fs.readFile(this.#Nt),t=JSON.parse(e);this.#Dt=await this.#jt(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Dt=null}}async save(e="project"){this.#Rt&&clearTimeout(this.#Rt),this.#Rt=window.setTimeout(async()=>{"global"===e?await this.#Ft():await this.#Bt(),this.#Rt=null},500)}async#Ft(){if(this.#Pt)if(this.#Mt.startsWith("localStorage:")){const e=this.#Mt.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#Pt,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Mt,JSON.stringify(this.#Pt,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#Bt(){this.#Dt||(this.#Dt={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Nt,JSON.stringify(this.#Dt,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#Qe)return void this.load();if("system"===e){const e=this.#Dt?.system?.[t];if(void 0!==e)return e;const n=this.#Pt?.system?.[t];return void 0!==n?n:void 0}const n=this.#Dt?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#Pt?.extensions?.[e]?.[t];if(void 0!==r)return r;const i=punica.extensions.metadata.manager.getExtension(e);return i?.configuration?.properties?.[t]?.default}async set(e,t,n,r="project"){if(this.#Qe||await this.load(),"system"===e){const i=this.get(e,t);return"global"===r?(this.#Pt||(this.#Pt={version:"1.0",extensions:{},system:{}}),this.#Pt.system||(this.#Pt.system={}),this.#Pt.system[t]=n,await this.save("global")):(this.#Dt||(this.#Dt={version:"1.0",extensions:{},system:{}}),this.#Dt.system||(this.#Dt.system={}),this.#Dt.system[t]=n,await this.save("project")),void this.#qt(e,t,n,i)}const i=this.validate(e,t,n);if(!i.ok)throw new Error(`Invalid setting value: ${i.errors?.join(", ")}`);const s=this.get(e,t);"global"===r?(this.#Pt||(this.#Pt={version:"1.0",extensions:{},system:{}}),this.#Pt.extensions[e]||(this.#Pt.extensions[e]={}),this.#Pt.extensions[e][t]=n,await this.save("global")):(this.#Dt||(this.#Dt={version:"1.0",extensions:{},system:{}}),this.#Dt.extensions[e]||(this.#Dt.extensions[e]={}),this.#Dt.extensions[e][t]=n,await this.save("project")),this.#qt(e,t,n,s)}getAll(e){if(!this.#Qe)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#Pt?.extensions?.[e]??{},i=this.#Dt?.extensions?.[e]??{},s={};for(const[e,t]of Object.entries(n)){const n=t;s[e]=n.default}return{...s,...r,...i}}validate(e,t,n){const r=punica.extensions.metadata.manager.getExtension(e),i=r?.configuration?.properties?.[t];if(!i)return{ok:!1,errors:[`Setting "${t}" not found in extension "${e}"`]};const s=[];switch(i.type){case"boolean":"boolean"!=typeof n&&s.push(`Setting "${t}" must be a boolean`);break;case"string":"string"!=typeof n?s.push(`Setting "${t}" must be a string`):i.enum&&!i.enum.includes(n)&&s.push(`Setting "${t}" must be one of: ${i.enum.join(", ")}`);break;case"number":("number"!=typeof n||isNaN(n))&&s.push(`Setting "${t}" must be a number`)}return{ok:0===s.length,errors:s.length>0?s:void 0}}getTyped(e,t,n){const r=this.get(e,t);if(void 0!==r&&typeof r===n)return r}async reset(e,t){const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Dt?.extensions?.[e]&&(delete this.#Dt.extensions[e][t],await this.save("project")),this.#Pt?.extensions?.[e]&&(delete this.#Pt.extensions[e][t],await this.save("global"))):await this.set(e,t,r,"project")}async resetExtension(e){const t=punica.extensions.metadata.manager.getExtension(e);if(t?.configuration?.properties)for(const n of Object.keys(t.configuration.properties))await this.reset(e,n)}getScope(e,t){return this.#Qe?"system"===e?void 0!==this.#Dt?.system?.[t]?"project":void 0!==this.#Pt?.system?.[t]?"global":"default":void 0!==this.#Dt?.extensions?.[e]?.[t]?"project":void 0!==this.#Pt?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#Ot.has(e)||this.#Ot.set(e,new Set),this.#Ot.get(e).add(t),()=>{this.#Ot.get(e)?.delete(t)}}async export(e){this.#Qe||await this.load();const t=e?.scope??"merged",n={version:this.#Pt?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Dt?.system:"global"===t?this.#Pt?.system:{...this.#Pt?.system,...this.#Dt?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#Pt?.extensions??{}),...Object.keys(this.#Dt?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Dt?.extensions?.[e]??{}:"global"===t?this.#Pt?.extensions?.[e]??{}:this.getAll(e);return JSON.stringify(n,null,2)}async import(e,t){const n=JSON.parse(e),r=t?.scope??"project";if(n.version&&"1.0"!==n.version&&console.warn(`[Settings] Imported settings version ${n.version} may need migration`),t?.merge){("project"===r?this.#Dt:this.#Pt)||("project"===r?this.#Dt={version:"1.0",extensions:{},system:{}}:this.#Pt={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Dt:this.#Pt;for(const[r,i]of Object.entries(n.extensions??{}))t.extensions&&!t.extensions.includes(r)||(e.extensions[r]={...e.extensions[r],...i});n.system&&(e.system={...e.system,...n.system})}else{if(t?.extensions)for(const e of t.extensions)n.extensions[e]&&("project"===r?(this.#Dt||(this.#Dt={version:"1.0",extensions:{},system:{}}),this.#Dt.extensions[e]=n.extensions[e]):(this.#Pt||(this.#Pt={version:"1.0",extensions:{},system:{}}),this.#Pt.extensions[e]=n.extensions[e]));else"project"===r?this.#Dt={...this.#Dt,...n,version:this.#Dt?.version??"1.0"}:this.#Pt={...this.#Pt,...n,version:this.#Pt?.version??"1.0"};n.system&&("project"===r?(this.#Dt||(this.#Dt={version:"1.0",extensions:{},system:{}}),this.#Dt.system=n.system):(this.#Pt||(this.#Pt={version:"1.0",extensions:{},system:{}}),this.#Pt.system=n.system))}await this.save(r)}async#jt(e){return e.version,e}#qt(e,t,n,r){const i=this.#Ot.get(e);i&&i.forEach(e=>e(t,n,r)),punica.kernel.Events.manager&&punica.kernel.Events.manager.publishEvent({name:"settings.changed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"extension-settings",kind:"info"},payload:{extensionName:e,key:t,newValue:n,oldValue:r}})}};function nm(e,t){try{const n=globalThis.punica?.kernel?.Events?.manager;if(!n?.publishEvent||!n?.createCorrelationId)return;n.publishEvent({name:e,envelope:{id:n.createCorrelationId(),timestampMs:Date.now(),source:"extensions:lifecycle",kind:"info"},payload:t})}catch{}}const rm=new Map;function im(e){const t=rm.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),rm.delete(e)}const sm={register(e,t,n){const r=n?.target??document.head,i=rm.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),rm.set(e,i),{id:e,dispose(){im(e)}};const s=document.createElement("style");if(s.id=e,n?.attrs)for(const[e,t]of Object.entries(n.attrs))s.setAttribute(e,t);return s.textContent=t,r.appendChild(s),rm.set(e,s),{id:e,dispose(){im(e)}}},unregister(e){im(e)},has:e=>!!rm.has(e)||!!document.getElementById(e)};const om={manager:new class{#zt;#Ut;#Vt;#Wt;#Kt;#Gt;#Ht;#Yt;#Jt;constructor(){this.#zt=new Map,this.#Ut=new Map,this.#Vt=new Map,this.#Wt=new Map,this.#Kt=new Set,this.#Gt=new Set,this.#Ht=new Map,this.#Yt=new Map,this.#Jt=new Map}getRuntimeState(e){return this.#Ut.get(e)}registerBuiltinCapabilities(e){const t=Array.isArray(e)?e:[];for(const e of t){const t=String(e?.id??""),n=String(e?.extensionName??""),r=e?.definition??{};if(!t)throw new Error("[Extensions] registerBuiltinCapabilities: Missing id");if(!n)throw new Error(`[Extensions] registerBuiltinCapabilities: Missing extensionName (id="${t}")`);const i=this.#Yt.get(t);if(i&&i.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${i.extensionName}" and "${n}".`);this.#Yt.set(t,{id:t,extensionName:n,definition:r})}}#Zt(e){const t=e,n=t?.capabilities;if(n&&"object"==typeof n){for(const[t,r]of Object.entries(n)){if(!t)continue;const n=r??{};n.id||(n.id=t);const i={id:t,extensionName:e.name,definition:n},s=this.#Yt.get(t);s&&s.extensionName!==e.name&&console.warn(`[Extensions] Capability id collision "${t}" between "${s.extensionName}" and "${e.name}". Keeping the last loaded.`),this.#Yt.set(t,i)}this.#Qt(e,n)}}#Qt(e,t){const n=Hl.lintAll(Object.values(t));let r=0;for(const t of n)for(const n of t.issues)"error"===n.severity?console.warn(`[Extensions] capability lint [${e.name}] ${n.message}`):"warning"===n.severity&&r++;r>0&&console.warn(`[Extensions] capability lint [${e.name}]: ${r} authoring warning(s) — run capability.lint for detail`)}#Xt(e){const t=e.instructionClasses;if(!Array.isArray(t)||0===t.length)return;const n=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;if(n){for(const r of t)try{n.register(r,e.name)}catch(e){console.error(`[Extensions] IC register failed ${r?.id}:`,e)}console.log(`[Extensions] Registered ${t.length} instruction class(es) from "${e.name}"`)}}async load(e,...t){try{const n=[e,...t],r=await Promise.allSettled(n.map(e=>(e=>{const t=new zf(e),n=new Hf(t),r=new Jf(n),i=new Zf(r),s=new Qf(i),o=new Xf(s);return new Gf(o)})(e).execute()));r.forEach((e,t)=>{if("rejected"===e.status)return void console.error(`[Extensions] analysis failed for ${n[t]}:`,e.reason);const r=e.value;this.#zt.set(r.name,r),this.#Ut.set(r.name,"loaded"),this.#Zt(r),this.#Xt(r);const i=r.activationEvents??[];(i.includes("onStartup")||i.includes("onStartup:begin"))&&this.#Kt.add(r.name),i.includes("onStartup:finish")&&this.#Gt.add(r.name),i.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#Ht.get(t);n||(n=new Set,this.#Ht.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#Ut.get(e))return;const n=this.#Vt.get(e);if(n)return n;if(!this.#zt.get(e))return void console.error(`Extension "${e}" not found.`);const r=function(e){const t=e?.reason??"host",n=e?.presentation??("capability"===t||"extension"===t?"headless":"interactive");return{reason:t,trigger:e?.trigger,presentation:n}}(t),i=this.#en(e,r);this.#Vt.set(e,i);try{await i}finally{this.#Vt.delete(e)}}async#en(e,t){this.#Ut.set(e,"activating"),nm("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new od(e),n=new ld(t),r=new ud(n);return new cd(r)})(e),r=await n.execute();if(!r||!r.module||"function"!=typeof r.module.activate)throw new Error(`Failed to activate extension "${e}". The "activate" method is missing or invalid.`);{const n=this.#tn(e,t);"headless"===t.presentation?await fn(()=>r.module.activate(n)):await r.module.activate(n);const i=this.#Wt.get(e);i&&(i.module=r.module),this.#Ut.set(e,"active"),nm("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#Ut.set(e,"failed"),nm("extension.lifecycle.activationFailed",{extensionName:e,reason:t.reason,trigger:t.trigger,error:n instanceof Error?n.message:String(n)}),console.error(`Error activating extension "${e}":`,n),n}}#tn(e,t){const n=[];this.#Wt.set(e,{subscriptions:n});const r={activation:Object.freeze({reason:t.reason,trigger:t.trigger,presentation:t.presentation}),subscriptions:n,capabilities:{registerHandler:(t,n)=>{this.#Jt.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const i=globalThis.punica?.shell?.Views?.manager;if(!i?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const s=i.registerProvider(t,r,e);return n.push(s),s},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway;if(i?.call){const s=r.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await i.call("shell.revealView",{viewId:e,focus:n?.focus??!1},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:o},policy:{mode:"execute"}})}const s=r.punica?.shell?.Views?.manager;if(!s?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await s.reveal(e,{kind:"extension",id:t})}(t,e,n)},hide:async t=>{await async function(e,t){const n=globalThis,r=n.punica?.runtime?.capabilities?.gateway;if(r?.call){const i=n.punica?.kernel?.Events?.manager,s=i?.createCorrelationId?.()??`ext-hide-${Date.now()}`;return void await r.call("shell.hideView",{viewId:e},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:s},policy:{mode:"execute"}})}const i=n.punica?.shell?.Views?.manager;if(!i?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);i.hide(e,{kind:"extension",id:t})}(t,e)}}};return r}async startupBegin(){await this.#nn(this.#Kt,"startup:begin")}async startupFinish(){await this.#nn(this.#Gt,"startup:finish")}async#nn(e,t){for(const n of e)try{await this.activate(n,{reason:t})}catch(e){console.error(`Error activating extension "${n}" on${t}:`,e)}}getExtension(e){return this.#zt.get(e)}getAllExtensions(){return Array.from(this.#zt.values())}getCapability(e){return this.#Yt.get(e)?.definition}listCapabilities(){return Array.from(this.#Yt.values())}validateCapabilityInput(e,t){const n=this.getCapability(e);if(!n)return{ok:!0};const r=n.inputs?.schema;if(!r)return{ok:!0};const i=Oa().validate(r,t);return i.ok?{ok:!0}:{ok:!1,errors:i.errors}}registerCapabilityHandler(e,t){this.#Jt.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#Yt.get(e);if(!r)throw new la(ca.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#Ut.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new la(ca.EXTENSION_ACTIVATION_FAILED,`Extension "${r.extensionName}" failed to activate for capability "${e}": `+(t instanceof Error?t.message:String(t)),{capability:e,extensionName:r.extensionName})}const i=this.#Jt.get(e);if(!i)throw new la(ca.CAPABILITY_HANDLER_MISSING,`Extension "${r.extensionName}" declared capability "${e}" but did not register a handler. Call context.capabilities.registerHandler("${e}", handler) inside activate().`,{capability:e,extensionName:r.extensionName});return await i.fn(t,n)}async deactivate(e){if("active"!==this.#Ut.get(e))return;const t=this.#zt.get(e);this.#Ut.set(e,"deactivating");try{const n=globalThis.punica?.shell?.Views?.manager;try{n?.unmountByExtension?.(e)}catch(t){console.warn(`[Extensions] view unmount failed for "${e}":`,t)}try{const n=this.#Wt.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#Wt.get(e);if(r){for(const t of r.subscriptions)try{t.dispose()}catch(t){console.warn(`[Extensions] subscription dispose failed for "${e}":`,t)}this.#Wt.delete(e)}for(const[t,n]of this.#Jt)n.extensionName===e&&this.#Jt.delete(t)}finally{this.#Ut.set(e,"loaded"),nm("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#Ut.get(e);if(void 0===t)return;if("loaded"!==t&&"failed"!==t)throw new Error(`[Extensions] cannot unload "${e}" while ${t} — deactivate() it first.`);try{const t=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;t?.unregisterByOrigin?.(e)}catch(t){console.warn(`[Extensions] instruction-class unregister failed for "${e}":`,t)}for(const[t,n]of this.#Yt)n.extensionName===e&&this.#Yt.delete(t);for(const[t,n]of this.#Ht)n.delete(e)&&0===n.size&&this.#Ht.delete(t);const n=this.#zt.get(e)?.integrations?.views;if(n){const t=globalThis.punica?.shell;try{n.activityBar?.id&&t?.ActivityBar?.manager?.removeItem?.(n.activityBar.id),n.statusBar?.id&&t?.Statusbar?.manager?.removeItem?.(n.statusBar.id),n.panel?.id&&t?.PanelTabs?.close?.(n.panel.id)}catch(t){console.warn(`[Extensions] UI contribution retract failed for "${e}":`,t)}}this.#Kt.delete(e),this.#Gt.delete(e),this.#Vt.delete(e),this.#Wt.delete(e),this.#zt.delete(e),this.#Ut.delete(e),nm("extension.lifecycle.unloaded",{extensionName:e})}async reload(e,t,n){if(await this.deactivate(e),await this.unload(e),await this.load(t),"loaded"!==this.#Ut.get(e))throw new Error(`[Extensions] reload failed: "${e}" did not load from ${t}`);await this.activate(e,n??{reason:"host",trigger:e})}getExtensionsForCommand(e){const t=this.#Ht.get(e);return t?Array.from(t):[]}},Styles:sm,metadata:{manager:em},settings:{manager:tm}};function am(e){if(null==e)return!1;if(Array.isArray(e))return e.some(am);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(am)}return!1}function cm(e){const t=[];if(!e||"object"!=typeof e)return{ok:!1,issues:[{path:"",message:"Manifest must be an object",code:"INVALID_TYPE",severity:"error"}]};const n=e;if("ivy.node/v0.2"!==n.apiVersion&&t.push({path:"apiVersion",message:`Expected "ivy.node/v0.2", got "${n.apiVersion}"`,code:"INVALID_API_VERSION",severity:"error"}),"IvyNode"!==n.kind&&t.push({path:"kind",message:`Expected "IvyNode", got "${n.kind}"`,code:"INVALID_KIND",severity:"error"}),!n.capability||"object"!=typeof n.capability)return t.push({path:"capability",message:"capability is required and must be an object (CapabilityDefinition)",code:"MISSING_CAPABILITY",severity:"error"}),{ok:!1,issues:t};const r=n.capability;if(r.id&&"string"==typeof r.id?/^[a-z0-9]+(\.[a-z0-9-]+)+$/.test(r.id)||t.push({path:"capability.id",message:'capability.id must be in CapabilityId format (namespace-prefixed, kebab-case, e.g., "ivy.node.email-builder")',code:"INVALID_ID_FORMAT",severity:"error"}):t.push({path:"capability.id",message:"capability.id is required and must be a string (CapabilityId format)",code:"MISSING_ID",severity:"error"}),r.title&&"string"==typeof r.title||t.push({path:"capability.title",message:"capability.title is required and must be a string",code:"MISSING_TITLE",severity:"error"}),r.version&&"string"==typeof r.version?/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(r.version)||t.push({path:"capability.version",message:'capability.version must be in semver format (e.g., "0.0.0", "1.2.3-beta.1")',code:"INVALID_VERSION_FORMAT",severity:"warning"}):t.push({path:"capability.version",message:"capability.version is required and must be a string (semver format)",code:"MISSING_VERSION",severity:"error"}),r.inputs&&r.inputs.schema){const e=lm(r.inputs.schema,"capability.inputs.schema");t.push(...e)}else t.push({path:"capability.inputs.schema",message:"capability.inputs.schema is required",code:"MISSING_INPUTS_SCHEMA",severity:"error"});if(r.outputs&&r.outputs.schema){const e=lm(r.outputs.schema,"capability.outputs.schema");t.push(...e)}else t.push({path:"capability.outputs.schema",message:"capability.outputs.schema is required",code:"MISSING_OUTPUTS_SCHEMA",severity:"error"});if(n.program&&"object"==typeof n.program){if("cells"!==n.program.format&&t.push({path:"program.format",message:'program.format must be "cells"',code:"INVALID_PROGRAM_FORMAT",severity:"error"}),Array.isArray(n.program.cells)){n.program.cells.forEach((e,n)=>{e&&"object"==typeof e?(e.id&&"string"==typeof e.id||t.push({path:`program.cells[${n}].id`,message:"Cell id is required and must be a string",code:"MISSING_CELL_ID",severity:"error"}),e.cell_type&&["code","markdown","raw"].includes(e.cell_type)||t.push({path:`program.cells[${n}].cell_type`,message:'Cell cell_type must be "code", "markdown", or "raw"',code:"INVALID_CELL_TYPE",severity:"error"}),void 0===e.source&&t.push({path:`program.cells[${n}].source`,message:"Cell source is required",code:"MISSING_CELL_SOURCE",severity:"error"})):t.push({path:`program.cells[${n}]`,message:"Cell must be an object",code:"INVALID_CELL_TYPE",severity:"error"})});const e=n.program;if(e?.roles){if(e.roles.inputCellId||t.push({path:"program.roles.inputCellId",message:"program.roles.inputCellId is required",code:"MISSING_INPUT_CELL_ID",severity:"error"}),e.roles.outputCellId||t.push({path:"program.roles.outputCellId",message:"program.roles.outputCellId is required",code:"MISSING_OUTPUT_CELL_ID",severity:"error"}),e.roles.inputCellId){if(e.cells.some(t=>t.id===e.roles.inputCellId)){const n=e.cells.find(t=>t.id===e.roles.inputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["input"]')||r.includes("['input']"));r.includes("__ivy_input__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_input__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["input"].',code:"LEGACY_INPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Input cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["input"] protocol.',code:"INVALID_INPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.inputCellId",message:`Input cell id "${e.roles.inputCellId}" not found in cells`,code:"INVALID_INPUT_CELL_ID",severity:"error"})}if(e.roles.outputCellId){if(e.cells.some(t=>t.id===e.roles.outputCellId)){const n=e.cells.find(t=>t.id===e.roles.outputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["output"]')||r.includes("['output']"));r.includes("__ivy_output__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_output__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["output"].',code:"LEGACY_OUTPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Output cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["output"] protocol.',code:"INVALID_OUTPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.outputCellId",message:`Output cell id "${e.roles.outputCellId}" not found in cells`,code:"INVALID_OUTPUT_CELL_ID",severity:"error"})}}else t.push({path:"program.roles",message:"program.roles is required for ivy.node/v0.2 (inputCellId/outputCellId)",code:"MISSING_PROGRAM_ROLES",severity:"error"})}else t.push({path:"program.cells",message:"program.cells is required and must be an array",code:"MISSING_PROGRAM_CELLS",severity:"error"});n.program.language&&"string"==typeof n.program.language||t.push({path:"program.language",message:"program.language is required and must be a string",code:"MISSING_PROGRAM_LANGUAGE",severity:"error"})}else t.push({path:"program",message:"program is required and must be an object",code:"MISSING_PROGRAM",severity:"error"});if(r.policy){const e=["low","medium","high"];r.policy.risk&&e.includes(r.policy.risk)||t.push({path:"capability.policy.risk",message:`capability.policy.risk must be one of: ${e.join(", ")}`,code:"INVALID_POLICY_RISK",severity:"error"});const n=["none","plan","step"];r.policy.approval&&n.includes(r.policy.approval)||t.push({path:"capability.policy.approval",message:`capability.policy.approval must be one of: ${n.join(", ")}`,code:"INVALID_POLICY_APPROVAL",severity:"error"})}else t.push({path:"capability.policy",message:"capability.policy is required",code:"MISSING_POLICY",severity:"error"});if(void 0!==n.runtime&&"object"!=typeof n.runtime&&t.push({path:"runtime",message:"runtime must be an object",code:"INVALID_RUNTIME_TYPE",severity:"error"}),void 0!==n.tests)if("object"!=typeof n.tests)t.push({path:"tests",message:"tests must be an object",code:"INVALID_TESTS_TYPE",severity:"error"});else{const e=["draft","verified","certified"];n.tests.tier&&e.includes(n.tests.tier)||t.push({path:"tests.tier",message:`tests.tier must be one of: ${e.join(", ")}`,code:"INVALID_TESTS_TIER",severity:"error"}),n.tests.cases&&!Array.isArray(n.tests.cases)?t.push({path:"tests.cases",message:"tests.cases must be an array",code:"INVALID_TESTS_CASES",severity:"error"}):Array.isArray(n.tests.cases)&&n.tests.cases.forEach((e,n)=>{e&&"object"==typeof e?("string"==typeof e.id&&e.id||t.push({path:`tests.cases[${n}].id`,message:"Test case id is required and must be a string",code:"MISSING_TEST_CASE_ID",severity:"error"}),"string"==typeof e.description&&e.description||t.push({path:`tests.cases[${n}].description`,message:"Test case description is required and must be a string",code:"MISSING_TEST_CASE_DESCRIPTION",severity:"error"}),"input"in e?am(e.input)&&t.push({path:`tests.cases[${n}].input`,message:'Test case input must not contain a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }) — it is not resolvable in isolated runner tests. Use literal JSON values in test inputs. (Domain $ref strings, e.g. inside a Swagger/JSON-Schema document, are allowed.)',code:"TEST_INPUT_REF_NOT_ALLOWED",severity:"error"}):t.push({path:`tests.cases[${n}].input`,message:"Test case input is required",code:"MISSING_TEST_CASE_INPUT",severity:"error"})):t.push({path:`tests.cases[${n}]`,message:"Test case must be an object",code:"INVALID_TEST_CASE",severity:"error"})})}return{ok:0===t.filter(e=>"error"===e.severity).length,issues:t}}function lm(e,t){const n=[];if(!e||"object"!=typeof e)return n.push({path:t,message:"Schema must be an object",code:"INVALID_SCHEMA_TYPE",severity:"error"}),n;const r=e;if(void 0!==r.type){const e=["object","string","number","boolean","array","null"];"string"!=typeof r.type||e.includes(r.type)||n.push({path:`${t}.type`,message:`Invalid type: ${r.type}. Must be one of: ${e.join(", ")}`,code:"INVALID_SCHEMA_TYPE",severity:"warning"})}return void 0!==r.properties&&("object"!=typeof r.properties||Array.isArray(r.properties))&&n.push({path:`${t}.properties`,message:"properties must be an object",code:"INVALID_SCHEMA_PROPERTIES",severity:"error"}),void 0!==r.required&&(Array.isArray(r.required)||n.push({path:`${t}.required`,message:"required must be an array",code:"INVALID_SCHEMA_REQUIRED",severity:"error"})),n}class um{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await vo().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=$a();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[NodeRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return dm(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[NodeRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n),i=cm(r);if(!i.ok)return void console.warn(`[NodeRegistry] Invalid manifest at ${t}:`,i.issues);const s=r,o=s.capability;if(!o||"object"!=typeof o||!("id"in o))return void console.warn(`[NodeRegistry] Missing capability.id in ${t}`);const a=t.lastIndexOf("/"),c=a>=0?t.slice(0,a):"";this.packages.set(o.id,{packageRoot:c,manifestPath:t,manifest:s})}catch(e){console.warn(`[NodeRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.runtime&&(t=t.filter(t=>t.manifest.runtime?.kind===e.runtime)),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}setTestReport(e,t){this.testReports.set(e,t)}getLatestTestReport(e){return this.testReports.get(e)}clear(){this.packages.clear(),this.testReports.clear()}}function dm(e,t){for(const n of e)n.isDirectory?n.children&&dm(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let pm;function hm(){return pm||(pm=new um),pm}function fm(e,t,n,r=!1){if("code"!==e.cell_type)throw new Error("Cell must be a code cell");let i=Array.isArray(e.source)?e.source.join(""):String(e.source||"");const s=JSON.stringify(t);return i=i.replace(/__ivy_node_id__/g,s),i}async function mm(e,t,n,r){let i={};for await(const s of e.run({id:"ivy-snapshot",language:"python",code:"import json as __ivy_json\ndef __ivy_snapshot__():\n out = {}\n __ivy_skip = ('In', 'Out', 'get_ipython', 'exit', 'quit', 'json')\n for __ivy_k in list(globals().keys()):\n if __ivy_k.startswith('_'):\n continue\n if __ivy_k in __ivy_skip:\n continue\n try:\n __ivy_v = globals()[__ivy_k]\n except Exception:\n continue\n if callable(__ivy_v):\n continue\n __ivy_tn = type(__ivy_v).__name__\n __ivy_m = getattr(type(__ivy_v), '__module__', '') or ''\n if __ivy_tn == 'module':\n continue\n try:\n if __ivy_tn in ('DataFrame', 'Series') and 'pandas' in __ivy_m:\n __ivy_shape = getattr(__ivy_v, 'shape', None)\n out[__ivy_k] = {'__type__': __ivy_tn, 'shape': list(__ivy_shape) if __ivy_shape is not None else None}\n elif __ivy_tn == 'ndarray' and 'numpy' in __ivy_m:\n out[__ivy_k] = {'__type__': 'ndarray', 'shape': list(__ivy_v.shape), 'dtype': str(__ivy_v.dtype)}\n else:\n try:\n __ivy_enc = __ivy_json.dumps(__ivy_v)\n if len(__ivy_enc) > 2000:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n else:\n out[__ivy_k] = __ivy_v\n except Exception:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n except Exception:\n try:\n out[__ivy_k] = repr(__ivy_v)[:500]\n except Exception:\n out[__ivy_k] = '<unrepr>'\n return out\nprint(__ivy_json.dumps(__ivy_snapshot__(), default=lambda o: repr(o)[:500]))\n",resources:r?{timeoutMs:r}:void 0},{runId:`${t}:snapshot:${n}`}))if("stdout"===s.type&&"text"in s){const e=s.text;try{const t=JSON.parse(e.trim());t&&"object"==typeof t&&(i=t)}catch{}}return i}function gm(e,t){const n={};for(const r of Object.keys(t))r in e&&JSON.stringify(e[r])===JSON.stringify(t[r])||(n[r]=t[r]);return n}const ym=/token|secret|key|password|passwd|api[_-]?key/i;function bm(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=ym.test(i)?"[REDACTED]":e[i],o=i.length+JSON.stringify(s??null).length;n+o>16e3?r=!0:(n+=o,t[i]=s)}return r&&(t.__truncated__=!0),t}async function wm(e,t){const n=Date.now(),r=hm().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=cm(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(am(t.input))throw new Error('Input contains a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }). punica.ivy.runner.run executes a single node in isolation and cannot resolve references. Resolve inputs before calling runner, or execute inside the workflow engine.');const o=s.capability;if(!o||"object"!=typeof o||!("inputs"in o))throw new Error("Manifest missing capability.inputs");const a=o.inputs;if(!a.schema)throw new Error("Manifest missing capability.inputs.schema");const c=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Input must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required property: ${e}`)}return{valid:0===n.length,errors:n}}(t.input,a.schema);if(!c.valid)throw new Error(`Input validation failed: ${c.errors.join(", ")}`);if(!s.program)throw new Error("Manifest missing program");const l=s.program,u=l.cells,d=l.roles?.inputCellId,p=l.roles?.outputCellId;if(!d)throw new Error("Program missing roles.inputCellId");if(!p)throw new Error("Program missing roles.outputCellId");const h=u.find(e=>e.id===d),f=u.find(e=>e.id===p);if(!h)throw new Error(`Input cell with id "${d}" not found in program.cells`);if(!f)throw new Error(`Output cell with id "${p}" not found in program.cells`);const m=function(){if(!punica.runtime?.compute)throw new Error("[IvyNodeRunner] Runtime compute API not available. Ensure compute provider is registered.");return punica.runtime.compute}(),g=[],y=l.language||(s.runtime,"python"),b=t.runId??`ivynode-${e}-${n}`,w=(e,t)=>{try{punica.kernel.Events.manager.publish(e,t)}catch{}},v=(e,t)=>{const n=Array.isArray(e.source)?e.source[0]:e.source;return String(n??"").replace(/^#+\s*/,"").trim().slice(0,50)||`Cell ${t+1}`},k=e=>{const t=e;return"stdout"!==t.type&&"stderr"!==t.type||"string"!=typeof t.text?"":t.text},I=await m.session.open({language:y}),E=t.runId||`ivynode-${e}-${Date.now()}`;let A={};try{const r=["# IvyNode runner context init (v0.2)","import json",'__ivy_ctx__ = {"nodes": {}}',`__ivy_ctx__["nodes"][${JSON.stringify(e)}] = {"input": json.loads(${JSON.stringify(JSON.stringify(t.input))}), "output": {}}`].join("\n");for await(const e of I.run({id:"init-ivy-ctx",language:"python",code:r,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:init`}))g.push({type:e.type,data:e});for(let n=0;n<u.length;n++){const r=u[n];if("code"!==r.cell_type)continue;const i=fm(r,e),s=r.id||`cell-${n}`,o=v(r,n),a=Date.now();let c,l="";w("ivy.node.cell.started",{runId:b,nodeId:e,cellId:s,index:n,label:o,startedAtMs:a});try{let e=null;for await(const n of I.run({id:s,language:y,code:i,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:cell:${s}`})){g.push({type:n.type,data:n}),l+=k(n);const t=n;if("error"===t.type){e=`${t.name?`${t.name}: `:""}${t.message??"cell execution error"}`.trim()}else if("finished"===t.type&&!1===t.ok){const n=null!=t.exitCode?` (exit code ${t.exitCode})`:"",r=l.trim()?`:\n${l.trim()}`:"";e=e??`Cell execution failed${n}${r}`}}if(e)throw new Error(e)}catch(t){throw w("ivy.node.cell.failed",{runId:b,nodeId:e,cellId:s,index:n,label:o,durationMs:Date.now()-a,error:t instanceof Error?t.message:String(t),logs:l}),t}try{const e=await mm(I,E,s,t.timeoutMs),n=bm(gm(A,e));Object.keys(n).length&&(c=n),A=e}catch{}w("ivy.node.cell.finished",{runId:b,nodeId:e,cellId:s,index:n,label:o,durationMs:Date.now()-a,logs:l,...c?{variables:c}:{}})}const i=await async function(e,t,n,r){const i=JSON.stringify(t),s=`\nimport json\ntry:\n if '__ivy_ctx__' in globals() and isinstance(__ivy_ctx__, dict):\n if "nodes" in __ivy_ctx__ and ${i} in __ivy_ctx__["nodes"]:\n node_data = __ivy_ctx__["nodes"][${i}]\n if "output" in node_data:\n print(json.dumps(node_data["output"]))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\nexcept Exception as e:\n print(json.dumps({"error": str(e)}))\n`;for await(const t of e.run({id:"extract-output",language:"python",code:s,resources:r?{timeoutMs:r}:void 0},{runId:`${n}:extract-output`}))if("stdout"===t.type&&"text"in t){const e=t.text;try{const t=JSON.parse(e.trim());if(t&&"object"==typeof t)return t}catch(e){}}throw new Error("Failed to extract output from execution context")}(I,e,E,t.timeoutMs),s=o.outputs;if(!s?.schema)throw new Error("Manifest missing capability.outputs.schema");const a=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Output must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required output property: ${e}`)}return{valid:0===n.length,errors:n}}(i,s.schema);if(!a.valid)throw new Error(`Output validation failed: ${a.errors.join(", ")}`);return{output:i,events:g,durationMs:Date.now()-n}}finally{await I.close()}}function vm(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function km(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function Im(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Em(e,t){const n=e.value;switch(e.type){case"isType":return{passed:km(t)===String(n??""),expected:String(n??""),actual:km(t)};case"equals":return{passed:Im(t,n),expected:JSON.stringify(n),actual:JSON.stringify(t)};case"matches":return{passed:void 0!==t&&new RegExp(String(n??"")).test(String(t)),expected:String(n??""),actual:void 0===t?void 0:String(t)};case"contains":return"string"==typeof t?{passed:t.includes(String(n??"")),expected:String(n??""),actual:t}:Array.isArray(t)?{passed:t.some(e=>Im(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:km(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:km(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):km(t)};case"greaterThan":return{passed:"number"==typeof t&&t>Number(n),expected:`> ${n}`,actual:String(t)};case"lessThan":return{passed:"number"==typeof t&&t<Number(n),expected:`< ${n}`,actual:String(t)};case"between":{const e=Array.isArray(n)?n:[];return{passed:"number"==typeof t&&2===e.length&&t>=Number(e[0])&&t<=Number(e[1]),expected:JSON.stringify(n),actual:String(t)}}default:return{passed:!0,expected:`unsupported matcher: ${e.type}`,actual:km(t)}}}function Am(e,t,n=""){const r=e.assertions||{},i={},s=[];if(void 0!==r.schema){const e=!0===r.schema;i.schema={passed:e},s.push(!e)}if(void 0!==r.expectsError){const e=!1===r.expectsError;i.error={passed:e},s.push(!e)}if(r.errorPattern&&r.expectsError){const e=new RegExp(r.errorPattern).test(n);i.error={passed:e,expected:r.errorPattern,actual:n||void 0},s.push(!e)}if(r.properties&&"object"==typeof r.properties){const e={};for(const[n,i]of Object.entries(r.properties)){if(!i||"object"!=typeof i)continue;const r=vm(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=Em(a,r);else if("string"==typeof a)o=Em({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=Em({type:"equals",value:i.expected},r)}e[n]=o,s.push(!o.passed)}Object.keys(e).length&&(i.properties=e)}return{status:s.some(Boolean)?"fail":"pass",assertions:Object.keys(i).length>0?i:void 0}}function Sm(e,t,n){const r=!0===e.assertions?.expectsError,i=e.assertions?.errorPattern;let s;return s=r?i?new RegExp(i).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:s,error:t,assertions:{error:{passed:r,expected:i,actual:t}}}}function _m(e){const{capabilityId:t,version:n,tier:r,results:i,startedAtMs:s}=e,o=i.filter(e=>"pass"===e.status).length,a=i.filter(e=>"fail"===e.status).length,c=i.filter(e=>"skip"===e.status).length,l=i.filter(e=>"error"===e.status).length;return{reportId:`report-${t}-${n}-${Date.now()}`,capabilityId:t,capabilityVersion:n,specVersion:"v0.1",timestampMs:Date.now(),runner:{version:"0.1.0",environment:"punica-editor"},summary:{tier:r,status:0===a&&0===l?"pass":a>0?"fail":"flaky",totalCases:i.length,passedCases:o,failedCases:a,skippedCases:c,durationMs:Date.now()-s},cases:i}}function xm(){return Date.now()}function Cm(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Tm(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function Nm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Mm(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"gateway"in t)return t.gateway}}function Dm(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"registry"in t){const e=t.registry;if(e&&"object"==typeof e&&"getSpec"in e)return{getSpec:e.getSpec}}}}function Pm(e){if(!e?.defaults)return;const t=e.defaults;if("object"!=typeof t||null===t)return;const n=t,r={};return"number"==typeof n.timeoutMs&&(r.timeoutMs=n.timeoutMs),"number"==typeof n.retries&&n.retries>0&&(r.retry={maxAttempts:n.retries,initialDelayMs:"number"==typeof n.retryBackoffMs?n.retryBackoffMs:1e3,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1}),n.rateLimit&&"object"==typeof n.rateLimit&&(r.rateLimit=n.rateLimit),n.concurrency&&"object"==typeof n.concurrency&&(r.concurrency=n.concurrency),"write"===e.sideEffect&&(r.requireIdempotencyKeyForWriteRetry=!0),Object.keys(r).length>0?r:void 0}async function Om(e){try{const n=Mm();if(!n)throw new Error("[FlowEngine] Capability gateway not available. Gateway is mandatory for all FS operations.");{const r=await t();await n.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}}catch{}}async function Rm(e,n){const r=Mm();if(!r)throw new Error("[FlowEngine] writeTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");const i=await t();await r.call("fs.writeFile",{path:e,content:n},{sessionId:"internal",workspaceId:i,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}function Lm(e,t,n,r,i){const s=i?.traceId??t;punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:t,traceId:s,spanId:i?.spanId,parentSpanId:i?.parentSpanId,timestampMs:xm(),source:i?.source??"flow:engine",kind:n},payload:r})}const $m=new Set(["sensitive","secret"]);function jm(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Fm(e,t,n,r){if(!function(e,t,n){return!(!n||!$m.has(n)||"meta"===t)||!(!e||"none"===e)&&("all"===e?"input"===t||"output"===t:"input"===e?"input"===t:"output"===e&&"output"===t)}(t,n,r))return e;return{redacted:!0,reason:"policy",policy:t,surface:n,originalBytes:jm(e)}}const Bm=new class{#rn=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#rn.set(e,(this.#rn.get(e)??0)+r),!0;const i=this.#rn.get(e)??0;return!(i+r>n)&&(this.#rn.set(e,i+r),!0)}used(e){return this.#rn.get(e)??0}release(e){this.#rn.delete(e)}reset(){this.#rn.clear()}};class qm{async ensureBase(){await Om(".punica"),await Om(Nm(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await Om(Nm(".punica","workflow-runs",e)),await Om(Nm(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=xm();await this.ensureRunDirs(e);const s=n.surface??"output",o=n.payload,a=n.text;let c,l=o,u=a;if(n.redactionPolicy||n.capabilityClassification){const e=Fm(o??a,n.redactionPolicy,s,n.capabilityClassification);e&&"object"==typeof e&&!0===e.redacted&&(c=e,l=c,u=void 0)}const d="string"==typeof u,p=Nm(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let h;h=d?String(u??""):Cm(l??{},2);const f=n.sizeBudget?.maxBytes;if(c||"number"!=typeof f)"number"==typeof f&&Bm.acquire(e,h.length,f);else{Bm.acquire(e,h.length,f)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,h.length),h=Cm(c,2),Bm.acquire(e,h.length,f))}await Rm(p,h);const m=h.length,g=Tm(d?String(u??""):Cm(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs:i,name:n.name,mimeType:n.mimeType,uri:p,preview:g,sizeBytes:m,meta:c?{...n.meta??{source:"flow:engine"},redacted:c}:n.meta??{source:"flow:engine"}};return Lm("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function zm(e,t){return Object.freeze(function(e,t){const n=[];for(const r of e.readyNodes){if(t&&n.length>=t)break;n.push(r)}return n}(e,t).slice())}function Um(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Vm(e){return function(e){const t=new Map,n=new Set;for(const n of e.graph.nodes){if(n.disabled)continue;const e={nodeId:n.id,status:"pending",dependencies:new Set,dependents:new Set,completedDependencies:new Set};t.set(n.id,e)}for(const n of e.graph.edges){const e=t.get(n.fromId),r=t.get(n.toId);e&&r&&(r.dependencies.add(n.fromId),e.dependents.add(n.toId))}for(const[e,r]of t.entries())0===r.dependencies.size&&(n.add(e),r.status="ready");return{nodes:t,readyNodes:n}}(e)}function Wm(e,t,n){t?function(e,t){const n=t.nodes.get(e);if(n){n.status="completed";for(const r of n.dependents){const n=t.nodes.get(r);n&&(n.completedDependencies.add(e),n.completedDependencies.size===n.dependencies.size&&"pending"===n.status&&(n.status="ready",t.readyNodes.add(r)))}}}(e,n):function(e,t){const n=t.nodes.get(e);n&&(n.status="failed",t.readyNodes.delete(e))}(e,n)}function Km(e,t){!function(e,t){const n=t.nodes.get(e);n&&"ready"===n.status&&(n.status="running",t.readyNodes.delete(e))}(e,t)}function Gm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Hm(e){const t=globalThis.punica,n=t?.runtime?.capabilities?.gateway;if(!n)throw new Error(`[FlowEngine] persistence.${e}: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).`);return n}async function Ym(e,t,n){const r=Hm(e);await r.call("fs.writeFile",{path:t,content:n},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}async function Jm(e,t){const n=Hm(e);try{await n.call("fs.ensureDir",{path:t},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}catch{}}async function Zm(e,t){const n=Hm(e);await n.call("fs.deleteFile",{path:t},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}async function Qm(e,t=".punica"){const n=Gm(t,"workflow-runs",e.runId),r=Gm(n,"checkpoint.json"),i=Gm(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await Jm("writeCheckpoint",n),await Ym("writeCheckpoint",i,s);try{await async function(e,t,n){const r=Hm(e);await r.call("fs.rename",{from:t,to:n},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}("writeCheckpoint",i,r)}catch{try{await Zm("writeCheckpoint",r)}catch{}await Ym("writeCheckpoint",r,s);try{await Zm("writeCheckpoint",i)}catch{}}}async function Xm(e,t=".punica"){const n=Gm(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=Hm(e);return await n.call("fs.readFile",{path:t},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}("readCheckpoint",n);return JSON.parse(e)}catch{return null}}function eg(e){try{const t=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!t?.publishEvent||!t?.createCorrelationId)&&(t.publishEvent({name:e.name,envelope:{id:t.createCorrelationId(),correlationId:e.correlationId,traceId:e.traceId,timestampMs:Date.now(),source:e.source??"flow:engine",kind:e.kind??"info"},payload:e.payload}),!0)}catch{return!1}}class tg{runs;runIdToSession;artifactStore;constructor(e,t,n){this.runs=e,this.runIdToSession=t,this.artifactStore=n}async startRun(e){const t=e?.spec,n=e?.workspaceId,r=e?.filePathOrUri,i=e?.input??null;if(!t||"ivy.workflow/v0.1"!==t.apiVersion||"Workflow"!==t.kind)throw new Error('Invalid WorkflowDocument: must have apiVersion="ivy.workflow/v0.1" and kind="Workflow"');if(!t.graph||!t.graph.nodes||!t.graph.edges)throw new Error("Invalid WorkflowDocument: missing graph.nodes or graph.edges");if(!t.graph.entryNodeId)throw new Error("Invalid WorkflowDocument: missing graph.entryNodeId");if(!t.graph.nodes.some(e=>e.id===t.graph.entryNodeId))throw new Error(`Invalid WorkflowDocument: entryNodeId "${t.graph.entryNodeId}" not found in graph.nodes`);const s=t,o=function(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=e.graph.edges.filter(e=>n.has(e.fromId)&&n.has(e.toId)),i=new Map,s=new Map;t.forEach(e=>{i.set(e.id,0),s.set(e.id,[])}),r.forEach(e=>{s.get(e.fromId).push(e.toId),i.set(e.toId,(i.get(e.toId)??0)+1)});const o=[];for(const[e,t]of i.entries())0===t&&o.push(e);const a=[];for(;o.length;){const e=o.shift();a.push(e);for(const t of s.get(e)??[])i.set(t,(i.get(t)??0)-1),0===(i.get(t)??0)&&o.push(t)}if(a.length!==t.length)throw new Error("Workflow graph is not a DAG (cycle detected).");return a}(s),a=punica.kernel.Events.manager.createCorrelationId(),c=a,l=punica.kernel.Events.manager.createCorrelationId(),u={runId:a,specVersion:"0.1",status:"QUEUED",createdAtMs:xm(),startedAtMs:xm(),traceId:c,entryNodeId:s.graph.entryNodeId,metadata:{title:s.title,tags:s.tags},steps:[]};for(const e of o){const t=s.graph.nodes.find(t=>t.id===e);if(!t)continue;const n="ivyNode"===t.ref.kind?"capability.call":"workflow"===t.ref.kind?"workflow.run":"flowInput"===t.ref.kind?"flow.input":"flowOutput"===t.ref.kind?"flow.output":"primitive"===t.ref.kind?`primitive.${t.ref.primitive}`:"unknown",r={stepId:t.id,nodeId:t.id,nodeType:n,attempt:0,status:t.disabled?"SKIPPED":"PENDING",cellId:void 0};u.steps.push(r)}u.status="RUNNING";const d=Vm(s),p=s.graph.runBudget?.maxInFlight;return this.runs.set(a,{run:u,spec:s,order:o,cursor:0,paused:!1,cancelled:!1,rootSpanId:l,filePathOrUri:r,dependencyGraph:d,inFlightNodes:new Set,maxInFlight:p,nodeOutputs:new Map,input:i}),Lm("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),eg({name:"flow.run.started",correlationId:a,traceId:c,payload:{runId:a,flowId:s.id,workspaceId:n,startedAtMs:u.startedAtMs??u.createdAtMs,entryNodeId:u.entryNodeId}}),await this.persistRun(a),await this.persistIndex(),{runId:a,workspaceId:n}}async pauseRun(e){const t=this.runs.get(e);return!!t&&(t.paused=!0,t.run.status="PAUSED",Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),!0)}async resumeRun(e){let t=this.runs.get(e);if(!t){const n=await Xm(e);if(!n)return!1;{const r=n.dependencyGraphState?Vm(n.spec):void 0;t={run:n.run,spec:n.spec,order:n.spec.graph.nodes.map(e=>e.id),cursor:n.cursor??0,paused:!1,cancelled:!1,rootSpanId:n.run.traceId,dependencyGraph:r,inFlightNodes:new Set(n.inFlightNodes??[]),maxInFlight:n.spec.graph.runBudget?.maxInFlight},this.runs.set(e,t)}}return t.paused=!1,"RUNNING"!==t.run.status&&(t.run.status="RUNNING"),Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"RUNNING"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),!0}async cancelRun(e,t){const n=this.runs.get(e);if(!n)return!1;n.cancelled=!0,n.run.status="CANCELLED",n.run.endedAtMs=xm();const r=this.runIdToSession.get(e);if(r){try{"hard"===(t??"best-effort")?await r.restart():await r.interrupt()}catch(t){console.warn(`[FlowEngine] Error cancelling session for run ${e}:`,t)}this.runIdToSession.delete(e)}return Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Lm("workflow.runFinished",e,"info",{runId:e,status:"CANCELLED",endedAtMs:n.run.endedAtMs},{traceId:n.run.traceId,spanId:n.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),await this.persistIndex(),!0}getRun(e){return this.runs.get(e)?.run??null}listRuns(e){const t=Array.from(this.runs.values()).map(e=>({runId:e.run.runId,status:e.run.status,createdAtMs:e.run.createdAtMs,startedAtMs:e.run.startedAtMs,endedAtMs:e.run.endedAtMs,traceId:e.run.traceId,metadata:{title:e.run.metadata?.title}})),n=e?.status?t.filter(t=>t.status===e.status):t,r="number"==typeof e?.limit&&e.limit>0?e.limit:n.length;return n.sort((e,t)=>(t.createdAtMs??0)-(e.createdAtMs??0)),n.slice(0,r)}async persistRun(e){const t=this.runs.get(e);if(!t)return;await this.artifactStore.ensureRunDirs(e);const n=Nm(".punica","workflow-runs",e,"run.json");await Rm(n,Cm({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=Nm(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Rm(e,Cm({version:1,updatedAtMs:xm(),runs:t},2))}async persistCheckpoint(e){const t=this.runs.get(e);if(!t)return;const n={runId:e,timestampMs:Date.now(),run:t.run,spec:t.spec,cursor:t.cursor,inFlightNodes:Array.from(t.inFlightNodes??[])};await Qm(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=Nm(".punica","workflow-runs","index.json"),n=await async function(e){const n=Mm();if(!n)throw new Error("[FlowEngine] readTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");try{const r=await t();return await n.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}catch{return null}}(e);if(n)try{const e=JSON.parse(n);Lm("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class ng{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,i,s){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=i,this.resumeRunLoop=s}setupApprovalSubscription(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{const t=e?.event?.payload?e.event:e,n=t?.envelope?.correlationId;if(!n)return;const r=this.pendingToRunStep.get(n);if(!r)return;const i=t?.payload??{},s=i?.request??{},o=i?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(s?.kind??"capability"),id:String(s?.id??""),risk:String(s?.risk??"low"),approval:String(s?.approval??"once"),reason:"string"==typeof s?.reason?s.reason:void 0,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:xm()};this.pendingByCorrelation.set(n,c);const l=this.runs.get(r.runId);if(l){const e=l.run.steps.find(e=>e.stepId===r.stepId);e&&(e.status="WAITING_APPROVAL",e.approval={pendingId:a,required:!0,requestedAtMs:xm(),resolved:!1},Lm("workflow.stepUpdated",l.run.runId,"info",{runId:l.run.runId,stepId:e.stepId,patch:{status:e.status,approval:e.approval}},{traceId:l.run.traceId,spanId:e.spanId,parentSpanId:l.rootSpanId})),l.run.status="WAITING_APPROVAL",Lm("workflow.runUpdated",l.run.runId,"info",{runId:l.run.runId,patch:{status:l.run.status,currentNodeId:e?.nodeId}},{traceId:l.run.traceId,spanId:l.rootSpanId}),Lm("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),eg({name:"flow.approval.requested",correlationId:l.run.runId,traceId:l.run.traceId,payload:{runId:l.run.runId,stepId:r.stepId,pendingId:c.pendingId,attemptCorrelationId:n,capability:{kind:c.kind,id:c.id},risk:c.risk,approval:c.approval,workspaceId:c.workspaceId}}),this.persistRun(l.run.runId)}})}approvePending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=e?.scope??"once",r=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!r)return!1;const i=this.pendingToRunStep.get(r.attemptCorrelationId);if(!i)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id},n,{workspaceId:r.workspaceId})}catch{}Lm("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:xm()},{traceId:i.runId}),eg({name:"flow.approval.granted",correlationId:i.runId,traceId:i.runId,payload:{runId:i.runId,stepId:i.stepId,pendingId:t,scope:n,capability:{kind:r.kind,id:r.id}}}),this.pendingByCorrelation.delete(r.attemptCorrelationId);const s=this.runs.get(i.runId);if(s){const e=s.run.steps.find(e=>e.stepId===i.stepId);e?.approval&&(e.approval.resolved=!0,e.approval.decision="approved"),s.run.status="RUNNING",Lm("workflow.runUpdated",s.run.runId,"info",{runId:s.run.runId,patch:{status:"RUNNING"}},{traceId:s.run.traceId,spanId:s.rootSpanId}),this.persistRun(s.run.runId),this.resumeRunLoop(s.run.runId)}return!0}rejectPending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!n)return!1;const r=this.pendingToRunStep.get(n.attemptCorrelationId);if(!r)return!1;Lm("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:xm()},{traceId:r.runId}),eg({name:"flow.approval.rejected",kind:"warn",correlationId:r.runId,traceId:r.runId,payload:{runId:r.runId,stepId:r.stepId,pendingId:t,capability:{kind:n.kind,id:n.id}}}),this.pendingByCorrelation.delete(n.attemptCorrelationId);const i=this.runs.get(r.runId);return i&&(i.run.status="FAILED",i.run.endedAtMs=xm(),Lm("workflow.runUpdated",i.run.runId,"error",{runId:i.run.runId,patch:{status:"FAILED",endedAtMs:i.run.endedAtMs,error:{message:"Approval rejected",nodeId:r.stepId}}},{traceId:i.run.traceId,spanId:i.rootSpanId}),Lm("workflow.runFinished",i.run.runId,"error",{runId:i.run.runId,status:"FAILED",endedAtMs:i.run.endedAtMs},{traceId:i.run.traceId,spanId:i.rootSpanId}),this.persistRun(i.run.runId),this.persistIndex()),!0}}const rg=3e4,ig={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const sg=new class{#pt=new Map;getSemaphore(e,t){let n=this.#pt.get(e);return n||(n={count:0,max:t,queue:[]},this.#pt.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e,t){const n=this.#pt.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function og(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function ag(e,t){if(!t.retry)return 0;const n=t.retry.initialDelayMs??1e3,r=t.retry.maxDelayMs??3e4,i=t.retry.backoffMultiplier??2,s=t.retry.jitter??"none";return function(e,t){if("none"===t)return e;if("full"===t)return Math.floor(Math.random()*e);if("decorrelated"===t){const t=e/2;return Math.floor(t+Math.random()*t)}return e}(Math.min(n*Math.pow(i,e-1),r),s)}const cg=new class{#in=new Map;register(e,t){this.#in.set(e,t)}get(e){return this.#in.get(e)}resolveOrThrow(e){const t=this.#in.get(e.ref.kind);if(!t)throw new Error(`No executor registered for node ref.kind: "${e.ref.kind}" (node id: ${e.id})`);return t}clear(){this.#in.clear()}};function lg(e,t){let n=e;for(const e of t){if(null==n)return;if("object"!=typeof n)return;if(Array.isArray(n)){const t=Number(e);if(!Number.isInteger(t)||t<0||t>=n.length)return;n=n[t];continue}if(!Object.prototype.hasOwnProperty.call(n,e))return;n=n[e]}return n}function ug(e,t){if(!e||"object"!=typeof e)return{ok:!1,reason:"invalid-ref"};if("literal"===e.kind)return{ok:!0,value:e.value};if("path"===e.kind){const n=String(e.path??"").split(".").filter(e=>e.length>0);if(0===n.length)return{ok:!1,reason:"invalid-ref"};const[r,...i]=n;if(!t.has(r))return{ok:!1,reason:"missing-node"};const s=t.get(r);if(0===i.length)return{ok:!0,value:s??null};const o=lg(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function dg(e){return null!=e&&("boolean"==typeof e?e:"number"==typeof e?0!==e&&!Number.isNaN(e):"string"==typeof e||Array.isArray(e)?e.length>0:"object"==typeof e&&Object.keys(e).length>0)}function pg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hg(e){return String(e??"").split(".").filter(e=>e.length>0)}function fg(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];pg(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function mg(e,t,n){const r=t.filter(t=>t.toId===e.id&&(void 0!==t.fromPath||void 0!==t.toPath)),i=e.data?.input;if(0===r.length)return void 0!==i?i:void 0!==e.defaults?e.defaults:void 0;const s={...pg(e.defaults)?e.defaults:{},...pg(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?hg(e.fromPath):[],i=r.length?lg(t,r):t;if(void 0===i)continue;const o=e.toPath?hg(e.toPath):[];o.length?fg(s,o,i):pg(i)?Object.assign(s,i):s[e.fromId]=i}return s}class gg extends Error{code="RUN_CANCELLED";runId;mode;constructor(e,t){super(`Run ${e??"<unknown>"} was cancelled (${t??"best-effort"} mode) — substrate refuses to continue in-flight node attempts.`),this.name="RunCancelledError",this.runId=e,this.mode=t}}function yg(e,t){if(function(e){return!0===e.cancelled}(e))throw new gg(e.run?.runId,t)}class bg{runs;pendingToRunStep;runIdToSession;artifactStore;persistRun;persistCheckpoint;persistIndex;notifyTerminal;constructor(e,t,n,r,i,s,o,a){this.runs=e,this.pendingToRunStep=t,this.runIdToSession=n,this.artifactStore=r,this.persistRun=i,this.persistCheckpoint=s,this.persistIndex=o,this.notifyTerminal=a}async executeSequential(e,t){const n=this.runs.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;if(!n.notebook&&n.filePathOrUri)try{const e=Mm();if(!e)throw new Error("[FlowEngine] notebook lazy-load: capability gateway is mandatory — substrate refuses to fall back to runtime.fs.");const r=await e.call("fs.readFile",{path:n.filePathOrUri},{sessionId:"internal",workspaceId:t?.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:n.run.traceId,parentSpanId:n.rootSpanId},policy:{mode:"execute"}});n.notebook=JSON.parse(r)}catch{}const r=n.run.traceId,i=n.rootSpanId;for(;n.cursor<n.order.length;){if(n.cancelled)return;if(n.paused)return;const s=n.order[n.cursor];n.run.currentNodeId=s;const o=n.spec.graph.nodes.find(e=>e.id===s),a=n.run.steps.find(e=>e.stepId===s);if(!o||!a){n.cursor++;continue}if(o.disabled){a.status="SKIPPED",n.cursor++;continue}const c=o.data?.breakpoint;if(c&&"PAUSED"!==n.run.status)return n.paused=!0,n.run.status="PAUSED",Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const l=this.prepareNodeExecutionConfig(o,n),u=l.retry,d=u?.maxAttempts??0,p=u?.retryOnTimeout??!1,h=l.timeoutMs;let f=a.attempt??0;for(;f<=d;){f++,a.attempt=f,"PENDING"!==a.status&&"RETRYING"!==a.status&&"WAITING_APPROVAL"!==a.status&&(a.status="PENDING"),a.status="RUNNING",a.startedAtMs=xm(),a.endedAtMs=void 0,a.error=void 0;const c=punica.kernel.Events.manager.createCorrelationId(),u=punica.kernel.Events.manager.createCorrelationId();a.attemptCorrelationId=c,a.spanId=u,this.pendingToRunStep.set(c,{runId:e,stepId:a.stepId}),Lm("workflow.stepStarted",e,"info",{runId:e,step:{stepId:a.stepId,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,status:"RUNNING",startedAtMs:a.startedAtMs,cellId:a.cellId,attemptCorrelationId:c,spanId:u,inputsPreview:a.inputsPreview}},{traceId:r,spanId:u,parentSpanId:i}),eg({name:"flow.node.started",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,attemptCorrelationId:c,spanId:u}});try{const s=await this.executeNodeAttempt(o,a,l,{attemptCorrelationId:c,spanId:u,rootSpanId:i,traceId:r,workspaceId:t?.workspaceId,filePathOrUri:n.filePathOrUri,notebook:n.notebook,timeoutMs:h,nodeOutputs:n.nodeOutputs,runBudget:n.spec.graph.runBudget,runInput:n.input,resolvedInput:mg(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),Lm("workflow.stepFinished",e,"result",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"SUCCESS",endedAtMs:a.endedAtMs,outputsPreview:a.outputsPreview,artifactIds:a.artifactIds}},{traceId:r,spanId:u,parentSpanId:i}),eg({name:"flow.node.completed",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,attempt:a.attempt,endedAtMs:a.endedAtMs,attemptCorrelationId:c,spanId:u}}),n.cursor++,await this.persistRun(e),await this.persistCheckpoint(e),await this.persistIndex();break}catch(t){const o=String(t?.message??t);if(o.includes("Approval required"))return a.status="WAITING_APPROVAL",Lm("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const h=o.includes("Timed out")||o.includes("timeout");if(!(f<=d&&(p||!h)&&!o.includes("Policy")&&!o.includes("Invalid input"))||f>d)return"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="FAILED",a.endedAtMs=xm(),a.error={message:o},Lm("workflow.stepFinished",e,"error",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"FAILED",endedAtMs:a.endedAtMs,error:{message:o},artifactIds:a.artifactIds??[]}},{traceId:r,spanId:u,parentSpanId:i}),eg({name:"flow.node.failed",kind:"error",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,attempt:a.attempt,endedAtMs:a.endedAtMs,attemptCorrelationId:c,spanId:u,error:{message:o}}}),n.run.status="FAILED",n.run.endedAtMs=xm(),n.run.error={message:o,nodeId:s,correlationId:c},Lm("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),Lm("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),eg({name:"flow.run.failed",kind:"error",correlationId:e,traceId:r,payload:{runId:e,endedAtMs:n.run.endedAtMs,error:n.run.error}}),await this.persistRun(e),await this.persistIndex(),void this.notifyTerminal?.(e,"FAILED");const m=ag(f,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Lm("workflow.stepRetry",e,"info",{runId:e,stepId:a.stepId,attempt:f,maxAttempts:d,delayMs:m,error:o},{traceId:r,spanId:u,parentSpanId:i}),await new Promise(e=>setTimeout(e,m))}}}"RUNNING"!==n.run.status&&"PAUSED"!==n.run.status&&console.warn(`[FlowEngine] Invalid state transition to COMPLETED from ${n.run.status}`),n.run.status="COMPLETED",n.run.endedAtMs=xm(),Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),Lm("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),eg({name:"flow.run.completed",correlationId:e,traceId:r,payload:{runId:e,endedAtMs:n.run.endedAtMs}}),await this.persistRun(e),await this.persistCheckpoint(e),await this.persistIndex(),await async function(e,t,n=".punica"){const r=Gm(n,"workflow-runs",e.runId),i=Gm(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await Jm("writeRunHistory",r),await Ym("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=Gm(t,"workflow-runs",e,"checkpoint.json");try{await Zm("deleteCheckpoint",n)}catch{}}(e);const s=this.runIdToSession.get(e);if(s){try{await s.close()}catch(t){console.warn(`[FlowEngine] Error closing session for run ${e}:`,t)}this.runIdToSession.delete(e)}this.notifyTerminal?.(e,"COMPLETED")}async executeParallel(e,t,n,r){const i=r.run.traceId,s=r.rootSpanId,o=r.maxInFlight??1/0,a=!!(c=r.spec.graph.runBudget)&&!0===c.failFast;for(var c;!Um(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=zm(n,c>0?c:void 0);if(0===l.length){if(0===(r.inFlightNodes?.size??0))break;await new Promise(e=>setTimeout(e,100));continue}const u=l.map(async o=>{Km(o,n),r.inFlightNodes?.add(o),r.run.currentNodeId=o;const c=r.spec.graph.nodes.find(e=>e.id===o),l=r.run.steps.find(e=>e.stepId===o);if(!c||!l)return r.inFlightNodes?.delete(o),void Wm(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Wm(o,!0,n);try{const a=this.prepareNodeExecutionConfig(c,r),u=a.retry,d=u?.maxAttempts??0,p=a.timeoutMs;let h=l.attempt??0,f=!1;for(;h<=d&&!f;){yg(r),h++,l.attempt=h,l.status="RUNNING",l.startedAtMs=xm();const e=punica.kernel.Events.manager.createCorrelationId(),n=punica.kernel.Events.manager.createCorrelationId();l.attemptCorrelationId=e,l.spanId=n;try{const o=await this.executeNodeAttempt(c,l,a,{attemptCorrelationId:e,spanId:n,rootSpanId:s,traceId:i,workspaceId:t?.workspaceId,filePathOrUri:r.filePathOrUri,notebook:r.notebook,timeoutMs:p,nodeOutputs:r.nodeOutputs,runBudget:r.spec.graph.runBudget,runInput:r.input,resolvedInput:mg(c,r.spec.graph.edges,r.nodeOutputs??new Map)});void 0!==o.output&&r.nodeOutputs&&r.nodeOutputs.set(c.id,o.output),f=!0}catch(e){if(e instanceof gg)throw l.status="CANCELLED",l.endedAtMs=xm(),e;const t=String(e?.message??e);if(h<=d){const e=ag(h,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=xm(),l.error={message:t},e}}f&&(Wm(o,!0,n),await this.persistRun(e))}catch(t){Wm(o,!1,n),t instanceof gg||(r.run.status="FAILED",r.run.endedAtMs=xm(),r.run.error={message:String(t?.message??t),nodeId:o},a&&(r.cancelled=!0),await this.persistRun(e))}finally{r.inFlightNodes?.delete(o)}});await Promise.allSettled(u)}"RUNNING"===r.run.status?(r.run.status="COMPLETED",r.run.endedAtMs=xm(),Lm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),Lm("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),eg({name:"flow.run.completed",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs}}),await this.persistRun(e),await this.persistIndex(),this.notifyTerminal?.(e,"COMPLETED")):"FAILED"===r.run.status&&(eg({name:"flow.run.failed",kind:"error",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs,error:r.run.error}}),this.notifyTerminal?.(e,"FAILED"))}prepareNodeExecutionConfig(e,t){const n=cg.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:rg,retry:{...ig},requireIdempotencyKeyForWriteRetry:!1};return e&&(void 0!==e.timeoutMs&&(n.timeoutMs=e.timeoutMs),e.retry&&(n.retry={...n.retry,...e.retry}),e.rateLimit&&(n.rateLimit={...e.rateLimit}),e.concurrency&&(n.concurrency={...e.concurrency}),void 0!==e.requireIdempotencyKeyForWriteRetry&&(n.requireIdempotencyKeyForWriteRetry=e.requireIdempotencyKeyForWriteRetry)),t&&(void 0!==t.timeoutMs&&(n.timeoutMs=t.timeoutMs),t.retry&&(n.retry={...n.retry,...t.retry}),t.rateLimit&&(n.rateLimit={...t.rateLimit}),t.concurrency&&(n.concurrency={...t.concurrency})),n}(r,e.executionOverride,t.spec.graph.runBudget)}async executeNodeAttempt(e,t,n,r){const i=cg.get(e.ref.kind);let s;try{s=await(i?.acquireResources?.(e,n,{workspaceId:r.workspaceId}))}catch(e){throw new Error(`Concurrency limit reached: ${e?.message??String(e)}`)}try{const n=this.executeNode(e,r),i=r.timeoutMs?await async function(e,t){return Promise.race([e,og(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=xm(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return cg.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class wg extends Error{code="SUBFLOW_DEPTH_EXCEEDED";parentDepth;cap;constructor(e,t=8){super(`Subflow depth ${e+1} exceeds substrate cap (${t}). Substrate refuses to spawn deeper subflows — restructure the flow or reduce nesting before retrying.`),this.name="SubflowDepthExceededError",this.parentDepth=e,this.cap=t}}function vg(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new wg(e??0,t);return n}const kg="__default__";class Ig{workspaceId;#sn=new Map;#on=new Map;#an=new Map;#cn=new qm;#ke=!1;#ln=new Map;#un;#dn;#pn;constructor(e=kg){this.workspaceId=e,this.#un=new tg(this.#sn,this.#ln,this.#cn),this.#dn=new ng(this.#sn,this.#on,this.#an,e=>this.#un.persistRun(e),()=>this.#un.persistIndex(),e=>this.#hn(e)),this.#pn=new bg(this.#sn,this.#an,this.#ln,this.#cn,e=>this.#un.persistRun(e),e=>this.#un.persistCheckpoint(e),()=>this.#un.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#ke||(this.#ke=!0,this.#dn.setupApprovalSubscription(),this.#un.loadIndex())}async startRun(e){const t=await this.#un.startRun(e);return this.#hn(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#un.pauseRun(e)}async resumeRun(e){const t=await this.#un.resumeRun(e);return t&&this.#hn(e,{}),t}async cancelRun(e,t){return this.#un.cancelRun(e,t)}getRun(e){return this.#un.getRun(e)}listRuns(e){return this.#un.listRuns(e)}approvePending(e){return this.#dn.approvePending(e)}rejectPending(e){return this.#dn.rejectPending(e)}hasRun(e){return this.#sn.has(e)}getNodeOutput(e,t){const n=this.#sn.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=vg(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#un.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;eg({name:"flow.subflow.spawned",correlationId:n,traceId:e.parentTraceId,payload:{runId:n,depth:t,parentRunId:e.parentRunId,parentTraceId:e.parentTraceId,workspaceId:this.workspaceId,flowId:e.spec.id}});const r=new Promise(e=>{const t=this.#fn.get(n);if(t)return this.#fn.delete(n),void e(t);this.#mn.set(n,e)});this.#hn(n,{workspaceId:this.workspaceId});const i=await r,s=this.getRun(n),o=this.getNodeOutput(n,"flow-output");return{runId:n,parentRunId:e.parentRunId,depth:t,status:i,output:o,startedAtMs:s?.startedAtMs,endedAtMs:s?.endedAtMs,error:s?.error}}notifyTerminal(e,t){const n=this.#mn.get(e);if(n)return this.#mn.delete(e),void n(t);this.#fn.set(e,t)}#mn=new Map;#fn=new Map;hasPending(e){return this.#an.has(e)}async#hn(e,t){const n=this.#sn.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;const r=void 0!==n.dependencyGraph,i=n.dependencyGraph;r&&i?await this.#pn.executeParallel(e,t,i,n):await this.#pn.executeSequential(e,t)}}const Eg=new Map,Ag=new Map,Sg=new Map;function _g(e){const t=e??kg;let n=Eg.get(t);return n||(n=new Ig(t),Eg.set(t,n)),n}let xg=!1;const Cg=new class{initialize(){if(xg)return;xg=!0;const e=punica.kernel.Commands.manager;e.registerCommand(We.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(We.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(We.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(We.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(We.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(We.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(We.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(We.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(We.RUN_SUBFLOW,{title:"Workflow: Run Subflow",execute:e=>this.runSubflow(e)})}async startRun(e){const t=function(e){const t=e?.workspaceId;return"string"==typeof t&&t.length>0?t:kg}(e),n=_g(t);n.initialize();const r=await n.startRun(e);return Ag.set(r.runId,t),r}async pauseRun(e){const t=this.#gn(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#gn(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#gn(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#gn(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#gn(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of Eg.values())t.push(...n.listRuns({status:e?.status}));return"number"==typeof e?.limit&&e.limit>0?t.slice(0,e.limit):t}approvePending(e){const t=this.#yn(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#yn(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(vg(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=_g(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Ag.set(n.runId,t.workspaceId),n}#gn(e){const t=Ag.get(e);if(t)return Eg.get(t);for(const[t,n]of Eg.entries())if(n.hasRun(e))return Ag.set(e,t),n}#yn(e){const t=Sg.get(e);if(t)return Eg.get(t);for(const[t,n]of Eg.entries())if(n.hasPending(e))return Sg.set(e,t),n}};function Tg(e){const t=e?.capability??{},n=t.outputs&&"object"==typeof t.outputs?t.outputs:{schema:{type:"object",properties:{}}};return{apiVersion:"ivy.workflow/v0.1",kind:"Workflow",id:t.id??e?.id,version:t.version??"0.0.0",title:t.title??"agent",description:t.description??"",tags:t.tags??[],inputs:t.inputs??{schema:{type:"object",properties:{}}},outputs:{...n,kind:n.kind??"direct"},policy:t.policy??{risk:"low",approval:"none"},graph:e?.graph??{entryNodeId:"flow-input",nodes:[],edges:[]}}}function Ng(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class Mg{packages=new Map;async discover(){this.packages.clear();try{if(!await vo().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=$a();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[AgentRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return Dg(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[AgentRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n);if(!Ng(r))return void console.warn(`[AgentRegistry] Not an IvyAgent manifest: ${t}`);const i=r,s=i.capability;if(!s||"object"!=typeof s||!("id"in s))return void console.warn(`[AgentRegistry] Missing capability.id in ${t}`);const o=t.lastIndexOf("/"),a=o>=0?t.slice(0,o):"";this.packages.set(s.id,{packageRoot:a,manifestPath:t,manifest:i})}catch(e){console.warn(`[AgentRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}unregister(e){return this.packages.delete(e)}clear(){this.packages.clear()}}function Dg(e,t){for(const n of e)n.isDirectory?n.children&&Dg(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let Pg;function Og(){return Pg||(Pg=new Mg),Pg}const Rg=new Set(["COMPLETED","FAILED","CANCELLED"]);function Lg(e){return new Promise(t=>setTimeout(t,e))}async function $g(e,t,n){const r=Date.now()+n;let i=e.getRun(t);for(;Date.now()<r;){i=e.getRun(t);const n=i?.status;if(n&&(Rg.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await Lg(250)}return{record:i,timedOut:!0}}async function jg(e,t,n,r,i){const s=Date.now(),o=(e,t)=>({caseId:n.id,status:e.status,durationMs:Date.now()-s,...void 0!==t?{output:t}:{},...void 0!==e.error?{error:e.error}:{},...e.assertions?{assertions:e.assertions}:{}});let a;try{const r=await e.startRun({spec:t,workspaceId:i,input:n.input});if(a=r?.runId,!a)throw new Error("Engine did not return a runId")}catch(e){const t=e instanceof Error?e.message:String(e);return o(Sm(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await $g(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(Sm(n,`Run did not complete in ${r}ms (status ${c?.status??"unknown"})`,{infrastructure:!0}))}const u=c?.status;if("WAITING_APPROVAL"===u){try{await e.cancelRun(a)}catch{}return o(Sm(n,"Run requires approval — not auto-approved in a test run",{infrastructure:!0}))}if("COMPLETED"===u){let t;try{t=e.getNodeOutput(a,"flow-output")}catch{t=void 0}return o(Am(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(Sm(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const Fg={validator:{validate:cm},registry:{discover:()=>hm().discover(),get:e=>hm().get(e),list:()=>hm().list(),search:e=>hm().search(e),setTestReport:(e,t)=>hm().setTestReport(e,t),getLatestTestReport:e=>hm().getLatestTestReport(e)},runner:{run:wm},test:{run:async function(e,t){const n=hm(),r=n.get(e);if(!r){if(t?.manifest){if(Ng(t.manifest))return async function(e,t){const n=e,r=String(n?.capability?.id??n?.id??"");if(!r)throw new Error("Agent manifest has no capability id — cannot run tests.");const i=n?.tests;if(!i||!Array.isArray(i.cases)||!i.cases.length)throw new Error(`No test specification found for agent: ${r}`);const s=Cg,o=Tg(n),a=Date.now(),c=[];for(const e of i.cases){if(e.skip){c.push({caseId:e.id,status:"skip",durationMs:0,error:"string"==typeof e.skip?e.skip:void 0});continue}const n=e.timeoutMs??i.timeoutMs??3e4;c.push(await jg(s,o,e,n,t?.workspaceId))}const l=_m({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{hm().setTestReport(r,l)}catch{}return l}(t.manifest);throw new Error(`Manifest for ${e} is not a testable IvyAgent (expected kind 'IvyAgent' with a graph).`)}throw new Error(`IvyNode not found: ${e}`)}const i=r.manifest,s=i.tests;if(!s)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of s.cases||[]){if(t.skip){a.push({caseId:t.id,status:"skip",durationMs:0,error:"string"==typeof t.skip?t.skip:void 0});continue}const n=Date.now();let r;try{const i=await wm(e,{input:t.input,runId:`test-${e}-${t.id}-${Date.now()}`,timeoutMs:s.timeoutMs||3e4}),o=i.events.filter(e=>"error"===e.type).map(e=>{const t=e.data;return t?.message||""}).join(" "),a=Am(t,i.output,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:i.output,assertions:a.assertions}}catch(e){const i=Sm(t,e instanceof Error?e.message:String(e));r={caseId:t.id,status:"error"===i.status?"fail":i.status,durationMs:Date.now()-n,error:i.error,assertions:i.assertions}}a.push(r)}const c=i.capability,l=_m({capabilityId:e,version:c&&"object"==typeof c&&"version"in c?String(c.version||"0.0.0"):"0.0.0",tier:s.tier,results:a,startedAtMs:o});return n.setTestReport(e,l),l}}},Bg={discover:()=>Og().discover(),get:e=>Og().get(e),list:()=>Og().list(),search:e=>Og().search(e),unregister:e=>Og().unregister(e),run:(e,t)=>async function(e,t){const n=Og().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??Cg,i=t?.timeoutMs??3e4,s=Tg(n.manifest),o=Date.now(),a=await r.startRun({spec:s,workspaceId:t?.workspaceId,input:t?.input??{}}),c=a?.runId;if(!c)throw new Error(`Engine did not return a runId for agent ${e}`);const{record:l,timedOut:u}=await $g(r,c,i);if(u){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} did not complete in ${i}ms (status ${l?.status??"unknown"})`)}const d=l?.status;if("WAITING_APPROVAL"===d){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} requires approval — approve the workflow run or lower the capability's approval policy`)}if("COMPLETED"===d){let e;try{e=r.getNodeOutput(c,"flow-output")}catch{e=void 0}return{output:e,runId:c,durationMs:Date.now()-o}}const p=l?.steps?.find(e=>"FAILED"===e.status);throw new Error(`Agent ${e} failed: ${l?.error?.message??p?.error?.message??`Run ended with status ${d??"unknown"}`}`)}(e,t),envelope:Tg,isAgentManifest:Ng},qg=new Map([["QUEUED",["RUNNING","CANCELLED"]],["RUNNING",["WAITING_APPROVAL","PAUSED","RETRYING","COMPLETED","FAILED","CANCELLED"]],["WAITING_APPROVAL",["RUNNING","FAILED","CANCELLED"]],["PAUSED",["RUNNING","CANCELLED"]],["RETRYING",["RUNNING","FAILED","CANCELLED"]],["COMPLETED",[]],["FAILED",[]],["CANCELLED",[]]]),zg=new Set(["COMPLETED","FAILED","CANCELLED"]);const Ug=new class{canTransitionTo(e,t){if(e===t)return!1;const n=qg.get(e);return!!n&&n.includes(t)}assertTransition(e,t){if(!this.canTransitionTo(e,t))throw new Error(`[RunStatusStateMachine] invalid transition: ${e} → ${t} (valid next states: ${this.getValidTransitions(e).join(", ")||"∅ (terminal)"})`)}getValidTransitions(e){return qg.get(e)??[]}isTerminal(e){return zg.has(e)}},Vg=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Wg={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Kg={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function Gg(e){return{x:Kg.marginX+e%6*240,y:Kg.marginY+120*Math.floor(e/6)}}function Hg(e){const t=Math.max(0,e.inputCount??0),n=Math.max(0,e.outputCount??0),r=22*(t+n),i=t>0&&n>0?9:0;return 60+Math.max(56,16+r+i)}function Yg(e,t){const n={...Kg,...t??{}},r=e.nodes??[],i={};if(!r.length)return i;const s=new Map;r.forEach((e,t)=>s.set(e.id,t));const o=(e.edges??[]).filter(e=>e.source!==e.target&&s.has(e.source)&&s.has(e.target));if(1===r.length)return i[r[0].id]={x:n.marginX,y:n.marginY},i;const a=new Map,c=new Map;for(const e of r)a.set(e.id,[]),c.set(e.id,[]);for(const e of o)a.get(e.source).push(e.target),c.get(e.target).push(e.source);const l=new Map;for(const e of r)l.set(e.id,c.get(e.id).length);const u=r.filter(e=>0===l.get(e.id)).map(e=>e.id),d=[];for(;u.length;){const e=u.shift();d.push(e);for(const t of a.get(e)){const e=l.get(t)-1;l.set(t,e),0===e&&u.push(t)}}if(d.length<r.length)return r.forEach((e,t)=>{i[e.id]=Gg(t)}),i;const p=e=>a.get(e).length>0||c.get(e).length>0,h=r.filter(e=>!p(e.id)),f=r.filter(e=>p(e.id));if(!f.length)return r.forEach((e,t)=>{i[e.id]=Gg(t)}),i;const m=new Map;for(const e of d){if(!p(e))continue;const t=c.get(e),n=t.length?Math.max(...t.map(e=>m.get(e)??0))+1:0;m.set(e,n)}const g=Math.max(...Array.from(m.values())),y=Array.from({length:g+1},()=>[]);for(const e of f)y[m.get(e.id)].push(e.id);const b=new Map,w=(e,t)=>{const n=e.map((e,n)=>{const r=t(e).filter(e=>b.has(e));return{id:e,i:n,score:r.length?r.reduce((e,t)=>e+b.get(t),0)/r.length:n}});return n.sort((e,t)=>e.score-t.score||e.i-t.i),n.map(e=>e.id)},v=e=>e.forEach((e,t)=>b.set(e,t));y.forEach(v);for(let e=1;e<y.length;e++)y[e]=w(y[e],e=>c.get(e)),v(y[e]);for(let e=y.length-2;e>=0;e--)y[e]=w(y[e],e=>a.get(e)),v(y[e]);const k=new Map;for(const e of r)k.set(e.id,Hg(e));const I=e=>e.reduce((e,t)=>e+k.get(t),0)+Math.max(0,e.length-1)*n.verticalGap,E=Math.max(...y.map(I)),A=n.marginY+E/2;y.forEach((e,t)=>{const r=n.marginX+t*(n.cardWidth+n.horizontalGap);let s=A-I(e)/2;for(const t of e)i[t]={x:r,y:s},s+=k.get(t)+n.verticalGap});const S=n.marginY+E+2*n.verticalGap;return h.forEach((e,t)=>{i[e.id]={x:n.marginX+t*(n.cardWidth+n.horizontalGap/2),y:S}}),i}let Jg;function Zg(e){if(!Jg)throw new Error(`[flow.shell] ${e}: no FlowRendererProvider injected — substrate refuses to ship a DOM implementation (D1). Hosts must call punica.flow.shell.setRendererProvider(...) before invoking the renderer.`);return Jg}function Qg(e){if(!e)throw new Error("flow.shell.setRendererProvider: provider must not be null");if("function"!=typeof e.createRenderer)throw new Error("flow.shell.setRendererProvider: provider must implement createRenderer");if("function"!=typeof e.createViewportController)throw new Error("flow.shell.setRendererProvider: provider must implement createViewportController");if("function"!=typeof e.attachZoomControl)throw new Error("flow.shell.setRendererProvider: provider must implement attachZoomControl");if("function"!=typeof e.attachMinimap)throw new Error("flow.shell.setRendererProvider: provider must implement attachMinimap");Jg=e}function Xg(){Jg=void 0}function ey(){return Jg}function ty(e){return Zg("createFlowRenderer").createRenderer(e)}function ny(e){return Zg("createViewportController").createViewportController(e)}function ry(e,t){return Zg("attachZoomControl").attachZoomControl(e,t)}function iy(e,t){return Zg("attachMinimap").attachMinimap(e,t)}function sy(e,t){const n={...e,metadata:{...e.metadata??{}}},r=n.metadata,i=r.ivy=r.ivy?{...r.ivy}:{},s=i.view??{},o={x:t.viewport?.x??s.viewport?.x??0,y:t.viewport?.y??s.viewport?.y??0,zoom:t.viewport?.zoom??s.viewport?.zoom??1},a={...s.nodes??{}};return t.nodes.forEach(e=>{e&&e.id&&(a[e.id]={x:e.x,y:e.y})}),i.view={...s,viewport:o,nodes:a},n}var oy={setRendererProvider:Qg,resetRendererProvider:Xg,getRendererProvider:ey,createFlowRenderer:ty,createViewportController:ny,attachZoomControl:ry,attachMinimap:iy,mergeViewSnapshotIntoNotebook:sy,computeFlowLayout:Yg,gridFallbackPosition:Gg,get rendererProvider(){return Jg}},ay=Object.freeze({__proto__:null,attachMinimap:iy,attachZoomControl:ry,computeFlowLayout:Yg,createFlowRenderer:ty,createViewportController:ny,default:oy,getRendererProvider:ey,gridFallbackPosition:Gg,mergeViewSnapshotIntoNotebook:sy,resetRendererProvider:Xg,setRendererProvider:Qg});function cy(e,t,n){return{path:e,message:t,severity:"error",code:n}}function ly(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const uy="WF_INVALID_VERSION",dy="WF_INVALID_EDGE_REF",py=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function hy(e){return"string"==typeof e&&py.test(e)}const fy=new class{#bn=new Map;register(e,t){if("string"!=typeof e||0===e.length)throw new Error("LambdaRegistry.register: id must be a non-empty string");if("function"!=typeof t)throw new Error("LambdaRegistry.register: fn must be a function");this.#bn.set(e,t)}unregister(e){return this.#bn.delete(e)}get(e){return this.#bn.get(e)}list(){return Array.from(this.#bn.keys())}clear(){this.#bn.clear()}},my={id:"capability-not-declared",severity:"error",check(e,t){const n=t.hasCapability??(e=>!!t.getCapability?.(e));if(!t.hasCapability&&!t.getCapability)return[];const r=[];for(let t=0;t<e.graph.nodes.length;t++){const i=e.graph.nodes[t];if(i.disabled)continue;const s=i.ref;if("ivyNode"!==s.kind&&"workflow"!==s.kind)continue;const o=s.id;"string"==typeof o&&0!==o.length&&(n(o)||r.push({ruleId:"capability-not-declared",severity:"error",message:`Capability "${o}" is not declared in the unified registry — flow refs must exist in at least one origin (extension / instruction-class / ivy-node)`,path:`graph.nodes[${t}].ref.id`,nodeId:i.id,code:"WF_UNKNOWN_CAPABILITY"}))}return r}},gy={id:"unreachable-node",severity:"warning",check(e){const t=[],n=e.graph.nodes.filter(e=>!e.disabled),r=new Set(n.map(e=>e.id)),i=e.graph.entryNodeId;if(!i||!r.has(i))return t;const s=new Map;for(const e of r)s.set(e,[]);for(const t of e.graph.edges)r.has(t.fromId)&&r.has(t.toId)&&s.get(t.fromId).push(t.toId);const o=new Set([i]),a=[i];for(;a.length>0;){const e=a.shift();for(const t of s.get(e)??[])o.has(t)||(o.add(t),a.push(t))}for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];r.disabled||(o.has(r.id)||t.push({ruleId:"unreachable-node",severity:"warning",message:`Node "${r.id}" is unreachable from entry node "${i}"`,path:`graph.nodes[${n}].id`,nodeId:r.id,code:"WF_UNREACHABLE_NODE"}))}return t}},yy={id:"dep-cycle",severity:"error",check(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=new Map,i=new Map;for(const e of t)r.set(e.id,0),i.set(e.id,[]);for(const t of e.graph.edges)n.has(t.fromId)&&n.has(t.toId)&&(i.get(t.fromId).push(t.toId),r.set(t.toId,(r.get(t.toId)??0)+1));const s=[];for(const[e,t]of r.entries())0===t&&s.push(e);let o=0;const a=new Set;for(;s.length>0;){const e=s.shift();a.add(e),o++;for(const t of i.get(e)??[])r.set(t,(r.get(t)??0)-1),0===(r.get(t)??0)&&s.push(t)}if(o===t.length)return[];const c=[],l=[];for(const e of t)a.has(e.id)||l.push(e.id);return c.push({ruleId:"dep-cycle",severity:"error",message:`Workflow graph contains a cycle among enabled nodes: ${l.join(", ")}`,path:"graph.edges",code:"WF_CYCLE"}),c}},by={id:"idempotency-required-but-no-key",severity:"error",check(e,t){if(!t.getCapability)return[];const n=[];for(let r=0;r<e.graph.nodes.length;r++){const i=e.graph.nodes[r];if(i.disabled)continue;if("ivyNode"!==i.ref.kind)continue;const s=i.ref.id;if("string"!=typeof s||0===s.length)continue;const o=t.getCapability(s);if(!o)continue;const a=o.defaults;if(!("required"===a?.execution?.idempotency))continue;const c=i.executionOverride;("none"===c?.idempotency||!0===i.data?.skipIdempotencyKey)&&n.push({ruleId:"idempotency-required-but-no-key",severity:"error",message:`Capability "${s}" declares idempotency: 'required' but node "${i.id}" opts out of key derivation — write/retry semantics will double-execute on a network retry`,path:`graph.nodes[${r}]`,nodeId:i.id,code:"WF_IDEMPOTENCY_REQUIRED"})}return n}};function wy(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function vy(e,t){if(!e)return;if(!t)return e;const n=t.split(".").filter(e=>e.length>0);let r=e;for(const e of n){if(!r||"object"!=typeof r)return;r=r.properties?.[e]}return r}const ky={id:"schema-mismatch",severity:"warning",check(e,t){if(!t.getCapability)return[];const n=[],r=new Map(e.graph.nodes.map(e=>[e.id,e]));for(let i=0;i<e.graph.edges.length;i++){const s=e.graph.edges[i],o=r.get(s.fromId),a=r.get(s.toId);if(!o||!a)continue;if(o.disabled||a.disabled)continue;const c=wy(o.ref),l=wy(a.ref);if(!c||!l)continue;const u=t.getCapability(c),d=t.getCapability(l);if(!u||!d)continue;const p=u.outputs?.schema,h=d.inputs?.schema;if(!p||!h)continue;const f=vy(p,s.fromPath),m=vy(h,s.toPath);f&&m&&(f.type&&m.type&&f.type!==m.type&&n.push({ruleId:"schema-mismatch",severity:"warning",message:`Edge ${s.fromId} → ${s.toId} type mismatch: upstream emits "${f.type}" but downstream expects "${m.type}"`,path:`graph.edges[${i}]`,code:"WF_SCHEMA_MISMATCH"}))}return n}},Iy=["while","forEach"],Ey={id:"infinite-loop",severity:"error",check(e){const t=[];for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];if(r.disabled)continue;if("primitive"!==r.ref.kind)continue;const i=r.ref.primitive;if(!Iy.includes(i))continue;const s=r.data,o=s?.maxIterations;"number"==typeof o?o<=0&&t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" has maxIterations=${o} — loops with zero or negative caps never execute the body`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"}):t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" is missing maxIterations — substrate refuses to ship unbounded loops`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"})}return t}};function Ay(e,t,n){let r=0;for(const i of e.graph.nodes){if(i.disabled)continue;if("workflow"!==i.ref.kind)continue;const e=i.ref,s=e.id??"<unnamed>";if(n.has(s))return t+1;if(!e.inline)continue;const o=new Set(n);o.add(s);const a=1+Ay(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const Sy={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Ay(e,n,new Set([i]));return s<=n||r.push({ruleId:"subflow-depth-exceeded",severity:"error",message:`Flow "${i}" has a statically-derivable inline subflow chain of depth ${s} — exceeds cap (${n}). Direct cycles count as depth > cap.`,path:"graph",code:"WF_SUBFLOW_DEPTH_EXCEEDED"}),r}},_y=[my,gy,yy,by,ky,Ey,Sy];const xy=new class{#gt=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#gt.values())try{const i=t.check(e,r);i&&i.length>0&&n.push(...i)}catch(e){n.push({ruleId:t.id,severity:"info",message:`Lint rule "${t.id}" threw during analysis: ${String(e?.message??e)}`,code:"WF_LINT_RULE_ERROR"})}return{ok:!n.some(e=>"error"===e.severity),issues:n}}register(e){if(!e||"function"!=typeof e.check)throw new Error("FlowLinter.register: rule must have a check(spec, ctx) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("FlowLinter.register: rule.id must be a non-empty string");this.#gt.set(e.id,e)}unregister(e){return this.#gt.delete(e)}list(){return Array.from(this.#gt.keys())}reset(){this.#gt.clear();for(const e of _y)this.#gt.set(e.id,e)}};function Cy(e,t,n){if(t===n)return[];const r=new Map;for(const t of e.values()){const e=r.get(t.from)??[];e.push(t),r.set(t.from,e)}const i=new Set([t]),s=new Map,o=[t];for(;o.length>0;){const e=o.shift();if(e===n)break;for(const t of r.get(e)??[])if(!i.has(t.to)){if(i.add(t.to),s.set(t.to,t),t.to===n){o.length=0;break}o.push(t.to)}}if(!i.has(n))return;const a=[];let c=n;for(;c!==t;){const e=s.get(c);if(!e)return;a.unshift(e),c=e.from}return a}function Ty(e){return e.map(e=>`${e.from}=>${e.to}`)}function Ny(e,t){return`${e}=>${t}`}const My=new class{#wn=new Map;register(e){if(!e||"function"!=typeof e.transform)throw new Error("MigrationRegistry.register: transformer must have a transform(doc) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("MigrationRegistry.register: transformer.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("MigrationRegistry.register: transformer.to must be a non-empty string");if(e.from===e.to)throw new Error("MigrationRegistry.register: transformer.from must differ from transformer.to (no self-edges)");this.#wn.set(Ny(e.from,e.to),e)}unregister(e,t){return this.#wn.delete(Ny(e,t))}find(e,t){return this.#wn.get(Ny(e,t))}list(){return Array.from(this.#wn.values())}clear(){this.#wn.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,i=e.targetVersion;if(!hy(r))return{ok:!1,reason:"invalid-result",message:`WorkflowDocument.version "${String(r)}" is not a valid semver — substrate refuses to migrate from an unrecognized version.`,appliedTransformers:[]};if(!hy(i))return{ok:!1,reason:"invalid-result",message:`targetVersion "${String(i)}" is not a valid semver — substrate refuses to migrate to an unrecognized version.`,appliedTransformers:[]};if(r===i)return{ok:!0,document:e.document,appliedTransformers:[],fromVersion:r,toVersion:i};if("reject"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'reject'. Re-invoke with 'auto-migrate' to apply registered transformers.`,appliedTransformers:[]};if("warn"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'warn'. Substrate did not migrate; downstream consumers may see a stale IR.`,partialDocument:e.document,appliedTransformers:[]};const s=("function"==typeof t.__plan?t.__plan.bind(t):(e,n)=>Cy(new Map(t.list().map(e=>[`${e.from}=>${e.to}`,e])),e,n))(r,i);if(!s||0===s.length)return{ok:!1,reason:"no-path",message:`No transformer chain from ${r} to ${i}. Register transformers via punica.flow.primitives.migrations.register(...).`,appliedTransformers:[]};let o=e.document;const a=[];for(const e of s)try{const t=e.transform(o);if(!t||"object"!=typeof t)return{ok:!1,reason:"invalid-result",message:`Transformer ${e.from}=>${e.to} returned a non-object — substrate refuses to thread an invalid document through the chain.`,partialDocument:o,appliedTransformers:Ty(a)};if(t.version!==e.to)return{ok:!1,reason:"invalid-result",message:`Transformer ${e.from}=>${e.to} produced a document with version "${String(t.version)}" — substrate enforces version-stamping on the output.`,partialDocument:o,appliedTransformers:Ty(a)};o=t,a.push(e)}catch(t){return{ok:!1,reason:"transformer-threw",message:`Transformer ${e.from}=>${e.to} threw during migration: ${String(t?.message??t)}`,partialDocument:o,appliedTransformers:Ty(a)}}return{ok:!0,document:o,appliedTransformers:Ty(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Cy(this.#wn,e,t)}};function Dy(){return Date.now()}class Py{#je=new Map;#Ot=new Set;register(e,t){if(!e||"string"!=typeof e.id||0===e.id.length)throw new Error("ManualTriggerProvider.register: trigger.id must be a non-empty string");if("string"!=typeof e.kind||0===e.kind.length)throw new Error("ManualTriggerProvider.register: trigger.kind must be a non-empty string");if("string"!=typeof e.flowId||0===e.flowId.length)throw new Error("ManualTriggerProvider.register: trigger.flowId must be a non-empty string");if("function"!=typeof t)throw new Error("ManualTriggerProvider.register: callback must be a function");const n={trigger:e,callback:t,unsubscribed:!1};return this.#je.set(e.id,n),this.#vn({type:"registered",triggerId:e.id,kind:e.kind,ts:Dy()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#je.get(e.id)===n&&(this.#je.delete(e.id),this.#vn({type:"unregistered",triggerId:e.id,ts:Dy()}))}}}unregister(e){const t=this.#je.get(e);return!!t&&(t.unsubscribed=!0,this.#je.delete(e),this.#vn({type:"unregistered",triggerId:e,ts:Dy()}),!0)}list(){return Array.from(this.#je.values()).map(e=>e.trigger)}subscribe(e){return this.#Ot.add(e),()=>{this.#Ot.delete(e)}}async fire(e,t){const n=this.#je.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Dy()}-${Math.floor(1e6*Math.random())}`,i=Dy();this.#vn({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),eg({name:"flow.trigger.fired",source:"flow:triggers",correlationId:r,payload:{triggerId:e,kind:n.trigger.kind,flowId:n.trigger.flowId,firedAtMs:i,payload:t??null}});try{return await n.callback({triggerId:e,firedAtMs:i,payload:t,correlationId:r}),!0}catch(t){return this.#vn({type:"error",triggerId:e,ts:Dy(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#je.values())e.unsubscribed=!0;this.#je.clear(),this.#Ot.clear()}#vn(e){for(const t of this.#Ot)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const Oy=new Py;let Ry=Oy;const Ly={get manager(){return Ry},setProvider(e){if(!e)throw new Error("triggers.setProvider: provider must not be null");if("function"!=typeof e.register)throw new Error("triggers.setProvider: provider must implement register()");if("function"!=typeof e.unregister)throw new Error("triggers.setProvider: provider must implement unregister()");if("function"!=typeof e.list)throw new Error("triggers.setProvider: provider must implement list()");if("function"!=typeof e.subscribe)throw new Error("triggers.setProvider: provider must implement subscribe()");Ry!==e&&Ry instanceof Py&&Ry.clear(),Ry=e},resetProvider(){Ry instanceof Py&&Ry.clear(),Ry=Oy}};function $y(e,t){return`${e}=>${t}`}const jy={migrators:new class{#kn=new Map;register(e){if(!e||"function"!=typeof e.migrate)throw new Error("CheckpointMigratorRegistry.register: migrator must have a migrate(checkpoint) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("CheckpointMigratorRegistry.register: migrator.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("CheckpointMigratorRegistry.register: migrator.to must be a non-empty string");if(e.from===e.to)throw new Error("CheckpointMigratorRegistry.register: migrator.from must differ from migrator.to");this.#kn.set($y(e.from,e.to),e)}unregister(e,t){return this.#kn.delete($y(e,t))}find(e,t){return this.#kn.get($y(e,t))}list(){return Array.from(this.#kn.values())}clear(){this.#kn.clear()}},isFresh:function(e,t,n=Date.now()){if("number"!=typeof e||Number.isNaN(e))return!1;if(!t||"number"!=typeof t.maxAgeMs)return!0;if(t.maxAgeMs<0)return!0;const r=n-e;return r>=0&&r<=t.maxAgeMs}},Fy={...Fg,agents:Bg,engine:{manager:Cg,statusStateMachine:Ug,subscribeNodeStatuses:function(e,t){const n=new Set(e.nodeIds);let r=null;const i=(e,i,s)=>{const o=String(e??"");if(!o||!n.has(o))return;const a=String(i??"").toUpperCase(),c=Wg[a];if(!c)return;const l=s?String(s):null,u=null!==l&&l!==r;u&&(r=l),t({nodeId:o,status:c,runId:l,isNewRun:u,stepStatus:a})},s=e=>{const t=e?.payload?.payload??e?.payload??{};switch(e?.name){case"workflow.stepStarted":return i(t?.step?.stepId,t?.step?.status??"RUNNING",t?.runId);case"workflow.stepUpdated":return i(t?.stepId,t?.patch?.status,t?.runId);case"workflow.stepFinished":return i(t?.step?.stepId,t?.step?.status,t?.runId);default:return}};let o=null;try{o=punica.kernel.Events.manager.subscribeMany(Vg,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:ay,validateWorkflowDocument:function(e,t){const n=[],r=[],i=t?.mode??"best-effort",s=t?.hasCapability;if(!e||"ivy.workflow/v0.1"!==e.apiVersion)return n.push(cy("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',uy)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(cy("kind",'kind must equal "Workflow"',uy)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!hy(o)){const e=cy("version","version must be a semver string (major.minor.patch[-prerelease][+build]); got "+("string"==typeof o?`"${o}"`:typeof o),"WF_INVALID_SEMVER");"strict"===i?n.push(e):r.push({...e,severity:"warning"})}if(!e.graph||"object"!=typeof e.graph)return n.push(cy("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(cy("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(cy("graph.edges","graph.edges must be an array")),{ok:!1,errors:n,warnings:r};const a=Array.isArray(e.graph.nodes)?e.graph.nodes:[],c=Array.isArray(e.graph.edges)?e.graph.edges:[],l=new Set;a.forEach((e,t)=>{const r=String(e?.id??"");if(r||n.push(cy(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(cy(`graph.nodes[${t}].id`,`id "${r}" must be unique`,"WF_DUPLICATE_ID")),l.add(r)),e.ref&&"object"==typeof e.ref){const r=e.ref;if(r.kind){const e=["flowInput","flowOutput","ivyNode","workflow","primitive"];if(e.includes(r.kind)||n.push(cy(`graph.nodes[${t}].ref.kind`,`ref.kind must be one of: ${e.join(", ")}`)),"ivyNode"!==r.kind&&"workflow"!==r.kind||"id"in r&&"string"==typeof r.id||n.push(cy(`graph.nodes[${t}].ref.id`,"ref.id is required for ivyNode/workflow refs")),"primitive"===r.kind){const e=["if","else","forEach","while","try","catch","finally","lambda"],i=r.primitive;"string"==typeof i&&e.includes(i)||n.push(cy(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(cy(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(cy(`graph.nodes[${t}].ref`,"ref is required"))});const u=a.some(e=>"flow-input"===e.id),d=a.some(e=>"flow-output"===e.id),p=c.some(e=>"flow-input"===e.fromId),h=c.some(e=>"flow-output"===e.toId);return p&&!u&&n.push(cy("graph.nodes","flow-input node is required when edges reference it")),h&&!d&&n.push(cy("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(cy("graph.entryNodeId",`entryNodeId "${e.graph.entryNodeId}" must reference an existing node`,"WF_INVALID_ENTRY")),c.forEach((e,t)=>{const r=String(e?.fromId??""),i=String(e?.toId??"");r||n.push(cy(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(cy(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(cy(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,dy)),i&&!l.has(i)&&n.push(cy(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,dy))}),"strict"===i&&function(e,t,n){const r=e.filter(e=>!e.disabled),i=new Set(r.map(e=>e.id)),s=t.filter(e=>i.has(e.fromId)&&i.has(e.toId)),o=new Map,a=new Map;for(const e of r)o.set(e.id,0),a.set(e.id,[]);for(const e of s)a.get(e.fromId).push(e.toId),o.set(e.toId,(o.get(e.toId)??0)+1);const c=[];for(const[e,t]of o.entries())0===t&&c.push(e);let l=0;for(;c.length;){const e=c.shift();l++;for(const t of a.get(e)??[])o.set(t,(o.get(t)??0)-1),0===(o.get(t)??0)&&c.push(t)}l!==r.length&&n.push(cy("edges","Workflow graph is not a DAG (cycle detected among enabled nodes).","WF_CYCLE"))}(a,c,n),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)&&function(e,t,n,r){const i=e.filter(e=>!e.disabled),s=new Set(i.map(e=>e.id));if(!s.has(n))return;const o=t.filter(e=>s.has(e.fromId)&&s.has(e.toId)),a=new Set,c=[n];for(a.add(n);c.length>0;){const e=c.shift();for(const t of o)t.fromId!==e||a.has(t.toId)||(a.add(t.toId),c.push(t.toId))}for(const t of i)if(!a.has(t.id)){const i=e.indexOf(t);r.push(ly(`graph.nodes[${i}].id`,`Node "${t.id}" is unreachable from entry node "${n}"`,"WF_UNREACHABLE_NODE"))}}(a,c,e.graph.entryNodeId,r),s&&a.forEach((e,t)=>{if(e.disabled)return;const o=e.ref;if(!o||"ivyNode"!==o.kind&&"workflow"!==o.kind)return;const a=o.id;if("string"!=typeof a||0===a.length)return;if(s(a))return;("strict"===i?n:r).push(("strict"===i?cy:ly)(`graph.nodes[${t}].ref.id`,`Capability "${a}" not found in the unified registry — flow references must exist in at least one origin (extension / instruction-class / ivy-node)`,"WF_UNKNOWN_CAPABILITY"))}),{ok:0===n.length,errors:n,warnings:r}},primitives:{lambdas:fy,linter:xy,migrations:My,checkpoints:jy},triggers:Ly};class By{name=qe.MANAGER;version="1.0.0";dependencies=[$e.COMMANDS,$e.EVENTS,je.WORKSPACE,Fe.LAYOUT];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.COMMANDS),s=r.getState($e.EVENTS),o=r.getState(je.WORKSPACE),a=r.getState(Fe.LAYOUT);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(a!==e.BOOTSTRAPPED)throw new Error("shell.layout must be bootstrapped before extensions.manager");if(!n.extensions?.manager)throw new Error("Extensions manager not available")}async start(e){}}class qy{name=Be.VALIDATOR;version="1.0.0";dependencies=[];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.kernel)throw new Error("Kernel not available");if(!t.flow?.validateWorkflowDocument)throw new Error("Flow validator not available")}async start(e){}}function zy(e){const t=e.data,n=t?.capabilityId;if(n)return String(n);const r=e.ref;return"ivyNode"===r?.kind&&null!=r.id?String(r.id):""}class Uy{prepareExecutionConfig(e){const t=zy(e);if(!t)return{};const n=Dm(),r=n?.getSpec?.(t);return{capabilityDefaults:Pm(r)}}async acquireResources(e,t,n){const r=zy(e);return async function(e,t){if(!e.concurrency)return()=>{};const n=function(e,t){let n=e;return n=n.replace(/\{workspaceId\}/g,t.workspaceId??""),n=n.replace(/\{capabilityId\}/g,t.capabilityId??""),n}(e.concurrency.key,t);return await sg.acquire(n,e.concurrency.max),()=>{sg.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=zy(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Mm();if(!o)throw new Error("[FlowEngine] Capability gateway not available");const a=function(e,t){return`${e.attemptCorrelationId}::${t}`}(t,e.id),c=await o.call(i,s,{sessionId:t.workspaceId??"default",workspaceId:t.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:t.traceId},trace:{traceId:t.traceId,parentSpanId:t.rootSpanId},policy:{mode:"execute"}},a),l=Dm(),u=l?.getSpec?.(i),d=u?.defaults?.dataClassification,p=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`${i}.result`,payload:c,meta:{source:"capability.call",capabilityId:i},redactionPolicy:e.redactionPolicy,surface:"output",capabilityClassification:d,sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Tm(Cm(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Vy(e){return e.data??{}}function Wy(e){return e.nodeOutputs??new Map}async function Ky(e,t,n,r,i){const s=await e.artifactStore.writeArtifact(t.traceId,n.id,{type:"json",name:`primitive.${r}.decision`,payload:i,meta:{source:"primitive",primitive:r},redactionPolicy:n.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Tm(Cm(i,0),320),artifactIds:[s.id]}}class Gy{async execute(e,t,n){const r=function(e){if("primitive"===e.ref.kind)return e.ref.primitive}(e);if(!r)throw new Error(`[PrimitiveExecutor] node "${e.id}" is not a primitive ref (ref.kind="${e.ref.kind}")`);switch(r){case"if":return async function(e,t,n){const r=Vy(e),i=ug(r.predicate,Wy(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:dg(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Ky(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Ky(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Vy(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:forEach] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:forEach] bodyFlowId is required on node "${e.id}"`);const i=ug(r.collection,Wy(t));if(!i.ok&&"missing-node"!==i.reason)throw new Error(`[primitive:forEach] collection did not resolve (${i.reason}) on node "${e.id}"`);const s=i.ok?i.value:null,o=Array.isArray(s)?s:[],a=o.length>r.maxIterations,c=Math.min(o.length,r.maxIterations),l={bodyFlowId:r.bodyFlowId,itemBinding:r.itemBinding??"item",maxIterations:r.maxIterations,plannedIterations:c,sourceLength:o.length,truncated:a};return{...await Ky(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Vy(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:while] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:while] bodyFlowId is required on node "${e.id}"`);const i=ug(r.predicate,Wy(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=dg(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Ky(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Vy(e);if(!r.tryBodyFlowId)throw new Error(`[primitive:try] tryBodyFlowId is required on node "${e.id}"`);const i={tryBodyFlowId:r.tryBodyFlowId,catchBodyFlowId:r.catchBodyFlowId??null,finallyBodyFlowId:r.finallyBodyFlowId??null};return{...await Ky(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Ky(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Ky(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Vy(e),i=r.lambdaId??"";if("string"!=typeof i||0===i.length)throw new Error(`[primitive:lambda] lambdaId is required on node "${e.id}"`);const s=fy.get(i);if(!s)throw new Error(`[primitive:lambda] lambdaId "${i}" is not registered (node "${e.id}")`);let o=null;if(void 0!==r.input){const n=ug(r.input,Wy(t));if(!n.ok)throw new Error(`[primitive:lambda] input did not resolve (${n.reason}) on node "${e.id}"`);o=n.value}const a=await s(o,{nodeId:e.id,attemptCorrelationId:t.attemptCorrelationId,traceId:t.traceId}),c=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`primitive.lambda.${i}.result`,payload:a,meta:{source:"primitive",primitive:"lambda",lambdaId:i},redactionPolicy:e.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Tm(Cm(a??{},0),320),artifactIds:[c.id],output:a}}(e,t,n);default:throw new Error(`[PrimitiveExecutor] unknown primitive kind: "${String(r)}" on node "${e.id}"`)}}}class Hy{async execute(e,t){return{output:t.runInput??null}}}class Yy{async execute(e,t){return{output:t.resolvedInput??null}}}let Jy=!1;class Zy{name=Be.ENGINE;version="1.0.0";dependencies=[$e.EVENTS,$e.POLICY,$e.COMMANDS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.EVENTS),s=r.getState($e.POLICY),o=r.getState($e.COMMANDS);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(Jy||(cg.register("ivyNode",new Uy),cg.register("primitive",new Gy),cg.register("flowInput",new Hy),cg.register("flowOutput",new Yy),Jy=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class Qy{name=Be.SHELL;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before shell.flow");if(!n.flow?.shell)throw new Error("Flow shell API not available")}async start(e){}}class Xy{name=$e.EVENTS;version="1.0.0";dependencies=[];#vt=e.CREATED;#l=null;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Events?.manager)throw new Error("Events manager not available");this.#l=t.kernel.Events.manager}async start(e){}get api(){return this.#l}}class eb{name=$e.COMMANDS;version="1.0.0";dependencies=[];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class tb{name=$e.POLICY;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.policy");if(!n.kernel?.Policy?.manager)throw new Error("Policy manager not available")}async start(e){}}class nb{name=$e.HISTORY;version="1.0.0";dependencies=[];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class rb{name=$e.TIME_SERVER;version="1.0.0";dependencies=[];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class ib{name=$e.TASKS;version="1.0.0";dependencies=[je.TERMINALS,je.WORKSPACE];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(je.TERMINALS),s=r.getState(je.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before kernel.tasks");if(!n.kernel?.Tasks)throw new Error("Tasks API not available")}async start(e){}}class sb{name=$e.NOTIFICATIONS;version="1.0.0";dependencies=[];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class ob{name=$e.AI;version="1.0.0";dependencies=[$e.EVENTS,$e.POLICY,$e.LLM];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.EVENTS),s=r.getState($e.POLICY),o=r.getState($e.LLM);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.llm must be bootstrapped before kernel.ai");if(!n.kernel?.AI?.manager?.initialize)throw new Error("AI manager not available");n.kernel.AI.manager.initialize()}async start(e){}}let ab=class{name=$e.LLM;version="1.0.0";dependencies=[$e.EVENTS,$e.POLICY];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.EVENTS),s=r.getState($e.POLICY);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.llm");if(!n.kernel?.llm?.manager)throw new Error("LLM manager not available");const o=n;if(o.kernel||(o.kernel={}),o.kernel.llm||(o.kernel.llm={}),!Object.prototype.hasOwnProperty.call(o.kernel.llm,"CodegenBundleV0_1Schema"))try{Object.defineProperty(o.kernel.llm,"CodegenBundleV0_1Schema",{value:Gt,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class cb{name=je.FS;version="1.0.0";dependencies=[];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class lb{name=je.SEARCH;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.search");if(!n.runtime?.search)throw new Error("Search facade not available")}async start(e){}}class ub{name=je.VCS;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.vcs");if(!n.runtime?.vcs)throw new Error("VCS facade not available")}async start(e){}}class db{name=je.WORKSPACE;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.workspace");if(!n.runtime?.workspace)throw new Error("Workspace facade not available")}async start(e){}}class pb{name=je.LLM;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.llm");if(!n.runtime?.llm)throw new Error("LLM facade not available")}async start(e){}}class hb{name=je.TASKS;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.tasks");if(!n.runtime?.tasks)throw new Error("Tasks facade not available")}async start(e){}}class fb{name=je.SECRETS;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.secrets");if(!n.runtime?.secrets)throw new Error("Secrets API not available")}async start(e){}}class mb{name=je.TERMINALS;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.terminals");if(!n.runtime?.terminals)throw new Error("Terminals facade not available")}async start(e){}}class gb{name=Fe.ACTIVITY_BAR;version="1.0.0";dependencies=[$e.COMMANDS,je.WORKSPACE];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.COMMANDS),s=r.getState(je.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.activityBar");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before shell.activityBar");if(!n.shell?.ActivityBar?.manager)throw new Error("ActivityBar manager not available")}async start(e){}}class yb{name=Fe.STATUSBAR;version="1.0.0";dependencies=[$e.EVENTS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before shell.statusbar");if(!n.shell?.Statusbar?.manager)throw new Error("Statusbar manager not available")}async start(e){}}class bb{name=Fe.VIEW;version="1.0.0";dependencies=[$e.COMMANDS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.view");if(!n.shell?.View)throw new Error("View API not available")}async start(e){const{punica:t}=e;if(t.shell?.View?.Theme?.manager)try{await t.shell.View.Theme.manager.initialize(),console.log("[ViewModule] Theme manager initialized")}catch(e){console.error("[ViewModule] Failed to initialize theme manager:",e)}}}class wb{name=Fe.VIEWS;version="1.0.0";dependencies=[Fe.LAYOUT,$e.COMMANDS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Fe.LAYOUT)!==e.BOOTSTRAPPED)throw new Error("shell.layout must be bootstrapped before shell.views");if(!n.shell?.Views?.manager)throw new Error("Views API not available")}async start(e){}}class vb{name=Fe.KEYBOARD_SHORTCUTS;version="1.0.0";dependencies=[$e.COMMANDS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.keyboardShortcuts");if(!n.shell?.KeyboardShortcuts?.manager)throw new Error("KeyboardShortcuts manager not available")}async start(e){!function(){const e=globalThis.punica?.shell?.KeyboardShortcuts?.manager;if(!e)return;const t=(t,n,r)=>{e.registerShortcut({command:n,keys:[Yf(t)],when:r})};t("mod+j",ze.TOGGLE_PANEL),t("mod+b",ze.TOGGLE_PRIMARY_SIDEBAR),t("mod+l",ze.TOGGLE_SECONDARY_SIDEBAR)}()}}class kb{name=Fe.LAYOUT;version="1.0.0";dependencies=[$e.COMMANDS,je.WORKSPACE];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState($e.COMMANDS),s=r.getState(je.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.layout");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before shell.layout");if(!n.shell?.Layout?.manager)throw new Error("Layout manager not available")}async start(e){}}class Ib{name=Fe.CONTENT_TABS;version="1.0.0";dependencies=[$e.COMMANDS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.contentTabs");if(!n.shell?.ContentTabs)throw new Error("ContentTabs API not available")}async start(e){}}class Eb{name=Fe.PANEL_TABS;version="1.0.0";dependencies=[$e.COMMANDS];#vt=e.CREATED;get state(){return this.#vt}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState($e.COMMANDS)!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.panelTabs");if(!n.shell?.PanelTabs)throw new Error("PanelTabs API not available")}async start(e){}}const Ab={schemaVersion:"1",identity:{id:"ivyx-classic",name:"ivyx",version:"1.0.0",audience:"ml-engineer",branding:{productName:"ivyx"}},shell:{activeModules:["shell.activityBar","shell.statusbar","shell.view","shell.keyboardShortcuts","shell.layout","shell.views","shell.contentTabs","shell.panelTabs","flow.shell"],layout:{id:"classic-editor",root:{type:"row",sizes:[70,30],children:[{type:"column",sizes:[80,20],children:[{type:"slot",id:"content",role:"content"},{type:"slot",id:"panel",role:"panel"}]},{type:"slot",id:"secondarySidebar",role:"secondarySidebar"}]}}},theme:{mode:"auto",density:"comfortable",branding:{productName:"ivyx"}},capabilities:{allowedIds:"*"}},Sb={schemaVersion:"1",identity:{id:"agent-ops-console",name:"Agent Ops Console",version:"1.0.0",audience:"compliance-officer",branding:{productName:"Agent Ops Console"}},shell:{activeModules:["shell.statusbar","shell.view","shell.layout","shell.views","shell.contentTabs"],layout:{id:"agent-ops-dashboard",root:{type:"column",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]}}},theme:{mode:"dark",density:"compact",branding:{productName:"Agent Ops Console"}},capabilities:{allowedIds:["capability.catalog","capability.schemaExport","event.query","event.replay","llm.listProviders","workspace.get","fs.read","fs.stat","fs.exists","fs.list","fs.snapshot","approval.grant","approval.revoke","delegation.create","flow.validate","cost.report"],deniedIds:["fs.write","fs.delete","fs.copy","fs.migrate","fs.restore","workspace.create","workspace.delete","secrets.set","secrets.delete","vcs.commit","vcs.push"],allowedOrigins:["core","extension","instruction-class"]}};function _b(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"gateway"in t)return t.gateway}}function xb(e,t,n){const r=t?.__punica??{};punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,timestampMs:Date.now(),source:r.source??"core.capabilities",kind:"result"},payload:n})}function Cb(e,t,n){const r=t?.__punica??{};punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,timestampMs:Date.now(),source:r.source??"core.capabilities",kind:"error"},payload:n})}async function Tb(e,n,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await t(),actor:{type:"user",id:void 0},origin:{kind:n,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function Nb(){const e=(e,t)=>{punica.kernel.Commands.manager.registerCommand(e,t)};e("workspace.readFile",{title:"Core: workspace.readFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=_b();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");xb("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Tb("workspace.readFile","command",t))})}catch(e){Cb("capability.workspace.readFile.error",t,{error:String(e?.message??e)})}}}),e("workspace.writeFile",{title:"Core: workspace.writeFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=String(e?.content??""),i=_b();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await Tb("workspace.writeFile","command",t)),xb("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Cb("capability.workspace.writeFile.error",t,{error:String(e?.message??e)})}}}),e("workspace.listFiles",{title:"Core: workspace.listFiles",execute:async(e,t)=>{try{const e=await punica.runtime.fs.getFileTree();xb("capability.workspace.listFiles.result",t,{entries:function(e){const t=[],n=e=>{for(const r of e??[])t.push({path:r.path,name:r.name,isDirectory:r.isDirectory}),r.isDirectory&&Array.isArray(r.children)&&r.children.length>0&&n(r.children)};return n(e??[]),t}(e)})}catch(e){Cb("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{xb("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Tb("vcs.status","command",t))})}catch(e){Cb("capability.vcs.status.error",t,{error:String(e?.message??e)})}}}),e("tasks.runCommand",{title:"Core: tasks.runCommand",execute:async(e,t)=>{try{const n=String(e?.command??""),r=Array.isArray(e?.args)?e.args.map(String):[],i=null!=e?.cwd?String(e.cwd):void 0,s=e?.env&&"object"==typeof e.env?e.env:void 0;xb("capability.tasks.runCommand.result",t,{command:n,args:r,cwd:i,...await punica.runtime.capabilities.gateway.call("tasks.runCommand",{command:n,args:r,cwd:i,env:s},await Tb("tasks.runCommand","command",t))})}catch(e){Cb("capability.tasks.runCommand.error",t,{error:String(e?.message??e)})}}}),e("llm.invoke",{title:"Core: llm.invoke",execute:async(e,t)=>{const n="capability.llm.invoke.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.invoke(e);return r.ok?xb("capability.llm.invoke.result",t,r):Cb(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Cb(n,t,i),i}}}),e("llm.plan",{title:"Core: llm.plan",execute:async(e,t)=>{const n="capability.llm.plan.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.plan(e);r.ok?xb("capability.llm.plan.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"planner",role:"planner"}})}}}),e("llm.generate-code",{title:"Core: llm.generate-code",execute:async(e,t)=>{const n="capability.llm.generate-code.result",r="capability.llm.generate-code.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const i=await punica.kernel.llm.manager.api.generateCode(e);if(i.ok)if(i.structured&&"object"==typeof i.structured){const e=i.structured;if("0.1"===e.specVersion&&Array.isArray(e.files)){const r=await(punica.runtime.workspace?.getCurrent?.());if(!r?.rootUri)throw new Error("No active workspace");const s=r.rootUri.replace(/^file:\/\//,"");xb(n,t,"confirm"===await punica.shell.View.showChangesPreview({title:"Code Generation Preview",summary:e.summary||`Generated ${e.files.length} file(s)`,files:e.files.map(e=>({path:e.path,action:e.action,content:e.content})),onConfirm:async()=>{const t=await Kt(e,s);if(t.errors.length>0)throw new Error(`Failed to apply some files:\n${t.errors.map(e=>`${e.path}: ${e.error}`).join("\n")}`)}})?{...i,metadata:{...i.metadata,applied:!0}}:{...i,metadata:{...i.metadata,applied:!1,cancelled:!0}})}else xb(n,t,i)}else xb(n,t,i);else Cb(r,t,i)}catch(e){Cb(r,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"code-generator",role:"code-generator"}})}}}),e("llm.validator",{title:"Core: llm.validator",execute:async(e,t)=>{const n="capability.llm.validator.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.validator(e);r.ok?xb("capability.llm.validator.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"validator",role:"validator"}})}}}),e("llm.edit-workflow",{title:"Core: llm.edit-workflow",execute:async(e,t)=>{const n="capability.llm.edit-workflow.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.editWorkflow(e);r.ok?xb("capability.llm.edit-workflow.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"workflow-editor",role:"workflow-editor"}})}}}),e("llm.reviewer",{title:"Core: llm.reviewer",execute:async(e,t)=>{const n="capability.llm.reviewer.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.reviewer(e);r.ok?xb("capability.llm.reviewer.result",t,r):Cb(n,t,r)}catch(e){Cb(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"reviewer",role:"reviewer"}})}}});const t=e=>async(t,n)=>{try{await punica.runtime.capabilities.gateway.call("shell.toggleSlot",{slot:e},await Tb("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(ze.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(ze.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(ze.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Mb="1.0.0",Db=Jt,Pb=no,Ob=sd,Rb=om,Lb=Fy,$b=new class{#In=new Map;#En=new Map;#An=new Map;register(t){if(this.#In.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#In.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#In.set(t.name,t),this.#En.set(t.name,e.CREATED)}get(e){return this.#In.get(e)}getAll(){return Array.from(this.#In.values())}resolveBootstrapOrder(){return this.#Sn()}resolveStartOrder(){return this.#Sn()}#Sn(){const e=new Set,t=new Set,n=[],r=i=>{if(t.has(i)){const e=Array.from(t).concat(i);throw new Error(`Circular dependency detected: ${e.join(" → ")}`)}if(e.has(i))return;t.add(i);const s=this.#In.get(i);if(!s)throw new Error(`Module ${i} not found`);for(const e of s.dependencies)r(e);t.delete(i),e.add(i),n.push(i)};for(const t of this.#In.keys())e.has(t)||r(t);return n}async bootstrapAll(){const t=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${t.join(" → ")}`);for(const n of t){const t=this.#In.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#En.set(n,e.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#En.set(n,e.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#En.set(n,e.BOOTSTRAP_FAILED),this.#An.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} bootstrap failed:`,r),new Error(`Critical module ${n} failed to bootstrap: ${r.message}`)}}console.log("[ModuleRegistry] All modules bootstrapped successfully")}async startAll(){const t=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${t.join(" → ")}`);for(const n of t){const t=this.#In.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#En.get(n);if(r!==e.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#En.set(n,e.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#En.set(n,e.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#En.set(n,e.START_FAILED),this.#An.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} start failed:`,r),new Error(`Critical module ${n} failed to start: ${r.message}`)}}for(const n of t){this.#En.get(n)===e.STARTED&&this.#En.set(n,e.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#En.get(e)}areAllModulesReady(){for(const[t,n]of this.#In){if(this.#En.get(t)!==e.READY)return!1}return!0}getError(e){return this.#An.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#In.keys())t.includes(n)&&e.push(n);return e}},jb={"shell.statusbar":()=>new yb,"shell.view":()=>new bb,"shell.views":()=>new wb,"shell.keyboardShortcuts":()=>new vb,"flow.shell":()=>new Qy,"shell.contentTabs":()=>new Ib,"shell.panelTabs":()=>new Eb,"shell.layout":()=>new kb,"shell.activityBar":()=>new gb};function Fb(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Mb,kernel:Db,shell:Pb,runtime:Ob,extensions:Rb,flow:Lb};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e);const t=e.debug??{};t.logTrinityCatalog=ku,t.logTrinityCatalogVerbose=Iu,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=ku,n.logTrinityCatalogVerbose=Iu);try{!function(){const e=(e,t)=>({id:e,extensionName:"core",definition:{...t,id:e,version:t.version||"1.0.0"}}),t=[e("workspace.readFile",{title:"Read file",description:"Read a file from the current workspace.",inputs:{schema:{type:"object",required:["path"],properties:{path:{type:"string"}}}},outputs:{kind:"event",resultEvent:"capability.workspace.readFile.result",errorEvent:"capability.workspace.readFile.error"},policy:{risk:"low",approval:"none"}}),e("workspace.writeFile",{title:"Write file",description:"Write textual content to a file in the current workspace.",inputs:{schema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}}},outputs:{kind:"event",resultEvent:"capability.workspace.writeFile.result",errorEvent:"capability.workspace.writeFile.error"},policy:{risk:"medium",approval:"step"}}),e("workspace.listFiles",{title:"List workspace files",description:"List the workspace file tree.",inputs:{schema:{type:"object",properties:{}}},outputs:{kind:"event",resultEvent:"capability.workspace.listFiles.result",errorEvent:"capability.workspace.listFiles.error"},policy:{risk:"low",approval:"none"}}),e("vcs.status",{title:"VCS status",description:"Get version control (git) status for the current workspace.",inputs:{schema:{type:"object",properties:{}}},outputs:{kind:"event",resultEvent:"capability.vcs.status.result",errorEvent:"capability.vcs.status.error"},policy:{risk:"low",approval:"none"}}),e("tasks.runCommand",{title:"Run task/command",description:"Run a command via the host task runner.",inputs:{schema:{type:"object",required:["command"],properties:{command:{type:"string"},args:{type:"array"},cwd:{type:"string"},env:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.tasks.runCommand.result",errorEvent:"capability.tasks.runCommand.error"},policy:{risk:"high",approval:"step"}}),e("llm.invoke",{title:"Invoke LLM with instruction class",description:"Invoke an LLM using a predefined instruction class (planner, code-generator, validator, etc.)",inputs:{schema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",description:"Instruction class ID (e.g., planner, code-generator, validator). Available classes are registered at runtime."},userPrompt:{type:"string"},context:{type:"object",properties:{workspaceId:{type:"string"},filePath:{type:"string"},previousOutputs:{type:"object"},capabilities:{type:"array"}}},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"}}}}}},outputs:{kind:"event",resultEvent:"capability.llm.invoke.result",errorEvent:"capability.llm.invoke.error"},policy:{risk:"medium",approval:"step"}}),e("llm.plan",{title:"LLM Planner",description:"Generate Workflow IR from natural language query",inputs:{schema:{type:"object",required:["query"],properties:{query:{type:"string"},capabilities:{type:"array"}}}},outputs:{kind:"event",resultEvent:"capability.llm.plan.result",errorEvent:"capability.llm.plan.error"},policy:{risk:"medium",approval:"step"}}),e("llm.generate-code",{title:"LLM Code Generator",description:"Generate code from requirements",inputs:{schema:{type:"object",required:["requirements"],properties:{requirements:{type:"string"},language:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.generate-code.result",errorEvent:"capability.llm.generate-code.error"},policy:{risk:"low",approval:"none"}}),e("llm.validator",{title:"LLM Code Validator",description:"Validate code and identify issues",inputs:{schema:{type:"object",required:["code"],properties:{code:{type:"string"},language:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.validator.result",errorEvent:"capability.llm.validator.error"},policy:{risk:"low",approval:"none"}}),e("llm.reviewer",{title:"LLM Code Reviewer",description:"Provide code review feedback",inputs:{schema:{type:"object",required:["code"],properties:{code:{type:"string"},language:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.reviewer.result",errorEvent:"capability.llm.reviewer.error"},policy:{risk:"low",approval:"none"}}),e("flow.migrate",{title:"Migrate WorkflowDocument",description:"Apply a host-registered transformer chain to bring a WorkflowDocument from its declared version to the requested target. Substrate ships an empty migration registry; hosts inject transformers. Pure analysis — no run state mutated.",inputs:{schema:{type:"object",required:["document","targetVersion"],properties:{document:{type:"object"},targetVersion:{type:"string"},policy:{type:"string",enum:["auto-migrate","warn","reject"]}}}},outputs:{kind:"event",resultEvent:"capability.flow.migrate.result",errorEvent:"capability.flow.migrate.error"},policy:{risk:"low",approval:"none"},sideEffects:[]}),e("flow.runSubflow",{title:"Run subflow",description:'Spawn a child Workflow run from an in-flight parent. Substrate enforces MAX_SUBFLOW_DEPTH (8) and inherits the parent workspace + approval scope so a parent "once" approval is not re-prompted by the child.',inputs:{schema:{type:"object",required:["spec"],properties:{spec:{type:"object",description:"WorkflowDocument to run. Must validate against the substrate validator before dispatch."},workspaceId:{type:"string"},input:{description:"Optional structured input threaded into the child flow-input node."},parentRunId:{type:"string"},parentTraceId:{type:"string"},parentDepth:{type:"number",minimum:0,maximum:8},filePathOrUri:{type:"string"}}}},outputs:{kind:"event",resultEvent:"capability.flow.runSubflow.result",errorEvent:"capability.flow.runSubflow.error"},policy:{risk:"medium",approval:"none"},sideEffects:["workflow-spawn"]}),e("llm.edit-workflow",{title:"LLM Workflow Editor",description:"Edit and optimize Workflow IR structures",inputs:{schema:{type:"object",required:["workflow"],properties:{workflow:{type:"object"},requirements:{type:"string"},context:{type:"object"}}}},outputs:{kind:"event",resultEvent:"capability.llm.edit-workflow.result",errorEvent:"capability.llm.edit-workflow.error"},policy:{risk:"medium",approval:"step"}})];punica.extensions.manager.registerBuiltinCapabilities(t)}(),console.log("[Punica] Core capabilities registered")}catch(e){console.error("[Punica] Failed to register core capabilities:",e?.message??e,e?.stack)}try{Nb(),console.log("[Punica] Core commands registered")}catch(e){console.error("[Punica] Failed to register core commands:",e?.message??e,e?.stack)}console.log("[Punica] Initialization completed successfully")}catch(e){throw console.error("[Punica] CRITICAL: Initialization failed:",e?.message??e,e?.stack),e}}async function Bb(e){try{console.log("[Punica] Starting module bootstrap...");const t=Pb.Profile.manager;t.registry.has("ivyx-classic")||t.registry.register(Ab),t.registry.has("agent-ops-console")||t.registry.register(Sb),void 0!==e?.profile?t.loadProfile(e.profile):t.registry.setActive("ivyx-classic");const n=t.registry.getActive();console.log(`[Punica] Active ApplicationProfile: ${n.identity.id}`);try{Pb.Layout.manager.applyApplicationProfile(n)}catch{}$b.register(new Xy),$b.register(new eb),$b.register(new nb),$b.register(new rb),$b.register(new sb),$b.register(new qy),$b.register(new tb),$b.register(new ab),$b.register(new ob),$b.register(new Zy),$b.register(new cb),$b.register(new lb),$b.register(new ub),$b.register(new db),$b.register(new pb),$b.register(new fb),$b.register(new mb),$b.register(new hb),$b.register(new Bu),$b.register(new ib);const r=t.getActiveModules();for(const e of r){const t=jb[e];t&&($b.register(t()),console.log(`[Punica] Shell module registered: ${e}`))}$b.register(new By),console.log(`[Punica] Module registry initialized with ${$b.getAll().length} modules`),await $b.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}}async function qb(){try{console.log("[Punica] Starting system..."),await $b.startAll(),$b.areAllModulesReady()&&punica.kernel?.Events?.manager&&punica.kernel.Events.manager.publishEvent({name:"punica.ready",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"punica:core",kind:"lifecycle"},payload:{version:Mb}}),console.log("[Punica] System started successfully"),ku()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}}var zb=Object.freeze({__proto__:null,StdioTransport:class{#_n;#xn;#Cn;#Tn=null;#Nn=null;#Mn=null;#Dn=null;#Pn=null;#On=new Map;#Rn=1;#Ln="";constructor(e,t=[],n={}){this.#_n=e,this.#xn=t,this.#Cn=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#$n(e):await this.#jn()}async#$n(e){this.#Mn=e;const{sessionId:t}=await e.spawn({command:this.#_n,args:this.#xn,env:this.#Cn});this.#Nn=t,this.#Dn=e.onData(e=>{e.sessionId===t&&this.#Fn(e.chunk)}),this.#Pn=e.onExit(e=>{if(e.sessionId!==t)return;const n=new Error(e.error??`MCP stdio process exited (${e.code})`);for(const{reject:e}of this.#On.values())e(n);this.#On.clear()})}async#jn(){const e=await import(
|
|
2
|
+
/* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#Tn=e.spawn(this.#_n,this.#xn,{env:{...n,...this.#Cn},stdio:["pipe","pipe","inherit"]}),this.#Tn.stdout.setEncoding("utf8"),this.#Tn.stdout.on("data",e=>{this.#Fn(e)}),this.#Tn.on("error",e=>{for(const{reject:t}of this.#On.values())t(e);this.#On.clear()})}#Fn(e){let t;for(this.#Ln+=e;-1!==(t=this.#Ln.indexOf("\n"));){const e=this.#Ln.slice(0,t).trim();this.#Ln=this.#Ln.slice(t+1),e&&this.#Bn(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#qn(n)}async request(e,t={}){const n=this.#Rn++;return new Promise((r,i)=>{this.#On.set(n,{resolve:r,reject:i});const s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#qn(s)}catch(e){this.#On.delete(n),i(e instanceof Error?e:new Error(String(e)))}})}#qn(e){if(this.#Mn&&this.#Nn)this.#Mn.write(this.#Nn,e);else{if(!this.#Tn?.stdin)throw new Error("MCP stdio transport is not connected");this.#Tn.stdin.write(e)}}close(){this.#Dn?.(),this.#Pn?.(),this.#Dn=null,this.#Pn=null,this.#Mn&&this.#Nn&&this.#Mn.close(this.#Nn),this.#Tn?.kill(),this.#Tn=null,this.#Nn=null,this.#Mn=null;for(const{reject:e}of this.#On.values())e(new Error("MCP stdio transport closed"));this.#On.clear()}#Bn(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#On.get(t.id);n&&(this.#On.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var Ub=Object.freeze({__proto__:null,StreamableHttpTransport:class{#zn;#Un;#Rn=1;#Nn;constructor(e,t={}){this.#zn=e.replace(/\/$/,""),this.#Un=t}async connect(){const e=await fetch(`${this.#zn}/sse`,{headers:{...this.#Un,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#Nn=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#Vn({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#Rn++,r=await this.#Vn({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#Vn(e){const t={...this.#Un,"Content-Type":"application/json",Accept:"application/json"};this.#Nn&&(t["mcp-session-id"]=this.#Nn);const n=await fetch(`${this.#zn}/messages`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw new Error(`MCP request failed: ${n.status} ${n.statusText}`);return await n.json()}close(){this.#Nn=void 0}}});var Vb=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return ju(jf(e))}});export{Bb as bootstrap,Rb as extensions,Lb as flow,Fb as initialize,Db as kernel,Ob as runtime,Pb as shell,qb as start,Mb as version};
|
|
3
3
|
//# sourceMappingURL=index.bundle.esm.js.map
|