@punica/editor 1.4.12 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PunicaEditor={})}(this,function(e){"use strict";var t;!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"}(t||(t={}));async function n(){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 r(){return punica.runtime?.fs}const i={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 s=new class{async write(e){try{const t=r();if(!t)return;const n=".punica/audit";await t.createFolder(n).catch(()=>{});const i=new Date(e.timestamp).toISOString().split("T")[0],s=`${n}/${`${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=r();if(!t)return[];const n=".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,n),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 o={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:s};const a={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 c(){return(new Date).toISOString()}function l(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,a){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=c(),{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,a?.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:c(),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:c()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const u=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=l(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 d={manager:u},p=Object.freeze({__proto__:null,createTasksApi:l,default:d,manager:u});function h(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 f(e){return h(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 m=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function g(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||m.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function y(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))g(t)?r[t]=null==i?i:"[REDACTED]":r[t]=e(i);return r}(e)}(e);return f(JSON.stringify(n,null,t))}function b(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 w(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 v=6048e5,k={rules:[],defaultTtlMs:v};function I(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 E(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(I(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??v)}const A=".punica/events";let S={};function _(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(A)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function x(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 C=new class{#d;#p=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const t=r();if(!t)return;if(punica.runtime?.workspace&&!await n())return;const i=Date.now();try{await t.createFolder(A)}catch{}if(!this.#p){this.#p=!0;try{await t.createFileWithContent(`${A}/.gitignore`,"*\n!.gitignore\n")}catch{}}for(const n of e)try{const e=n.envelope?.timestampMs??Date.now(),r=new Date(e).toISOString().split("T")[0],i=n.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,s=`${A}/${r}_${i}.json`,o=y(n);await t.createFileWithContent(s,o)}catch{}try{S.onWrite?.(Date.now()-i,e.length)}catch{}}async query(e){const t=r();if(!t)return[];let n;try{n=await t.getFileTree()}catch{return[]}if(!Array.isArray(n))return[];const i=_(n),s=[];for(const n of i)try{const r=await t.readFile(n),i=JSON.parse(r);x(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=r();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const i=_(n);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(x(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 n=r();if(!n)return 0;let i;try{i=await n.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=_(i);let o=0;for(const r of s)try{const i=await n.readFile(r),s=JSON.parse(i),a=s.envelope?.timestampMs??0;a<E(s.name,e,t)&&(await n.deleteFile(r),o++)}catch{}return o}};let T=C;function N(){return T}const M=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 D=M;function P(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=D.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function O(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(I(e.name,t)){r=!0;break}if(!r)return!1}return!0}class R extends Error{constructor(e){super(e),this.name="EventReplayError"}}let L={exportSpan:()=>{}};function $(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function j(){return Date.now()}function F(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;function o(){try{S.onQueueDepthChange?.(i.length)}catch{}}async function a(){if(0===i.length)return;const e=[...i];i=[],o(),s&&(clearTimeout(s),s=null);try{await N().write(e),V()}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:$(),timestampMs:j()},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(O(o,t.filter))try{t.listener(o)}catch{}}}async function d(e){try{return await N().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:$,publishEvent:function(e){const t=P({id:e.envelope?.id??$(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??j(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{L.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=y(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??"",y(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 y({exportedAt:j(),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 R('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(!O(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 B=F();var q={manager:B};let z=k;function U(){return z}async function V(){try{const e=N(),t=U();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??v;return await e.delete({until:j()-n})??0}catch{return 0}}var W=Object.freeze({__proto__:null,createCorrelationId:$,createEventsApi:F,default:q,getRetentionConfig:U,manager:B,runEventRetentionCleanup:V,setRetentionConfig:function(e){z=e??k}});function K(){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 G=K();var H={manager:G},Y=Object.freeze({__proto__:null,createNotificationsApi:K,default:H,manager:G});const J="punica.kernel.policy.v2";function Z(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function Q(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class X{#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=Q(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=Z();if(e)try{const t=e.getItem(J);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=Q(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=Z();if(e)try{let t={};try{const n=e.getItem(J);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(J,JSON.stringify(n))}catch{}}}let ee=new X;function te(){return Date.now()}function ne(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function re(e){return`${e.kind}:${e.id}`}function ie(e,t){return"workspace"===e?`workspace:${t??""}`:e}function se(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const oe="punica.kernel.policy.v1",ae="punica.kernel.policy.v2";class ce{#y="execute";#b;#w=new Set;#v=new Map;#k=[];#I=1e3;constructor(e){this.#b=e??new X,this.#E()}#E(){const e=se();if(e)try{const t=e.getItem(ae);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(oe);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(oe)}catch{}return}}}catch{}}#g(){const e=se();if(e)try{let t={};try{const n=e.getItem(ae);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#y,exportedAt:te()};e.setItem(ae,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{B.publishEvent({name:e,envelope:{id:B.createCorrelationId(),timestampMs:te(),source:"kernel:policy",kind:n},payload:t})}catch{}}#S(e,t){return`${e}|${t}`}revokeApproval(e){const t=re({kind:e.kind,id:e.id}),n="workspace"===e.scope?ie("workspace",e.workspaceId):ie(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=te();return n.filter(e=>!ne(e,r))}hasApproval(e,t,n){const r=re(e),i="workspace"===t?n?.workspaceId?ie("workspace",n.workspaceId):null:ie(t);if(null===i)return!1;const s=this.#b.get(r,i);if(!s)return!1;if(ne(s,te())){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=re(e),i="workspace"===t?ie("workspace",n?.workspaceId):ie(t),s={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:te(),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:te(),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;B.publishEvent({name:"policy.evaluated",envelope:{id:B.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){B.publishEvent({name:"policy.approvalRequested",envelope:{id:B.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:te(),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?ie("workspace",r):ie(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(),B.publishEvent({name:"policy.stateImported",envelope:{id:B.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??te(),updatedAtMs:te()};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:te(),version:1,count:n.length,entries:n},null,2)}}const le=new ce(ee);var ue={manager:le},de=Object.freeze({__proto__:null,PolicyManager:ce,default:ue,manager:le});async function pe(e,t,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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:t,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=t,s=await n(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:t,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:t},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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:t,step:e}})}catch(n){const r=String(n?.message??n);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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:t,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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:t,step:e}}),n}}}async function he(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 pe(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 fe={estimate:e=>Math.ceil(e.length/4)};function me(){return fe}function ge(e){const t=me();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 ye={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 be="[elided tool result:";function we(e){const t=(e.content??"").length;return`${be} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function ve(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 ke(e,t,n,r){const i=ge(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=ve(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(be)?{...e,content:we(e)}:e);let c=ge(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=ge(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 Ie=["capability.search","capability.describe"];function Ee(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function Ae(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Se(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 _e(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=Ee(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 xe(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function Ce(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function Te(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 Ne(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=Ee(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(xe).sort(Ce),deferredIndex:[]};const s=i.filter(e=>Ie.includes(String(e.id)));if(i=i.filter(e=>{return!Ie.includes(String(e.id))&&(!((n=String(e.id)).startsWith("ai.")||(n.startsWith("capability.")?!Ie.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(xe).sort(Ce),deferredIndex:[]};if(!1===t.deferToolLoading){return{hot:(await _e(e,i,t.query,n)).map(xe).sort(Ce),deferredIndex:[]}}const o="number"==typeof t.hotSetSize&&t.hotSetSize>0?Math.floor(t.hotSetSize):16,a=(await _e(e,i,t.query,n)).slice(0,o),c=new Set(a.map(e=>String(e.id))),l=s.length===Ie.length?s.map(xe):[{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:Te(e),category:Ee(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(xe)].sort(Ce),deferredIndex:u}}async function Me(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 De(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Re(n)}\nRejected arguments:\n${Re(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 Pe(e,t,n,r,i){let s=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Me(e,{...t,arguments:s},r,i);if("failed"!==l.status||!Ae(l.error))return o?{...l,arguments:s,repaired:!0}:l;if(a=l.error??"",2===c||i())break;const u=await De(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 Oe(e){return me().estimate(e)}function Re(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Le(e,t,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,ye[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,...e.images&&e.images.length>0?{images:e.images}:{}},...f];t&&n.push({role:"assistant",content:t});const r=n.map(e=>({id:"",createdAtMs:0,role:e.role,content:e.content??"",...e.images&&e.images.length>0?{images:e.images}:{},...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 Se("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),i};Se("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 n(),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 Ne(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(xe).sort(Ce);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,...e.images&&e.images.length>0?{images:e.images}:{}}),h=p.length;let P=0;for(let n=0;n<a;n++){if(t())return A("cancelled");let r,i=!1;if(ge(p)>c.maxContextTokens){const e=await ke(p,c,S,x);e.compacted&&(p.splice(0,p.length,...e.messages),P=0,i=!0,Se("ai.agentContextCompacted",o,"info",{runId:o,step:n,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const s=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:n,messageCount:p.length,toolsSent:T.length,toolChoice:"auto",toolNames:T.map(e=>e.name)});const t={stableToolsAndSystem:!0,stableMessagePrefix:P,cacheKey:o};r=await S("llm.chatStream",{messages:p,tools:T,toolChoice:"auto",correlationId:o,cacheHints:t,...e.profile?{profile:e.profile}:{}},x),P=p.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:n,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(t())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:n,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:n,estToolDefTokens:Oe(JSON.stringify(T)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+Oe(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+Oe(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)),Se("ai.agentTurnUsage",o,"info",{...O}),0===h.length)return u.push(m),Se("ai.agentStep",o,"info",{runId:o,turn:m}),A("final",l);u.push(m),Se("ai.agentStep",o,"info",{runId:o,turn:m});const R=h.map(e=>`${e.name}(${Re(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(t())return A("cancelled");if(Se("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 Pe(S,e,N.get(e.name),x,t);m.toolCalls.push(r),E++,"success"===r.status&&"capability.describe"===r.name&&D(r.resultPayload),console.log("[AgentLoop] tool dispatched",{step:n,name:r.name,arguments:r.arguments,status:r.status,repaired:r.repaired??!1,error:r.error,resultPreview:"success"===r.status?Re(r.resultPayload).slice(0,300):void 0}),Se("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const i={role:"tool",content:"success"===r.status?Re(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 $e(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 je={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"},Fe={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"},Be={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"},qe={SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},ze={MANAGER:"extensions.manager"},Ue={TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},Ve={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"},We={EXPORT:"policy.export",IMPORT:"policy.import",LIST_APPROVALS:"policy.listApprovals",SET_MODE:"policy.setMode",SHOW_MODE:"policy.showMode"},Ke={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 Ge(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 He(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 Ye="punica.kernel.ai.sessions.index.v1";function Je(e){return`punica.kernel.ai.session.${e}.v1`}function Ze(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const Qe=new class{readIndex(){const e=Ze();if(!e)return[];try{const t=e.getItem(Ye);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=Ze();if(t)try{t.setItem(Ye,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=Ze();if(t)try{const n=t.getItem(Je(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=Ze();if(t)try{t.setItem(Je(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=Ze();if(t)try{t.removeItem(Je(e))}catch{}}};let Xe=Qe;function et(){return Xe}const tt="New chat";function nt(){return Date.now()}function rt(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${nt().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function it(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:nt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function st(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function ot(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 at=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(We.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(We.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(We.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=$e(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(We.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(We.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`+$e(e,2))}}),t.registerCommand(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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"+$e(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+$e(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Ve.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;He("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:Ge(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();He("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:Ge(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),He("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){He("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 he(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 Le(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#M.delete(t)}}},ct=new class{#D;create(e){const t=et(),n={sessionId:rt("sess"),title:e?.title?.trim()||tt,createdAtMs:nt(),updatedAtMs:nt(),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),it("ai.sessionCreated",n),{...n}}list(e){const t=et().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return et().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&&(it("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#O(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(it("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=et(),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),it("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=et(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||rt("msg"),createdAtMs:e.createdAtMs||nt(),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=nt(),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===tt){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:tt}(e.content))}r.writeSession(i),this.#R(o),it("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=et().readSession(e);n&&(n.contextView=t,et().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=et().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(...st(n.messages).map(ot)),e}return st(t.transcript.slice(-40)).map(ot)}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=nt(),e.usage=n});return!!n&&(it("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#O(e,t){const n=et(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=nt(),n.writeSession(r),this.#R(r.meta),{...r.meta}}#R(e){const t=et(),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=et(),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),it("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};ct.setCompactor(function(){const e=ye.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=ve([{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(be)?{...e,content:we(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());var lt={manager:at,sessions:ct},ut=Object.freeze({__proto__:null,default:lt,manager:at,sessions:ct});const dt=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 pt(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 ht(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=dt.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 pt({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 ft(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 mt(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function gt(){const e=globalThis;return e.punica?.runtime?.fs}function yt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const bt={type:"ai",id:"llm:context"},wt={kind:"ai",id:"context-builder"};async function vt(e){if(e.filePath)try{const t=mt(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:bt,origin:wt,trace:{traceId:yt()},policy:{mode:"execute"}}):await(gt()?.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 kt(e){try{const t=mt(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:bt,origin:wt,trace:{traceId:yt()},policy:{mode:"execute"}}):await(gt()?.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 It(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Et(){return"undefined"==typeof document?void 0:document}function At(){const e=Et();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 St(e){try{const t=It();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=At();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 _t(){try{const e=It();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=At();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=Et();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 xt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Ct={type:"ai",id:"llm:context"},Tt={kind:"ai",id:"context-builder"};async function Nt(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:Ct,origin:Tt,trace:{traceId:xt()},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 Mt(){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 Dt(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 Pt="problems.getDiagnostics";function Ot(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===Pt))return;let r;try{r=t.executeCommand?.(Pt)}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 Rt(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 Lt=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=Rt(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 $t(e,t){const r=dt;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(ft(e)),vt(e),Promise.resolve(St(e)),kt(e),Nt(e),Mt(),Promise.resolve(_t()),Dt(e),Promise.resolve(Ot(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 ht(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,correlationId:t?.correlationId??punica.kernel.Events.manager.createCorrelationId()},c=!0===e.options?.stream?"llm.chatStream":"llm.chat";let l,u,d=0;const p=await n();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};Lt.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 jt(e){return $t({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 Ft(e){return $t({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function Bt(e){return $t({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 qt(e){return $t({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 zt(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 $t({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function Ut(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function Vt(e,t){const n=Ut(e).split("/").filter(Boolean),r=Ut(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function Wt(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function Kt(e,t){const n=Ut(e).split("/").filter(Boolean),r=Ut(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 Gt(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=Kt(t,Vt(t,Ut(r.path)));(e.startsWith("..")||Wt(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=Ut(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 Ht={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 Yt=new class{api;constructor(){this.api={instructionClassRegistry:dt,invoke:$t,plan:jt,generateCode:Ft,validator:Bt,reviewer:qt,editWorkflow:zt,listInstructionClasses:e=>dt.listSummaries(e)}}};var Jt={manager:Yt};const Zt={Commands:i,History:o,TimeServer:a,Tasks:p,Events:W,Notifications:Y,Policy:de,AI:ut,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:Ht,applyCodegenBundle:Gt,default:Jt,manager:Yt})};const Qt={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 Xt={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 en(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 tn={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("&lt;")?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:en,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=en(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 nn={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 rn=new class{currentProfileId=null;listeners=new Set;async loadProfile(e){const t=nn[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{...nn}}getProfile(e){return nn[e]}registerProfile(e){nn[e.id]=e}onDidChangeProfile(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDefaultImmediate(){const e=nn.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&&nn[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 sn(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 on(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 sn({title:s,message:n,tone:r,buttons:[{label:i,variant:"filled",color:"error"===r?"error":"primary",action:"ok"}]})}const an={showInformationMessage:async function(e,...t){return 0===t.length?void await on({message:e,variant:"info",title:"Information"}):await sn({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 on({message:e,variant:"warning",title:"Warning"}):await sn({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 on({message:e,variant:"error",title:"Error"}):await sn({title:"Error",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showDialog:sn,showConfirm:async function(e){const{title:t="Confirm",message:n,confirmLabel:r="OK",cancelLabel:i="Cancel",variant:s="info"}=e;return"confirm"===await sn({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:on,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`;sn({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=tn.createBadge({text:t.action,variant:"filled",color:"delete"===t.action?"error":"create"===t.action?"success":"primary",size:"small"}),i=tn.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=tn.createTypography(`This file will be deleted: ${t.path}`,{variant:"body"});return void e.appendChild(n)}if(!t.content){const t=tn.createTypography("No content preview available",{variant:"body"});return void e.appendChild(t)}const n=tn.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:tn,Theme:{manager:rn,profiles:nn}};function cn(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 ln(){return globalThis.punica?.shell?.Layout?.manager}function un(){return globalThis.punica?.shell?.ActivityBar?.manager}const dn={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),cn({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=ln();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{un()?.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)}cn({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=ln();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{un()?.setActiveByViewId?.(null)}catch{}cn({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),cn({name:"shell.view.hidden",source:"shell:views",payload:{viewId:t,slot:e,source:"host",sourceId:"slot-reset"}}))}#se(e){const t=ln();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=ln();i?.removeViewHost?.(t.slot,n)}}}};const pn={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 hn=0;function fn(){return hn>0}async function mn(e){hn++;try{return await e()}finally{hn>0&&hn--}}const gn={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"}]}},yn={id:"welcome",title:"Welcome",root:{type:"row",sizes:[100],children:[{type:"column",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]}]}},bn={type:"row",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]};const wn={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=gn}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 fn()?(cn({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??bn;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?yn:gn;this.#fe.childElementCount&&this.#ye.id===r.id||this.applyProfile(r)}catch{this.#fe.childElementCount||this.applyProfile(this.#ye)}e.appendChild(this.#fe)}}};const vn=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 kn=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!!fn()&&(cn({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 In(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function En(e){return"string"==typeof e}function An(e){return"string"==typeof e&&e.trim().length>0}function Sn(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const _n=new Set(["shell.activityBar","shell.statusbar","shell.view","shell.views","shell.keyboardShortcuts","shell.layout","shell.contentTabs","shell.panelTabs","flow.shell"]),xn=new Set(["light","dark","auto"]),Cn=new Set(["compact","comfortable"]),Tn=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const Nn=new class{validate(e){const t=[];if(!In(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)}`),In(e.identity)?(An(e.identity.id)||t.push("identity.id must be a non-empty string"),An(e.identity.name)||t.push("identity.name must be a non-empty string"),An(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),In(e.shell)?(Array.isArray(e.shell.activeModules)?e.shell.activeModules.forEach((e,n)=>{En(e)&&_n.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&&(In(e.shell.layout)?(An(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),In(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"),In(e.theme)?(xn.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||Cn.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"),In(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||Sn(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||Sn(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)=>{En(e)&&Tn.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 Mn{#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,cn({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Ke.has(e)}list(){return Array.from(this.#Ke.values())}}const Dn={manager:new class{registry=new Mn;get validator(){return Nn}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 cn({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),cn({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}},Pn={};function On(e,t){"string"!=typeof t&&(t=On.defaultChars);const n=function(e){let t=Pn[e];if(t)return t;t=Pn[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})}On.defaultChars=";/?:@&=+$,#",On.componentChars="";const Rn={};function Ln(e,t,n){"string"!=typeof t&&(n=t,t=Ln.defaultChars),void 0===n&&(n=!0);const r=function(e){let t=Rn[e];if(t)return t;t=Rn[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 $n(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 jn(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}Ln.defaultChars=";/?:@&=+$,-_.!~*'()#",Ln.componentChars="-_.!~*'()";const Fn=/^([a-z0-9.+-]+:)/i,Bn=/:[0-9]*$/,qn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,zn=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),Un=["'"].concat(zn),Vn=["%","/","?",";","#"].concat(Un),Wn=["/","?","#"],Kn=/^[+a-z0-9A-Z_-]{0,63}$/,Gn=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,Hn={javascript:!0,"javascript:":!0},Yn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function Jn(e,t){if(e&&e instanceof jn)return e;const n=new jn;return n.parse(e,t),n}jn.prototype.parse=function(e,t){let n,r,i,s=e;if(s=s.trim(),!t&&1===e.split("#").length){const e=qn.exec(s);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=Fn.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&&Hn[o]||(s=s.substr(2),this.slashes=!0)),!Hn[o]&&(i||o&&!Yn[o])){let e,t,n=-1;for(let e=0;e<Wn.length;e++)r=s.indexOf(Wn[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<Vn.length;e++)r=s.indexOf(Vn[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(Kn)){let r="";for(let e=0,t=n.length;e<t;e++)n.charCodeAt(e)>127?r+="x":r+=n[e];if(!r.match(Kn)){const r=e.slice(0,t),i=e.slice(t+1),o=n.match(Gn);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),Yn[n]&&this.hostname&&!this.pathname&&(this.pathname=""),this},jn.prototype.parseHost=function(e){let t=Bn.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 Zn,Qn=Object.freeze({__proto__:null,decode:On,encode:Ln,format:$n,parse:Jn}),Xn=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,er=/[\0-\x1F\x7F-\x9F]/,tr=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\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]/,nr=/[\$\+<->\^`\|~\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]/,rr=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,ir=Object.freeze({__proto__:null,Any:Xn,Cc:er,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:tr,S:nr,Z:rr}),sr=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୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢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;怳Ādp໩໮uct;戏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ǣጓ\0጖y;䐎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Ā;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀ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Ā;e᜚᜜lƀ;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\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩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ↄⅪ←ٖ↛ǰ↉\0↎proø₞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;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\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\0⹻m;櫳;櫽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))),or=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));const ar=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]]),cr=null!==(Zn=String.fromCodePoint)&&void 0!==Zn?Zn: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 lr;!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"}(lr||(lr={}));var ur,dr,pr;function hr(e){return e>=lr.ZERO&&e<=lr.NINE}function fr(e){return e>=lr.UPPER_A&&e<=lr.UPPER_F||e>=lr.LOWER_A&&e<=lr.LOWER_F}function mr(e){return e===lr.EQUALS||function(e){return e>=lr.UPPER_A&&e<=lr.UPPER_Z||e>=lr.LOWER_A&&e<=lr.LOWER_Z||hr(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"}(ur||(ur={})),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"}(dr||(dr={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(pr||(pr={}));class gr{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=dr.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=pr.Strict}startEntity(e){this.decodeMode=e,this.state=dr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case dr.EntityStart:return e.charCodeAt(t)===lr.NUM?(this.state=dr.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=dr.NamedEntity,this.stateNamedEntity(e,t));case dr.NumericStart:return this.stateNumericStart(e,t);case dr.NumericDecimal:return this.stateNumericDecimal(e,t);case dr.NumericHex:return this.stateNumericHex(e,t);case dr.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===lr.LOWER_X?(this.state=dr.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=dr.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(!hr(r)&&!fr(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(!hr(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===lr.SEMI)this.consumed+=1;else if(this.decodeMode===pr.Strict)return 0;return this.emitCodePoint(function(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=ar.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==lr.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&ur.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const s=e.charCodeAt(t);if(this.treeIndex=br(n,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return 0===this.result||this.decodeMode===pr.Attribute&&(0===i||mr(s))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],i=(r&ur.VALUE_LENGTH)>>14,0!==i){if(s===lr.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==pr.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]&ur.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]&~ur.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case dr.NamedEntity:return 0===this.result||this.decodeMode===pr.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case dr.NumericDecimal:return this.emitNumericEntity(0,2);case dr.NumericHex:return this.emitNumericEntity(0,3);case dr.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case dr.EntityStart:return 0}}}function yr(e){let t="";const n=new gr(e,e=>t+=cr(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 br(e,t,n,r){const i=(t&ur.BRANCH_LENGTH)>>7,s=t&ur.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 wr=yr(sr);function vr(e){return"[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}yr(or);const kr=Object.prototype.hasOwnProperty;function Ir(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 Er(e,t,n){return[].concat(e.slice(0,t),n,e.slice(t+1))}function Ar(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 Sr(e){if(e>65535){const t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}const _r=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,xr=new RegExp(_r.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),Cr=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function Tr(e,t){if(35===t.charCodeAt(0)&&Cr.test(t)){const n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Ar(n)?Sr(n):e}const n=function(e,t=pr.Legacy){return wr(e,t)}(e);return n!==e?n:e}function Nr(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(xr,function(e,t,n){return t||Tr(e,n)})}const Mr=/[&<>"]/,Dr=/[&<>"]/g,Pr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function Or(e){return Pr[e]}function Rr(e){return Mr.test(e)?e.replace(Dr,Or):e}const Lr=/[.?*+^$[\]\\(){}|-]/g;function $r(e){switch(e){case 9:case 32:return!0}return!1}function jr(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 Fr(e){return tr.test(e)||nr.test(e)}function Br(e){return Fr(Sr(e))}function qr(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 zr(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}function Ur(e){return 32===e||9===e||10===e||13===e}function Vr(e){let t=0;for(;t<e.length&&Ur(e.charCodeAt(t));t++);let n=e.length-1;for(;n>=t&&Ur(e.charCodeAt(n));n--);return e.slice(t,n+1)}const Wr={mdurl:Qn,ucmicro:ir};var Kr=Object.freeze({__proto__:null,arrayReplaceAt:Er,asciiTrim:Vr,assign:Ir,escapeHtml:Rr,escapeRE:function(e){return e.replace(Lr,"\\$&")},fromCodePoint:Sr,has:function(e,t){return kr.call(e,t)},isMdAsciiPunct:qr,isPunctChar:Fr,isPunctCharCode:Br,isSpace:$r,isString:vr,isValidEntityCode:Ar,isWhiteSpace:jr,lib:Wr,normalizeReference:zr,unescapeAll:Nr,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(_r,"$1")}});var Gr=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=Nr(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=Nr(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+=Nr(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+=Nr(e.slice(t,s)),o}});const Hr={};function Yr(){this.rules=Ir({},Hr)}function Jr(){this.__rules__=[],this.__cache__=null}function Zr(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 Qr(e,t,n){this.src=e,this.env=n,this.tokens=[],this.inlineMode=!1,this.md=t}Hr.code_inline=function(e,t,n,r,i){const s=e[t];return"<code"+i.renderAttrs(s)+">"+Rr(s.content)+"</code>"},Hr.code_block=function(e,t,n,r,i){const s=e[t];return"<pre"+i.renderAttrs(s)+"><code>"+Rr(e[t].content)+"</code></pre>\n"},Hr.fence=function(e,t,n,r,i){const s=e[t],o=s.info?Nr(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)||Rr(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`},Hr.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)},Hr.hardbreak=function(e,t,n){return n.xhtmlOut?"<br />\n":"<br>\n"},Hr.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"<br />\n":"<br>\n":"\n"},Hr.text=function(e,t){return Rr(e[t].content)},Hr.html_block=function(e,t){return e[t].content},Hr.html_inline=function(e,t){return e[t].content},Yr.prototype.renderAttrs=function(e){let t,n,r;if(!e.attrs)return"";for(r="",t=0,n=e.attrs.length;t<n;t++)r+=" "+Rr(e.attrs[t][0])+'="'+Rr(e.attrs[t][1])+'"';return r},Yr.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},Yr.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},Yr.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},Yr.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},Jr.prototype.__find__=function(e){for(let t=0;t<this.__rules__.length;t++)if(this.__rules__[t].name===e)return t;return-1},Jr.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))})})},Jr.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},Jr.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},Jr.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},Jr.prototype.push=function(e,t,n){const r=n||{};this.__rules__.push({name:e,enabled:!0,fn:t,alt:r.alt||[]}),this.__cache__=null},Jr.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},Jr.prototype.enableOnly=function(e,t){Array.isArray(e)||(e=[e]),this.__rules__.forEach(function(e){e.enabled=!1}),this.enable(e,t)},Jr.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},Jr.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},Zr.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},Zr.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]},Zr.prototype.attrSet=function(e,t){const n=this.attrIndex(e),r=[e,t];n<0?this.attrPush(r):this.attrs[n]=r},Zr.prototype.attrGet=function(e){const t=this.attrIndex(e);let n=null;return t>=0&&(n=this.attrs[t][1]),n},Zr.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},Qr.prototype.Token=Zr;const Xr=/\r\n?|\n/g,ei=/\0/g;function ti(e){return/^<a[>\s]/i.test(e)}function ni(e){return/^<\/a\s*>/i.test(e)}const ri=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,ii=/\((c|tm|r)\)/i,si=/\((c|tm|r)\)/gi,oi={c:"©",r:"®",tm:"™"};function ai(e,t){return oi[t.toLowerCase()]}function ci(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(si,ai)),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++}}function li(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||ri.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 ui=/['"]/,di=/['"]/g;function pi(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function hi(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;){di.lastIndex=l;const o=di.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=qr(f)||Br(f),y=qr(m)||Br(m),b=jr(f),w=jr(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]),pi(i,s,o.index,c),pi(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&&pi(i,s,o.index,"’")}else h&&pi(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 fi=[["normalize",function(e){let t;t=e.src.replace(Xr,"\n"),t=t.replace(ei,"�"),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&&(ti(o.content)&&i>0&&i--,ni(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=Er(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&&(ii.test(e.tokens[t].content)&&ci(e.tokens[t].children),ri.test(e.tokens[t].content)&&li(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&&ui.test(e.tokens[t].content)&&hi(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 mi(){this.ruler=new Jr;for(let e=0;e<fi.length;e++)this.ruler.push(fi[e][0],fi[e][1])}function gi(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($r(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}mi.prototype.process=function(e){const t=this.ruler.getRules("");for(let n=0,r=t.length;n<r;n++)t[n](e)},mi.prototype.State=Qr,gi.prototype.push=function(e,t,n){const r=new Zr(e,t,n);return r.block=!0,n<0&&this.level--,r.level=this.level,n>0&&this.level++,this.tokens.push(r),r},gi.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},gi.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},gi.prototype.skipSpaces=function(e){for(let t=this.src.length;e<t;e++){if(!$r(this.src.charCodeAt(e)))break}return e},gi.prototype.skipSpacesBack=function(e,t){if(e<=t)return e;for(;e>t;)if(!$r(this.src.charCodeAt(--e)))return e+1;return e},gi.prototype.skipChars=function(e,t){for(let n=this.src.length;e<n&&this.src.charCodeAt(e)===t;e++);return e},gi.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},gi.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($r(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("")},gi.prototype.Token=Zr;function yi(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function bi(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 wi(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(!$r(e.src.charCodeAt(r)))return-1}return r}function vi(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),!$r(s))?-1:i}const ki="<[A-Za-z][A-Za-z0-9\\-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^\"'=<>`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",Ii="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",Ei=new RegExp("^(?:"+ki+"|"+Ii+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|<![A-Za-z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)"),Ai=new RegExp("^(?:"+ki+"|"+Ii+")"),Si=[[/^<(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(Ai.source+"\\s*$"),/^$/,!1]];const _i=[["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&&!$r(a))return!1;if(45===o&&$r(a))return!1;for(;s<e.eMarks[i];){const t=e.src.charCodeAt(s);if(124!==t&&45!==t&&58!==t&&!$r(t))return!1;s++}let c=yi(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=yi(e,t).trim(),-1===c.indexOf("|"))return!1;if(e.sCount[t]-e.blkIndent>=4)return!1;l=bi(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=yi(e,i).trim(),!c)break;if(e.sCount[i]-e.blkIndent>=4)break;if(l=bi(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(!$r(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&&!$r(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=vi(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=wi(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=vi(e,c),p<0)break;o=e.bMarks[c]+e.tShift[c]}else if(p=wi(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(!$r(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(!$r(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(!$r(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i)&&m)for(m="",i=p,o=h;i<s;){if(!$r(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i))return!1;const y=zr(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<Si.length&&!Si[a][0].test(o);a++);if(a===Si.length)return!1;if(r)return Si[a][2];let c=t+1;const l=Si[a][1].test("");if(!Si[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),Si[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&&!$r(o))return!1;if(r)return!0;s=e.skipSpacesBack(s,i);const c=e.skipCharsBack(s,35,i);c>i&&$r(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=Vr(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=Vr(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=Vr(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 xi(){this.ruler=new Jr;for(let e=0;e<_i.length;e++)this.ruler.push(_i[e][0],_i[e][1],{alt:(_i[e][2]||[]).slice()})}function Ci(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 Ti(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}}xi.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)}},xi.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)},xi.prototype.State=gi,Ci.prototype.pushPending=function(){const e=new Zr("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},Ci.prototype.push=function(e,t,n){this.pending&&this.pushPending();const r=new Zr(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},Ci.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=qr(i)||Br(i),l=qr(a)||Br(a),u=jr(i),d=jr(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}},Ci.prototype.Token=Zr;const Ni=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;const Mi=[];for(let e=0;e<256;e++)Mi.push(0);function Di(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){Mi[e.charCodeAt(0)]=1});var Pi={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;Di(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Di(e,t[r].delimiters)}};function Oi(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 Ri={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;Oi(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Oi(e,t[r].delimiters)}};const Li=/^([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])?)*)$/,$i=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;const ji=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,Fi=/^&([a-z][a-z0-9]{1,31});/i;function Bi(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 qi=[["text",function(e,t){let n=e.pos;for(;n<e.posMax&&!Ti(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(Ni);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&&$r(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),$r(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!==Mi[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",Pi.tokenize],["emphasis",Ri.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),$r(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),$r(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),$r(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[zr(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),$r(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),$r(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),$r(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[zr(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($i.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(Li.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(Ei);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(ji);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=Ar(t)?Sr(t):Sr(65533),n.markup=r[0],n.info="entity"}return e.pos+=r[0].length,!0}}else{const r=e.src.slice(n).match(Fi);if(r){const n=(i=r[0],wr(i,pr.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}]],zi=[["balance_pairs",function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Bi(e.delimiters);for(let e=0;e<n;e++)t[e]&&t[e].delimiters&&Bi(t[e].delimiters)}],["strikethrough",Pi.postProcess],["emphasis",Ri.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 Ui(){this.ruler=new Jr;for(let e=0;e<qi.length;e++)this.ruler.push(qi[e][0],qi[e][1]);this.ruler2=new Jr;for(let e=0;e<zi.length;e++)this.ruler2.push(zi[e][0],zi[e][1])}function Vi(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(n){e[n]=t[n]})}),e}function Wi(e){return Object.prototype.toString.call(e)}function Ki(e){return"[object Function]"===Wi(e)}function Gi(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}Ui.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},Ui.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()},Ui.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)},Ui.prototype.State=Ci;const Hi={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};const Yi={"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}}},Ji="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function Zi(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=Xn.source,t.src_Cc=er.source,t.src_Z=rr.source,t.src_P=tr.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]"===Wi(n))return!function(e){return"[object RegExp]"===Wi(e)}(n.validate)?Ki(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(Ki(n.normalize)?r.normalize=n.normalize:n.normalize?s(t,n):r.normalize=function(e,t){t.normalize(e)});!function(e){return"[object String]"===Wi(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(Gi).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 Qi(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 Xi(e,t){if(!(this instanceof Xi))return new Xi(e,t);var n;t||(n=e,Object.keys(n||{}).reduce(function(e,t){return e||Hi.hasOwnProperty(t)},!1)&&(t=e,e={})),this.__opts__=Vi({},Hi,t),this.__schemas__=Vi({},Yi,e),this.__compiled__={},this.__tlds__=Ji,this.__tlds_replaced__=!1,this.re={},Zi(this)}Xi.prototype.add=function(e,t){return this.__schemas__[e]=t,Zi(this),this},Xi.prototype.set=function(e){return this.__opts__=Vi(this.__opts__,e),this},Xi.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))},Xi.prototype.pretest=function(e){return this.re.pretest.test(e)},Xi.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},Xi.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 Qi(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},Xi.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 Qi(e,t[2],t.index+t[1].length,t.index+t[0].length+n);return this.__compiled__[r.schema].normalize(r,this),r},Xi.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(),Zi(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,Zi(this),this)},Xi.prototype.normalize=function(e){e.schema||(e.url=`http://${e.url}`),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url=`mailto:${e.url}`)},Xi.prototype.onCompile=function(){};const es=2147483647,ts=36,ns=/^xn--/,rs=/[^\0-\x7F]/,is=/[\x2E\u3002\uFF0E\uFF61]/g,ss={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},os=Math.floor,as=String.fromCharCode;function cs(e){throw new RangeError(ss[e])}function ls(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(is,".")).split("."),t).join(".");return r+i}function us(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 ds=function(e){return e>=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:ts},ps=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},hs=function(e,t,n){let r=0;for(e=n?os(e/700):e>>1,e+=os(e/t);e>455;r+=ts)e=os(e/35);return os(r+36*e/(e+38))},fs=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&&cs("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=ts;;i+=ts){a>=n&&cs("invalid-input");const o=ds(e.charCodeAt(a++));o>=ts&&cs("invalid-input"),o>os((es-r)/t)&&cs("overflow"),r+=o*t;const c=i<=s?1:i>=s+26?26:i-s;if(o<c)break;const l=ts-c;t>os(es/l)&&cs("overflow"),t*=l}const c=t.length+1;s=hs(r-o,c,0==o),os(r/c)>es-i&&cs("overflow"),i+=os(r/c),r%=c,t.splice(r++,0,i)}return String.fromCodePoint(...t)},ms=function(e){const t=[],n=(e=us(e)).length;let r=128,i=0,s=72;for(const n of e)n<128&&t.push(as(n));const o=t.length;let a=o;for(o&&t.push("-");a<n;){let n=es;for(const t of e)t>=r&&t<n&&(n=t);const c=a+1;n-r>os((es-i)/c)&&cs("overflow"),i+=(n-r)*c,r=n;for(const n of e)if(n<r&&++i>es&&cs("overflow"),n===r){let e=i;for(let n=ts;;n+=ts){const r=n<=s?1:n>=s+26?26:n-s;if(e<r)break;const i=e-r,o=ts-r;t.push(as(ps(r+i%o,0))),e=os(i/o)}t.push(as(ps(e,0))),s=hs(i,c,a===o),i=0,++a}++i,++r}return t.join("")},gs=function(e){return ls(e,function(e){return rs.test(e)?"xn--"+ms(e):e})},ys=function(e){return ls(e,function(e){return ns.test(e)?fs(e.slice(4).toLowerCase()):e})};const bs={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"]}}}},ws=/^(vbscript|javascript|file|data):/,vs=/^data:image\/(gif|png|jpeg|webp);/;function ks(e){const t=e.trim().toLowerCase();return!ws.test(t)||vs.test(t)}const Is=["http:","https:","mailto:"];function Es(e){const t=Jn(e,!0);if(t.hostname&&(!t.protocol||Is.indexOf(t.protocol)>=0))try{t.hostname=gs(t.hostname)}catch(e){}return Ln($n(t))}function As(e){const t=Jn(e,!0);if(t.hostname&&(!t.protocol||Is.indexOf(t.protocol)>=0))try{t.hostname=ys(t.hostname)}catch(e){}return On($n(t),On.defaultChars+"%")}function Ss(e,t){if(!(this instanceof Ss))return new Ss(e,t);t||vr(e)||(t=e||{},e="default"),this.inline=new Ui,this.block=new xi,this.core=new mi,this.renderer=new Yr,this.linkify=new Xi,this.validateLink=ks,this.normalizeLink=Es,this.normalizeLinkText=As,this.utils=Kr,this.helpers=Ir({},Gr),this.options={},this.configure(e),t&&this.set(t)}function _s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var xs,Cs;function Ts(){if(Cs)return xs;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}Cs=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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}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({}),xs=ce,ce.HighlightJS=ce,ce.default=ce,xs}Ss.prototype.set=function(e){return Ir(this.options,e),this},Ss.prototype.configure=function(e){const t=this;if(vr(e)){const t=e;if(!(e=bs[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},Ss.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},Ss.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},Ss.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},Ss.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},Ss.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},Ss.prototype.parseInline=function(e,t){const n=new this.core.State(e,this,t);return n.inlineMode=!0,this.core.process(n),n.tokens},Ss.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var Ns=_s(Ts());const Ms="[A-Za-z$_][0-9A-Za-z$_]*",Ds=["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"],Ps=["true","false","null","undefined","NaN","Infinity"],Os=["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"],Rs=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Ls=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],$s=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],js=[].concat(Ls,Os,Rs);const Fs="[A-Za-z$_][0-9A-Za-z$_]*",Bs=["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"],qs=["true","false","null","undefined","NaN","Infinity"],zs=["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"],Us=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Vs=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ws=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Ks=[].concat(Vs,zs,Us);function Gs(e){const t=e.regex,n=Fs,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:Fs,keyword:Bs,literal:qs,built_in:Ks,"variable.language":Ws},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:{_:[...zs,...Us]}},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("|"),")")}([...Vs,"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 Hs=["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"],Ys=["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(),Js=["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(),Zs=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Qs=["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();Ns.registerLanguage("javascript",function(e){const t=e.regex,n=Ms,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:Ms,keyword:Ds,literal:Ps,built_in:js,"variable.language":$s},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:{_:[...Os,...Rs]}},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("|"),")")}([...Ls,"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:/\$[(.]/}]}}),Ns.registerLanguage("typescript",function(e){const t=e.regex,n=Gs(e),r=Fs,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:Fs,keyword:Bs.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:qs,built_in:Ks.concat(i),"variable.language":Ws},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}),Ns.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]}]}}),Ns.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"}}),Ns.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}}),Ns.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]}}),Ns.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}]}]}}),Ns.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:":("+Js.join("|")+")"},{begin:":(:)?("+Zs.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Qs.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:Ys.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Hs.join("|")+")\\b"}]}}),Ns.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}]}}),Ns.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});/}]}}),Ns.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 Xs={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 eo(e){const t=new Ss({html:!1,linkify:!0,breaks:!0,highlight:e?(e,t)=>{const n=function(e){const t=(e||"").trim().toLowerCase();if(!t)return;const n=Xs[t]??t;return Ns.getLanguage(n)?n:void 0}(t);if(n)try{return Ns.highlight(e,{language:n,ignoreIllegals:!0}).value}catch{}return""}:void 0});return t}const to=eo(!0),no=eo(!1);const ro={ActivityBar:Qt,Statusbar:Xt,View:an,Views:dn,KeyboardShortcuts:pn,Layout:wn,ContentTabs:vn,PanelTabs:kn,Profile:Dn,Markdown:{render:function(e,t){return(!1===t?.highlight?no:to).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 io(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 so=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=>io(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=>io(t,e))}).map(e=>({opener:e,command:e.command}))}};let oo,ao,co,lo,uo,po;function ho(){if(oo)return oo;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return oo=punica.runtime.resources,oo}function fo(){if(ao)return ao;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return ao=e,ao}function mo(){if(lo)return lo;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return lo=e,lo}function go(){if(uo)return uo;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function yo(){if(po)return po;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return po=e,po}function bo(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 wo(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 vo=bo({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 ko(){return vo.get()}function Io(e){vo.set(e),e&&wo({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Eo(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 Ao=Symbol("punica.llm.gatewayGovernedAi");let So,_o,xo;function Co(){if(So)return So;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return So=punica.runtime.llm,So}function To(e){if(So=e,_o=void 0,xo=void 0,!e)return;const t=e;Eo("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class No{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 Mo=null;function Do(){return Mo||(Mo=new No),Mo}class Po{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 Oo{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 Ro={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}}},Lo={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}}},$o={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},jo={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},Fo={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 Bo(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 qo{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=Bo("session");return new Oo(i,s,t.id,e.language,r,n)}}class zo{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 Uo=null;function Vo(){return Uo||(Uo=new zo),Uo}class Wo{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 Ko{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 Go=null;function Ho(){return Go||(Go=new Ko),Go}class Yo{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 Jo{#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 Zo=null;function Qo(){return Zo||(Zo=new Jo),Zo}function Xo(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 ea="default";class ta{#Je=new Map;#Ze(e){const t=e||ea;let n=this.#Je.get(t);return n||(n=new Map,this.#Je.set(t,n)),n}upsert(e,t=ea){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=ea){const r=this.#Ze(n),i=[];for(const t of r.values())i.push({id:t.id,score:Xo(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=ea){const n=this.#Ze(t);for(const t of e)n.delete(t)}clear(e=ea){this.#Je.delete(e||ea)}count(e=ea){return this.#Ze(e).size}export(e=ea){return Array.from(this.#Ze(e).values())}import(e,t=ea){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#Je.set(t||ea,n)}}const na=".punica/vectors";class ra{#b=new ta;#Qe=new Set;#Xe(){try{return punica.runtime?.fs}catch{return}}#et(e){return`${na}/${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(na)}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 ia,sa,oa;function aa(){return ia||(sa||(sa=new ra),sa)}function ca(){if(!oa)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 oa}var la;!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"}(la||(la={}));class ua extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const da=new class{#rt=new Map;#ne=new Map;registerCapability(e){if(!e.name)throw new ua(la.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new ua(la.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 ua(la.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 ua(la.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 ua(la.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 ua(la.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 ua(la.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 ua(la.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 pa(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 ha(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:fa(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 fa(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 ma=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function ga(){const e=globalThis;return e.punica?.extensions?.manager}function ya(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function ba(){const e=globalThis;return e.punica?.flow?.registry}function wa(){const e=globalThis;return e.punica?.flow?.agents}function va(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const ka={core:function(e){const t=da.getSpec(e);if(t)return{origin:"core",definition:pa(t)}},extension:function(e){const t=ga();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=ya();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=ba();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=wa();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=va();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},Ia={core:function(){return da.getAllSpecs().map(e=>({origin:"core",definition:pa(e)}))},extension:function(){const e=ga();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=ya();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=ba();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=wa();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=va();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Ea={getCapability(e){for(const t of ma){const n=ka[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 ma)if(!t||t.has(e))for(const t of Ia[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 Aa(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 ua(la.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 ua(la.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 ua(la.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 ua(la.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 ua(la.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 ua(la.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 ua(la.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Sa={recordSpan:()=>{}};function _a(e){try{Sa.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function xa(){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,_a({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 _a({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 ua?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function Ca(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ca);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ca(r);return t}return e}const Ta=new WeakMap;function Na(){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=Ca(s);else{const e=function(e){const t=Ta.get(e);if(t)return t;const n=b(e.inputSchema);return Ta.set(e,n),n}(r.spec);r.redactedInput=e.length>0?w(s,e):s}return await t()}}function Ma(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function Da(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Ma(t))}const Pa=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&&(Da(i,t)||n.push(`Expected type "${i}", got "${Ma(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&&(Da(i,r)||n.push(`Field "${t}": expected type "${i}", got "${Ma(r)}"`))}}return{ok:0===n.length,errors:n}}};let Oa=Pa;function Ra(){return Oa}function La(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=Ra().validate(s,i);if(!o.ok)throw new ua(la.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const $a=bo({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function ja(){return $a.get()}const Fa=["path","oldPath","newPath","src","dst","target","linkPath"];function Ba(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 qa(){try{return ja().cwd}catch{return}}function za(){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 Fa){const t=r[e];if("string"!=typeof t)continue;s||(i=qa(),s=!0);const n=Ba(t,i);if(!n.ok)throw new ua(la.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 Ua="encrypted-at-rest";function Va(){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 ja()}catch{return}}();if(!i)throw new ua(la.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:Ua,reason:"provider not registered"});if(!i.capabilities?.has(Ua))throw new ua(la.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${Ua}" capability flag`,{capability:n.name,required:Ua,reason:"capability not advertised"});return wo({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:Ua}}),t()}}function Wa(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 Ka(){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=Ea.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw Wa(o,c,"origin-not-allowed",t,a),new ua(la.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 Wa(o,c,"in-denylist",void 0,a),new ua(la.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 Wa(o,c,"not-in-allowlist",void 0,a),new ua(la.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Ga={alg:"HS256",typ:"PUNICA-APPROVAL"};class Ha extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function Ya(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 Ja(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 Za(e){return(new TextEncoder).encode(e)}function Qa(e){return Ya(Za(JSON.stringify(e)))}function Xa(e){return JSON.parse((t=Ja(e),(new TextDecoder).decode(t)));var t}function ec(){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 tc(){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 nc{#st;#ot;constructor(e){e?.secret instanceof Uint8Array?this.#st=e.secret:this.#st="string"==typeof e?.secret?Za(e.secret):tc()}async sign(e){const t=await this.#at(),n=Qa(Ga),r=Qa(e),i=Za(`${n}.${r}`),s=await ec().sign("HMAC",t,i);return`${n}.${r}.${Ya(new Uint8Array(s))}`}getSecret(){return this.#st}async#at(){return this.#ot||(this.#ot=await ec().importKey("raw",this.#st,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#ot}}class rc{#st;#ot;#ct=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#st=e.secret:this.#st="string"==typeof e?.secret?Za(e.secret):tc()}async verify(e){const t=e.split(".");if(3!==t.length)throw new Ha("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=Xa(n)}catch{throw new Ha("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new Ha("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=Xa(r)}catch{throw new Ha("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#at(),c=Za(`${n}.${r}`);let l;try{l=Ja(i)}catch{throw new Ha("MALFORMED","Token signature is not valid base64url")}const u=ec();if(!await u.verify("HMAC",a,l,c))throw new Ha("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new Ha("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new Ha("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 ec().importKey("raw",this.#st,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#ot}}let ic;function sc(){return ic||(ic=function(){const e=new nc,t=new rc({secret:e.getSecret()});return{signer:e,verifier:t}}()),ic}const oc=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function ac(){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 ua(la.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"===oc({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 sc().verifier.verify(s.policy.approvalToken)}catch(e){if(e instanceof Ha){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 ua(la.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 ua(la.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 ua(la.CAPABILITY_DENIED,f.reason??"Policy denied execution",{capability:i,decision:f});return await t()}}const cc=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 lc=cc;function uc(){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 ua(la.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=lc,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 ua(la.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 dc=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 pc(){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(!dc.consumeToken(c,a.perSecond))throw new ua(la.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const hc=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 fc(){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 hc.acquire(a,o.max)}catch(e){throw new ua(la.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{hc.release(a)}}}const mc=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 gc(){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=mc.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new ua(la.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 yc(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 bc(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new ua(la.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 wc(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 vc(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:wc(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(wc(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=ja()}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(wc(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 kc=new WeakMap;function Ic(e,t){if(!0===t.secretBearing)return Ec(e);const n=function(e){const t=kc.get(e);if(t)return t;const n=b(e.outputSchema);return kc.set(e,n),n}(t);return n.length>0?w(e,n):e}function Ec(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ec);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ec(r);return t}return e}function Ac(){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=Ic(r.output,o);await vc({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 Sc=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function _c(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const xc=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=da.getSpec(e),o=s?da.getProvider(e):void 0,a="core";if(!s){const t=Ea.getCapability(e);if(!t)throw _c({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 ua(la.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,s=ha(t.definition),o=Aa(t.origin,t.definition,t.metadata)}if(!o)throw new ua(la.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(s.requires)for(const t of s.requires)if(!da.hasCapability(t))throw new ua(la.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});s.deprecated&&_c({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 ua)throw e;throw new ua(la.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#ft(e){const t={auditTrail:Ac,traceMetrics:xa,redaction:Na,validateInput:La,pathTraversalGuard:za,encryptionRouting:Va,profileBudget:Ka,policyGate:ac,idempotency:uc,rateLimit:pc,concurrency:fc,circuitBreaker:gc,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 bc(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),h<=l&&d&&yc(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 Sc.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 Cc(e,t){const n=ja(),r=n[t];if("function"!=typeof r)throw new ua(la.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 Tc(e,t,n){const r=ja();if(!r.capabilities?.has(n))throw new ua(la.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 ua(la.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 Nc{name="fs.readFile";async execute(e,t){const n=ja();return await n.readFile(e.path)}}class Mc{name="fs.writeFile";async execute(e,t){const n=ja();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class Dc{name="fs.listFiles";async execute(e,t){const n=ja();return await n.getFileTree()}}class Pc{name="fs.stat";async execute(e,t){return await Cc("fs.stat","stat")(e.path)}}class Oc{name="fs.exists";async execute(e,t){return await Cc("fs.exists","exists")(e.path)}}class Rc{name="fs.copy";async execute(e,t){await Cc("fs.copy","copy")(e.src,e.dst)}}class Lc{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Cc("fs.mkdir","mkdir")(e.path,n)}}class $c{name="fs.history";async execute(e,t){return await Tc("fs.history","history","versioning")(e.path)}}class jc{name="fs.readAtVersion";async execute(e,t){return await Tc("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class Fc{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Cc("fs.list","list")(e.path,n)}}const Bc=bo({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 qc(){return Bc.get()}function zc(e){Bc.set(e),e&&wo({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class Uc{name="secrets.get";async execute(e,t){return qc().get(e.name)}}class Vc{name="secrets.set";async execute(e,t){qc().set(e.name,e.value)}}function Wc(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Ao]=!0,n}class Kc{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=Wc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class Gc{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=Wc(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 Hc{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 Yc{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 Jc{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 Zc{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 Qc{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 Xc{name="workspace.readFile";async execute(e,t){const n=ja();return await n.readFile(e.path)}}class el{name="workspace.writeFile";async execute(e,t){const n=ja();await n.createFileWithContent(e.path,e.content)}}class tl{name="workspace.listFiles";async execute(e,t){const n=ja(),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 nl{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 rl{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 il{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 sl{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 ol{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 al="capability.catalog";class cl{name=al;async execute(e,t){const n=e??{},r=Ea.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>ll(e,n));return{capabilities:r,count:r.length}}}function ll(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=ul(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=ul(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=ul(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 ul(e){return Array.isArray(e)?e:[e]}const dl=["examples","$comment","default","title"];function pl(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 hl=["properties","patternProperties","definitions","$defs"];function fl(e){if(Array.isArray(e))return e.map(e=>fl(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!dl.includes(n))if("description"!==n||"string"!=typeof r){if(hl.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=fl(n);t[n]=e;continue}t[n]=fl(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const ml="capability.schemaExport";class gl{name=ml;async execute(e,t){const n=e??{},r=n.filter??{},i=Ea.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>ll(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=pl(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=fl(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=pl(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 yl(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return[];const i=Ea.listCapabilities();if(0===i.length)return[];const s=function(e,t){const n=vl(wl(e));return t.map(e=>({...e,score:kl(n,vl(wl(e.text)))}))}(r,i.map(e=>({id:e.definition.id,description:e.definition.description,text:bl(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 Eo("llm.recommendIntent",{intent:r,limit:n,path:"text-similarity",topIds:o.map(e=>e.id),topScore:o[0]?.score??0}),o}function bl(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 wl(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(e=>e.length>0)}function vl(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function kl(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 Il="capability.recommend";class El{name=Il;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await yl(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 Al="capability.describe",Sl="capability.search";function _l(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class xl{name=Al;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new gl).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 Cl{name=Sl;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=Ea.listCapabilities(),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await yl(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:pl(t?.description??t?.title??e,100),category:_l(e)}});return{results:c,count:c.length}}}function Tl(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Nl(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 Ml{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Tl().create(n)}}}class Dl{name="ai.session.list";async execute(e,t){const n=Tl().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Pl{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Tl().get(n)}}}class Ol{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Tl().rename(String(n?.sessionId??""),String(n?.title??""))}}}class Rl{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Tl().archive(String(n?.sessionId??""),n?.archived)}}}class Ll{name="ai.session.delete";async execute(e,t){return{ok:Tl().delete(String(e?.sessionId??""))}}}const $l={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"}]}},jl={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"}]}},Fl=new Set(["low","medium","high"]),Bl={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&Fl.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"}]:[]}},ql=new Set(["none","plan","step"]),zl={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&ql.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 Ul={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"}]:[]}},Vl=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Wl={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Vl.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"}]}},Kl=new Set(["low","medium","high"]),Gl=["write","delete","remove","modify","destroy"],Hl=[$l,jl,Bl,zl,Ul,Wl,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Kl.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&&Gl.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 Yl=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 Hl)this.#gt.set(e.id,e)}},Jl="capability.lint";class Zl{name=Jl;async execute(e,t){const n=e??{},r=Ea.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=Yl.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 Ql={type:"object"};function Xl(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function eu(e){let t;return t=function(e){if(e instanceof ua)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:Xl(e),{content:[{type:"text",text:t}],isError:!0}}const tu="capability.serveList",nu="capability.serveCall",ru=new Set([tu,nu]);class iu{name=tu;async execute(e,t){const n=(e??{}).filter??{},r=Ea.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!ru.has(e.definition.id)).filter(e=>ll(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??Ql,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class su{name=nu;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||ru.has(r)||!Ea.getCapability(r))return eu(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:Xl(e)}],isError:!1}}(await xc.call(r,n.arguments??{},t))}catch(e){return eu(e)}}}const ou="shell.revealView",au="shell.hideView",cu="shell.listViews",lu="shell.toggleView",uu="shell.toggleSlot";function du(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new ua(la.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:ou});return e}function pu(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 hu{name=ou;async execute(e,t){const{viewId:n,focus:r}=e??{},i=du();if(!i.getPlacement(n))throw new ua(la.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:ou,viewId:n});return await i.reveal(n,pu(t),{focus:r}),{viewId:n,revealed:!0}}}class fu{name=au;async execute(e,t){const{viewId:n}=e??{};return du().hide(n,pu(t)),{viewId:n,hidden:!0}}}class mu{name=cu;async execute(e,t){return{views:du().listViews()}}}class gu{name=lu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=du();if(!i.getPlacement(n))throw new ua(la.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:lu,viewId:n});return"visible"===i.getState(n)?(i.hide(n,pu(t)),{viewId:n,visible:!1}):(await i.reveal(n,pu(t),{focus:r}),{viewId:n,visible:!0})}}const yu=new Map;class bu{name=uu;async execute(e,t){const{slot:n,focus:r}=e??{},i=du(),s=i.getVisibleView(n);if(s)return yu.set(n,s),i.hide(s,pu(t)),{slot:n,visible:!1,viewId:s};const o=yu.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,pu(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}function wu(e){try{da.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function vu(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 ku(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 Iu(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=Ea.getCapability(e.id);return t?void ku(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Ea.listCapabilities(n),i=r.map(vu);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)ku(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Eu(e){return Iu({...e,verbose:!0})}function Au(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 Su(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 _u(e){return JSON.stringify(e,null,2)}const xu=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{}}},Cu=16384,Tu="runtime:mcp:client";function Nu(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Mu(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 Mu(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=>Mu(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]=Mu(i,t+1);return n}return e}function Du(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=Cu)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Mu(e,0),null,2)??"null";if(r.length<=Cu)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,Cu)+"\n… [truncated]",bytes:n,truncated:!0}}function Pu(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const Ou=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 Bu}),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:Pu(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Nu(),s=Du(r??{});wo({name:"mcp.request",source:Tu,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:me().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Nu(),s=Date.now(),o=Du(r??{});wo({name:"mcp.request",source:Tu,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:me().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=Du(o??null);return wo({name:"mcp.response",source:Tu,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:me().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw wo({name:"mcp.response",source:Tu,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 Bb});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 qb});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}});xu.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(),xu.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})??{}}},Ru=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Lu(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(Ru):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 $u(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 zf}),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 ju(){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 zb}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await $u(e.id),n="stdio"===e.kind?Lu(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?Lu(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 Fu(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?Lu(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?Lu(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 Bu=Object.freeze({__proto__:null,loadMcpConfig:ju,loadServerOverrides:$u,parseStaticConfig:Fu,resolveEnvPlaceholders:Lu});class qu{name=Fe.MCP;version="1.0.0";dependencies=[je.EVENTS,Fe.FS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){this.#vt=t.BOOTSTRAPPING;const n=await ju();this.#kt(n),this.#vt=t.BOOTSTRAPPED}async#kt(e){for(const t of e)try{await Ou.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(e){this.#vt=t.STARTING,this.#vt=t.STARTED,console.log(`[Punica] MCP module started — ${xu.list().length} capability(ies) active`)}}const zu=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const Uu={get capabilities(){return $a.hasProvider()?$a.get().capabilities:void 0},get cwd(){return $a.hasProvider()?$a.get().cwd:void 0},getFileTree:()=>$a.get().getFileTree(),readFile:e=>$a.get().readFile(e),readBytes:(e,t,n)=>{const r=$a.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)=>$a.get().updateFileContent(e,t),createFolder:e=>$a.get().createFolder(e),deleteFolder:e=>$a.get().deleteFolder(e),deleteFile:(e,t)=>$a.get().deleteFile(e,t),renameFile:(e,t)=>$a.get().renameFile(e,t),renameFolder:(e,t)=>$a.get().renameFolder(e,t),createFileWithContent:(e,t)=>$a.get().createFileWithContent(e,t),list:(e,t)=>{const n=$a.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=$a.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=$a.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},Vu=function(e){return e||{query:e=>fo().query(e),startIndex:e=>{const t=fo();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(zu?.search),Wu=function(e){return e||{status:()=>yo().status(),branches:()=>yo().branches(),logs:e=>yo().logs(e),init:e=>yo().init(e),clone:e=>yo().clone(e),commit:e=>yo().commit(e),stage:e=>yo().stage(e),unstage:e=>yo().unstage(e),discard:e=>yo().discard(e),reset:e=>yo().reset(e),switchBranch:e=>yo().switchBranch(e),createBranch:(e,t)=>yo().createBranch(e,t),fetch:e=>yo().fetch(e),pull:e=>yo().pull(e),push:e=>yo().push(e)}}(zu?.vcs),Ku=function(e){return e||{create:e=>mo().create(e),write:(e,t)=>mo().write(e,t),resize:(e,t,n)=>mo().resize(e,t,n),close:e=>mo().close(e),onData:(e,t)=>mo().onData(e,t),onExit:(e,t)=>mo().onExit(e,t),list:()=>mo().list()}}(zu?.terminals),Gu=function(e){return e||{start:e=>go().start(e),send:(e,t)=>go().send(e,t),onMessage:(e,t)=>go().onMessage(e,t),onStderr:(e,t)=>go().onStderr(e,t),onExit:(e,t)=>go().onExit(e,t),stop:e=>go().stop(e),list:()=>go().list()}}(zu?.debug),Hu=function(e){return e||{run:e=>function(){if(co)return co;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return co=e,co}().run(e)}}(zu?.tasks),Yu=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&Io(e),{getCurrent:()=>vo.get().getCurrent(),list:()=>vo.get().list(),open:e=>vo.get().open(e),setEnvironment:(e,t)=>vo.get().setEnvironment(e,t),onDidChange:e=>vo.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(zu?.workspace),Ju=function(e){return e||{list:async e=>ho().list(e),get:e=>ho().get(e),register:e=>ho().register(e),unregister:e=>ho().unregister(e),onDidChange:e=>ho().onDidChange(e)}}(zu?.resources),Zu=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&To(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){(_o&&_o!==e||xo&&t&&xo!==t)&&B.publishEvent({name:"llm.providerChanged",envelope:{id:B.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:_o,newProviderId:e,previousEndpoint:xo,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),_o=e,t&&(xo=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??B.createCorrelationId(),s=le.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!s.allowed)throw s.requiresApproval&&le.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:i}),B.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:B.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 B.publishEvent({name:"llm.remoteRequestSent",envelope:{id:B.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=Co(),o=!0===e?.[Ao];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??B.createCorrelationId(),o=le.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw B.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:B.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&&le.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)");B.publishEvent({name:"llm.remoteRequestSent",envelope:{id:B.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=Co();let o=e;if(!(!0===e?.[Ao])&&("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}(zu?.llm),Qu=function(e){if(e)return e;const t=Do(),n=new Po(t),r=new qo(t,n);t.registerLanguageRuntime(Ro),t.registerLanguageRuntime(Lo),t.registerLanguageRuntime($o),t.registerLanguageRuntime(jo),t.registerLanguageRuntime(Fo);const i=new Map;return{async*run(e,t){const n=t?.runId??Bo("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}}(zu?.compute),Xu=function(e){if(e)return e;const t=Vo(),n=new Wo(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}(zu?.datasets),ed=function(e){if(e)return e;const t=Ho(),n=new Yo(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}(zu?.models),td=function(e){if(e)return e;const t=Qo();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)}}}(zu?.modelRuntimes),nd=function(e){if(e)return e;const t=Qo();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)}}}(zu?.inference),rd=function(e){return e||{upsert:(e,t)=>aa().upsert(e,t),query:e=>aa().query(e),delete:(e,t)=>aa().delete(e,t),clear:e=>aa().clear(e),count:e=>aa().count(e)}}(zu?.vectors),id=function(e){if(e)return e;function t(){const e=ca().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=ca().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:()=>ca().dataDir(),dataFs:{list:(e,t)=>ca().dataFs.list(e,t),readFile:e=>ca().dataFs.readFile(e),stat:e=>ca().dataFs.stat(e),mkdir:(e,t)=>ca().dataFs.mkdir(e,t),deleteFile:e=>ca().dataFs.deleteFile(e),deleteFolder:e=>ca().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=ca().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=ca().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=ca().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 oa?.mcpServer?r:void 0}}}(zu?.host),sd=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&zc(e);return{set:(e,t)=>Bc.get().set(e,t),get:e=>Bc.get().get(e),delete:e=>Bc.get().delete(e),list:()=>Bc.get().list(),__punicaWrappedSecretsFacade:!0}}(zu?.secrets);console.log("[Runtime] Facades created"),function(){wu({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}}),da.registerProvider(new Nc),wu({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"}}),da.registerProvider(new Mc),wu({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}}),da.registerProvider(new Dc),wu({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}}),da.registerProvider(new Pc),wu({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}}),da.registerProvider(new Oc),wu({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"}}),da.registerProvider(new Rc),wu({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"}}),da.registerProvider(new Lc),wu({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}}),da.registerProvider(new Fc),wu({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}}),da.registerProvider(new $c),wu({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}}),da.registerProvider(new jc),wu({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}}),da.registerProvider(new Uc),wu({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"}}),da.registerProvider(new Vc),wu({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}}}),da.registerProvider(new Kc),wu({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}}}),da.registerProvider(new Gc),wu({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}}}),da.registerProvider(new Yc),wu({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}}}),da.registerProvider(new Hc),wu({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}}),da.registerProvider(new Jc),wu({name:"vcs.status",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),da.registerProvider(new Zc),wu({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"}}),da.registerProvider(new Qc),wu({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}}),da.registerProvider(new Xc),wu({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"}}),da.registerProvider(new el),wu({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}}),da.registerProvider(new tl),wu({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"}}),da.registerProvider(new nl),wu({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"}}),da.registerProvider(new rl),wu({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"}}),da.registerProvider(new il),wu({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}}),da.registerProvider(new sl),wu({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"}}),da.registerProvider(new ol),wu({name:al,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}}),da.registerProvider(new cl),wu({name:ml,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}}),da.registerProvider(new gl),wu({name:Il,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}}),da.registerProvider(new El),wu({name:Sl,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}}),da.registerProvider(new Cl),wu({name:Al,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}}),da.registerProvider(new xl);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Nl("ai.session.create",{properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),Nl("ai.session.list",{properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),Nl("ai.session.get",{required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),Nl("ai.session.rename",{required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),Nl("ai.session.archive",{required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),Nl("ai.session.delete",{risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())wu(e);for(const e of[new Ml,new Dl,new Pl,new Ol,new Rl,new Ll])da.registerProvider(e);wu({name:Jl,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}}),da.registerProvider(new Zl),wu({name:tu,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}}),da.registerProvider(new iu),wu({name:nu,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}}),da.registerProvider(new su),wu({name:ou,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}}),da.registerProvider(new hu),wu({name:au,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}}),da.registerProvider(new fu),wu({name:cu,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}}),da.registerProvider(new mu),wu({name:lu,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}}),da.registerProvider(new gu),wu({name:uu,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}}),da.registerProvider(new bu)}(),console.log("[Runtime] Capabilities registered");const od={lifecyclePhase:zu?.lifecyclePhase??"bootstrapping",fs:Uu,fileOpeners:zu?.fileOpeners??so,search:Vu,vcs:Wu,terminals:Ku,debug:Gu,tasks:Hu,workspace:Yu,resources:Ju,secrets:sd,llm:Zu,compute:Qu,datasets:Xu,models:ed,modelRuntimes:td,inference:nd,vectors:rd,host:id,capabilities:{gateway:xc,unifiedRegistry:Ea,logTrinityCatalog:Iu,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(_u(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(_u(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(`## ${Au(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(Su(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:xu,connect:e=>Ou.connect(e),disconnect:e=>Ou.disconnect(e),listServers:()=>Ou.listServers(),listTools:e=>Ou.listTools(e),callTool:(e,t,n)=>Ou.callTool(e,t,n)},setFsProvider:function(e){$a.set(e),e&&wo({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:To,setComputeProvider:function(e){Do().registerProvider(e)},setComputeRuntime:function(e){Do().registerLanguageRuntime(e)},setDatasetProvider:function(e){Vo().registerProvider(e)},setModelProvider:function(e){Ho().registerProvider(e)},setModelRuntime:function(e){Qo().register(e)},setHostProvider:function(e){oa=e},setVectorsProvider:function(e){ia=e},setSearchProvider:function(e){ao=e},setWorkspaceProvider:Io,setTerminalProvider:function(e){lo=e},setDebugProvider:function(e){uo=e},setVcsProvider:function(e){po=e},setResourcesProvider:function(e){oo=e},setTasksProvider:function(e){co=e},setSecretsProvider:zc};class ad{#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 cd=class{#Et;constructor(e){this.#Et=e}async execute(){return await this.#Et.execute()}},ld=class extends cd{constructor(e){super(e)}async execute(){return await super.execute()}},ud=class extends cd{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))}}},dd=class extends cd{constructor(e){super(e)}async execute(){return await super.execute()}};const pd=Symbol.for("yaml.alias"),hd=Symbol.for("yaml.document"),fd=Symbol.for("yaml.map"),md=Symbol.for("yaml.pair"),gd=Symbol.for("yaml.scalar"),yd=Symbol.for("yaml.seq"),bd=Symbol.for("yaml.node.type"),wd=e=>!!e&&"object"==typeof e&&e[bd]===pd,vd=e=>!!e&&"object"==typeof e&&e[bd]===hd,kd=e=>!!e&&"object"==typeof e&&e[bd]===fd,Id=e=>!!e&&"object"==typeof e&&e[bd]===md,Ed=e=>!!e&&"object"==typeof e&&e[bd]===gd,Ad=e=>!!e&&"object"==typeof e&&e[bd]===yd;function Sd(e){if(e&&"object"==typeof e)switch(e[bd]){case fd:case yd:return!0}return!1}function _d(e){if(e&&"object"==typeof e)switch(e[bd]){case pd:case fd:case gd:case yd:return!0}return!1}const xd=Symbol("break visit"),Cd=Symbol("skip children"),Td=Symbol("remove node");function Nd(e,t){const n=Od(t);if(vd(e)){Md(null,e.contents,n,Object.freeze([e]))===Td&&(e.contents=null)}else Md(null,e,n,Object.freeze([]))}function Md(e,t,n,r){const i=Rd(e,t,n,r);if(_d(i)||Id(i))return Ld(e,r,i),Md(e,i,n,r);if("symbol"!=typeof i)if(Sd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Md(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===xd)return xd;i===Td&&(t.items.splice(e,1),e-=1)}}}else if(Id(t)){r=Object.freeze(r.concat(t));const e=Md("key",t.key,n,r);if(e===xd)return xd;e===Td&&(t.key=null);const i=Md("value",t.value,n,r);if(i===xd)return xd;i===Td&&(t.value=null)}return i}async function Dd(e,t){const n=Od(t);if(vd(e)){await Pd(null,e.contents,n,Object.freeze([e]))===Td&&(e.contents=null)}else await Pd(null,e,n,Object.freeze([]))}async function Pd(e,t,n,r){const i=await Rd(e,t,n,r);if(_d(i)||Id(i))return Ld(e,r,i),Pd(e,i,n,r);if("symbol"!=typeof i)if(Sd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await Pd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===xd)return xd;i===Td&&(t.items.splice(e,1),e-=1)}}}else if(Id(t)){r=Object.freeze(r.concat(t));const e=await Pd("key",t.key,n,r);if(e===xd)return xd;e===Td&&(t.key=null);const i=await Pd("value",t.value,n,r);if(i===xd)return xd;i===Td&&(t.value=null)}return i}function Od(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 Rd(e,t,n,r){return"function"==typeof n?n(e,t,r):kd(t)?n.Map?.(e,t,r):Ad(t)?n.Seq?.(e,t,r):Id(t)?n.Pair?.(e,t,r):Ed(t)?n.Scalar?.(e,t,r):wd(t)?n.Alias?.(e,t,r):void 0}function Ld(e,t,n){const r=t[t.length-1];if(Sd(r))r.items[e]=n;else if(Id(r))"key"===e?r.key=n:r.value=n;else{if(!vd(r)){const e=wd(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Nd.BREAK=xd,Nd.SKIP=Cd,Nd.REMOVE=Td,Dd.BREAK=xd,Dd.SKIP=Cd,Dd.REMOVE=Td;const $d={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},jd=e=>e.replace(/[!,[\]{}]/g,e=>$d[e]);class Fd{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Fd.defaultYaml,e),this.tags=Object.assign({},Fd.defaultTags,t)}clone(){const e=new Fd(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Fd(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Fd.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Fd.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Fd.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Fd.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+jd(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&&_d(e.contents)){const t={};Nd(e.contents,(e,n)=>{_d(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 Bd(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 qd(e){const t=new Set;return Nd(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function zd(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function Ud(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=Ud(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=Ud(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=Ud(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=Ud(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function Vd(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Vd(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Ed(r=e)&&!Sd(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)}Fd.defaultYaml={explicit:!1,version:"1.2"},Fd.defaultTags={"!!":"tag:yaml.org,2002:"};class Wd{constructor(e){Object.defineProperty(this,bd,{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(!vd(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=Vd(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?Ud(i,{"":o},"",o):o}}class Kd extends Wd{constructor(e){super(pd),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Nd(e,{Node:(e,n)=>{if(n===this)return Nd.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||(Vd(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=Gd(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(Bd(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 Gd(e,t,n){if(wd(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Sd(t)){let r=0;for(const i of t.items){const t=Gd(e,i,n);t>r&&(r=t)}return r}if(Id(t)){const r=Gd(e,t.key,n),i=Gd(e,t.value,n);return Math.max(r,i)}return 1}const Hd=e=>!e||"function"!=typeof e&&"object"!=typeof e;class Yd extends Wd{constructor(e){super(gd),this.value=e}toJSON(e,t){return t?.keep?this.value:Vd(this.value,e,t)}toString(){return String(this.value)}}Yd.BLOCK_FOLDED="BLOCK_FOLDED",Yd.BLOCK_LITERAL="BLOCK_LITERAL",Yd.PLAIN="PLAIN",Yd.QUOTE_DOUBLE="QUOTE_DOUBLE",Yd.QUOTE_SINGLE="QUOTE_SINGLE";function Jd(e,t,n){if(vd(e)&&(e=e.contents),_d(e))return e;if(Id(e)){const t=n.schema[fd].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 Kd(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 Yd(e);return c&&(c.node=t),t}l=e instanceof Map?o[fd]:Symbol.iterator in Object(e)?o[yd]:o[fd]}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 Yd(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Zd(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 Jd(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 Qd=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class Xd extends Wd{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=>_d(t)||Id(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Qd(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Sd(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,Zd(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(Sd(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&&Ed(i)?i.value:i:Sd(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Id(t))return!1;const n=t.value;return null==n||e&&Ed(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!!Sd(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(Sd(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,Zd(this.schema,r,t))}}}}Xd.maxFlowStringSingleLineLength=60;const ep=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function tp(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const np=(e,t,n)=>e.endsWith("\n")?tp(n,t):n.includes("\n")?"\n"+tp(n,t):(e.endsWith(" ")?"":" ")+n,rp="flow",ip="block",sp="quoted";function op(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===ip&&(m=ap(e,m,t.length),-1!==m&&(h=m+c));for(let r;r=e[m+=1];){if(n===sp&&"\\"===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===ip&&(m=ap(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===sp){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===sp&&u[i]&&(b+=`${e[i]}\\`),b+=`\n${t}${e.slice(i+1,s)}`)}return b}function ap(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 cp=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),lp=e=>/^(%|---|\.\.\.)/m.test(e);function up(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(lp(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:op(o,s,sp,cp(t,!1))}function dp(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return up(e,t);const n=t.indent||(lp(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:op(r,n,rp,cp(t,!1))}function pp(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=up;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?dp:i&&!t?up:n?dp:up}return r(e,t)}let hp;try{hp=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{hp=/\n+(?!\n|$)/g}function fp({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 pp(n,r);const l=r.indent||(r.forceBlockIndent||lp(n)?" ":""),u="literal"===o||"folded"!==o&&t!==Yd.BLOCK_FOLDED&&(t===Yd.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(hp,`$&${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}${op(`${b}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${h}`,l,ip,cp(r,!0))}`}function mp(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!==Yd.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Yd.QUOTE_DOUBLE);const c=e=>{switch(e){case Yd.BLOCK_FOLDED:case Yd.BLOCK_LITERAL:return i||s?pp(o.value,t):fp(o,t,n,r);case Yd.QUOTE_DOUBLE:return up(o.value,t);case Yd.QUOTE_SINGLE:return dp(o.value,t);case Yd.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 pp(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?pp(s,t):fp(e,t,n,r);if(!a&&!u&&i!==Yd.PLAIN&&s.includes("\n"))return fp(e,t,n,r);if(lp(s)){if(""===c)return t.forceBlockIndent=!0,fp(e,t,n,r);if(a&&c===l)return pp(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 pp(s,t)}return a?d:op(d,c,rp,cp(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 gp(e,t){const n=Object.assign({blockQuote:!0,commentString:ep,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 yp(e,t,n,r){if(Id(e))return e.toString(t,n,r);if(wd(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=_d(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(Ed(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=(Ed(e)||Sd(e))&&e.anchor;s&&Bd(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):Ed(s)?mp(s,t,n,r):s.toString(t,n,r);return o?Ed(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function bp(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function wp(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&vp(n))if(r=wd(r)?r.resolve(e.doc):r,Ad(r))for(const n of r.items)kp(e,t,n);else if(Array.isArray(r))for(const n of r)kp(e,t,n);else kp(e,t,r);else{const i=Vd(n,"",e);if(t instanceof Map)t.set(i,Vd(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(_d(e)&&n?.doc){const t=gp(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)+'..."'),bp(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=Vd(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const vp=e=>"<<"===e||Ed(e)&&"<<"===e.value&&(!e.type||e.type===Yd.PLAIN);function kp(e,t,n){const r=e&&wd(n)?n.resolve(e.doc):n;if(!kd(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 Ip(e,t,n){const r=Jd(e,void 0,n),i=Jd(t,void 0,n);return new Ep(r,i)}class Ep{constructor(e,t=null){Object.defineProperty(this,bd,{value:md}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return _d(t)&&(t=t.clone(e)),_d(n)&&(n=n.clone(e)),new Ep(t,n)}toJSON(e,t){return wp(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=_d(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Sd(e)||!_d(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||Sd(e)||(Ed(e)?e.type===Yd.BLOCK_FOLDED||e.type===Yd.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=yp(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+=np(w,n.indent,l(p)):b&&i&&i(),w;y&&(p=null),h?(p&&(w+=np(w,n.indent,l(p))),w=`? ${w}\n${a}:`):(w=`${w}:`,p&&(w+=np(w,n.indent,l(p)))),_d(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||!Ed(t)||(n.indentAtStart=w.length+1),b=!1,u||!(c.length>=2)||n.inFlow||h||!Ad(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let v=!1;const k=yp(t,n,()=>v=!0,()=>b=!0);let I=" ";if(p||f||m)I=f?"\n":"",m&&(I+=`\n${tp(l(m),n.indent)}`),""!==k||n.inFlow?I+=`\n${n.indent}`:"\n"===I&&(I="\n\n");else if(!h&&Sd(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+=np(w,n.indent,l(g)):b&&i&&i(),w}(this,e,t,n):JSON.stringify(this)}}function Ap(e,t,n){return(t.inFlow??e.flow?_p:Sp)(e,t,n)}function Sp({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(_d(i))!d&&i.spaceBefore&&p.push(""),xp(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(Id(i)){const e=_d(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),xp(n,p,e.commentBefore,d))}d=!1;let a=yp(i,u,()=>o=null,()=>d=!0);o&&(a+=np(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"+tp(l(e),c),a&&a()):d&&o&&o(),h}function _p({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(_d(i))i.spaceBefore&&d.push(""),xp(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(Id(i)){const e=_d(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),xp(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=_d(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=yp(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=np(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 xp({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=tp(t(r),e);n.push(i.trimStart())}}function Cp(e,t){const n=Ed(t)?t.value:t;for(const r of e)if(Id(r)){if(r.key===t||r.key===n)return r;if(Ed(r.key)&&r.key.value===n)return r}}class Tp extends Xd{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(fd,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(Ip(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=Id(e)?e:e&&"object"==typeof e&&"key"in e?new Ep(e.key,e.value):new Ep(e,e?.value);const r=Cp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Ed(r.value)&&Hd(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=Cp(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=Cp(this.items,e),r=n?.value;return(!t&&Ed(r)?r.value:r)??void 0}has(e){return!!Cp(this.items,e)}set(e,t){this.add(new Ep(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)wp(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!Id(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})),Ap(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Np={collection:"map",default:!0,nodeClass:Tp,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(kd(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Tp.from(e,t,n)};class Mp extends Xd{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(yd,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Dp(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Dp(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Ed(r)?r.value:r}has(e){const t=Dp(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Dp(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Ed(r)&&Hd(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(Vd(e,String(r++),t));return n}toString(e,t,n){return e?Ap(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(Jd(s,void 0,n))}}return i}}function Dp(e){let t=Ed(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const Pp={collection:"seq",default:!0,nodeClass:Mp,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Ad(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Mp.from(e,t,n)},Op={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>mp(e,t=Object.assign({actualString:!0},t),n,r)},Rp={identify:e=>null==e,createNode:()=>new Yd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Yd(null),stringify:({source:e},t)=>"string"==typeof e&&Rp.test.test(e)?e:t.options.nullStr},Lp={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Yd("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Lp.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function $p({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 jp={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:$p},Fp={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():$p(e)}},Bp={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 Yd(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:$p},qp=e=>"bigint"==typeof e||Number.isInteger(e),zp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Up(e,t,n){const{value:r}=e;return qp(r)&&r>=0?n+r.toString(t):$p(e)}const Vp={identify:e=>qp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>zp(e,2,8,n),stringify:e=>Up(e,8,"0o")},Wp={identify:qp,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>zp(e,0,10,n),stringify:$p},Kp={identify:e=>qp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>zp(e,2,16,n),stringify:e=>Up(e,16,"0x")},Gp=[Np,Pp,Op,Rp,Lp,Vp,Wp,Kp,jp,Fp,Bp];function Hp(e){return"bigint"==typeof e||Number.isInteger(e)}const Yp=({value:e})=>JSON.stringify(e),Jp=[Np,Pp].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Yp},{identify:e=>null==e,createNode:()=>new Yd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Yp},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:Yp},{identify:Hp,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})=>Hp(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:Yp}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),Zp={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=Yd.BLOCK_LITERAL),t!==Yd.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===Yd.BLOCK_LITERAL?"\n":" ")}return mp({comment:e,type:t,value:a},r,i,s)}};function Qp(e,t){if(Ad(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Id(r)){if(kd(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Ep(new Yd(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]=Id(r)?r:new Ep(r)}}else t("Expected a sequence for this tag");return e}function Xp(e,t,n){const{replacer:r}=n,i=new Mp(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(Ip(o,a,n))}return i}const eh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Qp,createNode:Xp};class th extends Mp{constructor(){super(),this.add=Tp.prototype.add.bind(this),this.delete=Tp.prototype.delete.bind(this),this.get=Tp.prototype.get.bind(this),this.has=Tp.prototype.has.bind(this),this.set=Tp.prototype.set.bind(this),this.tag=th.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(Id(e)?(r=Vd(e.key,"",t),i=Vd(e.value,r,t)):r=Vd(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=Xp(e,t,n),i=new this;return i.items=r.items,i}}th.tag="tag:yaml.org,2002:omap";const nh={collection:"seq",identify:e=>e instanceof Map,nodeClass:th,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=Qp(e,t),r=[];for(const{key:e}of n.items)Ed(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new th,n)},createNode:(e,t,n)=>th.from(e,t,n)};function rh({value:e,source:t},n){return t&&(e?ih:sh).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const ih={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 Yd(!0),stringify:rh},sh={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 Yd(!1),stringify:rh},oh={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:$p},ah={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():$p(e)}},ch={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 Yd(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:$p},lh=e=>"bigint"==typeof e||Number.isInteger(e);function uh(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 dh(e,t,n){const{value:r}=e;if(lh(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return $p(e)}const ph={identify:lh,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>uh(e,2,2,n),stringify:e=>dh(e,2,"0b")},hh={identify:lh,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>uh(e,1,8,n),stringify:e=>dh(e,8,"0")},fh={identify:lh,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>uh(e,0,10,n),stringify:$p},mh={identify:lh,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>uh(e,2,16,n),stringify:e=>dh(e,16,"0x")};class gh extends Tp{constructor(e){super(e),this.tag=gh.tag}add(e){let t;t=Id(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Ep(e.key,null):new Ep(e,null);Cp(this.items,t.key)||this.items.push(t)}get(e,t){const n=Cp(this.items,e);return!t&&Id(n)?Ed(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=Cp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ep(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(Ip(e,null,n));return i}}gh.tag="tag:yaml.org,2002:set";const yh={collection:"map",identify:e=>e instanceof Set,nodeClass:gh,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>gh.from(e,t,n),resolve(e,t){if(kd(e)){if(e.hasAllNullValues(!0))return Object.assign(new gh,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function bh(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 wh(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return $p(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 vh={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})=>bh(e,n),stringify:wh},kh={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=>bh(e,!1),stringify:wh},Ih={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(Ih.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=bh(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$/,"")},Eh=[Np,Pp,Op,Rp,ih,sh,ph,hh,fh,mh,oh,ah,ch,Zp,nh,eh,yh,vh,kh,Ih],Ah=new Map([["core",Gp],["failsafe",[Np,Pp,Op]],["json",Jp],["yaml11",Eh],["yaml-1.1",Eh]]),Sh={binary:Zp,bool:Lp,float:Bp,floatExp:Fp,floatNaN:jp,floatTime:kh,int:Wp,intHex:Kp,intOct:Vp,intTime:vh,map:Np,null:Rp,omap:nh,pairs:eh,seq:Pp,set:yh,timestamp:Ih},_h={"tag:yaml.org,2002:binary":Zp,"tag:yaml.org,2002:omap":nh,"tag:yaml.org,2002:pairs":eh,"tag:yaml.org,2002:set":yh,"tag:yaml.org,2002:timestamp":Ih};function xh(e,t){let n=Ah.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(Ah.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=Sh[e];if(t)return t;const n=Object.keys(Sh).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const Ch=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Th{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?xh(e,"compat"):e?xh(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?_h:{},this.tags=xh(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,fd,{value:Np}),Object.defineProperty(this,gd,{value:Op}),Object.defineProperty(this,yd,{value:Pp}),this.sortMapEntries="function"==typeof s?s:!0===s?Ch:null}clone(){const e=Object.create(Th.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Nh{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,bd,{value:hd});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 Fd({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Nh.prototype,{[bd]:{value:hd}});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=_d(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Mh(this.contents)&&this.contents.add(e)}addIn(e,t){Mh(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=qd(this);e.anchor=!t||n.has(t)?zd(t||"a",n):t}return new Kd(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=qd(e));const s=zd(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Ed(t.node)&&!Sd(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=Jd(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&Sd(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 Ep(r,i)}delete(e){return!!Mh(this.contents)&&this.contents.delete(e)}deleteIn(e){return Qd(e)?null!=this.contents&&(this.contents=null,!0):!!Mh(this.contents)&&this.contents.deleteIn(e)}get(e,t){return Sd(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Qd(e)?!t&&Ed(this.contents)?this.contents.value:this.contents:Sd(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!Sd(this.contents)&&this.contents.has(e)}hasIn(e){return Qd(e)?void 0!==this.contents:!!Sd(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=Zd(this.schema,[e],t):Mh(this.contents)&&this.contents.set(e,t)}setIn(e,t){Qd(e)?this.contents=t:null==this.contents?this.contents=Zd(this.schema,Array.from(e),t):Mh(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 Fd({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 Fd({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 Th(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=Vd(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?Ud(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=gp(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(tp(t,""))}let o=!1,a=null;if(e.contents){if(_d(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(tp(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=yp(e.contents,i,()=>a=null,t);a&&(c+=np(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(yp(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(tp(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(tp(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Mh(e){if(Sd(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Dh extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Ph extends Dh{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Oh extends Dh{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Rh=(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 Lh(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 $h(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($h(t.key)||$h(t.value))return!0}return!1;default:return!0}}function jh(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&$h(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function Fh(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Ed(t)&&Ed(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const Bh="All mapping items must start at the same column";function qh(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 zh="Block collections are not allowed within flow collections",Uh=e=>e&&("block-map"===e.type||"block-seq"===e.type);function Vh(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??Tp)(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=Lh(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",Bh)),!h.anchor&&!h.tag&&!d){c=h.end,h.comment&&(o.comment?o.comment+="\n"+h.comment:o.comment=h.comment);continue}(h.hasNewlineAfterProp||$h(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",Bh);const m=h.end,g=u?e(n,u,h,i):t(n,m,l,null,h,i);n.schema.compat&&jh(r.indent,u,i),Fh(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Lh(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&&jh(r.indent,p,i),a=c.range[2];const l=new Ep(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 Ep(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??Mp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Lh(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&&jh(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?Tp:Mp))(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=Lh(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&&$h(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];Id(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);Uh(p)&&i(g.range,"BLOCK_IN_FLOW",zh);const y=Lh(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?Uh(f)&&i(b.range,"BLOCK_IN_FLOW",zh):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const w=new Ep(g,b);if(n.options.keepSourceTokens&&(w.srcToken=l),o){const e=c;Fh(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(w)}else{const e=new Tp(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],Uh(f)&&i(r.range,"BLOCK_IN_FLOW",zh)}}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=qh(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 Wh(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?Yd.BLOCK_FOLDED:Yd.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===Yd.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 Kh(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=Yd.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 Gh(e)}(s,l);break;case"single-quoted-scalar":a=Yd.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Gh(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=Yd.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}=Hh(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=Yh[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+=Jh(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=qh(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Gh(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 Hh(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 Yh={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function Jh(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 Zh(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?Wh(e,t,r):Kh(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[gd];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[gd]}(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[gd];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[gd];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[gd];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Ed(s)?s:new Yd(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new Yd(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 Qh(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 Xh={composeNode:ef,composeEmptyNode:tf};function ef(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 Kd(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=qh(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=Zh(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===Tp.tagName&&"map"===o||s===Mp.tagName&&"seq"===o||!o)return Vh(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),Vh(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=Vh(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=_d(l)?l:new Yd(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(Xh,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=tf(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 tf(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=Zh(e,{type:"scalar",offset:Qh(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 nf(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 rf(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 sf{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=nf(e);r?this.warnings.push(new Oh(i,t,n)):this.errors.push(new Ph(i,t,n))},this.directives=new Fd({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=rf(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(Sd(i)&&!i.flow&&i.items.length>0){let e=i.items[0];Id(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:rf(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=nf(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 Nh(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Lh(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?ef(l,i,u,o):tf(l,u.end,r,null,u,o);const d=c.contents.range[2],p=qh(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 Ph(nf(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 Ph(nf(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=qh(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 Ph(nf(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 Nh(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 of(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 af(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 cf(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=cf(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=lf(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=lf(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=lf(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 lf({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=cf(t)),n)for(const e of n)i+=e.source;return r&&(i+=cf(r)),i}const uf=Symbol("break visit"),df=Symbol("skip children"),pf=Symbol("remove item");function hf(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),ff(Object.freeze([]),e,t)}function ff(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=ff(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===uf)return uf;r===pf&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}hf.BREAK=uf,hf.SKIP=df,hf.REMOVE=pf,hf.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},hf.parentCollection=(e,t)=>{const n=hf.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 mf="\ufeff",gf="",yf="",bf="";function wf(e){switch(e){case mf:return"byte-order-mark";case gf:return"doc-mode";case yf:return"flow-error-end";case bf: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 vf=Object.freeze({__proto__:null,BOM:mf,DOCUMENT:gf,FLOW_END:yf,SCALAR:bf,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=mp({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 of(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 mf:return"<BOM>";case gf:return"<DOC>";case yf:return"<FLOW_END>";case bf: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 Ph([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Kh(e,t,r);case"block-scalar":return Wh({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=mp({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}];of(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'"':af(e,c,"double-quoted-scalar");break;case"'":af(e,c,"single-quoted-scalar");break;default:af(e,c,"scalar")}},stringify:e=>"type"in e?cf(e):lf(e),tokenType:wf,visit:hf});function kf(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const If=new Set("0123456789ABCDEFabcdef"),Ef=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Af=new Set(",[]{}"),Sf=new Set(" ,[]{}\n\r\t"),_f=e=>!e||Sf.has(e);class xf{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)&&kf(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]===mf&&(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 gf,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&&kf(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&kf(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!kf(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)&&kf(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(_f),"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("..."))&&kf(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield yf,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(_f),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||kf(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=>kf(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 bf,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(kf(t)||e&&Af.has(t))break;n=r}else if(kf(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&&Af.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&&Af.has(t))break;n=r}return t||this.atEnd?(yield bf,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(_f))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(kf(t)||e&&Af.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(;!kf(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(Ef.has(t))t=this.buffer[++e];else{if("%"!==t||!If.has(this.buffer[e+1])||!If.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 Cf{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 Tf(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Nf(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 Mf(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 Df(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 Pf(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 Of(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Tf(t.start,"explicit-key-ind")||Tf(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Mf(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 Rf{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 xf,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=wf(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&&Of(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===Nf(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!==Nf(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=Pf(Df(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(Tf(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(Mf(t.key)&&!Tf(t.sep,"newline")){const e=Pf(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(Tf(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Pf(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]}):Tf(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||Tf(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=Pf(Df(t));Of(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=Pf(Df(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=Pf(Df(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 Lf(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new Cf||null,prettyErrors:t}}function $f(e,t={}){const{lineCounter:n,prettyErrors:r}=Lf(t),i=new Rf(n?.addNewLine),s=new sf(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(Rh(e,n)),t.warnings.forEach(Rh(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function jf(e,t={}){const{lineCounter:n,prettyErrors:r}=Lf(t),i=new Rf(n?.addNewLine),s=new sf(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 Ph(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(Rh(e,n)),o.warnings.forEach(Rh(e,n))),o}function Ff(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=jf(e,n);if(!i)return null;if(i.warnings.forEach(e=>bp(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 Bf(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 Nh(e,r,n).toString(n)}var qf=Object.freeze({__proto__:null,Alias:Kd,CST:vf,Composer:sf,Document:Nh,Lexer:xf,LineCounter:Cf,Pair:Ep,Parser:Rf,Scalar:Yd,Schema:Th,YAMLError:Dh,YAMLMap:Tp,YAMLParseError:Ph,YAMLSeq:Mp,YAMLWarning:Oh,isAlias:wd,isCollection:Sd,isDocument:vd,isMap:kd,isNode:_d,isPair:Id,isScalar:Ed,isSeq:Ad,parse:Ff,parseAllDocuments:$f,parseDocument:jf,stringify:Bf,visit:Nd,visitAsync:Dd}),zf=Object.freeze({__proto__:null,Alias:Kd,CST:vf,Composer:sf,Document:Nh,Lexer:xf,LineCounter:Cf,Pair:Ep,Parser:Rf,Scalar:Yd,Schema:Th,YAMLError:Dh,YAMLMap:Tp,YAMLParseError:Ph,YAMLSeq:Mp,YAMLWarning:Oh,default:qf,isAlias:wd,isCollection:Sd,isDocument:vd,isMap:kd,isNode:_d,isPair:Id,isScalar:Ed,isSeq:Ad,parse:Ff,parseAllDocuments:$f,parseDocument:jf,stringify:Bf,visit:Nd,visitAsync:Dd});class Uf{#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=qf.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=qf.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 qf.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Vf{#Et;constructor(e){this.#Et=e}async execute(){return await this.#Et.execute()}}class Wf{#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 Kf{}class Gf extends Kf{#_t;constructor(e){super(),this.#_t=e}execute(){}}let Hf=class extends Vf{#xt;constructor(e){super(e),this.#xt=new Wf,this.#xt.register("onExtension",Gf),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}},Yf=class extends Vf{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 Jf(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 Zf=class extends Vf{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:[Jf(n)],when:r})})}return e}},Qf=class extends Vf{constructor(e){super(e)}async execute(){return await super.execute()}},Xf=class extends Vf{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=od.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 em extends Vf{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 tm=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 nm=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 rm(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 im=new Map;function sm(e){const t=im.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),im.delete(e)}const om={register(e,t,n){const r=n?.target??document.head,i=im.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),im.set(e,i),{id:e,dispose(){sm(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),im.set(e,s),{id:e,dispose(){sm(e)}}},unregister(e){sm(e)},has:e=>!!im.has(e)||!!document.getElementById(e)};const am={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=Yl.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 Uf(e),n=new Yf(t),r=new Zf(n),i=new Qf(r),s=new Xf(i),o=new em(s);return new Hf(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"),rm("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new ad(e),n=new ud(t),r=new dd(n);return new ld(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 mn(()=>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"),rm("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#Ut.set(e,"failed"),rm("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=Ra().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 ua(la.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 ua(la.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 ua(la.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"),rm("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),rm("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:om,metadata:{manager:tm},settings:{manager:nm}};function cm(e){if(null==e)return!1;if(Array.isArray(e))return e.some(cm);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(cm)}return!1}function lm(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=um(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=um(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?cm(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 um(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 dm{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await ko().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=ja();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 pm(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=lm(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 pm(e,t){for(const n of e)n.isDirectory?n.children&&pm(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let hm;function fm(){return hm||(hm=new dm),hm}function mm(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 gm(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 ym(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 bm=/token|secret|key|password|passwd|api[_-]?key/i;function wm(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=bm.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 vm(e,t){const n=Date.now(),r=fm().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=lm(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(cm(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=mm(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 gm(I,E,s,t.timeoutMs),n=wm(ym(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 km(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Im(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function Em(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Am(e,t){const n=e.value;switch(e.type){case"isType":return{passed:Im(t)===String(n??""),expected:String(n??""),actual:Im(t)};case"equals":return{passed:Em(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=>Em(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:Im(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:Im(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):Im(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:Im(t)}}}function Sm(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=km(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=Am(a,r);else if("string"==typeof a)o=Am({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=Am({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 _m(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 xm(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 Cm(){return Date.now()}function Tm(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Nm(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function Mm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}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&&"gateway"in t)return t.gateway}}function Pm(){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 Om(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 Rm(e){try{const t=Dm();if(!t)throw new Error("[FlowEngine] Capability gateway not available. Gateway is mandatory for all FS operations.");{const r=await n();await t.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 Lm(e,t){const r=Dm();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 n();await r.call("fs.writeFile",{path:e,content:t},{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 $m(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:Cm(),source:i?.source??"flow:engine",kind:n},payload:r})}const jm=new Set(["sensitive","secret"]);function Fm(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Bm(e,t,n,r){if(!function(e,t,n){return!(!n||!jm.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:Fm(e)}}const qm=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 zm{async ensureBase(){await Rm(".punica"),await Rm(Mm(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await Rm(Mm(".punica","workflow-runs",e)),await Rm(Mm(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=Cm();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=Bm(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=Mm(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let h;h=d?String(u??""):Tm(l??{},2);const f=n.sizeBudget?.maxBytes;if(c||"number"!=typeof f)"number"==typeof f&&qm.acquire(e,h.length,f);else{qm.acquire(e,h.length,f)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,h.length),h=Tm(c,2),qm.acquire(e,h.length,f))}await Lm(p,h);const m=h.length,g=Nm(d?String(u??""):Tm(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 $m("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function Um(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 Vm(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Wm(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 Km(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 Gm(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 Hm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Ym(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 Jm(e,t,n){const r=Ym(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 Zm(e,t){const n=Ym(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 Qm(e,t){const n=Ym(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 Xm(e,t=".punica"){const n=Hm(t,"workflow-runs",e.runId),r=Hm(n,"checkpoint.json"),i=Hm(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await Zm("writeCheckpoint",n),await Jm("writeCheckpoint",i,s);try{await async function(e,t,n){const r=Ym(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 Qm("writeCheckpoint",r)}catch{}await Jm("writeCheckpoint",r,s);try{await Qm("writeCheckpoint",i)}catch{}}}async function eg(e,t=".punica"){const n=Hm(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=Ym(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 tg(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 ng{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:Cm(),startedAtMs:Cm(),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=Wm(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}),$m("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),tg({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",$m("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 eg(e);if(!n)return!1;{const r=n.dependencyGraphState?Wm(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"),$m("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=Cm();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 $m("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),$m("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=Mm(".punica","workflow-runs",e,"run.json");await Lm(n,Tm({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=Mm(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Lm(e,Tm({version:1,updatedAtMs:Cm(),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 Xm(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=Mm(".punica","workflow-runs","index.json"),t=await async function(e){const t=Dm();if(!t)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 n();return await t.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(t)try{const e=JSON.parse(t);$m("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class rg{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:Cm()};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:Cm(),resolved:!1},$m("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",$m("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}),$m("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),tg({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{}$m("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:Cm()},{traceId:i.runId}),tg({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",$m("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;$m("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:Cm()},{traceId:r.runId}),tg({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=Cm(),$m("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}),$m("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 ig=3e4,sg={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const og=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 ag(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function cg(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 lg=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 ug(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 dg(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=ug(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function pg(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 hg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fg(e){return String(e??"").split(".").filter(e=>e.length>0)}function mg(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];hg(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function gg(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={...hg(e.defaults)?e.defaults:{},...hg(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?fg(e.fromPath):[],i=r.length?ug(t,r):t;if(void 0===i)continue;const o=e.toPath?fg(e.toPath):[];o.length?mg(s,o,i):hg(i)?Object.assign(s,i):s[e.fromId]=i}return s}class yg 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 bg(e,t){if(function(e){return!0===e.cancelled}(e))throw new yg(e.run?.runId,t)}class wg{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=Dm();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",$m("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=Cm(),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}),$m("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}),tg({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:gg(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),$m("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}),tg({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",$m("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",$m("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=Cm(),a.error={message:o},$m("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}),tg({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=Cm(),n.run.error={message:o,nodeId:s,correlationId:c},$m("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),$m("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),tg({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=cg(f,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",$m("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=Cm(),$m("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),$m("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),tg({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=Hm(n,"workflow-runs",e.runId),i=Hm(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await Zm("writeRunHistory",r),await Jm("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=Hm(t,"workflow-runs",e,"checkpoint.json");try{await Qm("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;!Vm(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=Um(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=>{Gm(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 Km(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Km(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;){bg(r),h++,l.attempt=h,l.status="RUNNING",l.startedAtMs=Cm();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:gg(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 yg)throw l.status="CANCELLED",l.endedAtMs=Cm(),e;const t=String(e?.message??e);if(h<=d){const e=cg(h,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=Cm(),l.error={message:t},e}}f&&(Km(o,!0,n),await this.persistRun(e))}catch(t){Km(o,!1,n),t instanceof yg||(r.run.status="FAILED",r.run.endedAtMs=Cm(),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=Cm(),$m("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),$m("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),tg({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&&(tg({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=lg.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:ig,retry:{...sg},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=lg.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,ag(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=Cm(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return lg.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class vg 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 kg(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new vg(e??0,t);return n}const Ig="__default__";class Eg{workspaceId;#sn=new Map;#on=new Map;#an=new Map;#cn=new zm;#ke=!1;#ln=new Map;#un;#dn;#pn;constructor(e=Ig){this.workspaceId=e,this.#un=new ng(this.#sn,this.#ln,this.#cn),this.#dn=new rg(this.#sn,this.#on,this.#an,e=>this.#un.persistRun(e),()=>this.#un.persistIndex(),e=>this.#hn(e)),this.#pn=new wg(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=kg(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;tg({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 Ag=new Map,Sg=new Map,_g=new Map;function xg(e){const t=e??Ig;let n=Ag.get(t);return n||(n=new Eg(t),Ag.set(t,n)),n}let Cg=!1;const Tg=new class{initialize(){if(Cg)return;Cg=!0;const e=punica.kernel.Commands.manager;e.registerCommand(Ke.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(Ke.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(Ke.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(Ke.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(Ke.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(Ke.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(Ke.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(Ke.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(Ke.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:Ig}(e),n=xg(t);n.initialize();const r=await n.startRun(e);return Sg.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 Ag.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(kg(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=xg(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Sg.set(n.runId,t.workspaceId),n}#gn(e){const t=Sg.get(e);if(t)return Ag.get(t);for(const[t,n]of Ag.entries())if(n.hasRun(e))return Sg.set(e,t),n}#yn(e){const t=_g.get(e);if(t)return Ag.get(t);for(const[t,n]of Ag.entries())if(n.hasPending(e))return _g.set(e,t),n}};function Ng(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 Mg(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class Dg{packages=new Map;async discover(){this.packages.clear();try{if(!await ko().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=ja();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 Pg(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(!Mg(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 Pg(e,t){for(const n of e)n.isDirectory?n.children&&Pg(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let Og;function Rg(){return Og||(Og=new Dg),Og}const Lg=new Set(["COMPLETED","FAILED","CANCELLED"]);function $g(e){return new Promise(t=>setTimeout(t,e))}async function jg(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&&(Lg.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await $g(250)}return{record:i,timedOut:!0}}async function Fg(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(_m(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await jg(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(_m(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(_m(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(Sm(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(_m(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const Bg={validator:{validate:lm},registry:{discover:()=>fm().discover(),get:e=>fm().get(e),list:()=>fm().list(),search:e=>fm().search(e),setTestReport:(e,t)=>fm().setTestReport(e,t),getLatestTestReport:e=>fm().getLatestTestReport(e)},runner:{run:vm},test:{run:async function(e,t){const n=fm(),r=n.get(e);if(!r){if(t?.manifest){if(Mg(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=Tg,o=Ng(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 Fg(s,o,e,n,t?.workspaceId))}const l=xm({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{fm().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 vm(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=Sm(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=_m(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=xm({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}}},qg={discover:()=>Rg().discover(),get:e=>Rg().get(e),list:()=>Rg().list(),search:e=>Rg().search(e),unregister:e=>Rg().unregister(e),run:(e,t)=>async function(e,t){const n=Rg().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??Tg,i=t?.timeoutMs??3e4,s=Ng(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 jg(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:Ng,isAgentManifest:Mg},zg=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",[]]]),Ug=new Set(["COMPLETED","FAILED","CANCELLED"]);const Vg=new class{canTransitionTo(e,t){if(e===t)return!1;const n=zg.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 zg.get(e)??[]}isTerminal(e){return Ug.has(e)}},Wg=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Kg={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Gg={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function Hg(e){return{x:Gg.marginX+e%6*240,y:Gg.marginY+120*Math.floor(e/6)}}function Yg(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 Jg(e,t){const n={...Gg,...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]=Hg(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]=Hg(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,Yg(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 Zg;function Qg(e){if(!Zg)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 Zg}function Xg(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");Zg=e}function ey(){Zg=void 0}function ty(){return Zg}function ny(e){return Qg("createFlowRenderer").createRenderer(e)}function ry(e){return Qg("createViewportController").createViewportController(e)}function iy(e,t){return Qg("attachZoomControl").attachZoomControl(e,t)}function sy(e,t){return Qg("attachMinimap").attachMinimap(e,t)}function oy(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 ay={setRendererProvider:Xg,resetRendererProvider:ey,getRendererProvider:ty,createFlowRenderer:ny,createViewportController:ry,attachZoomControl:iy,attachMinimap:sy,mergeViewSnapshotIntoNotebook:oy,computeFlowLayout:Jg,gridFallbackPosition:Hg,get rendererProvider(){return Zg}},cy=Object.freeze({__proto__:null,attachMinimap:sy,attachZoomControl:iy,computeFlowLayout:Jg,createFlowRenderer:ny,createViewportController:ry,default:ay,getRendererProvider:ty,gridFallbackPosition:Hg,mergeViewSnapshotIntoNotebook:oy,resetRendererProvider:ey,setRendererProvider:Xg});function ly(e,t,n){return{path:e,message:t,severity:"error",code:n}}function uy(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const dy="WF_INVALID_VERSION",py="WF_INVALID_EDGE_REF",hy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function fy(e){return"string"==typeof e&&hy.test(e)}const my=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()}},gy={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}},yy={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}},by={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}},wy={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 vy(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function ky(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 Iy={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=vy(o.ref),l=vy(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=ky(p,s.fromPath),m=ky(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}},Ey=["while","forEach"],Ay={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(!Ey.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 Sy(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+Sy(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const _y={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Sy(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}},xy=[gy,yy,by,wy,Iy,Ay,_y];const Cy=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 xy)this.#gt.set(e.id,e)}};function Ty(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 Ny(e){return e.map(e=>`${e.from}=>${e.to}`)}function My(e,t){return`${e}=>${t}`}const Dy=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(My(e.from,e.to),e)}unregister(e,t){return this.#wn.delete(My(e,t))}find(e,t){return this.#wn.get(My(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(!fy(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(!fy(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)=>Ty(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:Ny(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:Ny(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:Ny(a)}}return{ok:!0,document:o,appliedTransformers:Ny(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Ty(this.#wn,e,t)}};function Py(){return Date.now()}class Oy{#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:Py()}),{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:Py()}))}}}unregister(e){const t=this.#je.get(e);return!!t&&(t.unsubscribed=!0,this.#je.delete(e),this.#vn({type:"unregistered",triggerId:e,ts:Py()}),!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-${Py()}-${Math.floor(1e6*Math.random())}`,i=Py();this.#vn({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),tg({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:Py(),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 Ry=new Oy;let Ly=Ry;const $y={get manager(){return Ly},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()");Ly!==e&&Ly instanceof Oy&&Ly.clear(),Ly=e},resetProvider(){Ly instanceof Oy&&Ly.clear(),Ly=Ry}};function jy(e,t){return`${e}=>${t}`}const Fy={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(jy(e.from,e.to),e)}unregister(e,t){return this.#kn.delete(jy(e,t))}find(e,t){return this.#kn.get(jy(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}},By={...Bg,agents:qg,engine:{manager:Tg,statusStateMachine:Vg,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=Kg[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(Wg,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:cy,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(ly("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',dy)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(ly("kind",'kind must equal "Workflow"',dy)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!fy(o)){const e=ly("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(ly("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(ly("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(ly("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(ly(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(ly(`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(ly(`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(ly(`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(ly(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(ly(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(ly(`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(ly("graph.nodes","flow-input node is required when edges reference it")),h&&!d&&n.push(ly("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(ly("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(ly(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(ly(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(ly(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,py)),i&&!l.has(i)&&n.push(ly(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,py))}),"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(ly("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(uy(`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?ly:uy)(`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:my,linter:Cy,migrations:Dy,checkpoints:Fy},triggers:$y};class qy{name=ze.MANAGER;version="1.0.0";dependencies=[je.COMMANDS,je.EVENTS,Fe.WORKSPACE,Be.LAYOUT];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.COMMANDS),s=r.getState(je.EVENTS),o=r.getState(Fe.WORKSPACE),a=r.getState(Be.LAYOUT);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(s!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==t.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(a!==t.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 zy{name=qe.VALIDATOR;version="1.0.0";dependencies=[];#vt=t.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 Uy(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 Vy{prepareExecutionConfig(e){const t=Uy(e);if(!t)return{};const n=Pm(),r=n?.getSpec?.(t);return{capabilityDefaults:Om(r)}}async acquireResources(e,t,n){const r=Uy(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 og.acquire(n,e.concurrency.max),()=>{og.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=Uy(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Dm();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=Pm(),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:Nm(Tm(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Wy(e){return e.data??{}}function Ky(e){return e.nodeOutputs??new Map}async function Gy(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:Nm(Tm(i,0),320),artifactIds:[s.id]}}class Hy{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=Wy(e),i=dg(r.predicate,Ky(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:pg(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Gy(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Gy(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Wy(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=dg(r.collection,Ky(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 Gy(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Wy(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=dg(r.predicate,Ky(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=pg(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Gy(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Wy(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 Gy(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Gy(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Gy(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Wy(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=my.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=dg(r.input,Ky(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:Nm(Tm(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 Yy{async execute(e,t){return{output:t.runInput??null}}}class Jy{async execute(e,t){return{output:t.resolvedInput??null}}}let Zy=!1;class Qy{name=qe.ENGINE;version="1.0.0";dependencies=[je.EVENTS,je.POLICY,je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.EVENTS),s=r.getState(je.POLICY),o=r.getState(je.COMMANDS);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(s!==t.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(Zy||(lg.register("ivyNode",new Vy),lg.register("primitive",new Hy),lg.register("flowInput",new Yy),lg.register("flowOutput",new Jy),Zy=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class Xy{name=qe.SHELL;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 eb{name=je.EVENTS;version="1.0.0";dependencies=[];#vt=t.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 tb{name=je.COMMANDS;version="1.0.0";dependencies=[];#vt=t.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 nb{name=je.POLICY;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 rb{name=je.HISTORY;version="1.0.0";dependencies=[];#vt=t.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 ib{name=je.TIME_SERVER;version="1.0.0";dependencies=[];#vt=t.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 sb{name=je.TASKS;version="1.0.0";dependencies=[Fe.TERMINALS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(Fe.TERMINALS),s=r.getState(Fe.WORKSPACE);if(i!==t.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(s!==t.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 ob{name=je.NOTIFICATIONS;version="1.0.0";dependencies=[];#vt=t.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 ab{name=je.AI;version="1.0.0";dependencies=[je.EVENTS,je.POLICY,je.LLM];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.EVENTS),s=r.getState(je.POLICY),o=r.getState(je.LLM);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(s!==t.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==t.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 cb=class{name=je.LLM;version="1.0.0";dependencies=[je.EVENTS,je.POLICY];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.EVENTS),s=r.getState(je.POLICY);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(s!==t.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:Ht,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class lb{name=Fe.FS;version="1.0.0";dependencies=[];#vt=t.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 ub{name=Fe.SEARCH;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 db{name=Fe.VCS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 pb{name=Fe.WORKSPACE;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 hb{name=Fe.LLM;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 fb{name=Fe.TASKS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 mb{name=Fe.SECRETS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 gb{name=Fe.TERMINALS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 yb{name=Be.ACTIVITY_BAR;version="1.0.0";dependencies=[je.COMMANDS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.COMMANDS),s=r.getState(Fe.WORKSPACE);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.activityBar");if(s!==t.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 bb{name=Be.STATUSBAR;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 wb{name=Be.VIEW;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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 vb{name=Be.VIEWS;version="1.0.0";dependencies=[Be.LAYOUT,je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(Be.LAYOUT)!==t.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 kb{name=Be.KEYBOARD_SHORTCUTS;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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:[Jf(t)],when:r})};t("mod+j",Ue.TOGGLE_PANEL),t("mod+b",Ue.TOGGLE_PRIMARY_SIDEBAR),t("mod+l",Ue.TOGGLE_SECONDARY_SIDEBAR)}()}}class Ib{name=Be.LAYOUT;version="1.0.0";dependencies=[je.COMMANDS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.COMMANDS),s=r.getState(Fe.WORKSPACE);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.layout");if(s!==t.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 Eb{name=Be.CONTENT_TABS;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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 Ab{name=Be.PANEL_TABS;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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 Sb={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:"*"}},_b={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 xb(){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 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:"result"},payload:n})}function Tb(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 Nb(e,t,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await n(),actor:{type:"user",id:void 0},origin:{kind:t,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function Mb(){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=xb();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");Cb("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Nb("workspace.readFile","command",t))})}catch(e){Tb("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=xb();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await Nb("workspace.writeFile","command",t)),Cb("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Tb("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();Cb("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){Tb("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{Cb("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Nb("vcs.status","command",t))})}catch(e){Tb("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;Cb("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 Nb("tasks.runCommand","command",t))})}catch(e){Tb("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?Cb("capability.llm.invoke.result",t,r):Tb(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Tb(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?Cb("capability.llm.plan.result",t,r):Tb(n,t,r)}catch(e){Tb(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:\/\//,"");Cb(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 Gt(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 Cb(n,t,i)}else Cb(n,t,i);else Tb(r,t,i)}catch(e){Tb(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?Cb("capability.llm.validator.result",t,r):Tb(n,t,r)}catch(e){Tb(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?Cb("capability.llm.edit-workflow.result",t,r):Tb(n,t,r)}catch(e){Tb(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?Cb("capability.llm.reviewer.result",t,r):Tb(n,t,r)}catch(e){Tb(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 Nb("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(Ue.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(Ue.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(Ue.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Db="1.0.0",Pb=Zt,Ob=ro,Rb=od,Lb=am,$b=By,jb=new class{#In=new Map;#En=new Map;#An=new Map;register(e){if(this.#In.has(e.name))throw new Error(`Module ${e.name} already registered`);for(const t of e.dependencies)if(!this.#In.has(t))throw new Error(`Module ${e.name} depends on ${t}, but ${t} is not registered. Register dependencies before dependent modules.`);this.#In.set(e.name,e),this.#En.set(e.name,t.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 e=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${e.join(" → ")}`);for(const n of e){const e=this.#In.get(n);if(!e)throw new Error(`Module ${n} not found in registry`);try{this.#En.set(n,t.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await e.bootstrap(r),this.#En.set(n,t.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw this.#En.set(n,t.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 e=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${e.join(" → ")}`);for(const n of e){const e=this.#In.get(n);if(!e)throw new Error(`Module ${n} not found in registry`);const r=this.#En.get(n);if(r!==t.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#En.set(n,t.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await e.start(r),this.#En.set(n,t.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw this.#En.set(n,t.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 e){this.#En.get(n)===t.STARTED&&this.#En.set(n,t.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#En.get(e)}areAllModulesReady(){for(const[e,n]of this.#In){if(this.#En.get(e)!==t.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}},Fb={"shell.statusbar":()=>new bb,"shell.view":()=>new wb,"shell.views":()=>new vb,"shell.keyboardShortcuts":()=>new kb,"flow.shell":()=>new Xy,"shell.contentTabs":()=>new Eb,"shell.panelTabs":()=>new Ab,"shell.layout":()=>new Ib,"shell.activityBar":()=>new yb};var Bb=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 qb=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 zb=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return Fu(Ff(e))}});e.bootstrap=async function(e){try{console.log("[Punica] Starting module bootstrap...");const t=Ob.Profile.manager;t.registry.has("ivyx-classic")||t.registry.register(Sb),t.registry.has("agent-ops-console")||t.registry.register(_b),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{Ob.Layout.manager.applyApplicationProfile(n)}catch{}jb.register(new eb),jb.register(new tb),jb.register(new rb),jb.register(new ib),jb.register(new ob),jb.register(new zy),jb.register(new nb),jb.register(new cb),jb.register(new ab),jb.register(new Qy),jb.register(new lb),jb.register(new ub),jb.register(new db),jb.register(new pb),jb.register(new hb),jb.register(new mb),jb.register(new gb),jb.register(new fb),jb.register(new qu),jb.register(new sb);const r=t.getActiveModules();for(const e of r){const t=Fb[e];t&&(jb.register(t()),console.log(`[Punica] Shell module registered: ${e}`))}jb.register(new qy),console.log(`[Punica] Module registry initialized with ${jb.getAll().length} modules`),await jb.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}},e.extensions=Lb,e.flow=$b,e.initialize=function(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Db,kernel:Pb,shell:Ob,runtime:Rb,extensions:Lb,flow:$b};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e);const t=e.debug??{};t.logTrinityCatalog=Iu,t.logTrinityCatalogVerbose=Eu,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=Iu,n.logTrinityCatalogVerbose=Eu);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{Mb(),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}},e.kernel=Pb,e.runtime=Rb,e.shell=Ob,e.start=async function(){try{console.log("[Punica] Starting system..."),await jb.startAll(),jb.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:Db}}),console.log("[Punica] System started successfully"),Iu()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}},e.version=Db});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PunicaEditor={})}(this,function(e){"use strict";var t;!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"}(t||(t={}));async function n(){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 r(){return punica.runtime?.fs}const i={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 s=new class{async write(e){try{const t=r();if(!t)return;const n=".punica/audit";await t.createFolder(n).catch(()=>{});const i=new Date(e.timestamp).toISOString().split("T")[0],s=`${n}/${`${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=r();if(!t)return[];const n=".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,n),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 o={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:s};const a={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 c(){return(new Date).toISOString()}function l(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,a){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=c(),{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,a?.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:c(),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:c()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const u=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=l(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 d={manager:u},p=Object.freeze({__proto__:null,createTasksApi:l,default:d,manager:u});function h(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 f(e){return h(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 m=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function g(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||m.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function y(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))g(t)?r[t]=null==i?i:"[REDACTED]":r[t]=e(i);return r}(e)}(e);return f(JSON.stringify(n,null,t))}function b(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 w(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 v=6048e5,k={rules:[],defaultTtlMs:v};function I(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 E(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(I(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??v)}const A=".punica/events";let S={};function _(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(A)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function x(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 C=new class{#d;#p=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const t=r();if(!t)return;if(punica.runtime?.workspace&&!await n())return;const i=Date.now();try{await t.createFolder(A)}catch{}if(!this.#p){this.#p=!0;try{await t.createFileWithContent(`${A}/.gitignore`,"*\n!.gitignore\n")}catch{}}for(const n of e)try{const e=n.envelope?.timestampMs??Date.now(),r=new Date(e).toISOString().split("T")[0],i=n.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,s=`${A}/${r}_${i}.json`,o=y(n);await t.createFileWithContent(s,o)}catch{}try{S.onWrite?.(Date.now()-i,e.length)}catch{}}async query(e){const t=r();if(!t)return[];let n;try{n=await t.getFileTree()}catch{return[]}if(!Array.isArray(n))return[];const i=_(n),s=[];for(const n of i)try{const r=await t.readFile(n),i=JSON.parse(r);x(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=r();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const i=_(n);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(x(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 n=r();if(!n)return 0;let i;try{i=await n.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=_(i);let o=0;for(const r of s)try{const i=await n.readFile(r),s=JSON.parse(i),a=s.envelope?.timestampMs??0;a<E(s.name,e,t)&&(await n.deleteFile(r),o++)}catch{}return o}};let T=C;function N(){return T}const M=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 D=M;function P(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=D.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function O(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(I(e.name,t)){r=!0;break}if(!r)return!1}return!0}class R extends Error{constructor(e){super(e),this.name="EventReplayError"}}let L={exportSpan:()=>{}};function $(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function j(){return Date.now()}function F(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;function o(){try{S.onQueueDepthChange?.(i.length)}catch{}}async function a(){if(0===i.length)return;const e=[...i];i=[],o(),s&&(clearTimeout(s),s=null);try{await N().write(e),V()}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:$(),timestampMs:j()},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(O(o,t.filter))try{t.listener(o)}catch{}}}async function d(e){try{return await N().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:$,publishEvent:function(e){const t=P({id:e.envelope?.id??$(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??j(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{L.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=y(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??"",y(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 y({exportedAt:j(),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 R('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(!O(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 B=F();var q={manager:B};let z=k;function U(){return z}async function V(){try{const e=N(),t=U();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??v;return await e.delete({until:j()-n})??0}catch{return 0}}var W=Object.freeze({__proto__:null,createCorrelationId:$,createEventsApi:F,default:q,getRetentionConfig:U,manager:B,runEventRetentionCleanup:V,setRetentionConfig:function(e){z=e??k}});function K(){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 G=K();var H={manager:G},Y=Object.freeze({__proto__:null,createNotificationsApi:K,default:H,manager:G});const J="punica.kernel.policy.v2";function Z(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function Q(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class X{#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=Q(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=Z();if(e)try{const t=e.getItem(J);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=Q(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=Z();if(e)try{let t={};try{const n=e.getItem(J);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(J,JSON.stringify(n))}catch{}}}let ee=new X;function te(){return Date.now()}function ne(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function re(e){return`${e.kind}:${e.id}`}function ie(e,t){return"workspace"===e?`workspace:${t??""}`:e}function se(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const oe="punica.kernel.policy.v1",ae="punica.kernel.policy.v2";class ce{#y="execute";#b;#w=new Set;#v=new Map;#k=[];#I=1e3;constructor(e){this.#b=e??new X,this.#E()}#E(){const e=se();if(e)try{const t=e.getItem(ae);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(oe);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(oe)}catch{}return}}}catch{}}#g(){const e=se();if(e)try{let t={};try{const n=e.getItem(ae);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#y,exportedAt:te()};e.setItem(ae,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{B.publishEvent({name:e,envelope:{id:B.createCorrelationId(),timestampMs:te(),source:"kernel:policy",kind:n},payload:t})}catch{}}#S(e,t){return`${e}|${t}`}revokeApproval(e){const t=re({kind:e.kind,id:e.id}),n="workspace"===e.scope?ie("workspace",e.workspaceId):ie(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=te();return n.filter(e=>!ne(e,r))}hasApproval(e,t,n){const r=re(e),i="workspace"===t?n?.workspaceId?ie("workspace",n.workspaceId):null:ie(t);if(null===i)return!1;const s=this.#b.get(r,i);if(!s)return!1;if(ne(s,te())){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=re(e),i="workspace"===t?ie("workspace",n?.workspaceId):ie(t),s={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:te(),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:te(),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;B.publishEvent({name:"policy.evaluated",envelope:{id:B.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){B.publishEvent({name:"policy.approvalRequested",envelope:{id:B.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:te(),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?ie("workspace",r):ie(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(),B.publishEvent({name:"policy.stateImported",envelope:{id:B.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??te(),updatedAtMs:te()};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:te(),version:1,count:n.length,entries:n},null,2)}}const le=new ce(ee);var ue={manager:le},de=Object.freeze({__proto__:null,PolicyManager:ce,default:ue,manager:le});async function pe(e,t,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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:t,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=t,s=await n(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:t,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:t},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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:t,step:e}})}catch(n){const r=String(n?.message??n);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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:t,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:t,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:t,step:e}}),n}}}async function he(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 pe(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 fe={estimate:e=>Math.ceil(e.length/4)};function me(){return fe}function ge(e){const t=me();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 ye={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 be="[elided tool result:";function we(e){const t=(e.content??"").length;return`${be} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function ve(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 ke(e,t,n,r){const i=ge(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=ve(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(be)?{...e,content:we(e)}:e);let c=ge(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=ge(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 Ie=["capability.search","capability.describe"];function Ee(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function Ae(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Se(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 _e(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=Ee(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 xe(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function Ce(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function Te(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 Ne(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=Ee(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(xe).sort(Ce),deferredIndex:[]};const s=i.filter(e=>Ie.includes(String(e.id)));if(i=i.filter(e=>{return!Ie.includes(String(e.id))&&(!((n=String(e.id)).startsWith("ai.")||(n.startsWith("capability.")?!Ie.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(xe).sort(Ce),deferredIndex:[]};if(!1===t.deferToolLoading){return{hot:(await _e(e,i,t.query,n)).map(xe).sort(Ce),deferredIndex:[]}}const o="number"==typeof t.hotSetSize&&t.hotSetSize>0?Math.floor(t.hotSetSize):16,a=(await _e(e,i,t.query,n)).slice(0,o),c=new Set(a.map(e=>String(e.id))),l=s.length===Ie.length?s.map(xe):[{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:Te(e),category:Ee(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(xe)].sort(Ce),deferredIndex:u}}async function Me(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 De(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Re(n)}\nRejected arguments:\n${Re(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 Pe(e,t,n,r,i){let s=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Me(e,{...t,arguments:s},r,i);if("failed"!==l.status||!Ae(l.error))return o?{...l,arguments:s,repaired:!0}:l;if(a=l.error??"",2===c||i())break;const u=await De(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 Oe(e){return me().estimate(e)}function Re(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Le(e,t,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,ye[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,...e.images&&e.images.length>0?{images:e.images}:{}},...f];t&&n.push({role:"assistant",content:t});const r=n.map(e=>({id:"",createdAtMs:0,role:e.role,content:e.content??"",...e.images&&e.images.length>0?{images:e.images}:{},...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 Se("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),i};Se("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 n(),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 Ne(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(xe).sort(Ce);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,...e.images&&e.images.length>0?{images:e.images}:{}}),h=p.length;let P=0;for(let n=0;n<a;n++){if(t())return A("cancelled");let r,i=!1;if(ge(p)>c.maxContextTokens){const e=await ke(p,c,S,x);e.compacted&&(p.splice(0,p.length,...e.messages),P=0,i=!0,Se("ai.agentContextCompacted",o,"info",{runId:o,step:n,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const s=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:n,messageCount:p.length,toolsSent:T.length,toolChoice:"auto",toolNames:T.map(e=>e.name)});const t={stableToolsAndSystem:!0,stableMessagePrefix:P,cacheKey:o};r=await S("llm.chatStream",{messages:p,tools:T,toolChoice:"auto",correlationId:o,cacheHints:t,...e.profile?{profile:e.profile}:{}},x),P=p.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:n,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(t())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:n,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:n,estToolDefTokens:Oe(JSON.stringify(T)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+Oe(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+Oe(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)),Se("ai.agentTurnUsage",o,"info",{...O}),0===h.length)return u.push(m),Se("ai.agentStep",o,"info",{runId:o,turn:m}),A("final",l);u.push(m),Se("ai.agentStep",o,"info",{runId:o,turn:m});const R=h.map(e=>`${e.name}(${Re(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(t())return A("cancelled");if(Se("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 Pe(S,e,N.get(e.name),x,t);m.toolCalls.push(r),E++,"success"===r.status&&"capability.describe"===r.name&&D(r.resultPayload),console.log("[AgentLoop] tool dispatched",{step:n,name:r.name,arguments:r.arguments,status:r.status,repaired:r.repaired??!1,error:r.error,resultPreview:"success"===r.status?Re(r.resultPayload).slice(0,300):void 0}),Se("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const i={role:"tool",content:"success"===r.status?Re(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 $e(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 je={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"},Fe={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"},Be={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"},qe={SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},ze={MANAGER:"extensions.manager"},Ue={TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},Ve={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"},We={EXPORT:"policy.export",IMPORT:"policy.import",LIST_APPROVALS:"policy.listApprovals",SET_MODE:"policy.setMode",SHOW_MODE:"policy.showMode"},Ke={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 Ge(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 He(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 Ye="punica.kernel.ai.sessions.index.v1";function Je(e){return`punica.kernel.ai.session.${e}.v1`}function Ze(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const Qe=new class{readIndex(){const e=Ze();if(!e)return[];try{const t=e.getItem(Ye);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=Ze();if(t)try{t.setItem(Ye,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=Ze();if(t)try{const n=t.getItem(Je(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=Ze();if(t)try{t.setItem(Je(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=Ze();if(t)try{t.removeItem(Je(e))}catch{}}};let Xe=Qe;function et(){return Xe}const tt="New chat";function nt(){return Date.now()}function rt(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${nt().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function it(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:nt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function st(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function ot(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 at=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(We.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(We.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(We.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=$e(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(We.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(We.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`+$e(e,2))}}),t.registerCommand(Ve.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(Ve.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(Ve.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(Ve.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,r=Array.isArray(n?.images)&&n.images.length>0;n&&(n.query.trim()||r)&&e.runAgent(n).catch(e=>{console.error("[AI] agent run failed",e)})}}),t.registerCommand(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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(Ve.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"+$e(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+$e(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Ve.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;He("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:Ge(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();He("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:Ge(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),He("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){He("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 he(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 Le(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#M.delete(t)}}},ct=new class{#D;create(e){const t=et(),n={sessionId:rt("sess"),title:e?.title?.trim()||tt,createdAtMs:nt(),updatedAtMs:nt(),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),it("ai.sessionCreated",n),{...n}}list(e){const t=et().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return et().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&&(it("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#O(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(it("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=et(),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),it("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=et(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||rt("msg"),createdAtMs:e.createdAtMs||nt(),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=nt(),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===tt){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:tt}(e.content))}r.writeSession(i),this.#R(o),it("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=et().readSession(e);n&&(n.contextView=t,et().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=et().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(...st(n.messages).map(ot)),e}return st(t.transcript.slice(-40)).map(ot)}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=nt(),e.usage=n});return!!n&&(it("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#O(e,t){const n=et(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=nt(),n.writeSession(r),this.#R(r.meta),{...r.meta}}#R(e){const t=et(),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=et(),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),it("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};ct.setCompactor(function(){const e=ye.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=ve([{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(be)?{...e,content:we(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());var lt={manager:at,sessions:ct},ut=Object.freeze({__proto__:null,default:lt,manager:at,sessions:ct});const dt=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 pt(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 ht(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=dt.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 pt({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 ft(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 mt(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function gt(){const e=globalThis;return e.punica?.runtime?.fs}function yt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const bt={type:"ai",id:"llm:context"},wt={kind:"ai",id:"context-builder"};async function vt(e){if(e.filePath)try{const t=mt(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:bt,origin:wt,trace:{traceId:yt()},policy:{mode:"execute"}}):await(gt()?.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 kt(e){try{const t=mt(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:bt,origin:wt,trace:{traceId:yt()},policy:{mode:"execute"}}):await(gt()?.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 It(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Et(){return"undefined"==typeof document?void 0:document}function At(){const e=Et();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 St(e){try{const t=It();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=At();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 _t(){try{const e=It();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=At();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=Et();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 xt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Ct={type:"ai",id:"llm:context"},Tt={kind:"ai",id:"context-builder"};async function Nt(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:Ct,origin:Tt,trace:{traceId:xt()},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 Mt(){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 Dt(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 Pt="problems.getDiagnostics";function Ot(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===Pt))return;let r;try{r=t.executeCommand?.(Pt)}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 Rt(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 Lt=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=Rt(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 $t(e,t){const r=dt;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(ft(e)),vt(e),Promise.resolve(St(e)),kt(e),Nt(e),Mt(),Promise.resolve(_t()),Dt(e),Promise.resolve(Ot(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 ht(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,correlationId:t?.correlationId??punica.kernel.Events.manager.createCorrelationId()},c=!0===e.options?.stream?"llm.chatStream":"llm.chat";let l,u,d=0;const p=await n();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};Lt.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 jt(e){return $t({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 Ft(e){return $t({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function Bt(e){return $t({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 qt(e){return $t({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 zt(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 $t({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function Ut(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function Vt(e,t){const n=Ut(e).split("/").filter(Boolean),r=Ut(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function Wt(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function Kt(e,t){const n=Ut(e).split("/").filter(Boolean),r=Ut(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 Gt(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=Kt(t,Vt(t,Ut(r.path)));(e.startsWith("..")||Wt(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=Ut(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 Ht={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 Yt=new class{api;constructor(){this.api={instructionClassRegistry:dt,invoke:$t,plan:jt,generateCode:Ft,validator:Bt,reviewer:qt,editWorkflow:zt,listInstructionClasses:e=>dt.listSummaries(e)}}};var Jt={manager:Yt};const Zt={Commands:i,History:o,TimeServer:a,Tasks:p,Events:W,Notifications:Y,Policy:de,AI:ut,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:Ht,applyCodegenBundle:Gt,default:Jt,manager:Yt})};const Qt={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 Xt={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 en(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 tn={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("&lt;")?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:en,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=en(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 nn={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 rn=new class{currentProfileId=null;listeners=new Set;async loadProfile(e){const t=nn[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{...nn}}getProfile(e){return nn[e]}registerProfile(e){nn[e.id]=e}onDidChangeProfile(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDefaultImmediate(){const e=nn.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&&nn[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 sn(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 on(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 sn({title:s,message:n,tone:r,buttons:[{label:i,variant:"filled",color:"error"===r?"error":"primary",action:"ok"}]})}const an={showInformationMessage:async function(e,...t){return 0===t.length?void await on({message:e,variant:"info",title:"Information"}):await sn({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 on({message:e,variant:"warning",title:"Warning"}):await sn({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 on({message:e,variant:"error",title:"Error"}):await sn({title:"Error",message:e,buttons:t.map(e=>({label:e,variant:"outlined",action:e}))})},showDialog:sn,showConfirm:async function(e){const{title:t="Confirm",message:n,confirmLabel:r="OK",cancelLabel:i="Cancel",variant:s="info"}=e;return"confirm"===await sn({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:on,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`;sn({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=tn.createBadge({text:t.action,variant:"filled",color:"delete"===t.action?"error":"create"===t.action?"success":"primary",size:"small"}),i=tn.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=tn.createTypography(`This file will be deleted: ${t.path}`,{variant:"body"});return void e.appendChild(n)}if(!t.content){const t=tn.createTypography("No content preview available",{variant:"body"});return void e.appendChild(t)}const n=tn.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:tn,Theme:{manager:rn,profiles:nn}};function cn(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 ln(){return globalThis.punica?.shell?.Layout?.manager}function un(){return globalThis.punica?.shell?.ActivityBar?.manager}const dn={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),cn({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=ln();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{un()?.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)}cn({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=ln();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{un()?.setActiveByViewId?.(null)}catch{}cn({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),cn({name:"shell.view.hidden",source:"shell:views",payload:{viewId:t,slot:e,source:"host",sourceId:"slot-reset"}}))}#se(e){const t=ln();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=ln();i?.removeViewHost?.(t.slot,n)}}}};const pn={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 hn=0;function fn(){return hn>0}async function mn(e){hn++;try{return await e()}finally{hn>0&&hn--}}const gn={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"}]}},yn={id:"welcome",title:"Welcome",root:{type:"row",sizes:[100],children:[{type:"column",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]}]}},bn={type:"row",sizes:[100],children:[{type:"slot",id:"content",role:"content"}]};const wn={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=gn}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 fn()?(cn({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??bn;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?yn:gn,i=this.#ye.id===gn.id||this.#ye.id===yn.id;this.#fe.childElementCount?i&&this.#ye.id!==r.id&&this.applyProfile(r):this.applyProfile(r)}catch{this.#fe.childElementCount||this.applyProfile(this.#ye)}e.appendChild(this.#fe)}}};const vn=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 kn=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!!fn()&&(cn({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")}},In=[];function En(e){In.push(e)}function An(){const e={};for(const t of In)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function Sn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _n(e){return"string"==typeof e}function xn(e){return"string"==typeof e&&e.trim().length>0}function Cn(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const Tn=new Set(["shell.activityBar","shell.statusbar","shell.view","shell.views","shell.keyboardShortcuts","shell.layout","shell.contentTabs","shell.panelTabs","flow.shell"]),Nn=new Set(["light","dark","auto"]),Mn=new Set(["compact","comfortable"]),Dn=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const Pn=new class{validate(e){const t=[];if(!Sn(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)}`),Sn(e.identity)?(xn(e.identity.id)||t.push("identity.id must be a non-empty string"),xn(e.identity.name)||t.push("identity.name must be a non-empty string"),xn(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),Sn(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys(An()),r=new Set([...Tn,...n]);e.shell.activeModules.forEach((e,n)=>{_n(e)&&r.has(e)||t.push(`shell.activeModules[${n}] is not a valid ShellModuleId: ${JSON.stringify(e)}`)})}else t.push("shell.activeModules must be an array");void 0!==e.shell.layout&&(Sn(e.shell.layout)?(xn(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),Sn(e.shell.layout.root)||t.push("shell.layout.root must be an object")):t.push("shell.layout must be an object when provided"))}else t.push("shell must be an object");if(Sn(e.theme)?(Nn.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||Mn.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"),Sn(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||Cn(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||Cn(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)=>{_n(e)&&Dn.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 On{#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,cn({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Ke.has(e)}list(){return Array.from(this.#Ke.values())}}const Rn={manager:new class{registry=new On;get validator(){return Pn}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 cn({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),cn({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}},Ln={};function $n(e,t){"string"!=typeof t&&(t=$n.defaultChars);const n=function(e){let t=Ln[e];if(t)return t;t=Ln[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})}$n.defaultChars=";/?:@&=+$,#",$n.componentChars="";const jn={};function Fn(e,t,n){"string"!=typeof t&&(n=t,t=Fn.defaultChars),void 0===n&&(n=!0);const r=function(e){let t=jn[e];if(t)return t;t=jn[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 Bn(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 qn(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}Fn.defaultChars=";/?:@&=+$,-_.!~*'()#",Fn.componentChars="-_.!~*'()";const zn=/^([a-z0-9.+-]+:)/i,Un=/:[0-9]*$/,Vn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,Wn=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),Kn=["'"].concat(Wn),Gn=["%","/","?",";","#"].concat(Kn),Hn=["/","?","#"],Yn=/^[+a-z0-9A-Z_-]{0,63}$/,Jn=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,Zn={javascript:!0,"javascript:":!0},Qn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function Xn(e,t){if(e&&e instanceof qn)return e;const n=new qn;return n.parse(e,t),n}qn.prototype.parse=function(e,t){let n,r,i,s=e;if(s=s.trim(),!t&&1===e.split("#").length){const e=Vn.exec(s);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=zn.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&&Zn[o]||(s=s.substr(2),this.slashes=!0)),!Zn[o]&&(i||o&&!Qn[o])){let e,t,n=-1;for(let e=0;e<Hn.length;e++)r=s.indexOf(Hn[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<Gn.length;e++)r=s.indexOf(Gn[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(Yn)){let r="";for(let e=0,t=n.length;e<t;e++)n.charCodeAt(e)>127?r+="x":r+=n[e];if(!r.match(Yn)){const r=e.slice(0,t),i=e.slice(t+1),o=n.match(Jn);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),Qn[n]&&this.hostname&&!this.pathname&&(this.pathname=""),this},qn.prototype.parseHost=function(e){let t=Un.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 er,tr=Object.freeze({__proto__:null,decode:$n,encode:Fn,format:Bn,parse:Xn}),nr=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,rr=/[\0-\x1F\x7F-\x9F]/,ir=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\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]/,sr=/[\$\+<->\^`\|~\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]/,or=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,ar=Object.freeze({__proto__:null,Any:nr,Cc:rr,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:ir,S:sr,Z:or}),cr=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୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢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;怳Ādp໩໮uct;戏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ǣጓ\0጖y;䐎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Ā;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀ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Ā;e᜚᜜lƀ;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\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩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ↄⅪ←ٖ↛ǰ↉\0↎proø₞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;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\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\0⹻m;櫳;櫽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))),lr=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));const ur=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]]),dr=null!==(er=String.fromCodePoint)&&void 0!==er?er: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 pr;!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"}(pr||(pr={}));var hr,fr,mr;function gr(e){return e>=pr.ZERO&&e<=pr.NINE}function yr(e){return e>=pr.UPPER_A&&e<=pr.UPPER_F||e>=pr.LOWER_A&&e<=pr.LOWER_F}function br(e){return e===pr.EQUALS||function(e){return e>=pr.UPPER_A&&e<=pr.UPPER_Z||e>=pr.LOWER_A&&e<=pr.LOWER_Z||gr(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"}(hr||(hr={})),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"}(fr||(fr={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(mr||(mr={}));class wr{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=fr.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=mr.Strict}startEntity(e){this.decodeMode=e,this.state=fr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case fr.EntityStart:return e.charCodeAt(t)===pr.NUM?(this.state=fr.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=fr.NamedEntity,this.stateNamedEntity(e,t));case fr.NumericStart:return this.stateNumericStart(e,t);case fr.NumericDecimal:return this.stateNumericDecimal(e,t);case fr.NumericHex:return this.stateNumericHex(e,t);case fr.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===pr.LOWER_X?(this.state=fr.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=fr.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(!gr(r)&&!yr(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(!gr(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===pr.SEMI)this.consumed+=1;else if(this.decodeMode===mr.Strict)return 0;return this.emitCodePoint(function(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=ur.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==pr.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&hr.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const s=e.charCodeAt(t);if(this.treeIndex=kr(n,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return 0===this.result||this.decodeMode===mr.Attribute&&(0===i||br(s))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],i=(r&hr.VALUE_LENGTH)>>14,0!==i){if(s===pr.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==mr.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]&hr.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]&~hr.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case fr.NamedEntity:return 0===this.result||this.decodeMode===mr.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case fr.NumericDecimal:return this.emitNumericEntity(0,2);case fr.NumericHex:return this.emitNumericEntity(0,3);case fr.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case fr.EntityStart:return 0}}}function vr(e){let t="";const n=new wr(e,e=>t+=dr(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 kr(e,t,n,r){const i=(t&hr.BRANCH_LENGTH)>>7,s=t&hr.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 Ir=vr(cr);function Er(e){return"[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}vr(lr);const Ar=Object.prototype.hasOwnProperty;function Sr(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 _r(e,t,n){return[].concat(e.slice(0,t),n,e.slice(t+1))}function xr(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 Cr(e){if(e>65535){const t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}const Tr=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,Nr=new RegExp(Tr.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),Mr=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function Dr(e,t){if(35===t.charCodeAt(0)&&Mr.test(t)){const n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return xr(n)?Cr(n):e}const n=function(e,t=mr.Legacy){return Ir(e,t)}(e);return n!==e?n:e}function Pr(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(Nr,function(e,t,n){return t||Dr(e,n)})}const Or=/[&<>"]/,Rr=/[&<>"]/g,Lr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function $r(e){return Lr[e]}function jr(e){return Or.test(e)?e.replace(Rr,$r):e}const Fr=/[.?*+^$[\]\\(){}|-]/g;function Br(e){switch(e){case 9:case 32:return!0}return!1}function qr(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 zr(e){return ir.test(e)||sr.test(e)}function Ur(e){return zr(Cr(e))}function Vr(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 Wr(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}function Kr(e){return 32===e||9===e||10===e||13===e}function Gr(e){let t=0;for(;t<e.length&&Kr(e.charCodeAt(t));t++);let n=e.length-1;for(;n>=t&&Kr(e.charCodeAt(n));n--);return e.slice(t,n+1)}const Hr={mdurl:tr,ucmicro:ar};var Yr=Object.freeze({__proto__:null,arrayReplaceAt:_r,asciiTrim:Gr,assign:Sr,escapeHtml:jr,escapeRE:function(e){return e.replace(Fr,"\\$&")},fromCodePoint:Cr,has:function(e,t){return Ar.call(e,t)},isMdAsciiPunct:Vr,isPunctChar:zr,isPunctCharCode:Ur,isSpace:Br,isString:Er,isValidEntityCode:xr,isWhiteSpace:qr,lib:Hr,normalizeReference:Wr,unescapeAll:Pr,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(Tr,"$1")}});var Jr=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=Pr(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=Pr(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+=Pr(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+=Pr(e.slice(t,s)),o}});const Zr={};function Qr(){this.rules=Sr({},Zr)}function Xr(){this.__rules__=[],this.__cache__=null}function ei(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 ti(e,t,n){this.src=e,this.env=n,this.tokens=[],this.inlineMode=!1,this.md=t}Zr.code_inline=function(e,t,n,r,i){const s=e[t];return"<code"+i.renderAttrs(s)+">"+jr(s.content)+"</code>"},Zr.code_block=function(e,t,n,r,i){const s=e[t];return"<pre"+i.renderAttrs(s)+"><code>"+jr(e[t].content)+"</code></pre>\n"},Zr.fence=function(e,t,n,r,i){const s=e[t],o=s.info?Pr(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)||jr(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`},Zr.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)},Zr.hardbreak=function(e,t,n){return n.xhtmlOut?"<br />\n":"<br>\n"},Zr.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"<br />\n":"<br>\n":"\n"},Zr.text=function(e,t){return jr(e[t].content)},Zr.html_block=function(e,t){return e[t].content},Zr.html_inline=function(e,t){return e[t].content},Qr.prototype.renderAttrs=function(e){let t,n,r;if(!e.attrs)return"";for(r="",t=0,n=e.attrs.length;t<n;t++)r+=" "+jr(e.attrs[t][0])+'="'+jr(e.attrs[t][1])+'"';return r},Qr.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},Qr.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},Qr.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},Qr.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},Xr.prototype.__find__=function(e){for(let t=0;t<this.__rules__.length;t++)if(this.__rules__[t].name===e)return t;return-1},Xr.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))})})},Xr.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},Xr.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},Xr.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},Xr.prototype.push=function(e,t,n){const r=n||{};this.__rules__.push({name:e,enabled:!0,fn:t,alt:r.alt||[]}),this.__cache__=null},Xr.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},Xr.prototype.enableOnly=function(e,t){Array.isArray(e)||(e=[e]),this.__rules__.forEach(function(e){e.enabled=!1}),this.enable(e,t)},Xr.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},Xr.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},ei.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},ei.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]},ei.prototype.attrSet=function(e,t){const n=this.attrIndex(e),r=[e,t];n<0?this.attrPush(r):this.attrs[n]=r},ei.prototype.attrGet=function(e){const t=this.attrIndex(e);let n=null;return t>=0&&(n=this.attrs[t][1]),n},ei.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},ti.prototype.Token=ei;const ni=/\r\n?|\n/g,ri=/\0/g;function ii(e){return/^<a[>\s]/i.test(e)}function si(e){return/^<\/a\s*>/i.test(e)}const oi=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,ai=/\((c|tm|r)\)/i,ci=/\((c|tm|r)\)/gi,li={c:"©",r:"®",tm:"™"};function ui(e,t){return li[t.toLowerCase()]}function di(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(ci,ui)),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++}}function pi(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||oi.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 hi=/['"]/,fi=/['"]/g;function mi(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function gi(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;){fi.lastIndex=l;const o=fi.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=Vr(f)||Ur(f),y=Vr(m)||Ur(m),b=qr(f),w=qr(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]),mi(i,s,o.index,c),mi(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&&mi(i,s,o.index,"’")}else h&&mi(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 yi=[["normalize",function(e){let t;t=e.src.replace(ni,"\n"),t=t.replace(ri,"�"),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&&(ii(o.content)&&i>0&&i--,si(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=_r(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&&(ai.test(e.tokens[t].content)&&di(e.tokens[t].children),oi.test(e.tokens[t].content)&&pi(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&&hi.test(e.tokens[t].content)&&gi(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 bi(){this.ruler=new Xr;for(let e=0;e<yi.length;e++)this.ruler.push(yi[e][0],yi[e][1])}function wi(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(Br(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}bi.prototype.process=function(e){const t=this.ruler.getRules("");for(let n=0,r=t.length;n<r;n++)t[n](e)},bi.prototype.State=ti,wi.prototype.push=function(e,t,n){const r=new ei(e,t,n);return r.block=!0,n<0&&this.level--,r.level=this.level,n>0&&this.level++,this.tokens.push(r),r},wi.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},wi.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},wi.prototype.skipSpaces=function(e){for(let t=this.src.length;e<t;e++){if(!Br(this.src.charCodeAt(e)))break}return e},wi.prototype.skipSpacesBack=function(e,t){if(e<=t)return e;for(;e>t;)if(!Br(this.src.charCodeAt(--e)))return e+1;return e},wi.prototype.skipChars=function(e,t){for(let n=this.src.length;e<n&&this.src.charCodeAt(e)===t;e++);return e},wi.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},wi.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(Br(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("")},wi.prototype.Token=ei;function vi(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function ki(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 Ii(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(!Br(e.src.charCodeAt(r)))return-1}return r}function Ei(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),!Br(s))?-1:i}const Ai="<[A-Za-z][A-Za-z0-9\\-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^\"'=<>`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",Si="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",_i=new RegExp("^(?:"+Ai+"|"+Si+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|<![A-Za-z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)"),xi=new RegExp("^(?:"+Ai+"|"+Si+")"),Ci=[[/^<(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(xi.source+"\\s*$"),/^$/,!1]];const Ti=[["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&&!Br(a))return!1;if(45===o&&Br(a))return!1;for(;s<e.eMarks[i];){const t=e.src.charCodeAt(s);if(124!==t&&45!==t&&58!==t&&!Br(t))return!1;s++}let c=vi(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=vi(e,t).trim(),-1===c.indexOf("|"))return!1;if(e.sCount[t]-e.blkIndent>=4)return!1;l=ki(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=vi(e,i).trim(),!c)break;if(e.sCount[i]-e.blkIndent>=4)break;if(l=ki(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(!Br(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&&!Br(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=Ei(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=Ii(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=Ei(e,c),p<0)break;o=e.bMarks[c]+e.tShift[c]}else if(p=Ii(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(!Br(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(!Br(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(!Br(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i)&&m)for(m="",i=p,o=h;i<s;){if(!Br(c.charCodeAt(i)))break;i++}if(i<s&&10!==c.charCodeAt(i))return!1;const y=Wr(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<Ci.length&&!Ci[a][0].test(o);a++);if(a===Ci.length)return!1;if(r)return Ci[a][2];let c=t+1;const l=Ci[a][1].test("");if(!Ci[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),Ci[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&&!Br(o))return!1;if(r)return!0;s=e.skipSpacesBack(s,i);const c=e.skipCharsBack(s,35,i);c>i&&Br(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=Gr(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=Gr(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=Gr(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 Ni(){this.ruler=new Xr;for(let e=0;e<Ti.length;e++)this.ruler.push(Ti[e][0],Ti[e][1],{alt:(Ti[e][2]||[]).slice()})}function Mi(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 Di(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}}Ni.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)}},Ni.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)},Ni.prototype.State=wi,Mi.prototype.pushPending=function(){const e=new ei("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},Mi.prototype.push=function(e,t,n){this.pending&&this.pushPending();const r=new ei(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},Mi.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=Vr(i)||Ur(i),l=Vr(a)||Ur(a),u=qr(i),d=qr(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}},Mi.prototype.Token=ei;const Pi=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;const Oi=[];for(let e=0;e<256;e++)Oi.push(0);function Ri(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){Oi[e.charCodeAt(0)]=1});var Li={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;Ri(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&Ri(e,t[r].delimiters)}};function $i(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 ji={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;$i(e,e.delimiters);for(let r=0;r<n;r++)t[r]&&t[r].delimiters&&$i(e,t[r].delimiters)}};const Fi=/^([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])?)*)$/,Bi=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;const qi=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,zi=/^&([a-z][a-z0-9]{1,31});/i;function Ui(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 Vi=[["text",function(e,t){let n=e.pos;for(;n<e.posMax&&!Di(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(Pi);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&&Br(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),Br(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!==Oi[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",Li.tokenize],["emphasis",ji.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),Br(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),Br(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),Br(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[Wr(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),Br(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),Br(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),Br(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[Wr(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(Bi.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(Fi.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(_i);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(qi);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=xr(t)?Cr(t):Cr(65533),n.markup=r[0],n.info="entity"}return e.pos+=r[0].length,!0}}else{const r=e.src.slice(n).match(zi);if(r){const n=(i=r[0],Ir(i,mr.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}]],Wi=[["balance_pairs",function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Ui(e.delimiters);for(let e=0;e<n;e++)t[e]&&t[e].delimiters&&Ui(t[e].delimiters)}],["strikethrough",Li.postProcess],["emphasis",ji.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 Ki(){this.ruler=new Xr;for(let e=0;e<Vi.length;e++)this.ruler.push(Vi[e][0],Vi[e][1]);this.ruler2=new Xr;for(let e=0;e<Wi.length;e++)this.ruler2.push(Wi[e][0],Wi[e][1])}function Gi(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(n){e[n]=t[n]})}),e}function Hi(e){return Object.prototype.toString.call(e)}function Yi(e){return"[object Function]"===Hi(e)}function Ji(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}Ki.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},Ki.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()},Ki.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)},Ki.prototype.State=Mi;const Zi={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};const Qi={"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}}},Xi="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function es(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=nr.source,t.src_Cc=rr.source,t.src_Z=or.source,t.src_P=ir.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]"===Hi(n))return!function(e){return"[object RegExp]"===Hi(e)}(n.validate)?Yi(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(Yi(n.normalize)?r.normalize=n.normalize:n.normalize?s(t,n):r.normalize=function(e,t){t.normalize(e)});!function(e){return"[object String]"===Hi(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(Ji).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 ts(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 ns(e,t){if(!(this instanceof ns))return new ns(e,t);var n;t||(n=e,Object.keys(n||{}).reduce(function(e,t){return e||Zi.hasOwnProperty(t)},!1)&&(t=e,e={})),this.__opts__=Gi({},Zi,t),this.__schemas__=Gi({},Qi,e),this.__compiled__={},this.__tlds__=Xi,this.__tlds_replaced__=!1,this.re={},es(this)}ns.prototype.add=function(e,t){return this.__schemas__[e]=t,es(this),this},ns.prototype.set=function(e){return this.__opts__=Gi(this.__opts__,e),this},ns.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))},ns.prototype.pretest=function(e){return this.re.pretest.test(e)},ns.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},ns.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 ts(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},ns.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 ts(e,t[2],t.index+t[1].length,t.index+t[0].length+n);return this.__compiled__[r.schema].normalize(r,this),r},ns.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(),es(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,es(this),this)},ns.prototype.normalize=function(e){e.schema||(e.url=`http://${e.url}`),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url=`mailto:${e.url}`)},ns.prototype.onCompile=function(){};const rs=2147483647,is=36,ss=/^xn--/,os=/[^\0-\x7F]/,as=/[\x2E\u3002\uFF0E\uFF61]/g,cs={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},ls=Math.floor,us=String.fromCharCode;function ds(e){throw new RangeError(cs[e])}function ps(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(as,".")).split("."),t).join(".");return r+i}function hs(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 fs=function(e){return e>=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:is},ms=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},gs=function(e,t,n){let r=0;for(e=n?ls(e/700):e>>1,e+=ls(e/t);e>455;r+=is)e=ls(e/35);return ls(r+36*e/(e+38))},ys=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&&ds("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=is;;i+=is){a>=n&&ds("invalid-input");const o=fs(e.charCodeAt(a++));o>=is&&ds("invalid-input"),o>ls((rs-r)/t)&&ds("overflow"),r+=o*t;const c=i<=s?1:i>=s+26?26:i-s;if(o<c)break;const l=is-c;t>ls(rs/l)&&ds("overflow"),t*=l}const c=t.length+1;s=gs(r-o,c,0==o),ls(r/c)>rs-i&&ds("overflow"),i+=ls(r/c),r%=c,t.splice(r++,0,i)}return String.fromCodePoint(...t)},bs=function(e){const t=[],n=(e=hs(e)).length;let r=128,i=0,s=72;for(const n of e)n<128&&t.push(us(n));const o=t.length;let a=o;for(o&&t.push("-");a<n;){let n=rs;for(const t of e)t>=r&&t<n&&(n=t);const c=a+1;n-r>ls((rs-i)/c)&&ds("overflow"),i+=(n-r)*c,r=n;for(const n of e)if(n<r&&++i>rs&&ds("overflow"),n===r){let e=i;for(let n=is;;n+=is){const r=n<=s?1:n>=s+26?26:n-s;if(e<r)break;const i=e-r,o=is-r;t.push(us(ms(r+i%o,0))),e=ls(i/o)}t.push(us(ms(e,0))),s=gs(i,c,a===o),i=0,++a}++i,++r}return t.join("")},ws=function(e){return ps(e,function(e){return os.test(e)?"xn--"+bs(e):e})},vs=function(e){return ps(e,function(e){return ss.test(e)?ys(e.slice(4).toLowerCase()):e})};const ks={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"]}}}},Is=/^(vbscript|javascript|file|data):/,Es=/^data:image\/(gif|png|jpeg|webp);/;function As(e){const t=e.trim().toLowerCase();return!Is.test(t)||Es.test(t)}const Ss=["http:","https:","mailto:"];function _s(e){const t=Xn(e,!0);if(t.hostname&&(!t.protocol||Ss.indexOf(t.protocol)>=0))try{t.hostname=ws(t.hostname)}catch(e){}return Fn(Bn(t))}function xs(e){const t=Xn(e,!0);if(t.hostname&&(!t.protocol||Ss.indexOf(t.protocol)>=0))try{t.hostname=vs(t.hostname)}catch(e){}return $n(Bn(t),$n.defaultChars+"%")}function Cs(e,t){if(!(this instanceof Cs))return new Cs(e,t);t||Er(e)||(t=e||{},e="default"),this.inline=new Ki,this.block=new Ni,this.core=new bi,this.renderer=new Qr,this.linkify=new ns,this.validateLink=As,this.normalizeLink=_s,this.normalizeLinkText=xs,this.utils=Yr,this.helpers=Sr({},Jr),this.options={},this.configure(e),t&&this.set(t)}function Ts(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ns,Ms;function Ds(){if(Ms)return Ns;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}Ms=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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}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({}),Ns=ce,ce.HighlightJS=ce,ce.default=ce,Ns}Cs.prototype.set=function(e){return Sr(this.options,e),this},Cs.prototype.configure=function(e){const t=this;if(Er(e)){const t=e;if(!(e=ks[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},Cs.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},Cs.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},Cs.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},Cs.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},Cs.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},Cs.prototype.parseInline=function(e,t){const n=new this.core.State(e,this,t);return n.inlineMode=!0,this.core.process(n),n.tokens},Cs.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var Ps=Ts(Ds());const Os="[A-Za-z$_][0-9A-Za-z$_]*",Rs=["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"],Ls=["true","false","null","undefined","NaN","Infinity"],$s=["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"],js=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Fs=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Bs=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],qs=[].concat(Fs,$s,js);const zs="[A-Za-z$_][0-9A-Za-z$_]*",Us=["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"],Vs=["true","false","null","undefined","NaN","Infinity"],Ws=["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"],Ks=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Gs=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Hs=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Ys=[].concat(Gs,Ws,Ks);function Js(e){const t=e.regex,n=zs,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:zs,keyword:Us,literal:Vs,built_in:Ys,"variable.language":Hs},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:{_:[...Ws,...Ks]}},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("|"),")")}([...Gs,"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 Zs=["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"],Qs=["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(),Xs=["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(),eo=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),to=["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();Ps.registerLanguage("javascript",function(e){const t=e.regex,n=Os,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:Os,keyword:Rs,literal:Ls,built_in:qs,"variable.language":Bs},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:{_:[...$s,...js]}},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("|"),")")}([...Fs,"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:/\$[(.]/}]}}),Ps.registerLanguage("typescript",function(e){const t=e.regex,n=Js(e),r=zs,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:zs,keyword:Us.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:Vs,built_in:Ys.concat(i),"variable.language":Hs},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}),Ps.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]}]}}),Ps.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"}}),Ps.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}}),Ps.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]}}),Ps.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}]}]}}),Ps.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:":("+Xs.join("|")+")"},{begin:":(:)?("+eo.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+to.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:Qs.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Zs.join("|")+")\\b"}]}}),Ps.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}]}}),Ps.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});/}]}}),Ps.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 no={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 ro(e){const t=new Cs({html:!1,linkify:!0,breaks:!0,highlight:e?(e,t)=>{const n=function(e){const t=(e||"").trim().toLowerCase();if(!t)return;const n=no[t]??t;return Ps.getLanguage(n)?n:void 0}(t);if(n)try{return Ps.highlight(e,{language:n,ignoreIllegals:!0}).value}catch{}return""}:void 0});return t}const io=ro(!0),so=ro(!1);const oo={ActivityBar:Qt,Statusbar:Xt,View:an,Views:dn,KeyboardShortcuts:pn,Layout:wn,ContentTabs:vn,PanelTabs:kn,Profile:Rn,Markdown:{render:function(e,t){return(!1===t?.highlight?so:io).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 ao(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 co=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=>ao(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=>ao(t,e))}).map(e=>({opener:e,command:e.command}))}};let lo,uo,po,ho,fo,mo;function go(){if(lo)return lo;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return lo=punica.runtime.resources,lo}function yo(){if(uo)return uo;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return uo=e,uo}function bo(){if(ho)return ho;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return ho=e,ho}function wo(){if(fo)return fo;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function vo(){if(mo)return mo;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return mo=e,mo}function ko(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 Io(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 Eo=ko({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 Ao(){return Eo.get()}function So(e){Eo.set(e),e&&Io({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function _o(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 xo=Symbol("punica.llm.gatewayGovernedAi");let Co,To,No;function Mo(){if(Co)return Co;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return Co=punica.runtime.llm,Co}function Do(e){if(Co=e,To=void 0,No=void 0,!e)return;const t=e;_o("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class Po{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 Oo=null;function Ro(){return Oo||(Oo=new Po),Oo}class Lo{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 $o{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 jo={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}}},Fo={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}}},Bo={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},qo={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},zo={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 Uo(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 Vo{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=Uo("session");return new $o(i,s,t.id,e.language,r,n)}}class Wo{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 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(`Dataset provider not found: ${e.provider}. Available providers: ${Array.from(this.registry.providers.keys()).join(", ")}`);return t}}class Yo{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 Jo=null;function Zo(){return Jo||(Jo=new Yo),Jo}class Qo{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 Xo{#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 ea=null;function ta(){return ea||(ea=new Xo),ea}function na(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 ra="default";class ia{#Je=new Map;#Ze(e){const t=e||ra;let n=this.#Je.get(t);return n||(n=new Map,this.#Je.set(t,n)),n}upsert(e,t=ra){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=ra){const r=this.#Ze(n),i=[];for(const t of r.values())i.push({id:t.id,score:na(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=ra){const n=this.#Ze(t);for(const t of e)n.delete(t)}clear(e=ra){this.#Je.delete(e||ra)}count(e=ra){return this.#Ze(e).size}export(e=ra){return Array.from(this.#Ze(e).values())}import(e,t=ra){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#Je.set(t||ra,n)}}const sa=".punica/vectors";class oa{#b=new ia;#Qe=new Set;#Xe(){try{return punica.runtime?.fs}catch{return}}#et(e){return`${sa}/${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(sa)}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 aa,ca,la;function ua(){return aa||(ca||(ca=new oa),ca)}function da(){if(!la)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 la}var pa;!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"}(pa||(pa={}));class ha extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const fa=new class{#rt=new Map;#ne=new Map;registerCapability(e){if(!e.name)throw new ha(pa.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ma(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 ga(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:ya(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 ya(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 ba=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function wa(){const e=globalThis;return e.punica?.extensions?.manager}function va(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function ka(){const e=globalThis;return e.punica?.flow?.registry}function Ia(){const e=globalThis;return e.punica?.flow?.agents}function Ea(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const Aa={core:function(e){const t=fa.getSpec(e);if(t)return{origin:"core",definition:ma(t)}},extension:function(e){const t=wa();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=va();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=ka();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=Ia();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=Ea();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},Sa={core:function(){return fa.getAllSpecs().map(e=>({origin:"core",definition:ma(e)}))},extension:function(){const e=wa();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=va();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=ka();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=Ia();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=Ea();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},_a={getCapability(e){for(const t of ba){const n=Aa[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 ba)if(!t||t.has(e))for(const t of Sa[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 xa(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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.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 ha(pa.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Ca={recordSpan:()=>{}};function Ta(e){try{Ca.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function Na(){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,Ta({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 Ta({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 ha?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function Ma(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ma);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ma(r);return t}return e}const Da=new WeakMap;function Pa(){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=Ma(s);else{const e=function(e){const t=Da.get(e);if(t)return t;const n=b(e.inputSchema);return Da.set(e,n),n}(r.spec);r.redactedInput=e.length>0?w(s,e):s}return await t()}}function Oa(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function Ra(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Oa(t))}const La=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&&(Ra(i,t)||n.push(`Expected type "${i}", got "${Oa(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&&(Ra(i,r)||n.push(`Field "${t}": expected type "${i}", got "${Oa(r)}"`))}}return{ok:0===n.length,errors:n}}};let $a=La;function ja(){return $a}function Fa(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=ja().validate(s,i);if(!o.ok)throw new ha(pa.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const Ba=ko({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function qa(){return Ba.get()}const za=["path","oldPath","newPath","src","dst","target","linkPath"];function Ua(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 Va(){try{return qa().cwd}catch{return}}function Wa(){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 za){const t=r[e];if("string"!=typeof t)continue;s||(i=Va(),s=!0);const n=Ua(t,i);if(!n.ok)throw new ha(pa.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 Ka="encrypted-at-rest";function Ga(){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 qa()}catch{return}}();if(!i)throw new ha(pa.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:Ka,reason:"provider not registered"});if(!i.capabilities?.has(Ka))throw new ha(pa.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${Ka}" capability flag`,{capability:n.name,required:Ka,reason:"capability not advertised"});return Io({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:Ka}}),t()}}function Ha(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 Ya(){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=_a.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw Ha(o,c,"origin-not-allowed",t,a),new ha(pa.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 Ha(o,c,"in-denylist",void 0,a),new ha(pa.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 Ha(o,c,"not-in-allowlist",void 0,a),new ha(pa.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Ja={alg:"HS256",typ:"PUNICA-APPROVAL"};class Za extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function Qa(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 Xa(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 ec(e){return(new TextEncoder).encode(e)}function tc(e){return Qa(ec(JSON.stringify(e)))}function nc(e){return JSON.parse((t=Xa(e),(new TextDecoder).decode(t)));var t}function rc(){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 ic(){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 sc{#st;#ot;constructor(e){e?.secret instanceof Uint8Array?this.#st=e.secret:this.#st="string"==typeof e?.secret?ec(e.secret):ic()}async sign(e){const t=await this.#at(),n=tc(Ja),r=tc(e),i=ec(`${n}.${r}`),s=await rc().sign("HMAC",t,i);return`${n}.${r}.${Qa(new Uint8Array(s))}`}getSecret(){return this.#st}async#at(){return this.#ot||(this.#ot=await rc().importKey("raw",this.#st,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#ot}}class oc{#st;#ot;#ct=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#st=e.secret:this.#st="string"==typeof e?.secret?ec(e.secret):ic()}async verify(e){const t=e.split(".");if(3!==t.length)throw new Za("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=nc(n)}catch{throw new Za("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new Za("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=nc(r)}catch{throw new Za("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#at(),c=ec(`${n}.${r}`);let l;try{l=Xa(i)}catch{throw new Za("MALFORMED","Token signature is not valid base64url")}const u=rc();if(!await u.verify("HMAC",a,l,c))throw new Za("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new Za("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new Za("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 rc().importKey("raw",this.#st,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#ot}}let ac;function cc(){return ac||(ac=function(){const e=new sc,t=new oc({secret:e.getSecret()});return{signer:e,verifier:t}}()),ac}const lc=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function uc(){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 ha(pa.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"===lc({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 cc().verifier.verify(s.policy.approvalToken)}catch(e){if(e instanceof Za){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 ha(pa.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 ha(pa.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 ha(pa.CAPABILITY_DENIED,f.reason??"Policy denied execution",{capability:i,decision:f});return await t()}}const dc=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 pc=dc;function hc(){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 ha(pa.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=pc,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 ha(pa.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 fc=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 mc(){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(!fc.consumeToken(c,a.perSecond))throw new ha(pa.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const gc=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 yc(){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 gc.acquire(a,o.max)}catch(e){throw new ha(pa.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{gc.release(a)}}}const bc=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 wc(){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=bc.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new ha(pa.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 vc(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 kc(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new ha(pa.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 Ic(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 Ec(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:Ic(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(Ic(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=qa()}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(Ic(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 Ac=new WeakMap;function Sc(e,t){if(!0===t.secretBearing)return _c(e);const n=function(e){const t=Ac.get(e);if(t)return t;const n=b(e.outputSchema);return Ac.set(e,n),n}(t);return n.length>0?w(e,n):e}function _c(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(_c);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=_c(r);return t}return e}function xc(){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=Sc(r.output,o);await Ec({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 Cc=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Tc(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const Nc=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=fa.getSpec(e),o=s?fa.getProvider(e):void 0,a="core";if(!s){const t=_a.getCapability(e);if(!t)throw Tc({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 ha(pa.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,s=ga(t.definition),o=xa(t.origin,t.definition,t.metadata)}if(!o)throw new ha(pa.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(s.requires)for(const t of s.requires)if(!fa.hasCapability(t))throw new ha(pa.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});s.deprecated&&Tc({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 ha)throw e;throw new ha(pa.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#ft(e){const t={auditTrail:xc,traceMetrics:Na,redaction:Pa,validateInput:Fa,pathTraversalGuard:Wa,encryptionRouting:Ga,profileBudget:Ya,policyGate:uc,idempotency:hc,rateLimit:mc,concurrency:yc,circuitBreaker:wc,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 kc(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),h<=l&&d&&vc(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 Cc.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 Mc(e,t){const n=qa(),r=n[t];if("function"!=typeof r)throw new ha(pa.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 Dc(e,t,n){const r=qa();if(!r.capabilities?.has(n))throw new ha(pa.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 ha(pa.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 Pc{name="fs.readFile";async execute(e,t){const n=qa();return await n.readFile(e.path)}}class Oc{name="fs.writeFile";async execute(e,t){const n=qa();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class Rc{name="fs.listFiles";async execute(e,t){const n=qa();return await n.getFileTree()}}class Lc{name="fs.stat";async execute(e,t){return await Mc("fs.stat","stat")(e.path)}}class $c{name="fs.exists";async execute(e,t){return await Mc("fs.exists","exists")(e.path)}}class jc{name="fs.copy";async execute(e,t){await Mc("fs.copy","copy")(e.src,e.dst)}}class Fc{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Mc("fs.mkdir","mkdir")(e.path,n)}}class Bc{name="fs.history";async execute(e,t){return await Dc("fs.history","history","versioning")(e.path)}}class qc{name="fs.readAtVersion";async execute(e,t){return await Dc("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class zc{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Mc("fs.list","list")(e.path,n)}}const Uc=ko({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 Vc(){return Uc.get()}function Wc(e){Uc.set(e),e&&Io({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class Kc{name="secrets.get";async execute(e,t){return Vc().get(e.name)}}class Gc{name="secrets.set";async execute(e,t){Vc().set(e.name,e.value)}}function Hc(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[xo]=!0,n}class Yc{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=Hc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class Jc{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=Hc(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 Zc{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 Qc{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 Xc{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 el{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 tl{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 nl{name="workspace.readFile";async execute(e,t){const n=qa();return await n.readFile(e.path)}}class rl{name="workspace.writeFile";async execute(e,t){const n=qa();await n.createFileWithContent(e.path,e.content)}}class il{name="workspace.listFiles";async execute(e,t){const n=qa(),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 sl{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 ol{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 al{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 cl{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 ll{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 ul="capability.catalog";class dl{name=ul;async execute(e,t){const n=e??{},r=_a.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>pl(e,n));return{capabilities:r,count:r.length}}}function pl(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=hl(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=hl(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=hl(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 hl(e){return Array.isArray(e)?e:[e]}const fl=["examples","$comment","default","title"];function ml(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 gl=["properties","patternProperties","definitions","$defs"];function yl(e){if(Array.isArray(e))return e.map(e=>yl(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!fl.includes(n))if("description"!==n||"string"!=typeof r){if(gl.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=yl(n);t[n]=e;continue}t[n]=yl(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const bl="capability.schemaExport";class wl{name=bl;async execute(e,t){const n=e??{},r=n.filter??{},i=_a.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>pl(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=ml(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=yl(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=ml(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 vl(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return[];const i=_a.listCapabilities();if(0===i.length)return[];const s=function(e,t){const n=El(Il(e));return t.map(e=>({...e,score:Al(n,El(Il(e.text)))}))}(r,i.map(e=>({id:e.definition.id,description:e.definition.description,text:kl(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 _o("llm.recommendIntent",{intent:r,limit:n,path:"text-similarity",topIds:o.map(e=>e.id),topScore:o[0]?.score??0}),o}function kl(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 Il(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(e=>e.length>0)}function El(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function Al(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 Sl="capability.recommend";class _l{name=Sl;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await vl(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 xl="capability.describe",Cl="capability.search";function Tl(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class Nl{name=xl;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new wl).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 Ml{name=Cl;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=_a.listCapabilities(),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await vl(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:ml(t?.description??t?.title??e,100),category:Tl(e)}});return{results:c,count:c.length}}}function Dl(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Pl(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 Ol{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Dl().create(n)}}}class Rl{name="ai.session.list";async execute(e,t){const n=Dl().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Ll{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Dl().get(n)}}}class $l{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Dl().rename(String(n?.sessionId??""),String(n?.title??""))}}}class jl{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Dl().archive(String(n?.sessionId??""),n?.archived)}}}class Fl{name="ai.session.delete";async execute(e,t){return{ok:Dl().delete(String(e?.sessionId??""))}}}const Bl={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"}]}},ql={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"}]}},zl=new Set(["low","medium","high"]),Ul={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&zl.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"}]:[]}},Vl=new Set(["none","plan","step"]),Wl={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Vl.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 Kl={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"}]:[]}},Gl=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Hl={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Gl.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"}]}},Yl=new Set(["low","medium","high"]),Jl=["write","delete","remove","modify","destroy"],Zl=[Bl,ql,Ul,Wl,Kl,Hl,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Yl.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&&Jl.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 Ql=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 Zl)this.#gt.set(e.id,e)}},Xl="capability.lint";class eu{name=Xl;async execute(e,t){const n=e??{},r=_a.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=Ql.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 tu={type:"object"};function nu(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ru(e){let t;return t=function(e){if(e instanceof ha)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:nu(e),{content:[{type:"text",text:t}],isError:!0}}const iu="capability.serveList",su="capability.serveCall",ou=new Set([iu,su]);class au{name=iu;async execute(e,t){const n=(e??{}).filter??{},r=_a.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!ou.has(e.definition.id)).filter(e=>pl(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??tu,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class cu{name=su;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||ou.has(r)||!_a.getCapability(r))return ru(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:nu(e)}],isError:!1}}(await Nc.call(r,n.arguments??{},t))}catch(e){return ru(e)}}}const lu="shell.revealView",uu="shell.hideView",du="shell.listViews",pu="shell.toggleView",hu="shell.toggleSlot";function fu(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new ha(pa.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:lu});return e}function mu(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 gu{name=lu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=fu();if(!i.getPlacement(n))throw new ha(pa.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:lu,viewId:n});return await i.reveal(n,mu(t),{focus:r}),{viewId:n,revealed:!0}}}class yu{name=uu;async execute(e,t){const{viewId:n}=e??{};return fu().hide(n,mu(t)),{viewId:n,hidden:!0}}}class bu{name=du;async execute(e,t){return{views:fu().listViews()}}}class wu{name=pu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=fu();if(!i.getPlacement(n))throw new ha(pa.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:pu,viewId:n});return"visible"===i.getState(n)?(i.hide(n,mu(t)),{viewId:n,visible:!1}):(await i.reveal(n,mu(t),{focus:r}),{viewId:n,visible:!0})}}const vu=new Map;class ku{name=hu;async execute(e,t){const{slot:n,focus:r}=e??{},i=fu(),s=i.getVisibleView(n);if(s)return vu.set(n,s),i.hide(s,mu(t)),{slot:n,visible:!1,viewId:s};const o=vu.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,mu(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}function Iu(e){try{fa.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function Eu(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 Au(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 Su(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=_a.getCapability(e.id);return t?void Au(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=_a.listCapabilities(n),i=r.map(Eu);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)Au(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function _u(e){return Su({...e,verbose:!0})}function xu(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 Cu(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 Tu(e){return JSON.stringify(e,null,2)}const Nu=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{}}},Mu=16384,Du="runtime:mcp:client";function Pu(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Ou(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 Ou(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=>Ou(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]=Ou(i,t+1);return n}return e}function Ru(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=Mu)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Ou(e,0),null,2)??"null";if(r.length<=Mu)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,Mu)+"\n… [truncated]",bytes:n,truncated:!0}}function Lu(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const $u=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 Uu}),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:Lu(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Pu(),s=Ru(r??{});Io({name:"mcp.request",source:Du,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:me().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Pu(),s=Date.now(),o=Ru(r??{});Io({name:"mcp.request",source:Du,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:me().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=Ru(o??null);return Io({name:"mcp.response",source:Du,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:me().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw Io({name:"mcp.response",source:Du,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}});Nu.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(),Nu.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})??{}}},ju=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Fu(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(ju):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 Bu(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 Wf}),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 qu(){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 Bu(e.id),n="stdio"===e.kind?Fu(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?Fu(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 zu(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?Fu(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?Fu(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 Uu=Object.freeze({__proto__:null,loadMcpConfig:qu,loadServerOverrides:Bu,parseStaticConfig:zu,resolveEnvPlaceholders:Fu});class Vu{name=Fe.MCP;version="1.0.0";dependencies=[je.EVENTS,Fe.FS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){this.#vt=t.BOOTSTRAPPING;const n=await qu();this.#kt(n),this.#vt=t.BOOTSTRAPPED}async#kt(e){for(const t of e)try{await $u.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(e){this.#vt=t.STARTING,this.#vt=t.STARTED,console.log(`[Punica] MCP module started — ${Nu.list().length} capability(ies) active`)}}const Wu=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const Ku={get capabilities(){return Ba.hasProvider()?Ba.get().capabilities:void 0},get cwd(){return Ba.hasProvider()?Ba.get().cwd:void 0},getFileTree:()=>Ba.get().getFileTree(),readFile:e=>Ba.get().readFile(e),readBytes:(e,t,n)=>{const r=Ba.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)=>Ba.get().updateFileContent(e,t),createFolder:e=>Ba.get().createFolder(e),deleteFolder:e=>Ba.get().deleteFolder(e),deleteFile:(e,t)=>Ba.get().deleteFile(e,t),renameFile:(e,t)=>Ba.get().renameFile(e,t),renameFolder:(e,t)=>Ba.get().renameFolder(e,t),createFileWithContent:(e,t)=>Ba.get().createFileWithContent(e,t),list:(e,t)=>{const n=Ba.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=Ba.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=Ba.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},Gu=function(e){return e||{query:e=>yo().query(e),startIndex:e=>{const t=yo();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(Wu?.search),Hu=function(e){return e||{status:()=>vo().status(),branches:()=>vo().branches(),logs:e=>vo().logs(e),init:e=>vo().init(e),clone:e=>vo().clone(e),commit:e=>vo().commit(e),stage:e=>vo().stage(e),unstage:e=>vo().unstage(e),discard:e=>vo().discard(e),reset:e=>vo().reset(e),switchBranch:e=>vo().switchBranch(e),createBranch:(e,t)=>vo().createBranch(e,t),fetch:e=>vo().fetch(e),pull:e=>vo().pull(e),push:e=>vo().push(e)}}(Wu?.vcs),Yu=function(e){return e||{create:e=>bo().create(e),write:(e,t)=>bo().write(e,t),resize:(e,t,n)=>bo().resize(e,t,n),close:e=>bo().close(e),onData:(e,t)=>bo().onData(e,t),onExit:(e,t)=>bo().onExit(e,t),list:()=>bo().list()}}(Wu?.terminals),Ju=function(e){return e||{start:e=>wo().start(e),send:(e,t)=>wo().send(e,t),onMessage:(e,t)=>wo().onMessage(e,t),onStderr:(e,t)=>wo().onStderr(e,t),onExit:(e,t)=>wo().onExit(e,t),stop:e=>wo().stop(e),list:()=>wo().list()}}(Wu?.debug),Zu=function(e){return e||{run:e=>function(){if(po)return po;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return po=e,po}().run(e)}}(Wu?.tasks),Qu=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&So(e),{getCurrent:()=>Eo.get().getCurrent(),list:()=>Eo.get().list(),open:e=>Eo.get().open(e),setEnvironment:(e,t)=>Eo.get().setEnvironment(e,t),onDidChange:e=>Eo.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(Wu?.workspace),Xu=function(e){return e||{list:async e=>go().list(e),get:e=>go().get(e),register:e=>go().register(e),unregister:e=>go().unregister(e),onDidChange:e=>go().onDidChange(e)}}(Wu?.resources),ed=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&Do(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){(To&&To!==e||No&&t&&No!==t)&&B.publishEvent({name:"llm.providerChanged",envelope:{id:B.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:To,newProviderId:e,previousEndpoint:No,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),To=e,t&&(No=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??B.createCorrelationId(),s=le.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!s.allowed)throw s.requiresApproval&&le.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:i}),B.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:B.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 B.publishEvent({name:"llm.remoteRequestSent",envelope:{id:B.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=Mo(),o=!0===e?.[xo];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??B.createCorrelationId(),o=le.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw B.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:B.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&&le.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)");B.publishEvent({name:"llm.remoteRequestSent",envelope:{id:B.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=Mo();let o=e;if(!(!0===e?.[xo])&&("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}(Wu?.llm),td=function(e){if(e)return e;const t=Ro(),n=new Lo(t),r=new Vo(t,n);t.registerLanguageRuntime(jo),t.registerLanguageRuntime(Fo),t.registerLanguageRuntime(Bo),t.registerLanguageRuntime(qo),t.registerLanguageRuntime(zo);const i=new Map;return{async*run(e,t){const n=t?.runId??Uo("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}}(Wu?.compute),nd=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:\/\/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}(Wu?.datasets),rd=function(e){if(e)return e;const t=Zo(),n=new Qo(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}(Wu?.models),id=function(e){if(e)return e;const t=ta();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)}}}(Wu?.modelRuntimes),sd=function(e){if(e)return e;const t=ta();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)}}}(Wu?.inference),od=function(e){return e||{upsert:(e,t)=>ua().upsert(e,t),query:e=>ua().query(e),delete:(e,t)=>ua().delete(e,t),clear:e=>ua().clear(e),count:e=>ua().count(e)}}(Wu?.vectors),ad=function(e){if(e)return e;function t(){const e=da().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=da().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:()=>da().dataDir(),dataFs:{list:(e,t)=>da().dataFs.list(e,t),readFile:e=>da().dataFs.readFile(e),stat:e=>da().dataFs.stat(e),mkdir:(e,t)=>da().dataFs.mkdir(e,t),deleteFile:e=>da().dataFs.deleteFile(e),deleteFolder:e=>da().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=da().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=da().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=da().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 la?.mcpServer?r:void 0}}}(Wu?.host),cd=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&Wc(e);return{set:(e,t)=>Uc.get().set(e,t),get:e=>Uc.get().get(e),delete:e=>Uc.get().delete(e),list:()=>Uc.get().list(),__punicaWrappedSecretsFacade:!0}}(Wu?.secrets);console.log("[Runtime] Facades created"),function(){Iu({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}}),fa.registerProvider(new Pc),Iu({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"}}),fa.registerProvider(new Oc),Iu({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}}),fa.registerProvider(new Rc),Iu({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}}),fa.registerProvider(new Lc),Iu({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}}),fa.registerProvider(new $c),Iu({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"}}),fa.registerProvider(new jc),Iu({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"}}),fa.registerProvider(new Fc),Iu({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}}),fa.registerProvider(new zc),Iu({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}}),fa.registerProvider(new Bc),Iu({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}}),fa.registerProvider(new qc),Iu({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}}),fa.registerProvider(new Kc),Iu({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"}}),fa.registerProvider(new Gc),Iu({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}}}),fa.registerProvider(new Yc),Iu({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}}}),fa.registerProvider(new Jc),Iu({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}}}),fa.registerProvider(new Qc),Iu({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}}}),fa.registerProvider(new Zc),Iu({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}}),fa.registerProvider(new Xc),Iu({name:"vcs.status",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),fa.registerProvider(new el),Iu({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"}}),fa.registerProvider(new tl),Iu({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}}),fa.registerProvider(new nl),Iu({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"}}),fa.registerProvider(new rl),Iu({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}}),fa.registerProvider(new il),Iu({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"}}),fa.registerProvider(new sl),Iu({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"}}),fa.registerProvider(new ol),Iu({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"}}),fa.registerProvider(new al),Iu({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}}),fa.registerProvider(new cl),Iu({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"}}),fa.registerProvider(new ll),Iu({name:ul,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}}),fa.registerProvider(new dl),Iu({name:bl,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}}),fa.registerProvider(new wl),Iu({name:Sl,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}}),fa.registerProvider(new _l),Iu({name:Cl,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}}),fa.registerProvider(new Ml),Iu({name:xl,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}}),fa.registerProvider(new Nl);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Pl("ai.session.create",{properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),Pl("ai.session.list",{properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),Pl("ai.session.get",{required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),Pl("ai.session.rename",{required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),Pl("ai.session.archive",{required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),Pl("ai.session.delete",{risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())Iu(e);for(const e of[new Ol,new Rl,new Ll,new $l,new jl,new Fl])fa.registerProvider(e);Iu({name:Xl,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}}),fa.registerProvider(new eu),Iu({name:iu,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}}),fa.registerProvider(new au),Iu({name:su,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}}),fa.registerProvider(new cu),Iu({name:lu,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}}),fa.registerProvider(new gu),Iu({name:uu,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}}),fa.registerProvider(new yu),Iu({name:du,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}}),fa.registerProvider(new bu),Iu({name:pu,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}}),fa.registerProvider(new wu),Iu({name:hu,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}}),fa.registerProvider(new ku)}(),console.log("[Runtime] Capabilities registered");const ld={lifecyclePhase:Wu?.lifecyclePhase??"bootstrapping",fs:Ku,fileOpeners:Wu?.fileOpeners??co,search:Gu,vcs:Hu,terminals:Yu,debug:Ju,tasks:Zu,workspace:Qu,resources:Xu,secrets:cd,llm:ed,compute:td,datasets:nd,models:rd,modelRuntimes:id,inference:sd,vectors:od,host:ad,capabilities:{gateway:Nc,unifiedRegistry:_a,logTrinityCatalog:Su,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(Tu(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Tu(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(`## ${xu(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(Cu(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:Nu,connect:e=>$u.connect(e),disconnect:e=>$u.disconnect(e),listServers:()=>$u.listServers(),listTools:e=>$u.listTools(e),callTool:(e,t,n)=>$u.callTool(e,t,n)},setFsProvider:function(e){Ba.set(e),e&&Io({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:Do,setComputeProvider:function(e){Ro().registerProvider(e)},setComputeRuntime:function(e){Ro().registerLanguageRuntime(e)},setDatasetProvider:function(e){Go().registerProvider(e)},setModelProvider:function(e){Zo().registerProvider(e)},setModelRuntime:function(e){ta().register(e)},setHostProvider:function(e){la=e},setVectorsProvider:function(e){aa=e},setSearchProvider:function(e){uo=e},setWorkspaceProvider:So,setTerminalProvider:function(e){ho=e},setDebugProvider:function(e){fo=e},setVcsProvider:function(e){mo=e},setResourcesProvider:function(e){lo=e},setTasksProvider:function(e){po=e},setSecretsProvider:Wc};class ud{#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 dd=class{#Et;constructor(e){this.#Et=e}async execute(){return await this.#Et.execute()}},pd=class extends dd{constructor(e){super(e)}async execute(){return await super.execute()}},hd=class extends dd{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))}}},fd=class extends dd{constructor(e){super(e)}async execute(){return await super.execute()}};const md=Symbol.for("yaml.alias"),gd=Symbol.for("yaml.document"),yd=Symbol.for("yaml.map"),bd=Symbol.for("yaml.pair"),wd=Symbol.for("yaml.scalar"),vd=Symbol.for("yaml.seq"),kd=Symbol.for("yaml.node.type"),Id=e=>!!e&&"object"==typeof e&&e[kd]===md,Ed=e=>!!e&&"object"==typeof e&&e[kd]===gd,Ad=e=>!!e&&"object"==typeof e&&e[kd]===yd,Sd=e=>!!e&&"object"==typeof e&&e[kd]===bd,_d=e=>!!e&&"object"==typeof e&&e[kd]===wd,xd=e=>!!e&&"object"==typeof e&&e[kd]===vd;function Cd(e){if(e&&"object"==typeof e)switch(e[kd]){case yd:case vd:return!0}return!1}function Td(e){if(e&&"object"==typeof e)switch(e[kd]){case md:case yd:case wd:case vd:return!0}return!1}const Nd=Symbol("break visit"),Md=Symbol("skip children"),Dd=Symbol("remove node");function Pd(e,t){const n=$d(t);if(Ed(e)){Od(null,e.contents,n,Object.freeze([e]))===Dd&&(e.contents=null)}else Od(null,e,n,Object.freeze([]))}function Od(e,t,n,r){const i=jd(e,t,n,r);if(Td(i)||Sd(i))return Fd(e,r,i),Od(e,i,n,r);if("symbol"!=typeof i)if(Cd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Od(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Nd)return Nd;i===Dd&&(t.items.splice(e,1),e-=1)}}}else if(Sd(t)){r=Object.freeze(r.concat(t));const e=Od("key",t.key,n,r);if(e===Nd)return Nd;e===Dd&&(t.key=null);const i=Od("value",t.value,n,r);if(i===Nd)return Nd;i===Dd&&(t.value=null)}return i}async function Rd(e,t){const n=$d(t);if(Ed(e)){await Ld(null,e.contents,n,Object.freeze([e]))===Dd&&(e.contents=null)}else await Ld(null,e,n,Object.freeze([]))}async function Ld(e,t,n,r){const i=await jd(e,t,n,r);if(Td(i)||Sd(i))return Fd(e,r,i),Ld(e,i,n,r);if("symbol"!=typeof i)if(Cd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await Ld(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Nd)return Nd;i===Dd&&(t.items.splice(e,1),e-=1)}}}else if(Sd(t)){r=Object.freeze(r.concat(t));const e=await Ld("key",t.key,n,r);if(e===Nd)return Nd;e===Dd&&(t.key=null);const i=await Ld("value",t.value,n,r);if(i===Nd)return Nd;i===Dd&&(t.value=null)}return i}function $d(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 jd(e,t,n,r){return"function"==typeof n?n(e,t,r):Ad(t)?n.Map?.(e,t,r):xd(t)?n.Seq?.(e,t,r):Sd(t)?n.Pair?.(e,t,r):_d(t)?n.Scalar?.(e,t,r):Id(t)?n.Alias?.(e,t,r):void 0}function Fd(e,t,n){const r=t[t.length-1];if(Cd(r))r.items[e]=n;else if(Sd(r))"key"===e?r.key=n:r.value=n;else{if(!Ed(r)){const e=Id(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Pd.BREAK=Nd,Pd.SKIP=Md,Pd.REMOVE=Dd,Rd.BREAK=Nd,Rd.SKIP=Md,Rd.REMOVE=Dd;const Bd={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qd=e=>e.replace(/[!,[\]{}]/g,e=>Bd[e]);class zd{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},zd.defaultYaml,e),this.tags=Object.assign({},zd.defaultTags,t)}clone(){const e=new zd(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new zd(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:zd.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},zd.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:zd.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},zd.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+qd(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&&Td(e.contents)){const t={};Pd(e.contents,(e,n)=>{Td(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 Ud(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 Vd(e){const t=new Set;return Pd(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Wd(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function Kd(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=Kd(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=Kd(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=Kd(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=Kd(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function Gd(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Gd(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!_d(r=e)&&!Cd(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)}zd.defaultYaml={explicit:!1,version:"1.2"},zd.defaultTags={"!!":"tag:yaml.org,2002:"};class Hd{constructor(e){Object.defineProperty(this,kd,{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(!Ed(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=Gd(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?Kd(i,{"":o},"",o):o}}class Yd extends Hd{constructor(e){super(md),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Pd(e,{Node:(e,n)=>{if(n===this)return Pd.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||(Gd(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=Jd(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(Ud(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 Jd(e,t,n){if(Id(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Cd(t)){let r=0;for(const i of t.items){const t=Jd(e,i,n);t>r&&(r=t)}return r}if(Sd(t)){const r=Jd(e,t.key,n),i=Jd(e,t.value,n);return Math.max(r,i)}return 1}const Zd=e=>!e||"function"!=typeof e&&"object"!=typeof e;class Qd extends Hd{constructor(e){super(wd),this.value=e}toJSON(e,t){return t?.keep?this.value:Gd(this.value,e,t)}toString(){return String(this.value)}}Qd.BLOCK_FOLDED="BLOCK_FOLDED",Qd.BLOCK_LITERAL="BLOCK_LITERAL",Qd.PLAIN="PLAIN",Qd.QUOTE_DOUBLE="QUOTE_DOUBLE",Qd.QUOTE_SINGLE="QUOTE_SINGLE";function Xd(e,t,n){if(Ed(e)&&(e=e.contents),Td(e))return e;if(Sd(e)){const t=n.schema[yd].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 Yd(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 Qd(e);return c&&(c.node=t),t}l=e instanceof Map?o[yd]:Symbol.iterator in Object(e)?o[vd]:o[yd]}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 Qd(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function ep(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 Xd(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 tp=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class np extends Hd{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=>Td(t)||Sd(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(tp(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Cd(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,ep(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(Cd(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&&_d(i)?i.value:i:Cd(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Sd(t))return!1;const n=t.value;return null==n||e&&_d(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!!Cd(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(Cd(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,ep(this.schema,r,t))}}}}np.maxFlowStringSingleLineLength=60;const rp=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ip(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const sp=(e,t,n)=>e.endsWith("\n")?ip(n,t):n.includes("\n")?"\n"+ip(n,t):(e.endsWith(" ")?"":" ")+n,op="flow",ap="block",cp="quoted";function lp(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===ap&&(m=up(e,m,t.length),-1!==m&&(h=m+c));for(let r;r=e[m+=1];){if(n===cp&&"\\"===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===ap&&(m=up(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===cp){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===cp&&u[i]&&(b+=`${e[i]}\\`),b+=`\n${t}${e.slice(i+1,s)}`)}return b}function up(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 dp=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),pp=e=>/^(%|---|\.\.\.)/m.test(e);function hp(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(pp(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:lp(o,s,cp,dp(t,!1))}function fp(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return hp(e,t);const n=t.indent||(pp(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:lp(r,n,op,dp(t,!1))}function mp(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=hp;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?fp:i&&!t?hp:n?fp:hp}return r(e,t)}let gp;try{gp=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{gp=/\n+(?!\n|$)/g}function yp({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 mp(n,r);const l=r.indent||(r.forceBlockIndent||pp(n)?" ":""),u="literal"===o||"folded"!==o&&t!==Qd.BLOCK_FOLDED&&(t===Qd.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(gp,`$&${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}${lp(`${b}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${h}`,l,ap,dp(r,!0))}`}function bp(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!==Qd.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Qd.QUOTE_DOUBLE);const c=e=>{switch(e){case Qd.BLOCK_FOLDED:case Qd.BLOCK_LITERAL:return i||s?mp(o.value,t):yp(o,t,n,r);case Qd.QUOTE_DOUBLE:return hp(o.value,t);case Qd.QUOTE_SINGLE:return fp(o.value,t);case Qd.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 mp(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?mp(s,t):yp(e,t,n,r);if(!a&&!u&&i!==Qd.PLAIN&&s.includes("\n"))return yp(e,t,n,r);if(pp(s)){if(""===c)return t.forceBlockIndent=!0,yp(e,t,n,r);if(a&&c===l)return mp(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 mp(s,t)}return a?d:lp(d,c,op,dp(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 wp(e,t){const n=Object.assign({blockQuote:!0,commentString:rp,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 vp(e,t,n,r){if(Sd(e))return e.toString(t,n,r);if(Id(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=Td(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(_d(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=(_d(e)||Cd(e))&&e.anchor;s&&Ud(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):_d(s)?bp(s,t,n,r):s.toString(t,n,r);return o?_d(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function kp(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function Ip(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&Ep(n))if(r=Id(r)?r.resolve(e.doc):r,xd(r))for(const n of r.items)Ap(e,t,n);else if(Array.isArray(r))for(const n of r)Ap(e,t,n);else Ap(e,t,r);else{const i=Gd(n,"",e);if(t instanceof Map)t.set(i,Gd(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(Td(e)&&n?.doc){const t=wp(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)+'..."'),kp(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=Gd(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const Ep=e=>"<<"===e||_d(e)&&"<<"===e.value&&(!e.type||e.type===Qd.PLAIN);function Ap(e,t,n){const r=e&&Id(n)?n.resolve(e.doc):n;if(!Ad(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 Sp(e,t,n){const r=Xd(e,void 0,n),i=Xd(t,void 0,n);return new _p(r,i)}class _p{constructor(e,t=null){Object.defineProperty(this,kd,{value:bd}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Td(t)&&(t=t.clone(e)),Td(n)&&(n=n.clone(e)),new _p(t,n)}toJSON(e,t){return Ip(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=Td(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Cd(e)||!Td(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||Cd(e)||(_d(e)?e.type===Qd.BLOCK_FOLDED||e.type===Qd.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=vp(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+=sp(w,n.indent,l(p)):b&&i&&i(),w;y&&(p=null),h?(p&&(w+=sp(w,n.indent,l(p))),w=`? ${w}\n${a}:`):(w=`${w}:`,p&&(w+=sp(w,n.indent,l(p)))),Td(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||!_d(t)||(n.indentAtStart=w.length+1),b=!1,u||!(c.length>=2)||n.inFlow||h||!xd(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let v=!1;const k=vp(t,n,()=>v=!0,()=>b=!0);let I=" ";if(p||f||m)I=f?"\n":"",m&&(I+=`\n${ip(l(m),n.indent)}`),""!==k||n.inFlow?I+=`\n${n.indent}`:"\n"===I&&(I="\n\n");else if(!h&&Cd(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+=sp(w,n.indent,l(g)):b&&i&&i(),w}(this,e,t,n):JSON.stringify(this)}}function xp(e,t,n){return(t.inFlow??e.flow?Tp:Cp)(e,t,n)}function Cp({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(Td(i))!d&&i.spaceBefore&&p.push(""),Np(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(Sd(i)){const e=Td(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),Np(n,p,e.commentBefore,d))}d=!1;let a=vp(i,u,()=>o=null,()=>d=!0);o&&(a+=sp(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"+ip(l(e),c),a&&a()):d&&o&&o(),h}function Tp({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(Td(i))i.spaceBefore&&d.push(""),Np(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(Sd(i)){const e=Td(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),Np(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Td(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=vp(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=sp(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 Np({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=ip(t(r),e);n.push(i.trimStart())}}function Mp(e,t){const n=_d(t)?t.value:t;for(const r of e)if(Sd(r)){if(r.key===t||r.key===n)return r;if(_d(r.key)&&r.key.value===n)return r}}class Dp extends np{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(yd,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(Sp(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=Sd(e)?e:e&&"object"==typeof e&&"key"in e?new _p(e.key,e.value):new _p(e,e?.value);const r=Mp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);_d(r.value)&&Zd(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=Mp(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=Mp(this.items,e),r=n?.value;return(!t&&_d(r)?r.value:r)??void 0}has(e){return!!Mp(this.items,e)}set(e,t){this.add(new _p(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)Ip(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!Sd(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})),xp(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Pp={collection:"map",default:!0,nodeClass:Dp,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(Ad(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Dp.from(e,t,n)};class Op extends np{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(vd,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Rp(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Rp(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&_d(r)?r.value:r}has(e){const t=Rp(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Rp(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];_d(r)&&Zd(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(Gd(e,String(r++),t));return n}toString(e,t,n){return e?xp(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(Xd(s,void 0,n))}}return i}}function Rp(e){let t=_d(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const Lp={collection:"seq",default:!0,nodeClass:Op,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(xd(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Op.from(e,t,n)},$p={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>bp(e,t=Object.assign({actualString:!0},t),n,r)},jp={identify:e=>null==e,createNode:()=>new Qd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Qd(null),stringify:({source:e},t)=>"string"==typeof e&&jp.test.test(e)?e:t.options.nullStr},Fp={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Qd("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Fp.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Bp({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 qp={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:Bp},zp={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():Bp(e)}},Up={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 Qd(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Bp},Vp=e=>"bigint"==typeof e||Number.isInteger(e),Wp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Kp(e,t,n){const{value:r}=e;return Vp(r)&&r>=0?n+r.toString(t):Bp(e)}const Gp={identify:e=>Vp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Wp(e,2,8,n),stringify:e=>Kp(e,8,"0o")},Hp={identify:Vp,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Wp(e,0,10,n),stringify:Bp},Yp={identify:e=>Vp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Wp(e,2,16,n),stringify:e=>Kp(e,16,"0x")},Jp=[Pp,Lp,$p,jp,Fp,Gp,Hp,Yp,qp,zp,Up];function Zp(e){return"bigint"==typeof e||Number.isInteger(e)}const Qp=({value:e})=>JSON.stringify(e),Xp=[Pp,Lp].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Qp},{identify:e=>null==e,createNode:()=>new Qd(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Qp},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:Qp},{identify:Zp,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})=>Zp(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:Qp}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),eh={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=Qd.BLOCK_LITERAL),t!==Qd.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===Qd.BLOCK_LITERAL?"\n":" ")}return bp({comment:e,type:t,value:a},r,i,s)}};function th(e,t){if(xd(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Sd(r)){if(Ad(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new _p(new Qd(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]=Sd(r)?r:new _p(r)}}else t("Expected a sequence for this tag");return e}function nh(e,t,n){const{replacer:r}=n,i=new Op(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(Sp(o,a,n))}return i}const rh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:th,createNode:nh};class ih extends Op{constructor(){super(),this.add=Dp.prototype.add.bind(this),this.delete=Dp.prototype.delete.bind(this),this.get=Dp.prototype.get.bind(this),this.has=Dp.prototype.has.bind(this),this.set=Dp.prototype.set.bind(this),this.tag=ih.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(Sd(e)?(r=Gd(e.key,"",t),i=Gd(e.value,r,t)):r=Gd(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=nh(e,t,n),i=new this;return i.items=r.items,i}}ih.tag="tag:yaml.org,2002:omap";const sh={collection:"seq",identify:e=>e instanceof Map,nodeClass:ih,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=th(e,t),r=[];for(const{key:e}of n.items)_d(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new ih,n)},createNode:(e,t,n)=>ih.from(e,t,n)};function oh({value:e,source:t},n){return t&&(e?ah:ch).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const ah={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 Qd(!0),stringify:oh},ch={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 Qd(!1),stringify:oh},lh={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:Bp},uh={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():Bp(e)}},dh={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 Qd(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:Bp},ph=e=>"bigint"==typeof e||Number.isInteger(e);function hh(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 fh(e,t,n){const{value:r}=e;if(ph(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return Bp(e)}const mh={identify:ph,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>hh(e,2,2,n),stringify:e=>fh(e,2,"0b")},gh={identify:ph,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>hh(e,1,8,n),stringify:e=>fh(e,8,"0")},yh={identify:ph,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>hh(e,0,10,n),stringify:Bp},bh={identify:ph,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>hh(e,2,16,n),stringify:e=>fh(e,16,"0x")};class wh extends Dp{constructor(e){super(e),this.tag=wh.tag}add(e){let t;t=Sd(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new _p(e.key,null):new _p(e,null);Mp(this.items,t.key)||this.items.push(t)}get(e,t){const n=Mp(this.items,e);return!t&&Sd(n)?_d(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=Mp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _p(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(Sp(e,null,n));return i}}wh.tag="tag:yaml.org,2002:set";const vh={collection:"map",identify:e=>e instanceof Set,nodeClass:wh,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>wh.from(e,t,n),resolve(e,t){if(Ad(e)){if(e.hasAllNullValues(!0))return Object.assign(new wh,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function kh(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 Ih(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Bp(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 Eh={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})=>kh(e,n),stringify:Ih},Ah={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=>kh(e,!1),stringify:Ih},Sh={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(Sh.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=kh(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$/,"")},_h=[Pp,Lp,$p,jp,ah,ch,mh,gh,yh,bh,lh,uh,dh,eh,sh,rh,vh,Eh,Ah,Sh],xh=new Map([["core",Jp],["failsafe",[Pp,Lp,$p]],["json",Xp],["yaml11",_h],["yaml-1.1",_h]]),Ch={binary:eh,bool:Fp,float:Up,floatExp:zp,floatNaN:qp,floatTime:Ah,int:Hp,intHex:Yp,intOct:Gp,intTime:Eh,map:Pp,null:jp,omap:sh,pairs:rh,seq:Lp,set:vh,timestamp:Sh},Th={"tag:yaml.org,2002:binary":eh,"tag:yaml.org,2002:omap":sh,"tag:yaml.org,2002:pairs":rh,"tag:yaml.org,2002:set":vh,"tag:yaml.org,2002:timestamp":Sh};function Nh(e,t){let n=xh.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(xh.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=Ch[e];if(t)return t;const n=Object.keys(Ch).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const Mh=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Dh{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?Nh(e,"compat"):e?Nh(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Th:{},this.tags=Nh(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,yd,{value:Pp}),Object.defineProperty(this,wd,{value:$p}),Object.defineProperty(this,vd,{value:Lp}),this.sortMapEntries="function"==typeof s?s:!0===s?Mh:null}clone(){const e=Object.create(Dh.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Ph{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kd,{value:gd});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 zd({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Ph.prototype,{[kd]:{value:gd}});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=Td(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Oh(this.contents)&&this.contents.add(e)}addIn(e,t){Oh(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Vd(this);e.anchor=!t||n.has(t)?Wd(t||"a",n):t}return new Yd(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=Vd(e));const s=Wd(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!_d(t.node)&&!Cd(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=Xd(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&Cd(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 _p(r,i)}delete(e){return!!Oh(this.contents)&&this.contents.delete(e)}deleteIn(e){return tp(e)?null!=this.contents&&(this.contents=null,!0):!!Oh(this.contents)&&this.contents.deleteIn(e)}get(e,t){return Cd(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return tp(e)?!t&&_d(this.contents)?this.contents.value:this.contents:Cd(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!Cd(this.contents)&&this.contents.has(e)}hasIn(e){return tp(e)?void 0!==this.contents:!!Cd(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=ep(this.schema,[e],t):Oh(this.contents)&&this.contents.set(e,t)}setIn(e,t){tp(e)?this.contents=t:null==this.contents?this.contents=ep(this.schema,Array.from(e),t):Oh(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 zd({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 zd({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 Dh(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=Gd(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?Kd(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=wp(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(ip(t,""))}let o=!1,a=null;if(e.contents){if(Td(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(ip(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=vp(e.contents,i,()=>a=null,t);a&&(c+=sp(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(vp(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(ip(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(ip(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Oh(e){if(Cd(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Rh extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Lh extends Rh{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class $h extends Rh{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const jh=(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 Fh(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 Bh(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(Bh(t.key)||Bh(t.value))return!0}return!1;default:return!0}}function qh(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&Bh(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function zh(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||_d(t)&&_d(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const Uh="All mapping items must start at the same column";function Vh(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 Wh="Block collections are not allowed within flow collections",Kh=e=>e&&("block-map"===e.type||"block-seq"===e.type);function Gh(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??Dp)(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=Fh(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",Uh)),!h.anchor&&!h.tag&&!d){c=h.end,h.comment&&(o.comment?o.comment+="\n"+h.comment:o.comment=h.comment);continue}(h.hasNewlineAfterProp||Bh(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",Uh);const m=h.end,g=u?e(n,u,h,i):t(n,m,l,null,h,i);n.schema.compat&&qh(r.indent,u,i),zh(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Fh(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&&qh(r.indent,p,i),a=c.range[2];const l=new _p(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 _p(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??Op)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Fh(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&&qh(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?Dp:Op))(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=Fh(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&&Bh(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];Sd(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);Kh(p)&&i(g.range,"BLOCK_IN_FLOW",Wh);const y=Fh(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?Kh(f)&&i(b.range,"BLOCK_IN_FLOW",Wh):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const w=new _p(g,b);if(n.options.keepSourceTokens&&(w.srcToken=l),o){const e=c;zh(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(w)}else{const e=new Dp(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],Kh(f)&&i(r.range,"BLOCK_IN_FLOW",Wh)}}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=Vh(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 Hh(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?Qd.BLOCK_FOLDED:Qd.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===Qd.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 Yh(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=Qd.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 Jh(e)}(s,l);break;case"single-quoted-scalar":a=Qd.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Jh(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=Qd.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}=Zh(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=Qh[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+=Xh(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=Vh(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Jh(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 Zh(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 Qh={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function Xh(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 ef(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?Hh(e,t,r):Yh(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[wd];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[wd]}(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[wd];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[wd];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[wd];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=_d(s)?s:new Qd(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new Qd(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 tf(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 nf={composeNode:rf,composeEmptyNode:sf};function rf(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 Yd(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=Vh(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=ef(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===Dp.tagName&&"map"===o||s===Op.tagName&&"seq"===o||!o)return Gh(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),Gh(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=Gh(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Td(l)?l:new Qd(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(nf,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=sf(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 sf(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=ef(e,{type:"scalar",offset:tf(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 of(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 af(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 cf{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=of(e);r?this.warnings.push(new $h(i,t,n)):this.errors.push(new Lh(i,t,n))},this.directives=new zd({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=af(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(Cd(i)&&!i.flow&&i.items.length>0){let e=i.items[0];Sd(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:af(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=of(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 Ph(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Fh(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?rf(l,i,u,o):sf(l,u.end,r,null,u,o);const d=c.contents.range[2],p=Vh(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 Lh(of(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 Lh(of(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=Vh(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 Lh(of(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 Ph(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 lf(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 uf(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 df(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=df(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=pf(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=pf(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=pf(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 pf({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=df(t)),n)for(const e of n)i+=e.source;return r&&(i+=df(r)),i}const hf=Symbol("break visit"),ff=Symbol("skip children"),mf=Symbol("remove item");function gf(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),yf(Object.freeze([]),e,t)}function yf(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=yf(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===hf)return hf;r===mf&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}gf.BREAK=hf,gf.SKIP=ff,gf.REMOVE=mf,gf.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},gf.parentCollection=(e,t)=>{const n=gf.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 bf="\ufeff",wf="",vf="",kf="";function If(e){switch(e){case bf:return"byte-order-mark";case wf:return"doc-mode";case vf:return"flow-error-end";case kf: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 Ef=Object.freeze({__proto__:null,BOM:bf,DOCUMENT:wf,FLOW_END:vf,SCALAR:kf,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=bp({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 lf(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 bf:return"<BOM>";case wf:return"<DOC>";case vf:return"<FLOW_END>";case kf: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 Lh([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Yh(e,t,r);case"block-scalar":return Hh({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=bp({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}];lf(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'"':uf(e,c,"double-quoted-scalar");break;case"'":uf(e,c,"single-quoted-scalar");break;default:uf(e,c,"scalar")}},stringify:e=>"type"in e?df(e):pf(e),tokenType:If,visit:gf});function Af(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const Sf=new Set("0123456789ABCDEFabcdef"),_f=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),xf=new Set(",[]{}"),Cf=new Set(" ,[]{}\n\r\t"),Tf=e=>!e||Cf.has(e);class Nf{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)&&Af(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]===bf&&(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 wf,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&&Af(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&Af(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Af(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)&&Af(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(Tf),"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("..."))&&Af(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield vf,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(Tf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Af(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=>Af(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 kf,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(Af(t)||e&&xf.has(t))break;n=r}else if(Af(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&&xf.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&&xf.has(t))break;n=r}return t||this.atEnd?(yield kf,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(Tf))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Af(t)||e&&xf.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(;!Af(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(_f.has(t))t=this.buffer[++e];else{if("%"!==t||!Sf.has(this.buffer[e+1])||!Sf.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 Mf{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 Df(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Pf(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 Of(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 Rf(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 Lf(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 $f(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Df(t.start,"explicit-key-ind")||Df(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Of(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 jf{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 Nf,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=If(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&&$f(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===Pf(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!==Pf(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=Lf(Rf(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(Df(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(Of(t.key)&&!Df(t.sep,"newline")){const e=Lf(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(Df(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Lf(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]}):Df(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||Df(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=Lf(Rf(t));$f(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=Lf(Rf(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=Lf(Rf(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 Ff(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new Mf||null,prettyErrors:t}}function Bf(e,t={}){const{lineCounter:n,prettyErrors:r}=Ff(t),i=new jf(n?.addNewLine),s=new cf(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(jh(e,n)),t.warnings.forEach(jh(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function qf(e,t={}){const{lineCounter:n,prettyErrors:r}=Ff(t),i=new jf(n?.addNewLine),s=new cf(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 Lh(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(jh(e,n)),o.warnings.forEach(jh(e,n))),o}function zf(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=qf(e,n);if(!i)return null;if(i.warnings.forEach(e=>kp(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 Uf(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 Ph(e,r,n).toString(n)}var Vf=Object.freeze({__proto__:null,Alias:Yd,CST:Ef,Composer:cf,Document:Ph,Lexer:Nf,LineCounter:Mf,Pair:_p,Parser:jf,Scalar:Qd,Schema:Dh,YAMLError:Rh,YAMLMap:Dp,YAMLParseError:Lh,YAMLSeq:Op,YAMLWarning:$h,isAlias:Id,isCollection:Cd,isDocument:Ed,isMap:Ad,isNode:Td,isPair:Sd,isScalar:_d,isSeq:xd,parse:zf,parseAllDocuments:Bf,parseDocument:qf,stringify:Uf,visit:Pd,visitAsync:Rd}),Wf=Object.freeze({__proto__:null,Alias:Yd,CST:Ef,Composer:cf,Document:Ph,Lexer:Nf,LineCounter:Mf,Pair:_p,Parser:jf,Scalar:Qd,Schema:Dh,YAMLError:Rh,YAMLMap:Dp,YAMLParseError:Lh,YAMLSeq:Op,YAMLWarning:$h,default:Vf,isAlias:Id,isCollection:Cd,isDocument:Ed,isMap:Ad,isNode:Td,isPair:Sd,isScalar:_d,isSeq:xd,parse:zf,parseAllDocuments:Bf,parseDocument:qf,stringify:Uf,visit:Pd,visitAsync:Rd});class Kf{#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=Vf.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=Vf.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 Vf.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Gf{#Et;constructor(e){this.#Et=e}async execute(){return await this.#Et.execute()}}class Hf{#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 Yf{}class Jf extends Yf{#_t;constructor(e){super(),this.#_t=e}execute(){}}let Zf=class extends Gf{#xt;constructor(e){super(e),this.#xt=new Hf,this.#xt.register("onExtension",Jf),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}},Qf=class extends Gf{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 Xf(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 em=class extends Gf{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:[Xf(n)],when:r})})}return e}},tm=class extends Gf{constructor(e){super(e)}async execute(){return await super.execute()}},nm=class extends Gf{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=ld.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 rm extends Gf{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 im=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 sm=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 om(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 am=new Map;function cm(e){const t=am.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),am.delete(e)}const lm={register(e,t,n){const r=n?.target??document.head,i=am.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),am.set(e,i),{id:e,dispose(){cm(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),am.set(e,s),{id:e,dispose(){cm(e)}}},unregister(e){cm(e)},has:e=>!!am.has(e)||!!document.getElementById(e)};const um={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=Ql.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 Kf(e),n=new Qf(t),r=new em(n),i=new tm(r),s=new nm(i),o=new rm(s);return new Zf(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"),om("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new ud(e),n=new hd(t),r=new fd(n);return new pd(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 mn(()=>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"),om("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#Ut.set(e,"failed"),om("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=ja().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 ha(pa.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 ha(pa.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 ha(pa.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"),om("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),om("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:lm,metadata:{manager:im},settings:{manager:sm}};function dm(e){if(null==e)return!1;if(Array.isArray(e))return e.some(dm);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(dm)}return!1}function pm(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=hm(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=hm(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?dm(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 hm(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 fm{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await Ao().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=qa();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 mm(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=pm(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 mm(e,t){for(const n of e)n.isDirectory?n.children&&mm(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let gm;function ym(){return gm||(gm=new fm),gm}function bm(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 wm(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 vm(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 km=/token|secret|key|password|passwd|api[_-]?key/i;function Im(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=km.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 Em(e,t){const n=Date.now(),r=ym().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=pm(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(dm(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=bm(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 wm(I,E,s,t.timeoutMs),n=Im(vm(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 Am(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Sm(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function _m(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xm(e,t){const n=e.value;switch(e.type){case"isType":return{passed:Sm(t)===String(n??""),expected:String(n??""),actual:Sm(t)};case"equals":return{passed:_m(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=>_m(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:Sm(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:Sm(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):Sm(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:Sm(t)}}}function Cm(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=Am(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=xm(a,r);else if("string"==typeof a)o=xm({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=xm({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 Tm(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 Nm(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 Mm(){return Date.now()}function Dm(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Pm(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function Om(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Rm(){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 Lm(){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 $m(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 jm(e){try{const t=Rm();if(!t)throw new Error("[FlowEngine] Capability gateway not available. Gateway is mandatory for all FS operations.");{const r=await n();await t.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 Fm(e,t){const r=Rm();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 n();await r.call("fs.writeFile",{path:e,content:t},{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 Bm(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:Mm(),source:i?.source??"flow:engine",kind:n},payload:r})}const qm=new Set(["sensitive","secret"]);function zm(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Um(e,t,n,r){if(!function(e,t,n){return!(!n||!qm.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:zm(e)}}const Vm=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 Wm{async ensureBase(){await jm(".punica"),await jm(Om(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await jm(Om(".punica","workflow-runs",e)),await jm(Om(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=Mm();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=Um(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=Om(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let h;h=d?String(u??""):Dm(l??{},2);const f=n.sizeBudget?.maxBytes;if(c||"number"!=typeof f)"number"==typeof f&&Vm.acquire(e,h.length,f);else{Vm.acquire(e,h.length,f)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,h.length),h=Dm(c,2),Vm.acquire(e,h.length,f))}await Fm(p,h);const m=h.length,g=Pm(d?String(u??""):Dm(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 Bm("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function Km(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 Gm(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Hm(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 Ym(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 Jm(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 Zm(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Qm(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 Xm(e,t,n){const r=Qm(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 eg(e,t){const n=Qm(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 tg(e,t){const n=Qm(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 ng(e,t=".punica"){const n=Zm(t,"workflow-runs",e.runId),r=Zm(n,"checkpoint.json"),i=Zm(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await eg("writeCheckpoint",n),await Xm("writeCheckpoint",i,s);try{await async function(e,t,n){const r=Qm(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 tg("writeCheckpoint",r)}catch{}await Xm("writeCheckpoint",r,s);try{await tg("writeCheckpoint",i)}catch{}}}async function rg(e,t=".punica"){const n=Zm(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=Qm(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 ig(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 sg{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:Mm(),startedAtMs:Mm(),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=Hm(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}),Bm("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),ig({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",Bm("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 rg(e);if(!n)return!1;{const r=n.dependencyGraphState?Hm(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"),Bm("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=Mm();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 Bm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Bm("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=Om(".punica","workflow-runs",e,"run.json");await Fm(n,Dm({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=Om(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Fm(e,Dm({version:1,updatedAtMs:Mm(),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 ng(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=Om(".punica","workflow-runs","index.json"),t=await async function(e){const t=Rm();if(!t)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 n();return await t.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(t)try{const e=JSON.parse(t);Bm("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class og{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:Mm()};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:Mm(),resolved:!1},Bm("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",Bm("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}),Bm("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),ig({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{}Bm("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:Mm()},{traceId:i.runId}),ig({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",Bm("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;Bm("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:Mm()},{traceId:r.runId}),ig({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=Mm(),Bm("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}),Bm("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 ag=3e4,cg={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const lg=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 ug(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function dg(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 pg=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 hg(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 fg(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=hg(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function mg(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 gg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function yg(e){return String(e??"").split(".").filter(e=>e.length>0)}function bg(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];gg(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function wg(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={...gg(e.defaults)?e.defaults:{},...gg(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?yg(e.fromPath):[],i=r.length?hg(t,r):t;if(void 0===i)continue;const o=e.toPath?yg(e.toPath):[];o.length?bg(s,o,i):gg(i)?Object.assign(s,i):s[e.fromId]=i}return s}class vg 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 kg(e,t){if(function(e){return!0===e.cancelled}(e))throw new vg(e.run?.runId,t)}class Ig{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=Rm();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",Bm("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=Mm(),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}),Bm("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}),ig({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:wg(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),Bm("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}),ig({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",Bm("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",Bm("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=Mm(),a.error={message:o},Bm("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}),ig({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=Mm(),n.run.error={message:o,nodeId:s,correlationId:c},Bm("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),Bm("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),ig({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=dg(f,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Bm("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=Mm(),Bm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),Bm("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),ig({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=Zm(n,"workflow-runs",e.runId),i=Zm(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await eg("writeRunHistory",r),await Xm("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=Zm(t,"workflow-runs",e,"checkpoint.json");try{await tg("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;!Gm(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=Km(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=>{Jm(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 Ym(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Ym(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;){kg(r),h++,l.attempt=h,l.status="RUNNING",l.startedAtMs=Mm();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:wg(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 vg)throw l.status="CANCELLED",l.endedAtMs=Mm(),e;const t=String(e?.message??e);if(h<=d){const e=dg(h,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=Mm(),l.error={message:t},e}}f&&(Ym(o,!0,n),await this.persistRun(e))}catch(t){Ym(o,!1,n),t instanceof vg||(r.run.status="FAILED",r.run.endedAtMs=Mm(),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=Mm(),Bm("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),Bm("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),ig({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&&(ig({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=pg.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:ag,retry:{...cg},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=pg.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,ug(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=Mm(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return pg.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class Eg 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 Ag(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new Eg(e??0,t);return n}const Sg="__default__";class _g{workspaceId;#sn=new Map;#on=new Map;#an=new Map;#cn=new Wm;#ke=!1;#ln=new Map;#un;#dn;#pn;constructor(e=Sg){this.workspaceId=e,this.#un=new sg(this.#sn,this.#ln,this.#cn),this.#dn=new og(this.#sn,this.#on,this.#an,e=>this.#un.persistRun(e),()=>this.#un.persistIndex(),e=>this.#hn(e)),this.#pn=new Ig(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=Ag(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;ig({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 xg=new Map,Cg=new Map,Tg=new Map;function Ng(e){const t=e??Sg;let n=xg.get(t);return n||(n=new _g(t),xg.set(t,n)),n}let Mg=!1;const Dg=new class{initialize(){if(Mg)return;Mg=!0;const e=punica.kernel.Commands.manager;e.registerCommand(Ke.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(Ke.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(Ke.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(Ke.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(Ke.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(Ke.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(Ke.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(Ke.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(Ke.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:Sg}(e),n=Ng(t);n.initialize();const r=await n.startRun(e);return Cg.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 xg.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(Ag(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=Ng(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Cg.set(n.runId,t.workspaceId),n}#gn(e){const t=Cg.get(e);if(t)return xg.get(t);for(const[t,n]of xg.entries())if(n.hasRun(e))return Cg.set(e,t),n}#yn(e){const t=Tg.get(e);if(t)return xg.get(t);for(const[t,n]of xg.entries())if(n.hasPending(e))return Tg.set(e,t),n}};function Pg(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 Og(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class Rg{packages=new Map;async discover(){this.packages.clear();try{if(!await Ao().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=qa();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 Lg(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(!Og(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 Lg(e,t){for(const n of e)n.isDirectory?n.children&&Lg(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let $g;function jg(){return $g||($g=new Rg),$g}const Fg=new Set(["COMPLETED","FAILED","CANCELLED"]);function Bg(e){return new Promise(t=>setTimeout(t,e))}async function qg(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&&(Fg.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await Bg(250)}return{record:i,timedOut:!0}}async function zg(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(Tm(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await qg(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(Tm(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(Tm(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(Cm(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(Tm(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const Ug={validator:{validate:pm},registry:{discover:()=>ym().discover(),get:e=>ym().get(e),list:()=>ym().list(),search:e=>ym().search(e),setTestReport:(e,t)=>ym().setTestReport(e,t),getLatestTestReport:e=>ym().getLatestTestReport(e)},runner:{run:Em},test:{run:async function(e,t){const n=ym(),r=n.get(e);if(!r){if(t?.manifest){if(Og(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=Dg,o=Pg(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 zg(s,o,e,n,t?.workspaceId))}const l=Nm({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{ym().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 Em(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=Cm(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=Tm(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=Nm({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}}},Vg={discover:()=>jg().discover(),get:e=>jg().get(e),list:()=>jg().list(),search:e=>jg().search(e),unregister:e=>jg().unregister(e),run:(e,t)=>async function(e,t){const n=jg().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??Dg,i=t?.timeoutMs??3e4,s=Pg(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 qg(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:Pg,isAgentManifest:Og},Wg=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",[]]]),Kg=new Set(["COMPLETED","FAILED","CANCELLED"]);const Gg=new class{canTransitionTo(e,t){if(e===t)return!1;const n=Wg.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 Wg.get(e)??[]}isTerminal(e){return Kg.has(e)}},Hg=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Yg={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Jg={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function Zg(e){return{x:Jg.marginX+e%6*240,y:Jg.marginY+120*Math.floor(e/6)}}function Qg(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 Xg(e,t){const n={...Jg,...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]=Zg(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]=Zg(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,Qg(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 ey;function ty(e){if(!ey)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 ey}function ny(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");ey=e}function ry(){ey=void 0}function iy(){return ey}function sy(e){return ty("createFlowRenderer").createRenderer(e)}function oy(e){return ty("createViewportController").createViewportController(e)}function ay(e,t){return ty("attachZoomControl").attachZoomControl(e,t)}function cy(e,t){return ty("attachMinimap").attachMinimap(e,t)}function ly(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 uy={setRendererProvider:ny,resetRendererProvider:ry,getRendererProvider:iy,createFlowRenderer:sy,createViewportController:oy,attachZoomControl:ay,attachMinimap:cy,mergeViewSnapshotIntoNotebook:ly,computeFlowLayout:Xg,gridFallbackPosition:Zg,get rendererProvider(){return ey}},dy=Object.freeze({__proto__:null,attachMinimap:cy,attachZoomControl:ay,computeFlowLayout:Xg,createFlowRenderer:sy,createViewportController:oy,default:uy,getRendererProvider:iy,gridFallbackPosition:Zg,mergeViewSnapshotIntoNotebook:ly,resetRendererProvider:ry,setRendererProvider:ny});function py(e,t,n){return{path:e,message:t,severity:"error",code:n}}function hy(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const fy="WF_INVALID_VERSION",my="WF_INVALID_EDGE_REF",gy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function yy(e){return"string"==typeof e&&gy.test(e)}const by=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()}},wy={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}},vy={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}},ky={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}},Iy={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 Ey(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function Ay(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 Sy={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=Ey(o.ref),l=Ey(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=Ay(p,s.fromPath),m=Ay(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}},_y=["while","forEach"],xy={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(!_y.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 Cy(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+Cy(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const Ty={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Cy(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}},Ny=[wy,vy,ky,Iy,Sy,xy,Ty];const My=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 Ny)this.#gt.set(e.id,e)}};function Dy(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 Py(e){return e.map(e=>`${e.from}=>${e.to}`)}function Oy(e,t){return`${e}=>${t}`}const Ry=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(Oy(e.from,e.to),e)}unregister(e,t){return this.#wn.delete(Oy(e,t))}find(e,t){return this.#wn.get(Oy(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(!yy(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(!yy(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)=>Dy(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:Py(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:Py(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:Py(a)}}return{ok:!0,document:o,appliedTransformers:Py(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Dy(this.#wn,e,t)}};function Ly(){return Date.now()}class $y{#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:Ly()}),{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:Ly()}))}}}unregister(e){const t=this.#je.get(e);return!!t&&(t.unsubscribed=!0,this.#je.delete(e),this.#vn({type:"unregistered",triggerId:e,ts:Ly()}),!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-${Ly()}-${Math.floor(1e6*Math.random())}`,i=Ly();this.#vn({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),ig({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:Ly(),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 jy=new $y;let Fy=jy;const By={get manager(){return Fy},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()");Fy!==e&&Fy instanceof $y&&Fy.clear(),Fy=e},resetProvider(){Fy instanceof $y&&Fy.clear(),Fy=jy}};function qy(e,t){return`${e}=>${t}`}const zy={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(qy(e.from,e.to),e)}unregister(e,t){return this.#kn.delete(qy(e,t))}find(e,t){return this.#kn.get(qy(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}},Uy={...Ug,agents:Vg,engine:{manager:Dg,statusStateMachine:Gg,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=Yg[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(Hg,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:dy,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(py("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',fy)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(py("kind",'kind must equal "Workflow"',fy)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!yy(o)){const e=py("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(py("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(py("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(py("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(py(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(py(`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(py(`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(py(`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(py(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(py(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(py(`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(py("graph.nodes","flow-input node is required when edges reference it")),h&&!d&&n.push(py("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(py("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(py(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(py(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(py(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,my)),i&&!l.has(i)&&n.push(py(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,my))}),"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(py("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(hy(`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?py:hy)(`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:by,linter:My,migrations:Ry,checkpoints:zy},triggers:By};class Vy{name=ze.MANAGER;version="1.0.0";dependencies=[je.COMMANDS,je.EVENTS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.COMMANDS),s=r.getState(je.EVENTS),o=r.getState(Fe.WORKSPACE),a=r.getState(Be.LAYOUT);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(s!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==t.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(void 0!==a&&a!==t.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 Wy{name=qe.VALIDATOR;version="1.0.0";dependencies=[];#vt=t.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 Ky(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 Gy{prepareExecutionConfig(e){const t=Ky(e);if(!t)return{};const n=Lm(),r=n?.getSpec?.(t);return{capabilityDefaults:$m(r)}}async acquireResources(e,t,n){const r=Ky(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 lg.acquire(n,e.concurrency.max),()=>{lg.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=Ky(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Rm();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=Lm(),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:Pm(Dm(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Hy(e){return e.data??{}}function Yy(e){return e.nodeOutputs??new Map}async function Jy(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:Pm(Dm(i,0),320),artifactIds:[s.id]}}class Zy{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=Hy(e),i=fg(r.predicate,Yy(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:mg(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Jy(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Jy(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Hy(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=fg(r.collection,Yy(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 Jy(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Hy(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=fg(r.predicate,Yy(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=mg(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Jy(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Hy(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 Jy(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Jy(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Jy(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Hy(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=by.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=fg(r.input,Yy(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:Pm(Dm(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 Qy{async execute(e,t){return{output:t.runInput??null}}}class Xy{async execute(e,t){return{output:t.resolvedInput??null}}}let eb=!1;class tb{name=qe.ENGINE;version="1.0.0";dependencies=[je.EVENTS,je.POLICY,je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.EVENTS),s=r.getState(je.POLICY),o=r.getState(je.COMMANDS);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(s!==t.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(eb||(pg.register("ivyNode",new Gy),pg.register("primitive",new Zy),pg.register("flowInput",new Qy),pg.register("flowOutput",new Xy),eb=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class nb{name=qe.SHELL;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 rb{name=je.EVENTS;version="1.0.0";dependencies=[];#vt=t.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 ib{name=je.COMMANDS;version="1.0.0";dependencies=[];#vt=t.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 sb{name=je.POLICY;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 ob{name=je.HISTORY;version="1.0.0";dependencies=[];#vt=t.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 ab{name=je.TIME_SERVER;version="1.0.0";dependencies=[];#vt=t.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 cb{name=je.TASKS;version="1.0.0";dependencies=[Fe.TERMINALS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(Fe.TERMINALS),s=r.getState(Fe.WORKSPACE);if(i!==t.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(s!==t.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 lb{name=je.NOTIFICATIONS;version="1.0.0";dependencies=[];#vt=t.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 ub{name=je.AI;version="1.0.0";dependencies=[je.EVENTS,je.POLICY,je.LLM];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.EVENTS),s=r.getState(je.POLICY),o=r.getState(je.LLM);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(s!==t.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==t.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 db=class{name=je.LLM;version="1.0.0";dependencies=[je.EVENTS,je.POLICY];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.EVENTS),s=r.getState(je.POLICY);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(s!==t.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:Ht,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class pb{name=Fe.FS;version="1.0.0";dependencies=[];#vt=t.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 hb{name=Fe.SEARCH;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 fb{name=Fe.VCS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 mb{name=Fe.WORKSPACE;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 gb{name=Fe.LLM;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 yb{name=Fe.TASKS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 bb{name=Fe.SECRETS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 wb{name=Fe.TERMINALS;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 vb{name=Be.ACTIVITY_BAR;version="1.0.0";dependencies=[je.COMMANDS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.COMMANDS),s=r.getState(Fe.WORKSPACE);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.activityBar");if(s!==t.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 kb{name=Be.STATUSBAR;version="1.0.0";dependencies=[je.EVENTS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.EVENTS)!==t.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 Ib{name=Be.VIEW;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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 Eb{name=Be.VIEWS;version="1.0.0";dependencies=[Be.LAYOUT,je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(Be.LAYOUT)!==t.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 Ab{name=Be.KEYBOARD_SHORTCUTS;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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:[Xf(t)],when:r})};t("mod+j",Ue.TOGGLE_PANEL),t("mod+b",Ue.TOGGLE_PRIMARY_SIDEBAR),t("mod+l",Ue.TOGGLE_SECONDARY_SIDEBAR)}()}}class Sb{name=Be.LAYOUT;version="1.0.0";dependencies=[je.COMMANDS,Fe.WORKSPACE];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e,i=r.getState(je.COMMANDS),s=r.getState(Fe.WORKSPACE);if(i!==t.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before shell.layout");if(s!==t.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 _b{name=Be.CONTENT_TABS;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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 xb{name=Be.PANEL_TABS;version="1.0.0";dependencies=[je.COMMANDS];#vt=t.CREATED;get state(){return this.#vt}async bootstrap(e){const{punica:n,registry:r}=e;if(r.getState(je.COMMANDS)!==t.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 Cb={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:"*"}},Tb={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 Nb(){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 Mb(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 Db(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 Pb(e,t,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await n(),actor:{type:"user",id:void 0},origin:{kind:t,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function Ob(){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=Nb();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");Mb("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Pb("workspace.readFile","command",t))})}catch(e){Db("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=Nb();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await Pb("workspace.writeFile","command",t)),Mb("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Db("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();Mb("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){Db("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{Mb("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Pb("vcs.status","command",t))})}catch(e){Db("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;Mb("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 Pb("tasks.runCommand","command",t))})}catch(e){Db("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?Mb("capability.llm.invoke.result",t,r):Db(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Db(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?Mb("capability.llm.plan.result",t,r):Db(n,t,r)}catch(e){Db(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:\/\//,""),o=punica.shell?.View?.showChangesPreview;if("function"!=typeof o)throw new Error("UnsupportedError: shell.View.showChangesPreview is not available (headless substrate — no shell contribution)");Mb(n,t,"confirm"===await o({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 Gt(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 Mb(n,t,i)}else Mb(n,t,i);else Db(r,t,i)}catch(e){Db(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?Mb("capability.llm.validator.result",t,r):Db(n,t,r)}catch(e){Db(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?Mb("capability.llm.edit-workflow.result",t,r):Db(n,t,r)}catch(e){Db(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?Mb("capability.llm.reviewer.result",t,r):Db(n,t,r)}catch(e){Db(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 Pb("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(Ue.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(Ue.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(Ue.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Rb="1.0.0",Lb=Zt,$b=oo,jb=ld,Fb=um,Bb=Uy,qb=new class{#In=new Map;#En=new Map;#An=new Map;register(e){if(this.#In.has(e.name))throw new Error(`Module ${e.name} already registered`);for(const t of e.dependencies)if(!this.#In.has(t))throw new Error(`Module ${e.name} depends on ${t}, but ${t} is not registered. Register dependencies before dependent modules.`);this.#In.set(e.name,e),this.#En.set(e.name,t.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 e=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${e.join(" → ")}`);for(const n of e){const e=this.#In.get(n);if(!e)throw new Error(`Module ${n} not found in registry`);try{this.#En.set(n,t.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await e.bootstrap(r),this.#En.set(n,t.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw this.#En.set(n,t.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 e=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${e.join(" → ")}`);for(const n of e){const e=this.#In.get(n);if(!e)throw new Error(`Module ${n} not found in registry`);const r=this.#En.get(n);if(r!==t.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#En.set(n,t.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await e.start(r),this.#En.set(n,t.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw this.#En.set(n,t.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 e){this.#En.get(n)===t.STARTED&&this.#En.set(n,t.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#En.get(e)}areAllModulesReady(){for(const[e,n]of this.#In){if(this.#En.get(e)!==t.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}};En({moduleFactories:{"flow.shell":()=>new nb}}),En({facade:oo,moduleFactories:{"shell.statusbar":()=>new kb,"shell.view":()=>new Ib,"shell.views":()=>new Eb,"shell.keyboardShortcuts":()=>new Ab,"shell.contentTabs":()=>new _b,"shell.panelTabs":()=>new xb,"shell.layout":()=>new Sb,"shell.activityBar":()=>new vb},profiles:[Cb,Tb],defaultProfileId:"ivyx-classic"});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 zu(zf(e))}});e.bootstrap=async function(e){try{console.log("[Punica] Starting module bootstrap...");const t=globalThis.punica;t&&(t.shell=Object.assign(t.shell??{},function(){const e={};for(const t of In)t.facade&&Object.assign(e,t.facade);return e}()));const n=$b.Profile.manager;for(const e of function(){const e=[];for(const t of In)t.profiles&&e.push(...t.profiles);return e}()){const t=e;t?.identity?.id&&!n.registry.has(t.identity.id)&&n.registry.register(t)}if(void 0!==e?.profile)n.loadProfile(e.profile);else{const e=function(){let e;for(const t of In)void 0!==t.defaultProfileId&&(e=t.defaultProfileId);return e}();e&&n.registry.has(e)&&n.registry.setActive(e)}let r;try{r=n.registry.getActive()}catch{r=void 0}if(r){console.log(`[Punica] Active ApplicationProfile: ${r.identity.id}`);const e=t?.shell?.Layout?.manager;if(e&&"function"==typeof e.applyApplicationProfile)try{e.applyApplicationProfile(r)}catch{}}else console.log("[Punica] No ApplicationProfile active — headless boot.");if(qb.register(new rb),qb.register(new ib),qb.register(new ob),qb.register(new ab),qb.register(new lb),qb.register(new Wy),qb.register(new sb),qb.register(new db),qb.register(new ub),qb.register(new tb),qb.register(new pb),qb.register(new hb),qb.register(new fb),qb.register(new mb),qb.register(new gb),qb.register(new bb),qb.register(new wb),qb.register(new yb),qb.register(new Vu),qb.register(new cb),r){const e=An(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(qb.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}qb.register(new Vy),console.log(`[Punica] Module registry initialized with ${qb.getAll().length} modules`),await qb.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}},e.extensions=Fb,e.flow=Bb,e.initialize=function(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Rb,kernel:Lb,shell:$b,runtime:jb,extensions:Fb,flow:Bb};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=En;const t=e.debug??{};t.logTrinityCatalog=Su,t.logTrinityCatalogVerbose=_u,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=Su,n.logTrinityCatalogVerbose=_u);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{Ob(),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}},e.kernel=Lb,e.registerShell=En,e.runtime=jb,e.shell=$b,e.start=async function(){try{console.log("[Punica] Starting system..."),await qb.startAll(),qb.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:Rb}}),console.log("[Punica] System started successfully"),Su()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}},e.version=Rb});
3
3
  //# sourceMappingURL=index.bundle.umd.js.map