@punica/editor 1.10.5 → 1.10.6

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;e.ModuleLifecycleState=void 0,(t=e.ModuleLifecycleState||(e.ModuleLifecycleState={})).CREATED="created",t.BOOTSTRAPPING="bootstrapping",t.BOOTSTRAPPED="bootstrapped",t.BOOTSTRAP_FAILED="bootstrap_failed",t.STARTING="starting",t.STARTED="started",t.START_FAILED="start_failed",t.READY="ready";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?.workspace}function s(){return punica.runtime?.fs}function i(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 o(e){return i(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 a=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function c(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||a.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function l(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,s]of Object.entries(n))c(t)?r[t]=null==s?s:"[REDACTED]":r[t]=e(s);return r}(e)}function u(e,t=2){const n=l(e);return o(JSON.stringify(n,null,t))}function d(e){const t=[];return function e(n,r){if(!n||"object"!=typeof n)return;const s=n,i=s.properties;if(i&&"object"==typeof i)for(const[n,s]of Object.entries(i)){if(!s||"object"!=typeof s)continue;const i=s,o=[...r,n];!0===i.sensitive&&t.push(o),e(i,o)}const o=s.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=s[t];if(Array.isArray(n))for(const t of n)e(t,r)}}(e,[]),t}function p(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 s=!1;for(const e of n)"*"===e[0]&&(1===e.length?s=!0:r.push(e.slice(1)));return s&&0===r.length?t.map(e=>null==e?e:"[REDACTED]"):t.map(t=>e(t,r))}const r={};for(const[s,i]of Object.entries(t)){const t=[];let o=!1;for(const e of n)e[0]===s&&(1===e.length?o=!0:t.push(e.slice(1)));o?r[s]=null==i?i:"[REDACTED]":t.length>0?r[s]=e(i,t):r[s]=i}return r}(e,t)}const f=/^(?:secrets|secret-manager)\./,h=new Set(["value"]);const m={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 s=r[0];return n.activate(s,{reason:"command",trigger:e}).then(()=>{const n=this.#e.get(e);return n?(console.log("[Commands] execute after activate",e,"via extension",s),n.execute(...t)):void console.error(`Command ${e} not found after activating extension "${s}"`)}).catch(t=>{console.error(`Error activating extension "${s}" for command ${e}:`,t)})}console.log("[Commands] execute",e,"with args",function(e,t){const n=f.test(e);return t.map(e=>{if(n&&e&&"object"==typeof e&&!Array.isArray(e)){const t={};for(const[n,r]of Object.entries(e))t[n]=h.has(n)?"[REDACTED]":r;return l(t)}return l(e)})}(e,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 g=new class{async write(e){try{const t=s();if(!t)return;const n=".punica/audit";await t.createFolder(n).catch(()=>{});const r=new Date(e.timestamp).toISOString().split("T")[0],i=`${n}/${`${r}_${e.invocationId}.json`}`;await t.createFileWithContent(i,JSON.stringify(e,null,2))}catch(e){console.warn("[AuditWriter] Failed to write audit record:",e)}}async read(e){try{const t=s();if(!t)return[];const n=".punica/audit",r=await t.getFileTree(),i=(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(...i(r.children,t)));return n},o=i(r,n),a=[];for(const n of o)if(n.name.endsWith(".json"))try{const r=await t.readFile(n.path),s=JSON.parse(r);if(e?.since&&s.timestamp<e.since)continue;if(e?.until&&s.timestamp>e.until)continue;if(e?.capability&&s.capability!==e.capability)continue;if(e?.workspaceId&&s.workspace!==e.workspaceId)continue;a.push(s)}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 y={manager:new class{#n=new Map;#r=[];#s=[];registerCommand(e){this.#n.set(e.id,e)}executeCommand(e){const t=this.#n.get(e);t?(t.execute(),this.#r.push(t),this.#s=[]):console.error(`Command with ID ${e} not found.`)}undo(){const e=this.#r.pop();e?(e.undo(),this.#s.push(e)):console.error("No command to undo.")}redo(){const e=this.#s.pop();e?(e.execute(),this.#r.push(e)):console.error("No command to redo.")}},auditWriter:g};const w={manager:new class{#i=[];#o=null;#a(){null===this.#o&&(this.#o=window.setInterval(()=>{const e=new Date;this.#i.forEach(t=>t.update(e))},1e3))}#c(){null!==this.#o&&(window.clearInterval(this.#o),this.#o=null)}subscribe(e){this.#i.push(e),1==this.#i.length&&this.#a()}unsubscribe(e){this.#i=this.#i.filter(t=>t!==e),0==this.#i.length&&this.#c()}}};function v(){return(new Date).toISOString()}function b(e,t){const n=new Map,r=new Map,s=new Set;function i(e){for(const t of s)try{t(e)}catch{}try{const t=window,n=t.punica?.Commands?.manager,r=t.punica?.runtime,s="failed"===e.status?"error":"cancelled"===e.status?"warning":"info";let i=`[${e.label}] ${e.status}`;null!=e.exitCode&&(i+=` (exitCode=${e.exitCode})`),n&&n.executeCommand("output.append",{channel:"Tasks",text:i,level:s}),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:i,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(s,a){const c=n.get(s);if(!c)throw new Error(`[Runtime.tasks] Task definition not found: ${s}`);const l=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`task_${Date.now()}_${Math.floor(1e6*Math.random())}`}(),u=v(),{env:d,workspaceId:p,resolvedEnvironmentId:f}=await async function(e,n){if(!t)return{env:e};try{const r=await t.getCurrent();if(!r)return{env:e};const s=n??r.currentEnvironmentId,i=r.environments.find(e=>e.id===s),o={...i?.variables??{},...e??{}};return{env:Object.keys(o).length?o:void 0,workspaceId:r.id,resolvedEnvironmentId:i?.id}}catch{return{env:e}}}(c.env,a?.environmentId),h=await e.create({cwd:c.cwd,env:d,title:c.label}),m={runId:l,definitionId:c.id,label:c.label,status:"running",startedAt:u,terminalId:h.id,workspaceId:p,environmentId:f};r.set(l,m),i(m);const g=[c.command,...c.args??[]].join(" ").trim();try{const e=window,t=e.punica?.Commands?.manager;t&&"function"==typeof t.executeCommand&&(g?t.executeCommand("terminal.openForTaskSession",{sessionId:h.id,commandLine:g}):t.executeCommand("terminal.openForSession",h.id))}catch{}return e.onExit(h.id,e=>{const t=r.get(l);if(!t)return;const n={...t,status:0===e||null==e?"success":"failed",finishedAt:v(),exitCode:e??null};r.set(l,n),i(n),c.autoRerun&&setTimeout(()=>{o.run(c.id,{environmentId:f}).catch(()=>{})},300)}),m},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 s={...n,status:"cancelled",finishedAt:v()};r.set(t,s),i(s)},onDidChangeRun:e=>(s.add(e),()=>{s.delete(e)})};return o}const I=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=b(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 k={manager:I},E=Object.freeze({__proto__:null,createTasksApi:b,default:k,manager:I});const S=6048e5,A={rules:[],defaultTtlMs:S};function x(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 C(e,t,n){const r=function(e,t){let n=null,r=-1;for(const s of t)if(x(e,s.pattern)){const e=s.pattern.length;e>r&&(n=s,r=e)}return n}(e,t.rules??[]);return n-(r?.ttlMs??t.defaultTtlMs??S)}const T=".punica/.gitignore",M="# Punica editor — workspace internal state.\n# Auto-generated. Everything under .punica/ is ignored by default;\n# only the authored artifacts and user config below are tracked.\n/*\n\n!.gitignore\n\n# Authored artifacts (user's project content)\n!/ivy-nodes/\n!/ivy-agents/\n!/ivy-mcps/\n!/ivy-inputs/\n\n# Generated, and required by something outside this machine. The CI generator\n# writes the gate drivers here and the workflow it produces calls them by path,\n# so a runner that checks out the repository must find them.\n!/ci/\n\n# User configuration\n!/settings.json\n!/tasks.json\n!/launch.json\n!/database.yaml\n!/experiments.yaml\n!/mlops.yaml\n!/python.yaml\n!/vectors.yaml\n!/mcp.yaml\n!/mcp/\n";function N(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.startsWith("!"))}async function P(){const e=s();if(e&&(!r()||await n()))try{if(!!e.exists&&await e.exists(T)){const t=function(e){if(!e.includes("# Punica editor — workspace internal state."))return null;const t=new Set(N(e)),n=N(M).filter(e=>!t.has(e));return 0===n.length?null:`${e.endsWith("\n")?e:`${e}\n`}\n# Added by a later version of the editor.\n${n.join("\n")}\n`}(await e.readFile(T)??"");return void(t&&e.updateFileContent&&await e.updateFileContent(T,t))}try{await e.createFolder(".punica")}catch{}await e.createFileWithContent(T,M)}catch{}}const _=".punica/events";let L={};function R(e){const t=[],n=[...e];for(;n.length>0;){const e=n.pop();if(e){if(Array.isArray(e.children))for(const t of e.children)n.push(t);!0!==e.isDirectory&&"string"==typeof e.path&&e.path.startsWith(_)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function $(e,t){if(!t)return!0;const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId&&n?.id!==t.correlationId)return!1;if(void 0!==t.name){if(!(Array.isArray(t.name)?t.name:[t.name]).includes(e.name))return!1}return!(void 0!==t.since&&(n?.timestampMs??0)<t.since)&&!(void 0!==t.until&&(n?.timestampMs??0)>t.until)}const O=new class{#d;#p=!1;#f=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const t=s();if(!t)return;if(r()&&!await n())return;const i=Date.now();try{await t.createFolder(_)}catch{}if(!this.#p){this.#p=!0;try{await t.createFileWithContent(`${_}/.gitignore`,"*\n!.gitignore\n")}catch{}}this.#f||(this.#f=!0,await P());for(const n of e)try{const e=n.envelope?.timestampMs??Date.now(),r=new Date(e).toISOString().split("T")[0],s=n.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,i=`${_}/${r}_${s}.json`,o=u(n);await t.createFileWithContent(i,o)}catch{}try{L.onWrite?.(Date.now()-i,e.length)}catch{}}async query(e){const t=s();if(!t)return[];let n;try{n=await t.getFileTree()}catch{return[]}if(!Array.isArray(n))return[];const r=R(n),i=[];for(const n of r)try{const r=await t.readFile(n),s=JSON.parse(r);$(s,e)&&i.push(s)}catch{}return i.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),e?.limit&&e.limit>0?i.slice(-e.limit):i}async delete(e){const t=s();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const r=R(n);let i=0;const o=[];for(const n of r)try{const r=await t.readFile(n);if($(JSON.parse(r),e))await t.deleteFile(n),i++;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),i++}catch{}}return i}async applyRetention(e,t=Date.now()){const n=s();if(!n)return 0;let r;try{r=await n.getFileTree()}catch{return 0}if(!Array.isArray(r))return 0;const i=R(r);let o=0;for(const r of i)try{const s=await n.readFile(r),i=JSON.parse(s),a=i.envelope?.timestampMs??0;a<C(i.name,e,t)&&(await n.deleteFile(r),o++)}catch{}return o}};let D=O;function j(){return D}const F=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 q=F;function B(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=q.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function U(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(x(e.name,t)){r=!0;break}if(!r)return!1}return!0}class V extends Error{constructor(e){super(e),this.name="EventReplayError"}}let K={exportSpan:()=>{}};function W(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function G(){return Date.now()}function Y(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let s=[],i=null;function o(){try{L.onQueueDepthChange?.(s.length)}catch{}}async function a(){if(0===s.length)return;const e=[...s];s=[],o(),i&&(clearTimeout(i),i=null);try{await j().write(e),Z()}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function c(e){(function(e){if("audit"===e.envelope?.kind)return!0;const t=e.name;return r.some(e=>e.test(t))})(e)&&(s.push(e),o(),s.length>=10?a():i||(i=setTimeout(()=>{a()},5e3)))}function l(n,r){if("string"==typeof n){const t=n;let s=e.get(t);return s||(s=new Set,e.set(t,s)),s.add(r),()=>{s?.delete(r),s&&0===s.size&&e.delete(t)}}const s={filter:n,listener:r};return t.push(s),()=>{const e=t.indexOf(s);e>=0&&t.splice(e,1)}}function d(r,s){const i=s,o=i&&"object"==typeof i&&i.name===r?i:{name:r,envelope:{id:W(),timestampMs:G()},payload:s};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(s)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(U(o,t.filter))try{t.listener(o)}catch{}}}async function p(e){try{return await j().query(e)}catch{return[]}}function f(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}return{publish:d,subscribe:l,subscribeMany(e,t){const n=e.map(e=>l(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:W,publishEvent:function(e){const t=B({id:e.envelope?.id??W(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??G(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{K.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=u(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 d(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:f,getTrace:function(e){return f({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?f(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??"",u(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 u({exportedAt:G(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:p,replay:async function(e){"dispatch"===e.mode&&function(){throw new V('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 s=[];if(t)try{s=await p({name:e.name,since:e.since,until:e.until})}catch{s=[]}const i=function(e,t,n){const r=new Set,s=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}s.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}s.push(e)}const i={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=s.filter(e=>{if(!U(e,i))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,s,{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 i)console.log("[Punica Replay]",e.name,e);else for(const e of i)d(e.name,e);return{count:i.length,events:i}}}}const z=Y();var J={manager:z};let H=A;function Q(){return H}async function Z(){try{const e=j(),t=Q();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??S;return await e.delete({until:G()-n})??0}catch{return 0}}var X=Object.freeze({__proto__:null,createCorrelationId:W,createEventsApi:Y,default:J,getRetentionConfig:Q,manager:z,runEventRetentionCleanup:Z,setRetentionConfig:function(e){H=e??A}});function ee(){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)}`,s=t.timestamp||(new Date).toISOString(),i={...t,id:r,timestamp:s};e=[i,...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 te=ee();var ne={manager:te},re=Object.freeze({__proto__:null,createNotificationsApi:ee,default:ne,manager:te});const se="punica.kernel.policy.v2";function ie(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function oe(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class ae{#m=new Map;constructor(){this.#g()}set(e,t,n){let r=this.#m.get(e);r||(r=new Map,this.#m.set(e,r)),r.set(t,n),this.#y()}get(e,t){return this.#m.get(e)?.get(t)}has(e,t){return this.#m.get(e)?.has(t)??!1}delete(e,t){const n=this.#m.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#m.delete(e),r&&this.#y(),r}list(){const e=[];for(const t of this.#m.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#m.size&&(this.#m.clear(),this.#y())}restoreAll(e){this.#m.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=oe(n);if(!e)continue;let r=this.#m.get(n.key);r||(r=new Map,this.#m.set(n.key,r)),r.set(e,n),t++}return this.#y(),t}#g(){const e=ie();if(e)try{const t=e.getItem(se);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=oe(e);if(!t)continue;let n=this.#m.get(e.key);n||(n=new Map,this.#m.set(e.key,n)),n.set(t,e)}}catch{}}#y(){const e=ie();if(e)try{let t={};try{const n=e.getItem(se);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(se,JSON.stringify(n))}catch{}}}let ce=new ae;function le(){return Date.now()}function ue(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function de(e){return`${e.kind}:${e.id}`}function pe(e,t){return"workspace"===e?`workspace:${t??""}`:e}function fe(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const he="punica.kernel.policy.v1",me="punica.kernel.policy.v2";class ge{#w="execute";#v;#b=new Set;#I=new Map;#k=[];#E=1e3;constructor(e){this.#v=e??new ae,this.#S()}#S(){const e=fe();if(e)try{const t=e.getItem(me);if(t){const e=JSON.parse(t);if(e&&2===e.v)return void("suggest"!==e.mode&&"execute"!==e.mode||(this.#w=e.mode))}const n=e.getItem(he);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#w=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#v.restoreAll(n),this.#y();try{e.removeItem(he)}catch{}return}}}catch{}}#y(){const e=fe();if(e)try{let t={};try{const n=e.getItem(me);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#w,exportedAt:le()};e.setItem(me,JSON.stringify(n))}catch{}}setMode(e){this.#w=e,this.#y()}getMode(){return this.#w}clearApprovals(){this.#v.clear(),this.#b.clear()}#A(e,t,n="info"){try{z.publishEvent({name:e,envelope:{id:z.createCorrelationId(),timestampMs:le(),source:"kernel:policy",kind:n},payload:t})}catch{}}#x(e,t){return`${e}|${t}`}revokeApproval(e){const t=de({kind:e.kind,id:e.id}),n="workspace"===e.scope?pe("workspace",e.workspaceId):pe(e.scope),r=this.#v.delete(t,n);return r&&(this.#C("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.#b.delete(this.#x(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#v.list();if(t)return n;const r=le();return n.filter(e=>!ue(e,r))}hasApproval(e,t,n){const r=de(e),s="workspace"===t?n?.workspaceId?pe("workspace",n.workspaceId):null:pe(t);if(null===s)return!1;const i=this.#v.get(r,s);if(!i)return!1;if(ue(i,le())){const e=this.#x(r,s);return this.#b.has(e)||(this.#b.add(e),this.#A("approval.expired",{kind:i.kind,id:i.id,scope:i.scope,workspaceId:i.workspaceId,expiresAt:i.expiresAt,decidedBy:i.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=de(e),s="workspace"===t?pe("workspace",n?.workspaceId):pe(t),i={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:le(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,chainRef:n?.chainRef};return this.#v.set(r,s,i),this.#C("approval",e,void 0,t,n?.workspaceId),this.#b.delete(this.#x(r,s)),this.#A("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:n?.decidedBy,expiresAt:n?.expiresAt}),i}#C(e,t,n,r,s){this.#k.push({timestampMs:le(),type:e,request:t,decision:n,scope:r,workspaceId:s}),this.#k.length>this.#E&&this.#k.splice(0,this.#k.length-this.#E)}evaluate(e,t){const n=n=>{const r=t,s=r?.correlationId,i=r?.traceId??s;z.publishEvent({name:"policy.evaluated",envelope:{id:z.createCorrelationId(),correlationId:s,traceId:i,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})};if("suggest"===this.#w){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===e.approval){const r={allowed:!0,mode:"execute",requiresApproval:!1};return this.#C("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.#C("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.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}requestApproval(e,t){z.publishEvent({name:"policy.approvalRequested",envelope:{id:z.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:le(),mode:this.#w,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.#w=e.mode);let s=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 i="workspace"===n?pe("workspace",r):pe(n);"string"==typeof i&&i&&(this.#v.has(t,i)||(this.#v.set(t,i,e),s++))}else s=this.#v.restoreAll(r),this.#b.clear();return this.#y(),z.publishEvent({name:"policy.stateImported",envelope:{id:z.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:s,merged:n}}),s}saveTemplate(e,t,n){const r=n??"global";let s=this.#I.get(r);s||(s=new Map,this.#I.set(r,s));const i={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??le(),updatedAtMs:le()};s.set(e,i),this.#y()}getTemplate(e,t){const n=t??"global",r=this.#I.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#I.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#I.get(n);if(!r)return!1;const s=r.delete(e);return s&&this.#y(),s}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:le(),version:1,count:n.length,entries:n},null,2)}}const ye=new ge(ce);var we={manager:ye},ve=Object.freeze({__proto__:null,PolicyManager:ge,default:we,manager:ye});async function be(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(),s=t,i=await n(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:t,workspaceId:i,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:t},trace:{traceId:s,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 Ie(e,t,n,r){let s=e;if(s||(s=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,s=n?.payload??n?.event?.payload;if("ai.planGenerated"===r&&s?.plan?.planId)return s.plan}}catch{}return null}(),s&&r(s)),!s)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 be(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}(s,t,n)}const ke={estimate:e=>Math.ceil(e.length/4)};function Ee(){return ke}function Se(e){const t=Ee();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 Ae={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 xe="[elided tool result:";function Ce(e){const t=(e.content??"").length;return`${xe} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function Te(e,t){let n=0;for(let r=e.length-1;r>0;r--){const s=e[r].role;if(("assistant"===s||"user"===s)&&(n++,n>=t))return r}return 1}async function Me(e,t,n,r){const s=Se(e);if(s<=t.maxContextTokens)return{messages:[...e],compacted:!1,strategy:"none",preTokens:s,postTokens:s,estSavedTokens:0};const i=Math.floor(.6*t.maxContextTokens),o=Te(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(xe)?{...e,content:Ce(e)}:e);let c=Se(a);if(c<=i||!t.summarizeWhenOver||!n){const e=c<s;return{messages:a,compacted:e,strategy:e?"elide":"none",preTokens:s,postTokens:c,estSavedTokens:s-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??{}),i=(t?.text??"").trim();if(i){const e=[a[0],{role:"assistant",content:`[conversation summary]\n${i}`},...u];return c=Se(e),{messages:e,compacted:!0,strategy:"summarize",preTokens:s,postTokens:c,estSavedTokens:s-c}}}catch{}return{messages:a,compacted:c<s,strategy:"elide",preTokens:s,postTokens:c,estSavedTokens:s-c}}const Ne=["capability.search","capability.describe"];function Pe(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function _e(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Le(e,t,n,r){const s=punica.kernel?.Events?.manager;s&&s.publishEvent({name:e,envelope:{id:s.createCorrelationId(),correlationId:t,timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}async function Re(e,t,n,r){try{const s=await e("capability.recommend",{intent:n,limit:200},r),i=s?.recommendations??[],o=new Map;let a=!1,c=0;i.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=Pe(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()],s=new Array(r.length).fill(0);let i=!0;for(;i&&n.length<t;){i=!1;for(let e=0;e<r.length&&n.length<t;e++){const t=s[e];t<r[e].length&&(n.push(r[e][t]),s[e]=t+1,i=!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))])),f=new Map(d.map((e,t)=>[e,t]));d.sort((e,t)=>{const n=p.get(e)-p.get(t);return 0!==n?n:f.get(e)-f.get(t)});const h=[];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)));h.push(...n,...r)}return h.slice(0,100)}catch{return t}}function $e(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function Oe(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function De(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 je(e,t,n){const r=await e("capability.schemaExport",{filter:t.toolFilter,mode:"ai-tools"},n);let s=r?.capabilities??[];if(console.log("[AgentLoop] schemaExport raw catalog",{total:s.length,byCategory:s.reduce((e,t)=>{const n=Pe(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:s.map(e=>String(e.id))}),t.toolFilter)return{hot:s.map($e).sort(Oe),deferredIndex:[]};const i=s.filter(e=>Ne.includes(String(e.id)));if(s=s.filter(e=>{return!Ne.includes(String(e.id))&&(!((n=String(e.id)).startsWith("ai.")||(n.startsWith("capability.")?!Ne.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:s.length,includeIvyNodes:!!t.includeIvyNodes,includeMcp:!!t.includeMcp,allowedMcpServers:t.allowedMcpServers??[],willTier:!1!==t.deferToolLoading&&s.length>24,narrowThreshold:24}),s.length<=24)return{hot:s.map($e).sort(Oe),deferredIndex:[]};if(!1===t.deferToolLoading){return{hot:(await Re(e,s,t.query,n)).map($e).sort(Oe),deferredIndex:[]}}const o="number"==typeof t.hotSetSize&&t.hotSetSize>0?Math.floor(t.hotSetSize):16,a=(await Re(e,s,t.query,n)).slice(0,o),c=new Set(a.map(e=>String(e.id))),l=i.length===Ne.length?i.map($e):[{name:"capability.search",description:"Search the deferred tool index by natural-language need; returns candidate tool ids with one-line descriptions.",parameters:{type:"object",required:["query"],properties:{query:{type:"string"},limit:{type:"number"}}}},{name:"capability.describe",description:"Load full definitions (input schema) for up to 16 tool ids from the deferred index; described tools become directly callable.",parameters:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},maxItems:16}}}}],u=s.filter(e=>!c.has(String(e.id))).map(e=>({id:String(e.id),line:De(e),category:Pe(String(e.id))})).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0);return console.log("[AgentLoop] tiered catalog",{hot:a.length,deferred:u.length,hotIds:[...c]}),{hot:[...l,...a.map($e)].sort(Oe),deferredIndex:u}}async function Fe(e,t,n,r){const s={id:t.id,name:t.name,arguments:t.arguments,status:"success"};try{const r=await e(t.name,t.arguments,n);return{...s,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{...s,status:"failed",error:String(e?.message??e)}}const i=String(n.trace?.traceId??n.sessionId??""),o=await function(e,t,n){return new Promise(r=>{const s=punica.kernel.Events.manager;let i=!1;const o=e=>{if(!i){i=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=s.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed"],n=>{const r=n?.payload?.payload??n?.payload,s=r?.pending;s?.id===e&&(s?.traceId&&s.traceId!==t||o("ai.approvalRecorded"===n?.name?"approved":"dismissed"))})??void 0,c=setInterval(()=>{n()&&o("cancelled")},250),l=setTimeout(()=>o("timeout"),18e4)})}(t.name,i,r);if("approved"!==o)return{...s,status:"blocked",error:`tool "${t.name}" not approved (${o})`};try{const r=await e(t.name,t.arguments,n);return{...s,status:"success",resultPayload:r}}catch(e){return{...s,status:"failed",error:String(e?.message??e)}}}async function qe(e,t,n,r,s,i){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Ve(n)}\nRejected arguments:\n${Ve(r)}\nValidation errors: ${s}\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:i.sessionId},i);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 Be(e,t,n,r,s){let i=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Fe(e,{...t,arguments:i},r,s);if("failed"!==l.status||!_e(l.error))return o?{...l,arguments:i,repaired:!0}:l;if(a=l.error??"",2===c||s())break;const u=await qe(e,t.name,n,i,a,r);if(!u)break;i=u,o=!0}const c={id:t.id,name:t.name,arguments:i,status:"failed",error:a||"input validation failed"};return o&&(c.repaired=!0),c}function Ue(e){return Ee().estimate(e)}function Ve(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Ke(e,t,r,s){const i=punica.kernel.Events.manager,o=s??i.createCorrelationId(),a="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,c=(l=e.profile,Ae[l??"balanced"]);var l;const u=[],d=e.sessionId?punica.kernel?.AI?.sessions:void 0,p=[];let f=0;const h=[],m=Date.now();let g=0,y=0,w=0,v=0,b=!1,I=0,k=!1,E=0;const S=(t,n)=>{const r={inputTokens:g,outputTokens:y,totalTokens:w,latencyMs:Date.now()-m,steps:u.length,toolCalls:E};k&&(r.totalCost=I),b&&(r.cacheReadTokens=v);const s={runId:o,finishReason:t,steps:u,usage:r};if(void 0!==n&&(s.finalText=n),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:u.length}),(t=>{if(d&&e.sessionId&&0!==f)try{const n=[{role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}},...h];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&&f>0)try{d.recordUsage?.(e.sessionId,r)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Le("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),s};Le("ai.agentStarted",o,"info",{runId:o,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{}});const A=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!A)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),S("error");const x=await n(),C=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,x,r);let T;e.sessionId&&(C.conversationId=e.sessionId);try{T=await je(A,e,C)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),S("error")}const M=[...T.hot];console.log("[AgentLoop] tool catalog built",{hot:M.length,deferred:T.deferredIndex.length,toolFilter:e.toolFilter??null,names:M.map(e=>e.name)});const N=new Map(M.map(e=>[e.name,e.parameters])),P=new Map(T.deferredIndex.map(e=>[e.id,e])),_=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!N.has(String(e.id))).map($e).sort(Oe);for(const e of n)M.push(e),N.set(e.name,e.parameters),P.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:M.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."}),e.includeProjectContext)try{const e=function(e){const t=e;if(!t||"object"!=typeof t)return null;const n=[],r=t.workspace;r?.name&&n.push(`Project: ${r.name} (${r.kind}) at ${r.rootUri}`+(r.environment?` [env: ${r.environment}]`:"")),Array.isArray(t.stack)&&t.stack.length&&n.push(`Stack: ${t.stack.join(", ")}`);const s=t.dependencies?.python;s&&n.push(`Python deps (${s.source}, ${s.count}): ${(s.names??[]).join(", ")}`);const i=t.dependencies?.node;i&&n.push(`Node deps (${i.source}, ${i.count}`+(i.dev?` + ${i.dev} dev`:"")+`): ${(i.names??[]).join(", ")}`),t.scripts&&Object.keys(t.scripts).length&&n.push(`Scripts: ${Object.entries(t.scripts).map(([e,t])=>`${e}=${t}`).join(" · ")}`),Array.isArray(t.entrypoints)&&t.entrypoints.length&&n.push(`Entrypoints: ${t.entrypoints.join(", ")}`);const o=t.vcs;return o&&n.push(`VCS: ${o.branch??"(detached)"}`+(o.ahead?` ↑${o.ahead}`:"")+(o.behind?` ↓${o.behind}`:"")+` · ${o.dirtyFiles} dirty`),t.readme&&n.push(`README: ${t.readme}`),Array.isArray(t.layout)&&t.layout.length&&n.push(`Layout${t.truncated?" (truncated)":""}:\n${t.layout.join("\n")}`),n.length?"Workspace orientation (already loaded — do not re-derive; call tools only for detail beyond this):\n"+n.join("\n"):null}(await A("workspace.projectContext",{},C));e&&p.push({role:"system",content:e})}catch(e){console.warn("[AgentLoop] projectContext orientation unavailable:",e)}if(T.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."}}(T.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}:{}}),f=p.length;let L=0;for(let n=0;n<a;n++){if(t())return S("cancelled");let r,s=!1;if(Se(p)>c.maxContextTokens){const e=await Me(p,c,A,C);e.compacted&&(p.splice(0,p.length,...e.messages),L=0,s=!0,Le("ai.agentContextCompacted",o,"info",{runId:o,step:n,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const i=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:n,messageCount:p.length,toolsSent:M.length,toolChoice:"auto",toolNames:M.map(e=>e.name)});const t={stableToolsAndSystem:!0,stableMessagePrefix:L,cacheKey:o};r=await A("llm.chatStream",{messages:p,tools:M,toolChoice:"auto",correlationId:o,cacheHints:t,...e.profile?{profile:e.profile}:{}},C),L=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),S("error")}if(t())return S("cancelled");const a=Date.now()-i,l=(r.text??"").trim(),d="string"==typeof r.thinking?r.thinking:void 0,f=r.toolCalls??[],m={index:n,assistantText:l||void 0,thinking:d,toolCalls:[],latencyMs:a},x=r.usage,T=r.meta;x?(m.usage=x,g+=x.inputTokens??0,y+=x.outputTokens??0,w+=x.totalTokens??(x.inputTokens??0)+(x.outputTokens??0),"number"==typeof x.cacheReadInputTokens&&(v+=x.cacheReadInputTokens,b=!0)):T&&(m.usage={inputTokens:T.promptTokens,outputTokens:T.completionTokens,totalTokens:T.promptTokens+T.completionTokens},g+=T.promptTokens,y+=T.completionTokens,w+=T.promptTokens+T.completionTokens),T&&"number"==typeof T.totalCost&&(I+=T.totalCost,k=!0);const R={runId:o,step:n,estToolDefTokens:Ue(JSON.stringify(M)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+Ue(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+Ue(t.content??""),0),toolCount:M.length,deferredToolCount:P.size,compactionApplied:s};if(m.usage&&(R.reportedInputTokens=m.usage.inputTokens,R.reportedOutputTokens=m.usage.outputTokens,"number"==typeof m.usage.cacheReadInputTokens&&(R.cacheReadTokens=m.usage.cacheReadInputTokens)),Le("ai.agentTurnUsage",o,"info",{...R}),0===f.length)return u.push(m),Le("ai.agentStep",o,"info",{runId:o,turn:m}),S("final",l);u.push(m),Le("ai.agentStep",o,"info",{runId:o,turn:m});const $=f.map(e=>`${e.name}(${Ve(e.arguments)})`).join(", "),O={role:"assistant",content:l?`${l}\n[calling tools: ${$}]`:`[calling tools: ${$}]`,toolCalls:f.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};p.push(O),h.push(O);let D=!1;for(const e of f){if(t())return S("cancelled");if(Le("ai.agentToolCall",o,"info",{runId:o,toolCall:{id:e.id,name:e.name,arguments:e.arguments},status:"running"}),!N.has(e.name)&&P.has(e.name))try{_(await A("capability.describe",{ids:[e.name]},C))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const r=await Be(A,e,N.get(e.name),C,t);m.toolCalls.push(r),E++,"success"===r.status&&"capability.describe"===r.name&&_(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?Ve(r.resultPayload).slice(0,300):void 0}),Le("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const s={role:"tool",content:"success"===r.status?Ve(r.resultPayload,c.toolResultMaxChars):`ERROR: ${r.error??"tool failed"}`,name:r.name,toolCallId:r.id};p.push(s),h.push(s),"blocked"===r.status&&(D=!0)}if(D)return S("blocked")}return S("maxSteps")}function We(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 Ge={KERNEL:{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"},RUNTIME:{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"},SHELL:{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",PANEL_LAYOUT:"shell.panelLayout"},FLOW:{SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},EXTENSIONS:{MANAGER:"extensions.manager"}},Ye={SHELL:{TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},AI:{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"},POLICY:{EXPORT:"policy.export",IMPORT:"policy.import",LIST_APPROVALS:"policy.listApprovals",SET_MODE:"policy.setMode",SHOW_MODE:"policy.showMode"},MCP:{CONNECT:"mcp.connect",DISCONNECT:"mcp.disconnect",LIST_SERVERS:"mcp.listServers",LIST_TOOLS:"mcp.listTools"},WORKFLOW:{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 ze(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 Je(e,t,n,r,s,i,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:s,parentSpanId:i,timestampMs:Date.now(),source:o,kind:t},payload:a})}const He="punica.kernel.ai.sessions.index.v1";function Qe(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 Xe=new class{readIndex(){const e=Ze();if(!e)return[];try{const t=e.getItem(He);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=Ze();if(t)try{t.setItem(He,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=Ze();if(t)try{const n=t.getItem(Qe(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(Qe(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=Ze();if(t)try{t.removeItem(Qe(e))}catch{}}};let et=Xe;function tt(){return et}const nt="New chat";function rt(){return Date.now()}function st(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${rt().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:rt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function ot(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function at(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 ct=new class{#T=null;#M=null;#N=new Map;#P=!1;#_=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 s=e?.envelope?.correlationId,i=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:s,...o?{traceId:o}:{},workspaceId:i,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#N)}),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#T=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(Ye.POLICY.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(Ye.POLICY.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(Ye.POLICY.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=We(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),s=e.document.createElement("a");s.href=r,s.download=`punica-policy-export-${Date.now()}.json`,e.document.body.appendChild(s),s.click(),e.document.body.removeChild(s),URL.revokeObjectURL(r)}else console.log("[Policy] Export:\n"+n)}}),t.registerCommand(Ye.POLICY.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(Ye.POLICY.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`+We(e,2))}}),t.registerCommand(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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 s="always"===r?"always":"workspace"===r?"workspace":"once";e.approvePending(n,s)||console.warn("[AI] Failed to approve pending",n)}}),t.registerCommand(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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(Ye.AI.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"+We(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+We(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Ye.AI.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(),s=t?.__punica?.traceId??r,i=t?.__punica?.spanId??punica.kernel.Events.manager.createCorrelationId(),o=t?.__punica?.source??"kernel:ai",a=e?.source;Je("ai.request","info",r,s,i,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:ze(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();Je("ai.response","result",r,s,u,i,o,{kind:"summarize",output:{summaryPreview:ze(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),Je("ai.summaryGenerated","result",r,s,punica.kernel.Events.manager.createCorrelationId(),u,o,{summary:l,usage:c?.usage,modelId:c?.modelId,provider:c?.provider,source:a})}catch(e){Je("ai.response","error",r,s,punica.kernel.Events.manager.createCorrelationId(),i,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.#M,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#_){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#P=e;for(const t of this.#_.values())t.cancelRequested=e,e&&t.controller.abort()}}})}getLastPlan(){return this.#T}getPendingApprovals(){return e=this.#N,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.#N)}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.#N)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#T=e);const t=await Ie(this.#T,this.#M,()=>this.#P,e=>{this.#T=e});return this.#M=t,this.#P=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#_.set(t,n);try{return await Ke(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#_.delete(t)}}},lt=new class{#L;create(e){const t=tt(),n={sessionId:st("sess"),title:e?.title?.trim()||nt,createdAtMs:rt(),updatedAtMs:rt(),messageCount:0,tokenEstimate:0};e?.workspaceId&&(n.workspaceId=e.workspaceId);const r={version:1,meta:n,transcript:[]};t.writeSession(r);const s=t.readIndex();return s.push(n),this.#R(s,n),t.writeIndex(s),it("ai.sessionCreated",n),{...n}}list(e){const t=tt().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return tt().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#$(e,e=>{e.title=n});return!!r&&(it("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#$(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(it("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=tt(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[s]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),it("ai.sessionDeleted",s),!0}appendMessages(e,t,n){if(0===t.length)return;const r=tt(),s=r.readSession(e);if(!s)return;const i=t.map(e=>{const t={...e,id:e.id||st("msg"),createdAtMs:e.createdAtMs||rt(),content:e.content.length>16e3?e.content.slice(0,16e3)+"…":e.content};return n?.runId&&!t.runId&&(t.runId=n.runId),t});s.transcript.push(...i),s.transcript.length>200&&s.transcript.splice(0,s.transcript.length-200);const o=s.meta;if(o.messageCount=s.transcript.length,o.updatedAtMs=rt(),n?.runId&&(o.lastRunId=n.runId),o.tokenEstimate=s.transcript.reduce((e,t)=>{return e+(n=t.content,Math.ceil(n.length/4));var n},0),o.title===nt){const e=s.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:nt}(e.content))}r.writeSession(s),this.#O(o),it("ai.sessionUpdated",o,{appendedCount:i.length,runId:n?.runId});const a=this.#L;a?.shouldCompact(s)&&Promise.resolve().then(()=>a.compact(s)).then(t=>{const n=tt().readSession(e);n&&(n.contextView=t,tt().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=tt().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(...ot(n.messages).map(at)),e}return ot(t.transcript.slice(-40)).map(at)}setCompactor(e){this.#L=e}recordUsage(e,t){const n=this.#$(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=rt(),e.usage=n});return!!n&&(it("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#$(e,t){const n=tt(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=rt(),n.writeSession(r),this.#O(r.meta),{...r.meta}}#O(e){const t=tt(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#R(e,t){const n=tt(),r=e=>e.workspaceId===t.workspaceId;let s=e.filter(r);for(;s.length>50;){const i=s.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(!i)break;const o=e.findIndex(e=>e.sessionId===i.sessionId);o>=0&&e.splice(o,1),n.deleteSession(i.sessionId),it("ai.sessionDeleted",i,{evicted:!0}),s=e.filter(r)}}};lt.setCompactor(function(){const e=Ae.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=Te([{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(xe)?{...e,content:Ce(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());var ut={manager:ct,sessions:lt},dt=Object.freeze({__proto__:null,default:ut,manager:ct,sessions:lt});const pt=new class{#D=new Map;#j=new Map;#F=new Map;#q;registerProductOriginResolver(e){this.#q=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.#D.has(e.id)){const n=this.#D.get(e.id),r=n?.originExtension||this.#F.get(e.id),s=t||e.originExtension;if(!r||!s||r!==s)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.#q&&(t=this.#q(e.productId)),t&&(e.originExtension=t,this.#F.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.#D.set(e.id,e),this.#j.set(e.id,e.capability)}unregister(e){this.#D.delete(e),this.#j.delete(e),this.#F.delete(e)}unregisterByOrigin(e){const t=[];this.#F.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>this.unregister(e))}get(e){return this.#D.get(e)}list(e=!1){const t=Array.from(this.#D.values());return e?t.filter(e=>{const t=e.originExtension||this.#F.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.#F.get(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0}))}has(e){return this.#D.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#F.get(e);return!n||this.#B(n)}getCapability(e){return this.#j.get(e)}listCapabilities(){return Array.from(this.#j.values())}};async function ft(e){const{primaryModelId:t,count:n,exclude:r}=e,s=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(!s||!Array.isArray(s.installed)||0===s.installed.length)return t?[t]:[];const i=new Set(s.installed.map(e=>e.id)),o=[],a=e=>{e&&i.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 s.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=pt.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,s=[];s.push("Assess the risk level for this task:"),s.push(""),s.push(`Instruction Class: ${e.id}`),s.push(`Role: ${e.role}`),s.push(""),s.push("User Prompt:"),s.push(t.userPrompt),s.push(""),s.push("Context:"),s.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),s.push(`- File Path: ${r?.filePath??"N/A"}`),s.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),s.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),s.push(""),s.push("Consider:"),s.push("- Is this production code?"),s.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),s.push("- Is it a critical business function?"),s.push("- Does it handle sensitive data?"),s.push("- Is it a simple utility or a complex system?"),s.push(""),s.push('Respond with ONLY one word: "low", "medium", or "high".');const i=s.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:i}],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:i}],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 s=[];return s=r&&r.length>0?r.slice():await ft({primaryModelId:t,count:3}),{strategy:s.length>1?"multi":"single",modelIds:s.length?s:[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 mt(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 gt(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function yt(){const e=globalThis;return e.punica?.runtime?.fs}function wt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const vt={type:"ai",id:"llm:context"},bt={kind:"ai",id:"context-builder"};async function It(e){if(e.filePath)try{const t=gt(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:vt,origin:bt,trace:{traceId:wt()},policy:{mode:"execute"}}):await(yt()?.readFile?.(e.filePath));if(!n)return;const r=5e3,s=n.length>r?n.slice(0,r)+"\n... (truncated)":n;return`File content (${e.filePath}):\n\`\`\`\n${s}\n\`\`\``}catch{return}}async function kt(e){try{const t=gt(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:vt,origin:bt,trace:{traceId:wt()},policy:{mode:"execute"}}):await(yt()?.getFileTree?.());if(!n||!Array.isArray(n)||0===n.length)return;const r=n.filter(e=>!e.isDirectory).length,s=n.filter(e=>e.isDirectory).length;return`Workspace structure: ${r} files, ${s} 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 Et(){const e=globalThis;return e.punica?.shell?.ContentTabs}function St(){return"undefined"==typeof document?void 0:document}function At(){const e=St();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 xt(e){try{const t=Et();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=At();if(!n)return;const r=n.getSelection?.(),s=n.getModel?.();if(!r||!s||r.isEmpty())return;const i=s.getValueInRange(r),o=String(i??"").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 Ct(){try{const e=Et();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,s=n.column,i=r.getOffsetAt(n);t.push(`Cursor position: Line ${e}, Column ${s} (offset: ${i})`)}}}catch{}try{const e=St();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 Tt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Mt={type:"ai",id:"llm:context"},Nt={kind:"ai",id:"context-builder"};async function Pt(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}(),s=r?await r.call("vcs.status",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Mt,origin:Nt,trace:{traceId:Tt()},policy:{mode:"execute"}}):await t.status();if(s){const e=[];s.current&&(e.push(`Branch: ${s.current}`),s.tracking&&e.push(`Tracking: ${s.tracking}`),s.ahead&&s.ahead>0&&e.push(`Ahead: ${s.ahead}`),s.behind&&s.behind>0&&e.push(`Behind: ${s.behind}`));const t=s.modified??[],r=s.staged??[],i=s.created??[],o=s.deleted??[],a=s.renamed??[],c=(t,n,r)=>{if(0===n.length)return;const s=n.slice(0,r).join(", "),i=n.length>r?"...":"";e.push(`${t} (${n.length}): ${s}${i}`)};c("Staged",r,5),c("Modified",t,5),c("Created",i,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??"",s=(e.message??"").split("\n")[0].substring(0,60);return` ${t} ${n} ${r?`(${r})`:""}: ${s}${s.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),s=[];t?.name&&s.push(`Current: ${t.name}`),r.length>0&&s.push(`Other branches: ${r.map(e=>e.name).filter(Boolean).join(", ")}`),s.length>0&&n.push(`Branches:\n${s.join("\n")}`)}}catch{}return n.length>0?n.join("\n\n"):void 0}async function _t(){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})`:"",s=e.startedAt?new Date(e.startedAt).toLocaleDateString():"";return` ${n}: ${t}${r}${s?` (${s})`:""}`}).join("\n");t.push(`Recent Task History:\n${e}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}async function Lt(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 Rt="problems.getDiagnostics";function $t(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===Rt))return;let r;try{r=t.executeCommand?.(Rt)}catch{return}if(!r||!Array.isArray(r)||0===r.length)return;const s=e.filePath?r.filter(t=>t.file===e.filePath):r;if(0===s.length)return;const i=s.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=s.length;return`Diagnostics (${o} ${1===o?"issue":"issues"}):\n${i}${o>10?`\n ... and ${o-10} more`:""}`}catch{return}}function Ot(e,t){switch(e){case"tenant":return t.workspaceId??"(unknown)";case"user":return t.userId??"(unknown)";case"capability":return t.capabilityId??"(unknown)";case"provider":return t.provider}}const Dt=new class{#U;#V=[];constructor(e){this.#U=Math.max(1,e?.maxRecords??1e4)}record(e){this.#V.push(e),this.#V.length>this.#U&&this.#V.splice(0,this.#V.length-this.#U)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,s=new Map;let i=0,o=0,a=0,c=0,l=0;for(const e of this.#V){if(e.timestamp<n||e.timestamp>r)continue;const u=Ot(t,e),d=s.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,s.set(u,d),i+=e.totalCost,o+=1,a+=e.promptTokens,c+=e.completionTokens,l+=e.cachedPromptTokens??0}const u=Array.from(s.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:i,totalCalls:o,totalPromptTokens:a,totalCompletionTokens:c,totalCachedPromptTokens:l,byKey:u}}clear(){this.#V.length=0}};function jt(e){return e.remaining[0]}function Ft(e,t,n,r){if(e.terminal)return e;const s=function(e,t){return"error"===e?t.onError??"fail":"timeout"===e?t.onTimeout??"fail":t.onRateLimit??"next"}(t,n),i=e.remaining[0];if(!i)return{...e,terminal:!0,lastError:r??e.lastError};if("fail"===s)return{...e,attempted:[...e.attempted,i],position:e.position+1,remaining:[],terminal:!0,pendingQueue:!1,lastError:r??e.lastError};if("queue"===s)return{...e,pendingQueue:!0,lastError:r??e.lastError};const o=e.remaining.slice(1);return{...e,position:e.position+1,attempted:[...e.attempted,i],remaining:o,terminal:0===o.length,pendingQueue:!1,lastError:r??e.lastError}}function qt(e){return{...e,terminal:!0,pendingQueue:!1}}let Bt;function Ut(e){Bt=e}function Vt(e){return!!e&&"string"==typeof e.providerId&&""!==e.providerId.trim()}const Kt={onError:"next",onTimeout:"next",onRateLimit:"next"};function Wt(e){const t=e?.status??e?.statusCode;return"number"==typeof t&&(408!==t&&429!==t&&(401!==t&&403!==t&&(t>=400&&t<500)))}function Gt(e){const t=e?.status??e?.statusCode;if(429===t)return"rateLimit";if(408===t||504===t)return"timeout";const n=String(e?.name??"").toLowerCase();if("aborterror"===n||"timeouterror"===n)return"timeout";const r=String(e?.message??e??"").toLowerCase();return r.includes("rate limit")||r.includes("rate_limit")||r.includes("too many requests")||r.includes("429")?"rateLimit":r.includes("timed out")||r.includes("timeout")||r.includes("etimedout")?"timeout":"error"}function Yt(e){const t=e.providerId.trim(),n=t.toLowerCase(),r=n.startsWith("local:")?"local":n.startsWith("remote:")?"remote":void 0;return{providerId:t,...r?{route:r}:{},...e.modelId?{modelId:e.modelId}:{}}}async function zt(e,t){const r=pt;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 s=r.get(e.instructionClass);if(!s)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(mt(e)),It(e),Promise.resolve(xt(e)),kt(e),Pt(e),_t(),Promise.resolve(Ct()),Lt(e),Promise.resolve($t(e))])).filter(e=>void 0!==e&&e.length>0).join("\n\n"):""}(e.context),i=r?`${r}\n\n${e.userPrompt}`:e.userPrompt,o=await ht(s,e),a={messages:[{role:"system",content:s.systemPrompt},{role:"user",content:i,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??s.temperature??.2,maxTokens:e.options?.maxTokens??s.maxTokens??2e3,responseFormat:s.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(),f=async(t,n)=>{const r=punica.kernel.Events.manager;return await punica.runtime.capabilities.gateway.call(t,{...a,...n},{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"}})},h=(e,t,n)=>{try{const r=punica.kernel.Events.manager;r.publishEvent({name:"llm.fallback",envelope:{id:r.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:s.id,fromProviderId:e,toProviderId:t,reason:n}})}catch{}},m=function(e){const t=e.providerChain;if(Array.isArray(t)&&t.length>0)return t.filter(Vt);if(!Bt)return[];try{const e=Bt();return Array.isArray(e)?e.filter(Vt):[]}catch{return[]}}(s);let g,y;if(m.length>0){let e,t=function(e){return{position:0,attempted:[],remaining:e.slice(),terminal:0===e.length,pendingQueue:!1}}(m);const n=Date.now();for(;!t.terminal;){const n=jt(t);if(!n)break;const r=Date.now();try{l=await f(c,Yt(n)),d=Date.now()-r,g=t.position,t=qt(t);break}catch(r){if(e=r,Wt(r))break;const i=Ft(t,Gt(r),s.fallbackPolicy??Kt,r);if(i.pendingQueue){t={...i,terminal:!0};break}const o=jt(i);o&&h(n.providerId,o.providerId,r?.message??"unknown"),t=i}}if(!l)throw e??new Error(`No provider in the chain for "${s.id}" produced a response.`);0===d&&(d=Date.now()-n)}else 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(),i=punica.kernel.Events.manager;try{i.publishEvent({name:"llm.fallback",envelope:{id:i.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:s.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??i.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??i.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(),i=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(s.outputSchema&&"json_object"===s.responseFormat)try{c=JSON.parse(i.text)}catch{}return{res:i,expert:{modelId:i.modelId??t,text:i.text,structured:c,usage:i.usage,latencyMs:o}}}),i=await Promise.all(r);u=i.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,s);l={text:c.text,modelId:c.modelId,provider:i.find(e=>e.expert.modelId===c.modelId)?.res.provider,usage:c.usage},d=Date.now()-t}if(s.outputSchema&&"json_object"===s.responseFormat)try{y=JSON.parse(l.text)}catch(e){return{ok:!1,error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}`,metadata:{instructionClass:s.id,role:s.role,originExtension:s.originExtension,productId:s.productId}}}const w={ok:!0,text:l.text,structured:y,metadata:{instructionClass:s.id,role:s.role,originExtension:s.originExtension,productId:s.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"),i=String(l.modelId??"unknown"),o=0,c={provider:r,model:i,promptTokens:e,completionTokens:t,totalCost:o,latencyMs:d,...void 0!==g?{fallbackChainPosition:g}:{}};Dt.record({capabilityId:s.id,provider:r,model:i,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:s.id,workspaceId:p,meta:c}})}catch{}return w}catch(e){return{ok:!1,error:`LLM invocation failed: ${e?.message??String(e)}`,metadata:{instructionClass:s.id,role:s.role,originExtension:s.originExtension,productId:s.productId}}}}async function Jt(e){return zt({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 Ht(e){return zt({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function Qt(e){let t="";e.requirements?t+=`Requirements:\n${e.requirements}\n\n`:t+="Optimize and improve this Workflow:\n\n",t+=`Current Workflow:\n${JSON.stringify(e.workflow,null,2)}\n\n`,e.requirements?(t+="Please edit this Workflow according to the requirements above. ",t+="Maintain DAG structure, preserve all node.ref and node.data, ",t+='ensure all IDs remain valid, and maintain apiVersion="ivy.workflow/v0.1" and kind="Workflow".\n'):(t+="Please optimize this Workflow: ",t+="- Improve parallelization opportunities\n",t+="- Remove redundant nodes/edges\n",t+="- Improve node labels\n",t+="- Maintain DAG structure (no cycles)\n",t+="- Preserve all functionality\n",t+='- Maintain apiVersion="ivy.workflow/v0.1" and kind="Workflow"\n');return await zt({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function Zt(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function Xt(e,t){const n=Zt(e).split("/").filter(Boolean),r=Zt(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function en(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function tn(e,t){const n=Zt(e).split("/").filter(Boolean),r=Zt(t).split("/").filter(Boolean);let s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;const i=n.length-s,o=r.slice(s);return[...Array(i).fill(".."),...o].join("/")}async function nn(e,t){const n=[];let r=0;const s=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 i=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}i+=r.content.length}const e=tn(t,Xt(t,Zt(r.path)));(e.startsWith("..")||en(e))&&n.push({path:r.path,error:"Path traversal detected"})}if(i>s)throw new Error(`CodegenBundle exceeds max total size: ${i} > 1048576 bytes`);for(const t of e.files)if(!n.some(e=>e.path===t.path))try{const e=Zt(t.path);if("create"===t.action){const n=e.split("/");if(n.length>1){const e=n.slice(0,-1).join("/");try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFolder(e)}catch{}}const s=punica.runtime.capabilities?.gateway;s?await s.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 s=punica.runtime.capabilities?.gateway;s?await s.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 rn={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 sn=new class{api;constructor(){this.api={instructionClassRegistry:pt,invoke:zt,plan:Jt,generateCode:Ht,editWorkflow:Qt,listInstructionClasses:e=>pt.listSummaries(e),setDefaultProviderChainResolver:Ut}}};var on={manager:sn};const an={Commands:m,History:y,TimeServer:w,Tasks:E,Events:X,Notifications:re,Policy:ve,AI:dt,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:rn,applyCodegenBundle:nn,default:on,manager:sn})};function cn(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__",s=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(`^${s}$`,"i").test(t.path)}(e.pattern,t);default:return!1}}const ln=new class{#K=[];register(e){this.#K=this.#K.filter(t=>t.id!==e.id),this.#K.push({priority:0,...e}),this.#K.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#K=this.#K.filter(t=>t.id!==e)}clear(){this.#K=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#K){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>cn(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.#K.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>cn(t,e))}).map(e=>({opener:e,command:e.command}))}};let un,dn,pn,fn,hn,mn;function gn(){if(un)return un;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return un=punica.runtime.resources,un}function yn(){if(dn)return dn;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return dn=e,dn}function wn(){if(fn)return fn;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return fn=e,fn}function vn(){if(hn)return hn;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function bn(){if(mn)return mn;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return mn=e,mn}function In(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 kn(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 En=In({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 Sn(){return En.get()}function An(e){En.set(e),e&&kn({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function xn(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 Cn=Symbol("punica.llm.gatewayGovernedAi");let Tn,Mn,Nn;function Pn(){if(Tn)return Tn;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return Tn=punica.runtime.llm,Tn}function _n(e){if(Tn=e,Mn=void 0,Nn=void 0,!e)return;const t=e;xn("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class Ln{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 Rn=null;function $n(){return Rn||(Rn=new Ln),Rn}class On{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 Dn{providerSession;id;providerId;language;kernelspec;languageRuntime;constructor(e,t,n,r,s,i){this.providerSession=e,this.id=t,this.providerId=n,this.language=r,this.kernelspec=s,this.languageRuntime=i}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},s=this.languageRuntime.prepare(e,r);return this.providerSession.run(s,n,t)}async interrupt(){return this.providerSession.interrupt()}async restart(){return this.providerSession.restart()}async close(){return this.providerSession.close()}}const jn={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}}},Fn={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}}},qn={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},Bn={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},Un={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 Vn(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 Kn{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),s=await t.openSession({...e,kernelspec:r}),i=Vn("session");return new Dn(s,i,t.id,e.language,r,n)}}class Wn{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 Gn=null;function Yn(){return Gn||(Gn=new Wn),Gn}class zn{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 Jn{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 Hn=null;function Qn(){return Hn||(Hn=new Jn),Hn}class Zn{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 Xn{#W=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#W.set(e.id,e)}get(e){return this.#W.get(e)}list(){return Array.from(this.#W.values())}select(e){return this.list().find(t=>t.canRun(e))}}let er=null;function tr(){return er||(er=new Xn),er}function nr(e,t){const n=Math.min(e.length,t.length);let r=0,s=0,i=0;for(let o=0;o<n;o++)r+=e[o]*t[o],s+=e[o]*e[o],i+=t[o]*t[o];return 0===s||0===i?0:r/(Math.sqrt(s)*Math.sqrt(i))}const rr="default";class sr{#G=new Map;#Y(e){const t=e||rr;let n=this.#G.get(t);return n||(n=new Map,this.#G.set(t,n)),n}upsert(e,t=rr){const n=this.#Y(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=rr){const r=this.#Y(n),s=[];for(const t of r.values())s.push({id:t.id,score:nr(e,t.vector),text:t.text,metadata:t.metadata});return s.sort((e,t)=>t.score-e.score),s.slice(0,Math.max(0,t))}delete(e,t=rr){const n=this.#Y(t);for(const t of e)n.delete(t)}clear(e=rr){this.#G.delete(e||rr)}count(e=rr){return this.#Y(e).size}export(e=rr){return Array.from(this.#Y(e).values())}import(e,t=rr){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#G.set(t||rr,n)}}const ir=".punica/vectors";class or{#v=new sr;#z=new Set;#J(){try{return punica.runtime?.fs}catch{return}}#H(e){return`${ir}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#Q(e){const t=e||"default";if(this.#z.has(t))return;this.#z.add(t);const n=this.#J();if(n?.readFile)try{const e=await n.readFile(this.#H(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#v.import(r.records,t)}catch{}}async#Z(e){const t=this.#J();if(t)try{if(t.mkdir)try{await t.mkdir(ir)}catch{}const n={version:1,records:this.#v.export(e)},r=this.#H(e),s=JSON.stringify(n);try{await t.updateFileContent(r,s)}catch{await t.createFileWithContent(r,s)}}catch(e){console.warn("[Runtime.vectors] Failed to persist collection:",e)}}async upsert(e,t){const n=t?.collection??"default";await this.#Q(n),this.#v.upsert(e,n),await this.#Z(n)}async query(e){const t=e.collection??"default";return await this.#Q(t),this.#v.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#Q(n),this.#v.delete(e,n),await this.#Z(n)}async clear(e){const t=e?.collection??"default";await this.#Q(t),this.#v.clear(t),await this.#Z(t)}async count(e){const t=e?.collection??"default";return await this.#Q(t),this.#v.count(t)}}let ar,cr,lr;function ur(){return ar||(cr||(cr=new or),cr)}function dr(){if(!lr)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 lr}var pr;!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"}(pr||(pr={}));class fr extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const hr=new class{#X=new Map;#ee=new Map;registerCapability(e){if(!e.name)throw new fr(pr.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new fr(pr.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 fr(pr.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.#X.has(e.name))throw new fr(pr.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 fr(pr.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 fr(pr.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.#te(t,e.name);if(n)throw new fr(pr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#X.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{}}#te(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#X.get(e);if(!r?.requires)return null;for(const s of r.requires){const r=this.#te(s,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#X.has(e.name))throw new fr(pr.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ee.set(e.name,e)}getSpec(e){return this.#X.get(e)}getProvider(e){return this.#ee.get(e)}hasCapability(e){return this.#X.has(e)}hasProvider(e){return this.#ee.has(e)}listCapabilities(){return Array.from(this.#X.keys())}getAllSpecs(){return Array.from(this.#X.values())}clear(){this.#X.clear(),this.#ee.clear()}};function mr(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 gr(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:br(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}const yr=["write","delete","remove","modify","destroy","create","update","install","publish","process","spawn","exec","run"],wr=["network","http","fetch","request","upload","download"],vr=["read","list","get","query","inspect","search"];function br(e){if(!e||0===e.length)return"none";let t="none";for(const n of e){if("string"!=typeof n)continue;const e=n.toLowerCase(),r="none"===e?"none":yr.some(t=>e.includes(t))?"write":wr.some(t=>e.includes(t))?"network":vr.some(t=>e.includes(t))?"read":"write";if("write"===r)return"write";"network"===r?t="network":"read"===r&&"none"===t&&(t="read")}return t}const Ir=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function kr(){const e=globalThis;return e.punica?.extensions?.manager}function Er(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function Sr(){const e=globalThis;return e.punica?.flow?.registry}function Ar(){const e=globalThis;return e.punica?.flow?.agents}function xr(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const Cr={core:function(e){const t=hr.getSpec(e);if(t)return{origin:"core",definition:mr(t)}},extension:function(e){const t=kr();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=Er();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=Sr();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=Ar();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=xr();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},Tr={core:function(){return hr.getAllSpecs().map(e=>({origin:"core",definition:mr(e)}))},extension:function(){const e=kr();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=Er();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=Sr();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=Ar();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=xr();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Mr={getCapability(e){for(const t of Ir){const n=Cr[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,s=[];for(const e of Ir)if(!t||t.has(e))for(const t of Tr[e]()){const e=t.definition.id;r.has(e)||(r.add(e),s.push(t))}return s},hasCapability(e){return void 0!==this.getCapability(e)}};function Nr(e,t,n){switch(e){case"mcp":return function(e,t){const{mcpServerId:n,mcpToolName:r}=t;return{name:e.id,async execute(t,s){const i=globalThis.punica?.runtime?.mcp;if(!i?.callTool)throw new fr(pr.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 fr(pr.CAPABILITY_PROVIDER_MISSING,`MCP capability "${e.id}" is missing serverId or toolName metadata`,{capability:e.id,origin:"mcp"});return await i.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 fr(pr.CAPABILITY_PROVIDER_MISSING,`LLM kernel API is not initialized — cannot invoke instruction-class capability "${e.id}".`,{capability:e.id,origin:"instruction-class"});const s=null!==t&&"object"==typeof t?t:{},i="string"==typeof s.instructionClass?s.instructionClass:e.id,o="string"==typeof s.userPrompt?s.userPrompt:"string"==typeof s.prompt?s.prompt:JSON.stringify(t);return await r.invokeLlmCapability({instructionClass:i,userPrompt:o,context:s.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 fr(pr.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 s="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,i=await r.run(e.id,{input:t??{},timeoutMs:s});return i?.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 fr(pr.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 s="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,i=await r.run(e.id,{input:t??{},timeoutMs:s});return i?.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 fr(pr.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 fr(pr.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Pr={recordSpan:()=>{}};function _r(e){try{Pr.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function Lr(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=n,o={capability:s,"actor.type":i.actor.type,"origin.kind":i.origin.kind};i.actor.extensionName&&(o["actor.extension"]=i.actor.extensionName),i.origin.extension&&(o["origin.extension"]=i.origin.extension),i.workspaceId&&(o["workspace.id"]=i.workspaceId),r.tags={...r.tags,...o};try{const e=await t();return r.durationMs=Date.now()-r.startTimeMs,_r({invocationId:n.invocationId,capability:s,traceId:i.trace.traceId,spanId:n.invocationId,parentSpanId:i.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:i.trace.traceId,spanId:i.trace.parentSpanId??n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"error"},payload:{invocationId:n.invocationId,capability:s,error:r.error.message,durationMs:r.durationMs}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.failed event:",e)}throw _r({invocationId:n.invocationId,capability:s,traceId:i.trace.traceId,spanId:n.invocationId,parentSpanId:i.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"error",errorCode:e instanceof fr?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function Rr(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Rr);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Rr(r);return t}return e}const $r=new WeakMap;function Or(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,input:i}=n;if(!0===r.spec.secretBearing||s.startsWith("secrets."))r.redactedInput=Rr(i);else{const e=function(e){const t=$r.get(e);if(t)return t;const n=d(e.inputSchema);return $r.set(e,n),n}(r.spec);r.redactedInput=e.length>0?p(i,e):i}return await t()}}function Dr(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function jr(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Dr(t))}const Fr=new class{validate(e,t){const n=[];if(!e||"object"!=typeof e)return{ok:!0,errors:n};const r=e,s=r.type;if(s&&(jr(s,t)||n.push(`Expected type "${s}", got "${Dr(t)}"`)),"object"===s&&t&&"object"==typeof t&&!Array.isArray(t)){const e=t,s=r.required,i=r.properties;if(Array.isArray(s))for(const t of s)t in e&&void 0!==e[t]||n.push(`Missing required field: "${t}"`);if(i)for(const[t,r]of Object.entries(e)){if(void 0===r)continue;const e=i[t];if(!e)continue;const s=e.type;s&&(jr(s,r)||n.push(`Field "${t}": expected type "${s}", got "${Dr(r)}"`))}}return{ok:0===n.length,errors:n}}};let qr=Fr;function Br(){return qr}function Ur(){return async(e,t)=>{const{req:n,state:r}=e,{input:s}=n,{inputSchema:i}=r.spec,o=Br().validate(i,s);if(!o.ok)throw new fr(pr.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const Vr=In({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function Kr(){return Vr.get()}const Wr=["path","oldPath","newPath","src","dst","target","linkPath"];function Gr(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("/"),s=n.split("/").filter(e=>""!==e&&"."!==e),i=[];for(const e of s)if(".."===e){if(0===i.length)return{ok:!1,reason:"traversal above root"};i.pop()}else i.push(e);let o=(r?"/":"")+i.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 Yr(){try{return Kr().cwd}catch{return}}function zr(){return async(e,t)=>{const{input:n}=e.req;if("object"!=typeof n||null===n)return await t();const r=n;let s,i=!1;for(const e of Wr){const t=r[e];if("string"!=typeof t)continue;i||(s=Yr(),i=!0);const n=Gr(t,s);if(!n.ok)throw new fr(pr.CAPABILITY_PATH_TRAVERSAL_DENIED,`Path traversal denied on field "${e}": ${n.reason}`,{field:e,reason:n.reason,value:t,...void 0!==s?{cwd:s}:{}})}return await t()}}const Jr="encrypted-at-rest";function Hr(){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 s=function(){try{return Kr()}catch{return}}();if(!s)throw new fr(pr.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:Jr,reason:"provider not registered"});if(!s.capabilities?.has(Jr))throw new fr(pr.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${Jr}" capability flag`,{capability:n.name,required:Jr,reason:"capability not advertised"});return kn({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:Jr}}),t()}}function Qr(e,t,n,r,s){try{const i=globalThis.punica?.kernel?.Events?.manager;if(!i||"function"!=typeof i.publishEvent)return;i.publishEvent({name:"capability.denied_by_profile",source:"runtime:capabilities:middleware:profileBudget",kind:"warn",correlationId:s,payload:{invocationId:s,capability:e,profile:t,reason:n,origin:r??"unknown"}})}catch{}}function Zr(){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:s,allowedOrigins:i}=n.capabilities;if("*"===r&&!s?.length&&!i?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(i&&i.length>0){const e=Mr.getCapability(o),t=e?.origin;if(!t||!i.includes(t))throw Qr(o,c,"origin-not-allowed",t,a),new fr(pr.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(s&&s.includes(o))throw Qr(o,c,"in-denylist",void 0,a),new fr(pr.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 Qr(o,c,"not-in-allowlist",void 0,a),new fr(pr.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Xr={alg:"HS256",typ:"PUNICA-APPROVAL"};class es extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function ts(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 ns(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 rs(e){return(new TextEncoder).encode(e)}function ss(e){return ts(rs(JSON.stringify(e)))}function is(e){return JSON.parse((t=ns(e),(new TextDecoder).decode(t)));var t}function os(){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 as(){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 cs{#ne;#re;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?rs(e.secret):as()}async sign(e){const t=await this.#se(),n=ss(Xr),r=ss(e),s=rs(`${n}.${r}`),i=await os().sign("HMAC",t,s);return`${n}.${r}.${ts(new Uint8Array(i))}`}getSecret(){return this.#ne}async#se(){return this.#re||(this.#re=await os().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#re}}class ls{#ne;#re;#ie=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?rs(e.secret):as()}async verify(e){const t=e.split(".");if(3!==t.length)throw new es("MALFORMED","Token must have 3 dot-separated segments");const[n,r,s]=t;let i,o;try{i=is(n)}catch{throw new es("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==i.alg||"PUNICA-APPROVAL"!==i.typ)throw new es("BAD_HEADER",`Unexpected token header: alg=${i.alg??"(missing)"} typ=${i.typ??"(missing)"}`);try{o=is(r)}catch{throw new es("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#se(),c=rs(`${n}.${r}`);let l;try{l=ns(s)}catch{throw new es("MALFORMED","Token signature is not valid base64url")}const u=os();if(!await u.verify("HMAC",a,l,c))throw new es("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new es("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new es("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#ie.add(e)}isRevoked(e){return this.#ie.has(e)}async#se(){return this.#re||(this.#re=await os().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#re}}let us;function ds(){return us||(us=function(){const e=new cs,t=new ls({secret:e.getSecret()});return{signer:e,verifier:t}}()),us}const ps=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function fs(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=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:i.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:d?"error":"warning"},payload:{capability:s,risk:a,approval:c,actor:i.actor,decision:d?"deny":"allow",failClosed:u}})}catch{}if(console.warn(`[CapabilityGateway] Policy manager not available for "${s}" (risk=${a}, approval=${c}); `+(d?"DENYING (fail-closed)":"allowing (fail-open)")+"."),d)throw new fr(pr.CAPABILITY_DENIED,`Policy manager unavailable and capability "${s}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:s,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"===i.actor.type){"approval"===ps({capabilityId:s,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 f={kind:"capability",id:s,risk:l,approval:u,reason:o.description??o.title??`Capability: ${s}`},h=a.evaluate(f,{workspaceId:i.workspaceId,correlationId:n.invocationId,traceId:i.trace.traceId});if(r.policyDecision={allowed:h.allowed,requiresApproval:h.requiresApproval||d,approvalToken:i.policy.approvalToken,reason:h.reason||p},d||h.requiresApproval)if(i.policy.approvalToken)try{await ds().verifier.verify(i.policy.approvalToken)}catch(e){if(e instanceof es){try{const t=globalThis.punica?.kernel?.Events?.manager;t&&t.publishEvent({name:"token.invalid",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:i.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:"error"},payload:{capability:s,tokenError:e.code,actor:i.actor}})}catch{}throw new fr(pr.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:s,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!(a.hasApproval(f,"always",{workspaceId:i.workspaceId})||a.hasApproval(f,"workspace",{workspaceId:i.workspaceId})||a.hasApproval(f,"once",{workspaceId:i.workspaceId}))){a.requestApproval(f,{workspaceId:i.workspaceId,correlationId:n.invocationId,traceId:i.trace.traceId});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:i.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:s,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}throw new fr(pr.CAPABILITY_APPROVAL_REQUIRED,`Approval required: ${p}`,{capability:s,reason:p})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:i.workspaceId};if(!(a.hasApproval(f,"always",e)||a.hasApproval(f,"workspace",e))&&"function"==typeof a.revokeApproval)try{a.revokeApproval({kind:f.kind,id:f.id,scope:"once"})}catch{}}}if(!h.allowed&&!d&&"suggest"!==h.mode)throw new fr(pr.CAPABILITY_DENIED,h.reason??"Policy denied execution",{capability:s,decision:h});return await t()}}const hs=new class{#m=new Map;#oe;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#oe=t<=0?1:t}get(e,t){const n=this.#ae(e,t),r=this.#m.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#m.delete(n),this.#m.set(n,r),r;this.#m.delete(n)}}set(e){const t=this.#ae(e.capabilityId,e.key);for(this.#m.delete(t),this.#m.set(t,e);this.#m.size>this.#oe;){const e=this.#m.keys().next().value;if(void 0===e)break;this.#m.delete(e)}}delete(e,t){return this.#m.delete(this.#ae(e,t))}clear(){this.#m.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#m)r.expiresAtMs<=e&&(this.#m.delete(n),t++);return t}size(){return this.#m.size}#ae(e,t){return`${e}|${t}`}};let ms=hs;function gs(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,input:i,idempotencyKey:o}=n,a=r.spec.defaults?.idempotency??"none";if("none"===a)return t();if("required"===a&&!o)throw new fr(pr.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${s}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:s});if(!o)return t();const c=ms,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")}(i),u=c.get(s,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:s,idempotencyKey:o,cachedAtMs:u.createdAtMs,actor:n.ctx.actor}}),new fr(pr.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED,`Capability "${s}" idempotencyKey "${o}" was previously used with a different input`,{capability:s,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:s,inputHash:l,response:d,createdAtMs:p,expiresAtMs:p+864e5}),r.tags["idempotency.cached"]="true",d}}const ys=new class{#ce=new Map;getBucket(e,t){let n=this.#ce.get(e);return n||(n={tokens:t,lastRefillMs:Date.now(),perSecond:t,maxTokens:t},this.#ce.set(e,n)),n}consumeToken(e,t){const n=this.getBucket(e,t),r=Date.now(),s=(r-n.lastRefillMs)/1e3*t;return n.tokens=Math.min(n.maxTokens,n.tokens+s),n.lastRefillMs=r,n.tokens>=1&&(n.tokens-=1,!0)}};function ws(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=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(":")}(s,i.actor.type,i.actor.extensionName??i.origin.extension);if(!ys.consumeToken(c,a.perSecond))throw new fr(pr.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${s}" (${a.perSecond}/s)`,{capability:s,perSecond:a.perSecond,key:c});return await t()}}const vs=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.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.#le.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function bs(){return async(e,t)=>{const{req:n,state:r}=e,{ctx:s}=n,{spec:i}=r,o=i.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:s.workspaceId,tenantId:s.tenantId,extension:s.actor.extensionName??s.origin.extension,actorType:s.actor.type});try{await vs.acquire(a,o.max)}catch(e){throw new fr(pr.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{vs.release(a)}}}const Is=new class{#ue=new Map;getBreaker(e){let t=this.#ue.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#ue.set(e,t)),t}};function ks(){return async(e,t)=>{const{req:n,state:r}=e,{name:s}=n,i=r.spec.defaults?.circuitBreaker;if(!i)return await t();const o=i.failureThreshold??3,a=i.cooldownMs??6e4,c=Is.getBreaker(s),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new fr(pr.CAPABILITY_CIRCUIT_OPEN,`Circuit breaker open for "${s}"`,{capability:s,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 Es(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 Ss(e,t,n,r){let s;const i=new Promise((e,t)=>{s=setTimeout(()=>{t(new fr(pr.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),i])}finally{void 0!==s&&clearTimeout(s)}}function As(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 xs(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:As(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(As(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=Kr()}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(As(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 Cs=new WeakMap;function Ts(e,t){if(!0===t.secretBearing)return Ms(e);const n=function(e){const t=Cs.get(e);if(t)return t;const n=d(e.outputSchema);return Cs.set(e,n),n}(t);return n.length>0?p(e,n):e}function Ms(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ms);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ms(r);return t}return e}function Ns(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=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=Ts(r.output,o);await xs({invocationId:n.invocationId,capability:s,actor:i.actor,origin:i.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:i.workspaceId,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Ps=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function _s(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const Ls=new class{async call(e,t,n,r){const s=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let i=hr.getSpec(e),o=i?hr.getProvider(e):void 0,a="core";if(!i){const t=Mr.getCapability(e);if(!t)throw _s({name:"capability.unknown_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:n.actor}}),new fr(pr.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,i=gr(t.definition),o=Nr(t.origin,t.definition,t.metadata)}if(!o)throw new fr(pr.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(i.requires)for(const t of i.requires)if(!hr.hasCapability(t))throw new fr(pr.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});i.deprecated&&_s({name:"capability.deprecated_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:a,since:i.deprecated.since,reason:i.deprecated.reason,replacement:i.deprecated.replacement,actor:n.actor}});const c={req:{invocationId:s,name:e,input:t,ctx:n,idempotencyKey:r},state:{spec:i,capabilityOrigin:a,startTimeMs:Date.now(),tags:{}}},l=this.#de(o);try{return await this.#pe(l,c)}catch(e){if(e instanceof fr)throw e;throw new fr(pr.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#de(e){const t={auditTrail:Ns,traceMetrics:Lr,redaction:Or,validateInput:Ur,pathTraversalGuard:zr,encryptionRouting:Hr,profileBudget:Zr,policyGate:fs,idempotency:gs,rateLimit:ws,concurrency:bs,circuitBreaker:ks,timeoutRetry:()=>function(e){return async(t,n)=>{const{req:r,state:s}=t,{input:i,idempotencyKey:o}=r,{spec:a}=s,c=a.defaults?.timeoutMs??3e4,l=a.defaults?.retries??0,u=a.defaults?.retryBackoffMs??1e3,d="write"!==a.sideEffect||Boolean(o);let p=null,f=0;for(;f<=l;){f++;try{const n=await Ss(e,i,t,c);return s.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),f<=l&&d&&Es(p)){const e=u*Math.pow(2,f-1);await new Promise(t=>setTimeout(t,e));continue}throw s.error=p,p}}throw s.error=p??new Error("Execution failed"),s.error}}(e)};return Ps.map(e=>t[e]())}#pe(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const s=e[n];return n++,await s(t,r)};return r()}};function Rs(e,t){const n=Kr(),r=n[t];if("function"!=typeof r)throw new fr(pr.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 $s(e,t,n){const r=Kr();if(!r.capabilities?.has(n))throw new fr(pr.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 s=r[t];if("function"!=typeof s)throw new fr(pr.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 s.bind(r)}class Os{name="fs.readFile";async execute(e,t){const n=Kr();return await n.readFile(e.path)}}class Ds{name="fs.writeFile";async execute(e,t){const n=Kr();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class js{name="fs.listFiles";async execute(e,t){const n=Kr();return await n.getFileTree()}}class Fs{name="fs.stat";async execute(e,t){return await Rs("fs.stat","stat")(e.path)}}class qs{name="fs.exists";async execute(e,t){return await Rs("fs.exists","exists")(e.path)}}class Bs{name="fs.copy";async execute(e,t){await Rs("fs.copy","copy")(e.src,e.dst)}}class Us{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Rs("fs.mkdir","mkdir")(e.path,n)}}class Vs{name="fs.history";async execute(e,t){return await $s("fs.history","history","versioning")(e.path)}}class Ks{name="fs.readAtVersion";async execute(e,t){return await $s("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class Ws{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Rs("fs.list","list")(e.path,n)}}const Gs=In({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 s=String(n??"").trim();if(!s)throw new Error("[Runtime.secrets] Secret name is required");const i=Date.now();if(t.has(s)){const e=t.get(s);t.set(s,{...e,updatedAtMs:i})}else t.set(s,{createdAtMs:i,updatedAtMs:i});e.set(s,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 Ys(){return Gs.get()}function zs(e){Gs.set(e),e&&kn({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class Js{name="secrets.get";async execute(e,t){return Ys().get(e.name)}}class Hs{name="secrets.set";async execute(e,t){Ys().set(e.name,e.value)}}function Qs(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Cn]=!0,n}class Zs{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=Qs(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class Xs{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,s=t.sessionId??t.trace?.traceId,i=e=>{if(r)try{r.publishEvent({name:"llm.chunk",envelope:{id:r.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"progress"},payload:{capabilityId:this.name,chunk:e}})}catch{}},o=Qs(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);if("function"!=typeof n.chatStream){const e=await n.chat(o);return i({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(i(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 ei{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 ti{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 ni{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 ri{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 si{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 ii{name="workspace.readFile";async execute(e,t){const n=Kr();return await n.readFile(e.path)}}class oi{name="workspace.writeFile";async execute(e,t){const n=Kr();await n.createFileWithContent(e.path,e.content)}}class ai{name="workspace.listFiles";async execute(e,t){const n=Kr(),r=await n.getFileTree(),s=[],i=e=>{for(const t of e??[])s.push({path:t.path,name:t.name,isDirectory:t.isDirectory}),t.isDirectory&&Array.isArray(t.children)&&t.children.length&&i(t.children)};return i(r??[]),{entries:s}}}const ci=[".git",".hg",".svn",".punica","node_modules","bower_components",".pnpm-store","dist","build","out",".next",".nuxt",".svelte-kit",".turbo",".parcel-cache",".cache","coverage","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".venv","venv",".eggs","target",".gradle",".idea",".vscode","vendor"],li=["png","jpg","jpeg","gif","webp","bmp","ico","tiff","psd","woff","woff2","ttf","otf","eot","zip","tar","gz","tgz","bz2","xz","7z","rar","jar","mp3","mp4","mov","avi","mkv","webm","wav","flac","ogg","pdf","doc","docx","xls","xlsx","ppt","pptx","parquet","feather","arrow","orc","avro","db","sqlite","sqlite3","mdb","h5","hdf5","npy","npz","pkl","pickle","pt","pth","ckpt","safetensors","onnx","gguf","ggml","bin","model","pyc","pyo","class","o","obj","so","dylib","dll","exe","wasm","map"];function ui(e){let t=e.trim();if(!t||t.startsWith("#")||t.startsWith("!"))return null;t.endsWith("/")&&(t=t.slice(0,-1));const n=t.startsWith("/");if(n&&(t=t.replace(/^\/+/,"")),!t)return null;const r=t.includes("/"),s=function(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];"*"===r?"*"===e[n+1]?(n++,"/"===e[n+1]?(n++,t+="(?:.*/)?"):t+=".*"):t+="[^/]*":"?"===r?t+="[^/]":".+^${}()|[]\\".includes(r)?t+="\\"+r:t+=r}return t}(t),i=new RegExp(`^${r||n?"":"(?:.*/)?"}${s}(?:/.*)?$`);return e=>i.test(e)}const di={py:"python",ipynb:"python",ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",rs:"rust",go:"go",java:"java",kt:"kotlin",rb:"ruby",php:"php",c:"c",h:"c",cpp:"c++",cc:"c++",hpp:"c++",cs:"c#",swift:"swift",scala:"scala",r:"r",jl:"julia",sh:"shell",sql:"sql"},pi=new Set(["main.py","app.py","manage.py","wsgi.py","asgi.py","__main__.py","cli.py","run.py","train.py","index.ts","index.js","main.ts","main.js","server.ts","server.js"]);function fi(e){const t=e.trim();if(!t||t.startsWith("#")||t.startsWith("-"))return null;const n=t.split(" #")[0].trim().match(/^[A-Za-z0-9._-]+/);return n?n[0]:null}function hi(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function mi(e,t,n){const r=new Map;for(const t of e){if(t.endsWith("/"))continue;const e=di[hi(t)];e&&r.set(e,(r.get(e)??0)+1)}return n&&r.set("python",(r.get("python")??0)+1),t&&r.set("node",(r.get("node")??0)+1),[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,6).map(([e])=>e)}function gi(e,t){const n=new Set;t&&n.add(t.replace(/^\.\//,""));for(const t of e){if(t.endsWith("/"))continue;const e=t.slice(t.lastIndexOf("/")+1);if(pi.has(e)&&n.add(t),n.size>=8)break}return[...n].slice(0,8)}function yi(e){const t={};let n,r;if(e.packageJson)try{const s=JSON.parse(e.packageJson),i=Object.keys(s.dependencies??{}),o=Object.keys(s.devDependencies??{});if(t.node={source:"package.json",count:i.length,dev:o.length,names:[...i,...o].slice(0,60)},s.scripts&&Object.keys(s.scripts).length){n={};for(const[e,t]of Object.entries(s.scripts).slice(0,30))n[e]=t}"string"==typeof s.main&&(r=s.main)}catch{t.node={source:"package.json",count:0,dev:0,names:[]}}const s=e.requirementsTxt?function(e){const t=[];for(const n of e.split(/\r?\n/)){const e=fi(n);e&&t.push(e)}return t}(e.requirementsTxt):e.pyproject?function(e){const t=e.search(/dependencies\s*=\s*\[/);if(t<0)return[];const n=e.indexOf("[",t);let r=0,s=-1;for(let t=n;t<e.length;t++)if("["===e[t])r++;else if("]"===e[t]&&0===--r){s=t;break}if(s<0)return[];const i=[];for(const t of e.slice(n+1,s).match(/["']([^"']+)["']/g)??[]){const e=fi(t.replace(/["']/g,""));e&&i.push(e)}return i}(e.pyproject):null;s&&(t.python={source:e.requirementsTxt?"requirements.txt":"pyproject.toml",count:s.length,names:s.slice(0,60)});const i={workspace:e.workspace,stack:mi(e.layout,!!t.node,!!t.python),dependencies:t,entrypoints:gi(e.layout,r),layout:e.layout.slice(0,250),truncated:e.layoutTruncated||e.layout.length>250};if(n&&(i.scripts=n),e.readme&&(i.readme=function(e){const t=e.replace(/\r\n/g,"\n").trim();return t.length<=800?t:t.slice(0,800).replace(/\s+\S*$/,"")+" …"}(e.readme)),e.vcs){const t=e.vcs,n=(t.staged?.length??0)+(t.modified?.length??0)+(t.created?.length??0)+(t.deleted?.length??0)+(t.renamed?.length??0)+(t.not_added?.length??0);i.vcs={branch:t.current??null,...null!=t.ahead?{ahead:t.ahead}:{},...null!=t.behind?{behind:t.behind}:{},dirtyFiles:n}}return i}const wi=["readme.md","readme.rst","readme.txt","readme"];async function vi(e,t){try{return await e.readFile(t)}catch{return}}async function bi(){const e=Kr(),t=await e.getFileTree()??[],n=function(e){const t=new Map;for(const n of e??[])n.isDirectory||t.set(n.name.toLowerCase(),n.path);return t}(t),r=function(e={}){const t=new Set(ci),n=new Set(li),r=(e.gitignore??"").split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")&&!e.startsWith("!")),s=r.map(ui).filter(e=>null!=e),i=[],o=new Set,a=e=>{o.has(e)||(o.add(e),i.push(e))};for(const e of ci)a(`${e}/`);for(const e of li)a(`*.${e}`);for(const e of r)a(e);return{patterns:i,isNoise:e=>{const r=String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"");if(!r)return!1;const i=r.split("/");for(const e of i)if(t.has(e))return!0;const o=i[i.length-1],a=o.lastIndexOf(".");if(a>0){const e=o.slice(a+1).toLowerCase();if(n.has(e))return!0}for(const e of s)if(e(r))return!0;return!1}}}({gitignore:n.has(".gitignore")?await vi(e,n.get(".gitignore")):void 0}),{layout:s,truncated:i}=function(e,t){const n=[];let r=!1;const s=(e,i)=>{for(const o of e??[]){const e=o.path.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"");if(!t(e)){if(n.length>=250)return void(r=!0);n.push(o.isDirectory?`${e}/`:e),o.isDirectory&&o.children?.length&&i<2&&s(o.children,i+1)}}};return s(e??[],0),{layout:n,truncated:r}}(t,r.isNoise),o=t=>n.has(t)?vi(e,n.get(t)):Promise.resolve(void 0),[a,c,l]=await Promise.all([o("package.json"),o("requirements.txt"),o("pyproject.toml")]);let u;for(const t of wi)if(n.has(t)&&(u=await vi(e,n.get(t)),u))break;let d=null;try{const e=await(punica.runtime.workspace?.getCurrent?.());if(e){const t=e.environments?.find(t=>t.id===e.currentEnvironmentId);d={name:e.name,kind:e.kind,rootUri:e.rootUri,...t?{environment:t.name}:{}}}}catch{}let p=null;try{const e=globalThis.punica?.runtime?.vcs;e?.status&&(p=await e.status())}catch{}return{context:yi({workspace:d,layout:s,layoutTruncated:i,packageJson:a,requirementsTxt:c,pyproject:l,readme:u,vcs:p}),noisePatterns:r.patterns}}class Ii{name="workspace.projectContext";async execute(e,t){const{context:n}=await bi();return n}}async function ki(e,t,n){try{await e.updateFileContent(t,n)}catch{await e.createFileWithContent(t,n)}}class Ei{name="workspace.writeOrientation";async execute(e,t){const n=!1!==e?.claudeMd,r=!1!==e?.claudeignore,s=Kr(),{context:i,noisePatterns:o}=await bi(),a=[];if(n&&(await ki(s,"CLAUDE.md",function(e){const t=[],n=e.workspace;t.push(`# ${n?.name??"Workspace"}`,""),t.push("> Orientation generated by Punica. A snapshot to start from — verify against the code before relying on any single line.",""),n&&(t.push(`- **Kind:** ${n.kind}`),t.push(`- **Root:** ${n.rootUri}`),n.environment&&t.push(`- **Environment:** ${n.environment}`)),e.stack.length&&t.push(`- **Stack:** ${e.stack.join(", ")}`),e.vcs&&t.push(`- **VCS:** ${e.vcs.branch??"(detached)"}`+(e.vcs.ahead?` ↑${e.vcs.ahead}`:"")+(e.vcs.behind?` ↓${e.vcs.behind}`:"")+` · ${e.vcs.dirtyFiles} uncommitted`),t.push("");const r=e.dependencies.python,s=e.dependencies.node;if((r||s)&&(t.push("## Dependencies",""),r&&t.push(`**Python** (\`${r.source}\`, ${r.count}): ${r.names.join(", ")}`,""),s&&t.push(`**Node** (\`${s.source}\`, ${s.count} + ${s.dev} dev): ${s.names.join(", ")}`,"")),e.scripts&&Object.keys(e.scripts).length){t.push("## Scripts","");for(const[n,r]of Object.entries(e.scripts))t.push(`- \`${n}\`: ${r}`);t.push("")}if(e.entrypoints.length){t.push("## Entry points","");for(const n of e.entrypoints)t.push(`- \`${n}\``);t.push("")}return e.readme&&t.push("## README (digest)","",e.readme,""),e.layout.length&&(t.push("## Layout"+(e.truncated?" (truncated)":""),"","```"),t.push(...e.layout),t.push("```","")),t.join("\n")}(i)),a.push("CLAUDE.md")),r){const e="# Generated by Punica (workspace.writeOrientation).\n# Paths an assistant should skip: dependencies, build output, caches, binary/data blobs, plus your .gitignore.\n"+o.join("\n")+"\n";await ki(s,".claudeignore",e),a.push(".claudeignore")}return{written:a}}}const Si=".punica/facts",Ai=`${Si}/facts.json`;async function xi(e){let t;try{t=await e.readFile(Ai)}catch{return{}}try{const e=JSON.parse(t);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}class Ci{name="context.remember";async execute(e,t){const n=String(e?.key??"").trim();if(!n)throw new Error("context.remember requires input { key: string }.");const r=Kr(),s=await xi(r);return s[n]=e.value??null,await async function(e,t){const n=`${JSON.stringify(t,null,2)}\n`;try{await e.updateFileContent(Ai,n)}catch{try{await e.createFolder(".punica")}catch{}try{await e.createFolder(Si)}catch{}await e.createFileWithContent(Ai,n)}}(r,s),{key:n,count:Object.keys(s).length}}}class Ti{name="context.recall";async execute(e,t){const n=Kr(),r=await xi(n),s=e?.key?String(e.key).trim():"";if(s){const e=Object.prototype.hasOwnProperty.call(r,s);return{key:s,value:e?r[s]:null,found:e}}const i=Object.keys(r),o={};for(const e of i.slice(0,200))o[e]=r[e];return{facts:o,count:i.length,truncated:i.length>200}}}class Mi{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 Ni{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 Pi{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 _i{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 Li{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 s={...e,workspaceId:e.workspaceId??t.workspaceId,parentTraceId:e.parentTraceId??t.trace?.traceId};return r.runSubflow(s)}}const Ri="capability.catalog";class $i{name=Ri;async execute(e,t){const n=e??{},r=Mr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>Oi(e,n));return{capabilities:r,count:r.length}}}function Oi(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=Di(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=Di(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=Di(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 Di(e){return Array.isArray(e)?e:[e]}const ji=["examples","$comment","default","title"];function Fi(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 qi=["properties","patternProperties","definitions","$defs"];function Bi(e){if(Array.isArray(e))return e.map(e=>Bi(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!ji.includes(n))if("description"!==n||"string"!=typeof r){if(qi.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=Bi(n);t[n]=e;continue}t[n]=Bi(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const Ui="capability.schemaExport";class Vi{name=Ui;async execute(e,t){const n=e??{},r=n.filter??{},s=Mr.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>Oi(e,r)),i=n.mode??"full",o=s.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"===i?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=Fi(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=Bi(e.inputSchema));e.policy&&(t.policy={...e.policy});return t}(t):"summary"===i?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=Fi(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 Ki(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return[];const s=Mr.listCapabilities();if(0===s.length)return[];const i=function(e,t){const n=Yi(Gi(e));return t.map(e=>({...e,score:zi(n,Yi(Gi(e.text)))}))}(r,s.map(e=>({id:e.definition.id,description:e.definition.description,text:Wi(e.definition)}))),o=i.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 xn("llm.recommendIntent",{intent:r,limit:n,path:"text-similarity",topIds:o.map(e=>e.id),topScore:o[0]?.score??0}),o}function Wi(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 Gi(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(e=>e.length>0)}function Yi(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function zi(e,t){if(0===e.size||0===t.size)return 0;let n=0,r=0,s=0;for(const[,t]of e)r+=t*t;for(const[,e]of t)s+=e*e;for(const[r,s]of e){const e=t.get(r);void 0!==e&&(n+=s*e)}const i=Math.sqrt(r)*Math.sqrt(s);return 0===i?0:n/i}const Ji="capability.recommend";class Hi{name=Ji;async execute(e,t){const n=e??{},r=String(n.intent??""),s=await Ki(r,"number"==typeof n.limit?{limit:n.limit}:void 0);return{recommendations:s.map(e=>({id:e.id,score:e.score,description:e.description})),path:"text-similarity",count:s.length}}}const Qi="capability.describe",Zi="capability.search";function Xi(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class eo{name=Qi;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),s=(await(new Vi).execute({mode:"ai-tools"},t)).capabilities.filter(e=>r.has(String(e.id))),i=new Set(s.map(e=>String(e.id)));return{tools:s,missing:n.filter(e=>!i.has(e))}}}class to{name=Zi;async execute(e,t){const n=e??{},r=String(n.query??"").trim(),s=Math.min(Math.max(1,Math.floor(n.limit??16)),50);if(!r)return{results:[],count:0};const i=Mr.listCapabilities(),o=new Map(i.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await Ki(r,{limit:s});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=i.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,s).map(e=>{const t=o.get(e);return{id:e,description:Fi(t?.description??t?.title??e,100),category:Xi(e)}});return{results:c,count:c.length}}}function no(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function ro(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 so{name="ai.session.create";async execute(e,t){const n=e??{};return{session:no().create(n)}}}class io{name="ai.session.list";async execute(e,t){const n=no().list(e?.workspaceId);return{sessions:n,count:n.length}}}class oo{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:no().get(n)}}}class ao{name="ai.session.rename";async execute(e,t){const n=e;return{ok:no().rename(String(n?.sessionId??""),String(n?.title??""))}}}class co{name="ai.session.archive";async execute(e,t){const n=e;return{ok:no().archive(String(n?.sessionId??""),n?.archived)}}}class lo{name="ai.session.delete";async execute(e,t){return{ok:no().delete(String(e?.sessionId??""))}}}const uo={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"}]}},po={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"}]}},fo=new Set(["low","medium","high"]),ho={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&fo.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"}]:[]}},mo=new Set(["none","plan","step"]),go={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&mo.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 yo={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"}]:[]}},wo=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,vo={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&wo.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"}]}},bo=new Set(["low","medium","high"]),Io=["write","delete","remove","modify","destroy"],ko=[uo,po,ho,go,yo,vo,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!bo.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&&Io.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 Eo=new class{#fe=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#fe.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.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of ko)this.#fe.set(e.id,e)}},So="capability.lint";class Ao{name=So;async execute(e,t){const n=e??{},r=Mr.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),s=Eo.lintAll(r).map(e=>({id:e.id,ok:e.ok,issues:e.issues}));return{results:s,ok:s.every(e=>e.ok),count:s.length}}}const xo={type:"object"};function Co(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function To(e){let t;return t=function(e){if(e instanceof fr)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:Co(e),{content:[{type:"text",text:t}],isError:!0}}const Mo="capability.serveList",No="capability.serveCall",Po=new Set([Mo,No]);class _o{name=Mo;async execute(e,t){const n=(e??{}).filter??{},r=Mr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!Po.has(e.definition.id)).filter(e=>Oi(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??xo,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class Lo{name=No;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||Po.has(r)||!Mr.getCapability(r))return To(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:Co(e)}],isError:!1}}(await Ls.call(r,n.arguments??{},t))}catch(e){return To(e)}}}const Ro="shell.revealView",$o="shell.hideView",Oo="shell.listViews",Do="shell.toggleView",jo="shell.toggleSlot",Fo="shell.moveView";function qo(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new fr(pr.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:Ro});return e}function Bo(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 Uo{name=Ro;async execute(e,t){const{viewId:n,focus:r}=e??{},s=qo();if(!s.getPlacement(n))throw new fr(pr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:Ro,viewId:n});return await s.reveal(n,Bo(t),{focus:r}),{viewId:n,revealed:!0}}}class Vo{name=$o;async execute(e,t){const{viewId:n}=e??{};return qo().hide(n,Bo(t)),{viewId:n,hidden:!0}}}class Ko{name=Oo;async execute(e,t){return{views:qo().listViews()}}}class Wo{name=Do;async execute(e,t){const{viewId:n,focus:r}=e??{},s=qo();if(!s.getPlacement(n))throw new fr(pr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:Do,viewId:n});return"visible"===s.getState(n)?(s.hide(n,Bo(t)),{viewId:n,visible:!1}):(await s.reveal(n,Bo(t),{focus:r}),{viewId:n,visible:!0})}}const Go=new Map;class Yo{name=jo;async execute(e,t){const{slot:n,focus:r}=e??{},s=qo(),i=s.getVisibleView(n);if(i)return Go.set(n,i),s.hide(i,Bo(t)),{slot:n,visible:!1,viewId:i};const o=Go.get(n);let a=o&&s.getPlacement(o)?o:void 0;return a||(a=s.listViews().find(e=>e.slot===n)?.viewId),a?(await s.reveal(a,Bo(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}class zo{name=Fo;async execute(e,t){const{viewId:n,slot:r}=e??{},s=qo(),i=s.getPlacement(n);if(!i)throw new fr(pr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover movable views.`,{capability:Fo,viewId:n});const o=i.allowedSlots??[];if(!o.includes(r))throw new fr(pr.CAPABILITY_INPUT_INVALID,`View "${n}" cannot be moved to slot "${r}". Allowed slots: ${o.length?o.join(", "):"(none)"}.`,{capability:Fo,viewId:n,slot:r});return await s.moveView(n,r,Bo(t)),{viewId:n,slot:r,moved:!0}}}function Jo(e){try{hr.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function Ho(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 Qo(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 Zo(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=Mr.getCapability(e.id);return t?void Qo(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Mr.listCapabilities(n),s=r.map(Ho);if(console.log("[Punica] Trinity capability catalog",{count:s.length}),s.length>0){if(console.table(s),e?.verbose){console.log("[Punica] Full definitions (same fields as .punica/capabilities.yaml):");for(const e of r)Qo(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Xo(e){return Zo({...e,verbose:!0})}function ea(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 ta(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,s=t.policy?.risk??"—",i=function(e){const t=e.indexOf("\n");return(-1===t?e:e.slice(0,t)).trim()}(t.description??t.title??"")||"—";return`| ${n} | ${r} | ${s} | ${o=i,o.replace(/\|/g,"\\|")} |`;var o}function na(e){return JSON.stringify(e,null,2)}const ra=new class{#he=new Map;get(e){return this.#he.get(e)}list(){return[...this.#he.values()]}register(e,t){for(const e of t)this.#he.set(e.definition.id,e),this.#me(e.definition.id)}unregister(e){for(const[t,n]of this.#he)n.serverId===e&&(this.#he.delete(t),this.#ge(t))}hasServer(e){for(const t of this.#he.values())if(t.serverId===e)return!0;return!1}#me(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{}}#ge(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{}}},sa=16384,ia="runtime:mcp:client";function oa(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function aa(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 aa(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=>aa(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,s]of Object.entries(e))n[r]=aa(s,t+1);return n}return e}function ca(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=sa)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(aa(e,0),null,2)??"null";if(r.length<=sa)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,sa)+"\n… [truncated]",bytes:n,truncated:!0}}function la(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const ua=new class{#ye=new Map;async connect(e){if(this.#ye.has(e.id))return this.#ye.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return wa}),r=e.toolOverrides??await t(e.id),s="stdio"===e.kind?await n(e.env):e.env,i="streamable-http"===e.kind||"sse"===e.kind?await n(e.headers):e.headers,o={...e,env:s,headers:i,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:la(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const s=oa(),i=ca(r??{});kn({name:"mcp.request",source:ia,correlationId:s,payload:{...n(s,e,r),kind:"notification",requestJson:i.json,requestBytes:i.bytes,requestTokens:Ee().estimate(i.json),truncated:i.truncated}}),t.notify(e,r)},async request(e,r){const s=oa(),i=Date.now(),o=ca(r??{});kn({name:"mcp.request",source:ia,correlationId:s,payload:{...n(s,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:Ee().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=ca(o??null);return kn({name:"mcp.response",source:ia,correlationId:s,payload:{...n(s,e,r),kind:"request",isError:!1,durationMs:Date.now()-i,responseJson:a.json,responseBytes:a.bytes,responseTokens:Ee().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw kn({name:"mcp.response",source:ia,correlationId:s,kind:"error",payload:{...n(s,e,r),kind:"request",isError:!0,durationMs:Date.now()-i,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 Rm});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 $m});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??{},s={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},i={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:s,sideEffects:u,executionDefaults:i,tags:l}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});ra.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(),ra.unregister(e.id),this.#ye.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#ye.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#ye.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#ye.values()].map(e=>e.handle)}listTools(e){return e?this.#ye.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#ye.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},da=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/,pa=/^\$\{secret\.([A-Za-z0-9_.-]+)\}$/;async function fa(e){try{const t=globalThis.punica?.runtime?.secrets,n=await(t?.resolve?.(e));return"string"==typeof n&&""!==n?n:void 0}catch{return}}async function ha(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[s,i]of Object.entries(e)){if("string"!=typeof i){t[s]=i;continue}const e=i.match(pa);if(e){const n=e[1],r=await fa(n);void 0!==r?t[s]=r:console.warn(`[Punica] MCP secret placeholder \${secret.${n}} — not found in Secret Manager`);continue}const o=i.match(da);if(o){const e=o[1];if(!r){console.warn(`[Punica] MCP env placeholder \${env.${e}} skipped — not in Node/Electron`);continue}const i=n[e];void 0!==i?t[s]=i:console.warn(`[Punica] MCP env placeholder \${env.${e}} — variable unset`)}else t[s]=i}return t}async function ma(e){try{const t=globalThis,n=t.punica?.runtime?.fs,r=n?.readFile,s=n?.exists;if(!r)return{};if(s){const t=`.punica/mcp/${e}.yaml`;if(!await s(t))return{}}let i;try{i=await r(`.punica/mcp/${e}.yaml`,{encoding:"utf8"})}catch{return{}}if("string"!=typeof i||""===i.trim())return{};const{parse:o}=await Promise.resolve().then(function(){return vd}),a=o(i);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 ga(){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 s;try{s=await n(".punica/mcp.yaml",{encoding:"utf8"})}catch{return[]}const{parseYamlMcpConfig:i}=await Promise.resolve().then(function(){return Om}),o=i(s);return Promise.all(o.map(e=>async function(e){const t=await ma(e.id),n="stdio"===e.kind?await ha(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?await ha(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 ya(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?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?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 wa=Object.freeze({__proto__:null,loadMcpConfig:ga,loadServerOverrides:ma,parseStaticConfig:ya,resolveEnvPlaceholders:ha});class va{name=Ge.RUNTIME.MCP;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS,Ge.RUNTIME.FS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){this.#we=e.ModuleLifecycleState.BOOTSTRAPPING;const n=await ga();this.#ve(n),this.#we=e.ModuleLifecycleState.BOOTSTRAPPED}async#ve(e){for(const t of e)try{await ua.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#we=e.ModuleLifecycleState.STARTING,this.#we=e.ModuleLifecycleState.STARTED,console.log(`[Punica] MCP module started — ${ra.list().length} capability(ies) active`)}}const ba=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const Ia={get capabilities(){return Vr.hasProvider()?Vr.get().capabilities:void 0},get cwd(){return Vr.hasProvider()?Vr.get().cwd:void 0},hasProvider:()=>Vr.hasProvider(),getFileTree:()=>Vr.get().getFileTree(),readFile:e=>Vr.get().readFile(e),readBytes:(e,t,n)=>{const r=Vr.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)=>Vr.get().updateFileContent(e,t),createFolder:e=>Vr.get().createFolder(e),deleteFolder:e=>Vr.get().deleteFolder(e),deleteFile:(e,t)=>Vr.get().deleteFile(e,t),renameFile:(e,t)=>Vr.get().renameFile(e,t),renameFolder:(e,t)=>Vr.get().renameFolder(e,t),revealInOS:e=>{const t=Vr.get();if("function"!=typeof t.revealInOS)throw new Error("[Runtime.fs] Provider does not implement revealInOS()");return t.revealInOS(e)},createFileWithContent:(e,t)=>Vr.get().createFileWithContent(e,t),list:(e,t)=>{const n=Vr.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=Vr.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=Vr.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},ka=function(e){return e||{query:e=>yn().query(e),startIndex:e=>{const t=yn();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(ba?.search),Ea=function(e){return e||{status:()=>bn().status(),branches:()=>bn().branches(),logs:e=>bn().logs(e),init:e=>bn().init(e),clone:e=>bn().clone(e),commit:e=>bn().commit(e),stage:e=>bn().stage(e),unstage:e=>bn().unstage(e),discard:e=>bn().discard(e),reset:e=>bn().reset(e),switchBranch:e=>bn().switchBranch(e),createBranch:(e,t)=>bn().createBranch(e,t),fetch:e=>bn().fetch(e),pull:e=>bn().pull(e),push:e=>bn().push(e)}}(ba?.vcs),Sa=function(e){return e||{create:e=>wn().create(e),write:(e,t)=>wn().write(e,t),resize:(e,t,n)=>wn().resize(e,t,n),close:e=>wn().close(e),onData:(e,t)=>wn().onData(e,t),onExit:(e,t)=>wn().onExit(e,t),list:()=>wn().list()}}(ba?.terminals),Aa=function(e){return e||{start:e=>vn().start(e),send:(e,t)=>vn().send(e,t),onMessage:(e,t)=>vn().onMessage(e,t),onStderr:(e,t)=>vn().onStderr(e,t),onExit:(e,t)=>vn().onExit(e,t),stop:e=>vn().stop(e),list:()=>vn().list()}}(ba?.debug),xa=function(e){return e||{run:e=>function(){if(pn)return pn;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return pn=e,pn}().run(e)}}(ba?.tasks),Ca=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&An(e),{getCurrent:()=>En.get().getCurrent(),list:()=>En.get().list(),open:e=>En.get().open(e),setEnvironment:(e,t)=>En.get().setEnvironment(e,t),onDidChange:e=>En.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(ba?.workspace),Ta=function(e){return e||{list:async e=>gn().list(e),get:e=>gn().get(e),register:e=>gn().register(e),unregister:e=>gn().unregister(e),onDidChange:e=>gn().onDidChange(e)}}(ba?.resources),Ma=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&_n(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){(Mn&&Mn!==e||Nn&&t&&Nn!==t)&&z.publishEvent({name:"llm.providerChanged",envelope:{id:z.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:Mn,newProviderId:e,previousEndpoint:Nn,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),Mn=e,t&&(Nn=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)}})(),s=e?.correlationId??z.createCorrelationId(),i=ye.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!i.allowed)throw i.requiresApproval&&ye.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:s}),z.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:z.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(i.reason??"[Policy] Remote LLM request denied");return z.publishEvent({name:"llm.remoteRequestSent",envelope:{id:z.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),function(e){return"remote"===e?.route||String(e?.providerId??"").toLowerCase().startsWith("remote:")}(e)?{...e,correlationId:s,route:"remote",providerId:t}:{...e,correlationId:s}}const s={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",s=e?.providerId??"remote",i=Pn(),o=!0===e?.[Cn];if(!o&&("remote"===t||n(e))){const t=e?.endpoint,n=await r(e,s,t);return await i.chat(n)}const a=await i.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:s,r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch{return}})(),i=e?.correlationId??z.createCorrelationId(),o=ye.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw z.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:z.createCorrelationId(),correlationId:i,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&&ye.requestApproval({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r,correlationId:i}),new Error(o.reason??"[Policy] Remote LLM request denied (auto route bypass detected)");z.publishEvent({name:"llm.remoteRequestSent",envelope:{id:z.createCorrelationId(),correlationId:i,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",s=e?.providerId??"remote",i=Pn();let o=e;if(!(!0===e?.[Cn])&&("remote"===t||n(e))){const t=e?.endpoint;o=await r(e,s,t)}if("function"!=typeof i.chatStream){const e=await i.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 i.chatStream(o)){if(o?.signal?.aborted)return;yield e}},__punicaWrappedLlmFacade:!0};return s.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))},..."function"==typeof e.registerModelFile?{registerModelFile:async t=>{await e.registerModelFile(t)}}:{},localServerStatus:async()=>await(e.localServerStatus?.()),startLocalServer:async t=>await(e.startLocalServer?.(t)),stopLocalServer:async()=>{await(e.stopLocalServer?.())}}}(),s}(ba?.llm),Na=function(e){if(e)return e;const t=$n(),n=new On(t),r=new Kn(t,n);t.registerLanguageRuntime(jn),t.registerLanguageRuntime(Fn),t.registerLanguageRuntime(qn),t.registerLanguageRuntime(Bn),t.registerLanguageRuntime(Un);const s=new Map;return{async*run(e,t){const n=t?.runId??Vn("run"),i=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});s.set(n,i);try{for await(const n of i.run(e,t))yield n}finally{s.delete(n),await i.close()}},async cancel(e){const t=s.get(e);t&&(await t.interrupt(),s.delete(e))},session:r,registry:t}}(ba?.compute),Pa=function(e){if(e)return e;const t=Yn(),n=new zn(t);return{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],s=t.getProvider(r);if(!s)throw new Error(`Dataset provider not found: ${r}`);return s.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}}(ba?.datasets),_a=function(e){if(e)return e;const t=Qn(),n=new Zn(t);return{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],s=t.getProvider(r);if(!s)throw new Error(`Model provider not found: ${r}`);return s.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}}(ba?.models),La=function(e){if(e)return e;const t=tr();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,s=t.select(r);if(!s){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 s.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)}}}(ba?.modelRuntimes),Ra=function(e){if(e)return e;const t=tr();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)}}}(ba?.inference),$a=function(e){return e||{upsert:(e,t)=>ur().upsert(e,t),query:e=>ur().query(e),delete:(e,t)=>ur().delete(e,t),clear:e=>ur().clear(e),count:e=>ur().count(e)}}(ba?.vectors),Oa=function(e){if(e)return e;function t(){const e=dr().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=dr().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}function r(){const e=dr().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 s={start:e=>r().start(e),stop:()=>r().stop(),status:()=>r().status(),onRequest:e=>r().onRequest(e),reply:(e,t)=>r().reply(e,t)},i={info:e=>{const t=dr().system;return t?t.info(e):Promise.reject(new Error("[Runtime.host] No machine-facts (system) surface is registered. This is only available on hosts that can measure the machine (e.g. Electron); a browser host does not provide it."))}};return{dataDir:()=>dr().dataDir(),dataFs:{list:(e,t)=>dr().dataFs.list(e,t),readFile:e=>dr().dataFs.readFile(e),stat:e=>dr().dataFs.stat(e),mkdir:(e,t)=>dr().dataFs.mkdir(e,t),deleteFile:e=>dr().dataFs.deleteFile(e),deleteFolder:e=>dr().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=dr().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=dr().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=>n().requestJson(e),get download(){const e=lr?.http?.download;if(e)return e=>n().download(e)},get onDownloadProgress(){const e=lr?.http?.onDownloadProgress;if(e)return e=>n().onDownloadProgress(e)}},get mcpServer(){return lr?.mcpServer?s:void 0},get system(){return lr?.system?i:void 0}}}(ba?.host),Da=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&zs(e);return{set:(e,t)=>Gs.get().set(e,t),get:e=>Gs.get().get(e),delete:e=>Gs.get().delete(e),list:()=>Gs.get().list(),resolve:async e=>{const t=await async function(e){try{const t=punica.kernel?.Commands?.manager?.executeCommand("secrets.get",{name:e}),n=await Promise.resolve(t);if(void 0===n)return;const r=n.value;return"string"==typeof r&&""!==r?r:null}catch{return}}(e);return void 0!==t?t:Gs.get().get(`secret-manager.${e}`)},__punicaWrappedSecretsFacade:!0}}(ba?.secrets);console.log("[Runtime] Facades created"),function(){Jo({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}}),hr.registerProvider(new Os),Jo({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"}}),hr.registerProvider(new Ds),Jo({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}}),hr.registerProvider(new js),Jo({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}}),hr.registerProvider(new Fs),Jo({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}}),hr.registerProvider(new qs),Jo({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"}}),hr.registerProvider(new Bs),Jo({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"}}),hr.registerProvider(new Us),Jo({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}}),hr.registerProvider(new Ws),Jo({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}}),hr.registerProvider(new Vs),Jo({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}}),hr.registerProvider(new Ks),Jo({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}}),hr.registerProvider(new Js),Jo({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"}}),hr.registerProvider(new Hs),Jo({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}}}),hr.registerProvider(new Zs),Jo({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}}}),hr.registerProvider(new Xs),Jo({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}}}),hr.registerProvider(new ti),Jo({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}}}),hr.registerProvider(new ei),Jo({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}}),hr.registerProvider(new ni),Jo({name:"vcs.status",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),hr.registerProvider(new ri),Jo({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"}}),hr.registerProvider(new si),Jo({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}}),hr.registerProvider(new ii),Jo({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"}}),hr.registerProvider(new oi),Jo({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}}),hr.registerProvider(new ai),Jo({name:"workspace.projectContext",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),hr.registerProvider(new Ii),Jo({name:"workspace.writeOrientation",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",properties:{claudeMd:{type:"boolean"},claudeignore:{type:"boolean"}}},outputSchema:{type:"object",properties:{written:{type:"array",items:{type:"string"}}}},defaults:{timeoutMs:3e4,idempotency:"optional"}}),hr.registerProvider(new Ei),Jo({name:"context.remember",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["key"],properties:{key:{type:"string"},value:{}}},outputSchema:{type:"object",properties:{key:{type:"string"},count:{type:"number"}}},defaults:{timeoutMs:1e4,idempotency:"optional"}}),hr.registerProvider(new Ci),Jo({name:"context.recall",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{key:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),hr.registerProvider(new Ti),Jo({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"}}),hr.registerProvider(new Mi),Jo({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"}}),hr.registerProvider(new Ni),Jo({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"}}),hr.registerProvider(new Pi),Jo({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}}),hr.registerProvider(new _i),Jo({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"}}),hr.registerProvider(new Li),Jo({name:Ri,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}}),hr.registerProvider(new $i),Jo({name:Ui,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}}),hr.registerProvider(new Vi),Jo({name:Ji,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}}),hr.registerProvider(new Hi),Jo({name:Zi,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}}),hr.registerProvider(new to),Jo({name:Qi,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}}),hr.registerProvider(new eo);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[ro("ai.session.create",{properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),ro("ai.session.list",{properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),ro("ai.session.get",{required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),ro("ai.session.rename",{required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),ro("ai.session.archive",{required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),ro("ai.session.delete",{risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())Jo(e);for(const e of[new so,new io,new oo,new ao,new co,new lo])hr.registerProvider(e);Jo({name:So,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}}),hr.registerProvider(new Ao),Jo({name:Mo,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}}),hr.registerProvider(new _o),Jo({name:No,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}}),hr.registerProvider(new Lo),Jo({name:Ro,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}}),hr.registerProvider(new Uo),Jo({name:$o,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}}),hr.registerProvider(new Vo),Jo({name:Oo,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}}),hr.registerProvider(new Ko),Jo({name:Do,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}}),hr.registerProvider(new Wo),Jo({name:jo,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}}),hr.registerProvider(new Yo),Jo({name:Fo,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId","slot"],properties:{viewId:{type:"string"},slot:{type:"string"}}},outputSchema:{type:"object",required:["viewId","slot","moved"],properties:{viewId:{type:"string"},slot:{type:"string"},moved:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),hr.registerProvider(new zo)}(),console.log("[Runtime] Capabilities registered");const ja={lifecyclePhase:ba?.lifecyclePhase??"bootstrapping",fs:Ia,fileOpeners:ba?.fileOpeners??ln,search:ka,vcs:Ea,terminals:Sa,debug:Aa,tasks:xa,workspace:Ca,resources:Ta,secrets:Da,llm:Ma,compute:Na,datasets:Pa,models:_a,modelRuntimes:La,inference:Ra,vectors:$a,host:Oa,capabilities:{gateway:Ls,unifiedRegistry:Mr,logTrinityCatalog:Zo,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??"—",s=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${s}`);const i=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";return n.push(`**Side effects:** ${i}`),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(na(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(na(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 s=t.requires;if(s&&s.length>0){n.push("## Requires"),n.push("");for(const e of s)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 i=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(i&&(n.push("## Source"),n.push(""),n.push(i),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(`## ${ea(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(ta(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:ra,connect:e=>ua.connect(e),disconnect:e=>ua.disconnect(e),listServers:()=>ua.listServers(),listTools:e=>ua.listTools(e),callTool:(e,t,n)=>ua.callTool(e,t,n)},setFsProvider:function(e){Vr.set(e),e&&kn({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:_n,setComputeProvider:function(e){$n().registerProvider(e)},setComputeRuntime:function(e){$n().registerLanguageRuntime(e)},setDatasetProvider:function(e){Yn().registerProvider(e)},setModelProvider:function(e){Qn().registerProvider(e)},setModelRuntime:function(e){tr().register(e)},setHostProvider:function(e){lr=e},setVectorsProvider:function(e){ar=e},setSearchProvider:function(e){dn=e},setWorkspaceProvider:An,setTerminalProvider:function(e){fn=e},setDebugProvider:function(e){hn=e},setVcsProvider:function(e){mn=e},setResourcesProvider:function(e){un=e},setTasksProvider:function(e){pn=e},setSecretsProvider:zs};class Fa{#be;constructor(e){this.#be=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#be);n?e(n):t(new Error("Extension not found"))})}}let qa=class{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}},Ba=class extends qa{constructor(e){super(e)}async execute(){return await super.execute()}},Ua=class extends qa{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))}}},Va=class extends qa{constructor(e){super(e)}async execute(){return await super.execute()}};const Ka=Symbol.for("yaml.alias"),Wa=Symbol.for("yaml.document"),Ga=Symbol.for("yaml.map"),Ya=Symbol.for("yaml.pair"),za=Symbol.for("yaml.scalar"),Ja=Symbol.for("yaml.seq"),Ha=Symbol.for("yaml.node.type"),Qa=e=>!!e&&"object"==typeof e&&e[Ha]===Ka,Za=e=>!!e&&"object"==typeof e&&e[Ha]===Wa,Xa=e=>!!e&&"object"==typeof e&&e[Ha]===Ga,ec=e=>!!e&&"object"==typeof e&&e[Ha]===Ya,tc=e=>!!e&&"object"==typeof e&&e[Ha]===za,nc=e=>!!e&&"object"==typeof e&&e[Ha]===Ja;function rc(e){if(e&&"object"==typeof e)switch(e[Ha]){case Ga:case Ja:return!0}return!1}function sc(e){if(e&&"object"==typeof e)switch(e[Ha]){case Ka:case Ga:case za:case Ja:return!0}return!1}const ic=Symbol("break visit"),oc=Symbol("skip children"),ac=Symbol("remove node");function cc(e,t){const n=pc(t);if(Za(e)){lc(null,e.contents,n,Object.freeze([e]))===ac&&(e.contents=null)}else lc(null,e,n,Object.freeze([]))}function lc(e,t,n,r){const s=fc(e,t,n,r);if(sc(s)||ec(s))return hc(e,r,s),lc(e,s,n,r);if("symbol"!=typeof s)if(rc(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=lc(e,t.items[e],n,r);if("number"==typeof s)e=s-1;else{if(s===ic)return ic;s===ac&&(t.items.splice(e,1),e-=1)}}}else if(ec(t)){r=Object.freeze(r.concat(t));const e=lc("key",t.key,n,r);if(e===ic)return ic;e===ac&&(t.key=null);const s=lc("value",t.value,n,r);if(s===ic)return ic;s===ac&&(t.value=null)}return s}async function uc(e,t){const n=pc(t);if(Za(e)){await dc(null,e.contents,n,Object.freeze([e]))===ac&&(e.contents=null)}else await dc(null,e,n,Object.freeze([]))}async function dc(e,t,n,r){const s=await fc(e,t,n,r);if(sc(s)||ec(s))return hc(e,r,s),dc(e,s,n,r);if("symbol"!=typeof s)if(rc(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=await dc(e,t.items[e],n,r);if("number"==typeof s)e=s-1;else{if(s===ic)return ic;s===ac&&(t.items.splice(e,1),e-=1)}}}else if(ec(t)){r=Object.freeze(r.concat(t));const e=await dc("key",t.key,n,r);if(e===ic)return ic;e===ac&&(t.key=null);const s=await dc("value",t.value,n,r);if(s===ic)return ic;s===ac&&(t.value=null)}return s}function pc(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 fc(e,t,n,r){return"function"==typeof n?n(e,t,r):Xa(t)?n.Map?.(e,t,r):nc(t)?n.Seq?.(e,t,r):ec(t)?n.Pair?.(e,t,r):tc(t)?n.Scalar?.(e,t,r):Qa(t)?n.Alias?.(e,t,r):void 0}function hc(e,t,n){const r=t[t.length-1];if(rc(r))r.items[e]=n;else if(ec(r))"key"===e?r.key=n:r.value=n;else{if(!Za(r)){const e=Qa(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}cc.BREAK=ic,cc.SKIP=oc,cc.REMOVE=ac,uc.BREAK=ic,uc.SKIP=oc,uc.REMOVE=ac;const mc={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},gc=e=>e.replace(/[!,[\]{}]/g,e=>mc[e]);class yc{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},yc.defaultYaml,e),this.tags=Object.assign({},yc.defaultTags,t)}clone(){const e=new yc(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new yc(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:yc.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},yc.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:yc.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},yc.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 s=this.tags[n];if(s)try{return s+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+gc(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&&sc(e.contents)){const t={};cc(e.contents,(e,n)=>{sc(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(const[s,i]of n)"!!"===s&&"tag:yaml.org,2002:"===i||e&&!r.some(e=>e.startsWith(i))||t.push(`%TAG ${s} ${i}`);return t.join("\n")}}function wc(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 vc(e){const t=new Set;return cc(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function bc(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function Ic(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],s=Ic(e,r,String(t),n);void 0===s?delete r[t]:s!==n&&(r[t]=s)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),s=Ic(e,r,t,n);void 0===s?r.delete(t):s!==n&&r.set(t,s)}else if(r instanceof Set)for(const t of Array.from(r)){const n=Ic(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 s=Ic(e,r,t,n);void 0===s?delete r[t]:s!==n&&(r[t]=s)}return e.call(t,n,r)}function kc(e,t,n){if(Array.isArray(e))return e.map((e,t)=>kc(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!tc(r=e)&&!rc(r)||!r.anchor))return e.toJSON(t,n);const s={aliasCount:0,count:1,res:void 0};n.anchors.set(e,s),n.onCreate=e=>{s.res=e,delete n.onCreate};const i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}var r;return"bigint"!=typeof e||n?.keep?e:Number(e)}yc.defaultYaml={explicit:!1,version:"1.2"},yc.defaultTags={"!!":"tag:yaml.org,2002:"};class Ec{constructor(e){Object.defineProperty(this,Ha,{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:s}={}){if(!Za(e))throw new TypeError("A document argument is required");const i={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=kc(this,"",i);if("function"==typeof r)for(const{count:e,res:t}of i.anchors.values())r(t,e);return"function"==typeof s?Ic(s,{"":o},"",o):o}}class Sc extends Ec{constructor(e){super(Ka),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return cc(e,{Node:(e,n)=>{if(n===this)return cc.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:s}=t,i=this.resolve(r);if(!i){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(i);if(o||(kc(i,null,t),o=n.get(i)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(s>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=Ac(r,i,n)),o.count*o.aliasCount>s)){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(wc(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 Ac(e,t,n){if(Qa(t)){const r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}if(rc(t)){let r=0;for(const s of t.items){const t=Ac(e,s,n);t>r&&(r=t)}return r}if(ec(t)){const r=Ac(e,t.key,n),s=Ac(e,t.value,n);return Math.max(r,s)}return 1}const xc=e=>!e||"function"!=typeof e&&"object"!=typeof e;class Cc extends Ec{constructor(e){super(za),this.value=e}toJSON(e,t){return t?.keep?this.value:kc(this.value,e,t)}toString(){return String(this.value)}}Cc.BLOCK_FOLDED="BLOCK_FOLDED",Cc.BLOCK_LITERAL="BLOCK_LITERAL",Cc.PLAIN="PLAIN",Cc.QUOTE_DOUBLE="QUOTE_DOUBLE",Cc.QUOTE_SINGLE="QUOTE_SINGLE";function Tc(e,t,n){if(Za(e)&&(e=e.contents),sc(e))return e;if(ec(e)){const t=n.schema[Ga].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:s,onTagObj:i,schema:o,sourceObjects:a}=n;let c;if(r&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=s(e)),new Sc(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 Cc(e);return c&&(c.node=t),t}l=e instanceof Map?o[Ga]:Symbol.iterator in Object(e)?o[Ja]:o[Ga]}i&&(i(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 Cc(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Mc(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 Tc(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 Nc=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class Pc extends Ec{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=>sc(t)||ec(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Nc(e))this.add(t);else{const[n,...r]=e,s=this.get(n,!0);if(rc(s))s.addIn(r,t);else{if(void 0!==s||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,Mc(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(rc(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,s=this.get(n,!0);return 0===r.length?!t&&tc(s)?s.value:s:rc(s)?s.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ec(t))return!1;const n=t.value;return null==n||e&&tc(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!!rc(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(rc(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,Mc(this.schema,r,t))}}}}Pc.maxFlowStringSingleLineLength=60;const _c=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Lc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Rc=(e,t,n)=>e.endsWith("\n")?Lc(n,t):n.includes("\n")?"\n"+Lc(n,t):(e.endsWith(" ")?"":" ")+n,$c="flow",Oc="block",Dc="quoted";function jc(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return e;const c=Math.max(1+i,1+s-t.length);if(e.length<=c)return e;const l=[],u={};let d,p,f=s-t.length;"number"==typeof r&&(r>s-Math.max(2,i)?l.push(0):f=s-r);let h=!1,m=-1,g=-1,y=-1;n===Oc&&(m=Fc(e,m,t.length),-1!==m&&(f=m+c));for(let r;r=e[m+=1];){if(n===Dc&&"\\"===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===Oc&&(m=Fc(e,m,t.length)),f=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>=f)if(d)l.push(d),f=d+c,d=void 0;else if(n===Dc){for(;" "===p||"\t"===p;)p=r,r=e[m+=1],h=!0;const t=m>y+1?m-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,f=t+c,d=void 0}else h=!0}p=r}if(h&&a&&a(),0===l.length)return e;o&&o();let w=e.slice(0,l[0]);for(let r=0;r<l.length;++r){const s=l[r],i=l[r+1]||e.length;0===s?w=`\n${t}${e.slice(0,i)}`:(n===Dc&&u[s]&&(w+=`${e[s]}\\`),w+=`\n${t}${e.slice(s+1,i)}`)}return w}function Fc(e,t,n){let r=t,s=t+1,i=e[s];for(;" "===i||"\t"===i;)if(t<s+n)i=e[++t];else{do{i=e[++t]}while(i&&"\n"!==i);r=t,s=t+1,i=e[s]}return r}const qc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Bc=e=>/^(%|---|\.\.\.)/m.test(e);function Uc(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(Bc(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<s)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+=i," "===n[e+2]&&(o+="\\"),e+=1,a=e+1}break;default:e+=1}return o=a?o+n.slice(a):n,r?o:jc(o,i,Dc,qc(t,!1))}function Vc(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return Uc(e,t);const n=t.indent||(Bc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:jc(r,n,$c,qc(t,!1))}function Kc(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=Uc;else{const t=e.includes('"'),s=e.includes("'");r=t&&!s?Vc:s&&!t?Uc:n?Vc:Uc}return r(e,t)}let Wc;try{Wc=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{Wc=/\n+(?!\n|$)/g}function Gc({comment:e,type:t,value:n},r,s,i){const{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return Kc(n,r);const l=r.indent||(r.forceBlockIndent||Bc(n)?" ":""),u="literal"===o||"folded"!==o&&t!==Cc.BLOCK_FOLDED&&(t===Cc.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const r=t-n,s=e.length;if(s<=r)return!1;for(let t=0,n=0;t<s;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,s-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 f=n.substring(p);const h=f.indexOf("\n");-1===h?d="-":n===f||h!==f.length-1?(d="+",i&&i()):d="",f&&(n=n.slice(0,-f.length),"\n"===f[f.length-1]&&(f=f.slice(0,-1)),f=f.replace(Wc,`$&${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 w=n.substring(0,y<m?y+1:m);w&&(n=n.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let v=(u?"|":">")+(g?l?"2":"1":"")+d;if(e&&(v+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),u)return`${v}\n${l}${w}${n=n.replace(/\n+/g,`$&${l}`)}${f}`;return`${v}\n${l}${jc(`${w}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${f}`,l,Oc,qc(r,!0))}`}function Yc(e,t,n,r){const{implicitKey:s,inFlow:i}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Cc.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Cc.QUOTE_DOUBLE);const c=e=>{switch(e){case Cc.BLOCK_FOLDED:case Cc.BLOCK_LITERAL:return s||i?Kc(o.value,t):Gc(o,t,n,r);case Cc.QUOTE_DOUBLE:return Uc(o.value,t);case Cc.QUOTE_SINGLE:return Vc(o.value,t);case Cc.PLAIN:return function(e,t,n,r){const{type:s,value:i}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&i.includes("\n")||u&&/[[\]{},]/.test(i))return Kc(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes("\n")?Kc(i,t):Gc(e,t,n,r);if(!a&&!u&&s!==Cc.PLAIN&&i.includes("\n"))return Gc(e,t,n,r);if(Bc(i)){if(""===c)return t.forceBlockIndent=!0,Gc(e,t,n,r);if(a&&c===l)return Kc(i,t)}const d=i.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 Kc(i,t)}return a?d:jc(d,c,$c,qc(t,!1))}(o,t,n,r);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=s&&e||n;if(l=c(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}function zc(e,t){const n=Object.assign({blockQuote:!0,commentString:_c,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 Jc(e,t,n,r){if(ec(e))return e.toString(t,n,r);if(Qa(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 s;const i=sc(e)?e:t.doc.createNode(e,{onTagObj:e=>s=e});s||(s=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(tc(t)){r=t.value;const s=e.filter(e=>e.identify?.(r));n=s.find(e=>e.format===t.format)??s.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,i));const o=function(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const s=[],i=(tc(e)||rc(e))&&e.anchor;i&&wc(i)&&(n.add(i),s.push(`&${i}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&s.push(r.directives.tagString(o)),s.join(" ")}(i,s,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof s.stringify?s.stringify(i,t,n,r):tc(i)?Yc(i,t,n,r):i.toString(t,n,r);return o?tc(i)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function Hc(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function Qc(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&Zc(n))if(r=Qa(r)?r.resolve(e.doc):r,nc(r))for(const n of r.items)Xc(e,t,n);else if(Array.isArray(r))for(const n of r)Xc(e,t,n);else Xc(e,t,r);else{const s=kc(n,"",e);if(t instanceof Map)t.set(s,kc(r,s,e));else if(t instanceof Set)t.add(s);else{const i=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(sc(e)&&n?.doc){const t=zc(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)+'..."'),Hc(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,s,e),o=kc(r,i,e);i in t?Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[i]=o}}return t}const Zc=e=>"<<"===e||tc(e)&&"<<"===e.value&&(!e.type||e.type===Cc.PLAIN);function Xc(e,t,n){const r=e&&Qa(n)?n.resolve(e.doc):n;if(!Xa(r))throw new Error("Merge sources must be maps or map aliases");const s=r.toJSON(null,e,Map);for(const[e,n]of s)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 el(e,t,n){const r=Tc(e,void 0,n),s=Tc(t,void 0,n);return new tl(r,s)}class tl{constructor(e,t=null){Object.defineProperty(this,Ha,{value:Ya}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return sc(t)&&(t=t.clone(e)),sc(n)&&(n=n.clone(e)),new tl(t,n)}toJSON(e,t){return Qc(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,r,s){const{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n;let p=sc(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(rc(e)||!sc(e)&&"object"==typeof e)throw new Error("With simple keys, collection cannot be used as a key value")}let f=!d&&(!e||p&&null==t&&!n.inFlow||rc(e)||(tc(e)?e.type===Cc.BLOCK_FOLDED||e.type===Cc.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!f&&(d||!i),indent:a+c});let h,m,g,y=!1,w=!1,v=Jc(e,n,()=>y=!0,()=>w=!0);if(!f&&!n.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(n.inFlow){if(i||null==t)return y&&r&&r(),""===v?"?":f?`? ${v}`:v}else if(i&&!d||null==t&&f)return v=`? ${v}`,p&&!y?v+=Rc(v,n.indent,l(p)):w&&s&&s(),v;y&&(p=null),f?(p&&(v+=Rc(v,n.indent,l(p))),v=`? ${v}\n${a}:`):(v=`${v}:`,p&&(v+=Rc(v,n.indent,l(p)))),sc(t)?(h=!!t.spaceBefore,m=t.commentBefore,g=t.comment):(h=!1,m=null,g=null,t&&"object"==typeof t&&(t=o.createNode(t))),n.implicitKey=!1,f||p||!tc(t)||(n.indentAtStart=v.length+1),w=!1,u||!(c.length>=2)||n.inFlow||f||!nc(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let b=!1;const I=Jc(t,n,()=>b=!0,()=>w=!0);let k=" ";if(p||h||m)k=h?"\n":"",m&&(k+=`\n${Lc(l(m),n.indent)}`),""!==I||n.inFlow?k+=`\n${n.indent}`:"\n"===k&&(k="\n\n");else if(!f&&rc(t)){const e=I[0],r=I.indexOf("\n"),s=-1!==r,i=n.inFlow??t.flow??0===t.items.length;if(s||!i){let t=!1;if(s&&("&"===e||"!"===e)){let n=I.indexOf(" ");"&"===e&&-1!==n&&n<r&&"!"===I[n+1]&&(n=I.indexOf(" ",n+1)),(-1===n||r<n)&&(t=!0)}t||(k=`\n${n.indent}`)}}else""!==I&&"\n"!==I[0]||(k="");return v+=k+I,n.inFlow?b&&r&&r():g&&!b?v+=Rc(v,n.indent,l(g)):w&&s&&s(),v}(this,e,t,n):JSON.stringify(this)}}function nl(e,t,n){return(t.inFlow??e.flow?sl:rl)(e,t,n)}function rl({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:i,type:null});let d=!1;const p=[];for(let e=0;e<t.length;++e){const s=t[e];let o=null;if(sc(s))!d&&s.spaceBefore&&p.push(""),il(n,p,s.commentBefore,d),s.comment&&(o=s.comment);else if(ec(s)){const e=sc(s.key)?s.key:null;e&&(!d&&e.spaceBefore&&p.push(""),il(n,p,e.commentBefore,d))}d=!1;let a=Jc(s,u,()=>o=null,()=>d=!0);o&&(a+=Rc(a,i,l(o))),d&&o&&(d=!1),p.push(r+a)}let f;if(0===p.length)f=s.start+s.end;else{f=p[0];for(let e=1;e<p.length;++e){const t=p[e];f+=t?`\n${c}${t}`:"\n"}}return e?(f+="\n"+Lc(l(e),c),a&&a()):d&&o&&o(),f}function sl({items:e},t,{flowChars:n,itemIndent:r}){const{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=t;r+=i;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 s=e[n];let i=null;if(sc(s))s.spaceBefore&&d.push(""),il(t,d,s.commentBefore,!1),s.comment&&(i=s.comment);else if(ec(s)){const e=sc(s.key)?s.key:null;e&&(e.spaceBefore&&d.push(""),il(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=sc(s.value)?s.value:null;n?(n.comment&&(i=n.comment),n.commentBefore&&(l=!0)):null==s.value&&e?.comment&&(i=e.comment)}i&&(l=!0);let o=Jc(s,c,()=>i=null);n<e.length-1&&(o+=","),i&&(o+=Rc(o,r,a(i))),!l&&(d.length>u||o.includes("\n"))&&(l=!0),d.push(o),u=d.length}const{start:p,end:f}=n;if(0===d.length)return p+f;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${i}${s}${t}`:"\n";return`${e}\n${s}${f}`}return`${p}${o}${d.join(" ")}${o}${f}`}function il({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){const s=Lc(t(r),e);n.push(s.trimStart())}}function ol(e,t){const n=tc(t)?t.value:t;for(const r of e)if(ec(r)){if(r.key===t||r.key===n)return r;if(tc(r.key)&&r.key.value===n)return r}}class al extends Pc{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ga,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:s}=n,i=new this(e),o=(e,o)=>{if("function"==typeof s)o=s.call(t,e,o);else if(Array.isArray(s)&&!s.includes(e))return;(void 0!==o||r)&&i.items.push(el(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&&i.items.sort(e.sortMapEntries),i}add(e,t){let n;n=ec(e)?e:e&&"object"==typeof e&&"key"in e?new tl(e.key,e.value):new tl(e,e?.value);const r=ol(this.items,n.key),s=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);tc(r.value)&&xc(n.value)?r.value.value=n.value:r.value=n.value}else if(s){const e=this.items.findIndex(e=>s(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=ol(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=ol(this.items,e),r=n?.value;return(!t&&tc(r)?r.value:r)??void 0}has(e){return!!ol(this.items,e)}set(e,t){this.add(new tl(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)Qc(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!ec(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})),nl(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const cl={collection:"map",default:!0,nodeClass:al,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(Xa(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>al.from(e,t,n)};class ll extends Pc{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ja,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=ul(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=ul(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&tc(r)?r.value:r}has(e){const t=ul(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=ul(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];tc(r)&&xc(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(kc(e,String(r++),t));return n}toString(e,t,n){return e?nl(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,s=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let i of t){if("function"==typeof r){const n=t instanceof Set?i:String(e++);i=r.call(t,n,i)}s.items.push(Tc(i,void 0,n))}}return s}}function ul(e){let t=tc(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const dl={collection:"seq",default:!0,nodeClass:ll,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(nc(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>ll.from(e,t,n)},pl={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>Yc(e,t=Object.assign({actualString:!0},t),n,r)},fl={identify:e=>null==e,createNode:()=>new Cc(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Cc(null),stringify:({source:e},t)=>"string"==typeof e&&fl.test.test(e)?e:t.options.nullStr},hl={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Cc("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&hl.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function ml({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const s="number"==typeof r?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(i)){let e=i.indexOf(".");e<0&&(e=i.length,i+=".");let n=t-(i.length-e-1);for(;n-- >0;)i+="0"}return i}const gl={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:ml},yl={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():ml(e)}},wl={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 Cc(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:ml},vl=e=>"bigint"==typeof e||Number.isInteger(e),bl=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Il(e,t,n){const{value:r}=e;return vl(r)&&r>=0?n+r.toString(t):ml(e)}const kl={identify:e=>vl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>bl(e,2,8,n),stringify:e=>Il(e,8,"0o")},El={identify:vl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>bl(e,0,10,n),stringify:ml},Sl={identify:e=>vl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>bl(e,2,16,n),stringify:e=>Il(e,16,"0x")},Al=[cl,dl,pl,fl,hl,kl,El,Sl,gl,yl,wl];function xl(e){return"bigint"==typeof e||Number.isInteger(e)}const Cl=({value:e})=>JSON.stringify(e),Tl=[cl,dl].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Cl},{identify:e=>null==e,createNode:()=>new Cc(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Cl},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:Cl},{identify:xl,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})=>xl(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:Cl}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),Ml={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,s,i){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=Cc.BLOCK_LITERAL),t!==Cc.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(a.length/e),s=new Array(n);for(let t=0,r=0;t<n;++t,r+=e)s[t]=a.substr(r,e);a=s.join(t===Cc.BLOCK_LITERAL?"\n":" ")}return Yc({comment:e,type:t,value:a},r,s,i)}};function Nl(e,t){if(nc(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ec(r)){if(Xa(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new tl(new Cc(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]=ec(r)?r:new tl(r)}}else t("Expected a sequence for this tag");return e}function Pl(e,t,n){const{replacer:r}=n,s=new ll(e);s.tag="tag:yaml.org,2002:pairs";let i=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(i++),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;s.items.push(el(o,a,n))}return s}const _l={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Nl,createNode:Pl};class Ll extends ll{constructor(){super(),this.add=al.prototype.add.bind(this),this.delete=al.prototype.delete.bind(this),this.get=al.prototype.get.bind(this),this.has=al.prototype.has.bind(this),this.set=al.prototype.set.bind(this),this.tag=Ll.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,s;if(ec(e)?(r=kc(e.key,"",t),s=kc(e.value,r,t)):r=kc(e,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,s)}return n}static from(e,t,n){const r=Pl(e,t,n),s=new this;return s.items=r.items,s}}Ll.tag="tag:yaml.org,2002:omap";const Rl={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ll,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=Nl(e,t),r=[];for(const{key:e}of n.items)tc(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new Ll,n)},createNode:(e,t,n)=>Ll.from(e,t,n)};function $l({value:e,source:t},n){return t&&(e?Ol:Dl).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const Ol={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 Cc(!0),stringify:$l},Dl={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 Cc(!1),stringify:$l},jl={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:ml},Fl={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():ml(e)}},ql={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 Cc(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:ml},Bl=e=>"bigint"==typeof e||Number.isInteger(e);function Ul(e,t,n,{intAsBigInt:r}){const s=e[0];if("-"!==s&&"+"!==s||(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"-"===s?BigInt(-1)*t:t}const i=parseInt(e,n);return"-"===s?-1*i:i}function Vl(e,t,n){const{value:r}=e;if(Bl(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return ml(e)}const Kl={identify:Bl,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Ul(e,2,2,n),stringify:e=>Vl(e,2,"0b")},Wl={identify:Bl,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Ul(e,1,8,n),stringify:e=>Vl(e,8,"0")},Gl={identify:Bl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Ul(e,0,10,n),stringify:ml},Yl={identify:Bl,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Ul(e,2,16,n),stringify:e=>Vl(e,16,"0x")};class zl extends al{constructor(e){super(e),this.tag=zl.tag}add(e){let t;t=ec(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new tl(e.key,null):new tl(e,null);ol(this.items,t.key)||this.items.push(t)}get(e,t){const n=ol(this.items,e);return!t&&ec(n)?tc(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=ol(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new tl(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,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof r&&(e=r.call(t,e,e)),s.items.push(el(e,null,n));return s}}zl.tag="tag:yaml.org,2002:set";const Jl={collection:"map",identify:e=>e instanceof Set,nodeClass:zl,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>zl.from(e,t,n),resolve(e,t){if(Xa(e)){if(e.hasAllNullValues(!0))return Object.assign(new zl,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function Hl(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,s=e=>t?BigInt(e):Number(e),i=r.replace(/_/g,"").split(":").reduce((e,t)=>e*s(60)+s(t),s(0));return"-"===n?s(-1)*i:i}function Ql(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return ml(e);let r="";t<0&&(r="-",t*=n(-1));const s=n(60),i=[t%s];return t<60?i.unshift(0):(t=(t-i[0])/s,i.unshift(t%s),t>=60&&(t=(t-i[0])/s,i.unshift(t))),r+i.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const Zl={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})=>Hl(e,n),stringify:Ql},Xl={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=>Hl(e,!1),stringify:Ql},eu={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(eu.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,s,i,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,r-1,s,i||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=Hl(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$/,"")},tu=[cl,dl,pl,fl,Ol,Dl,Kl,Wl,Gl,Yl,jl,Fl,ql,Ml,Rl,_l,Jl,Zl,Xl,eu],nu=new Map([["core",Al],["failsafe",[cl,dl,pl]],["json",Tl],["yaml11",tu],["yaml-1.1",tu]]),ru={binary:Ml,bool:hl,float:wl,floatExp:yl,floatNaN:gl,floatTime:Xl,int:El,intHex:Sl,intOct:kl,intTime:Zl,map:cl,null:fl,omap:Rl,pairs:_l,seq:dl,set:Jl,timestamp:eu},su={"tag:yaml.org,2002:binary":Ml,"tag:yaml.org,2002:omap":Rl,"tag:yaml.org,2002:pairs":_l,"tag:yaml.org,2002:set":Jl,"tag:yaml.org,2002:timestamp":eu};function iu(e,t){let n=nu.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(nu.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=ru[e];if(t)return t;const n=Object.keys(ru).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const ou=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class au{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:s,sortMapEntries:i,toStringDefaults:o}){this.compat=Array.isArray(e)?iu(e,"compat"):e?iu(null,e):null,this.merge=!!n,this.name="string"==typeof s&&s||"core",this.knownTags=r?su:{},this.tags=iu(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,Ga,{value:cl}),Object.defineProperty(this,za,{value:pl}),Object.defineProperty(this,Ja,{value:dl}),this.sortMapEntries="function"==typeof i?i:!0===i?ou:null}clone(){const e=Object.create(au.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class cu{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ha,{value:Wa});let r=null;"function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t,t=void 0);const s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:i}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new yc({version:i}),this.setSchema(i,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(cu.prototype,{[Ha]:{value:Wa}});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=sc(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){lu(this.contents)&&this.contents.add(e)}addIn(e,t){lu(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=vc(this);e.anchor=!t||n.has(t)?bc(t||"a",n):t}return new Sc(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:s,anchorPrefix:i,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=function(e,t){const n=[],r=new Map;let s=null;return{onAnchor:r=>{n.push(r),s||(s=vc(e));const i=bc(t,s);return s.add(i),i},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!tc(t.node)&&!rc(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,i||"a"),f=Tc(e,l,{aliasDuplicateObjects:s??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&rc(f)&&(f.flow=!0),d(),f}createPair(e,t,n={}){const r=this.createNode(e,null,n),s=this.createNode(t,null,n);return new tl(r,s)}delete(e){return!!lu(this.contents)&&this.contents.delete(e)}deleteIn(e){return Nc(e)?null!=this.contents&&(this.contents=null,!0):!!lu(this.contents)&&this.contents.deleteIn(e)}get(e,t){return rc(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Nc(e)?!t&&tc(this.contents)?this.contents.value:this.contents:rc(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!rc(this.contents)&&this.contents.has(e)}hasIn(e){return Nc(e)?void 0!==this.contents:!!rc(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=Mc(this.schema,[e],t):lu(this.contents)&&this.contents.set(e,t)}setIn(e,t){Nc(e)?this.contents=t:null==this.contents?this.contents=Mc(this.schema,Array.from(e),t):lu(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 yc({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 yc({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 au(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:i}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},a=kc(this.contents,t??"",o);if("function"==typeof s)for(const{count:e,res:t}of o.anchors.values())s(t,e);return"function"==typeof i?Ic(i,{"":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 s=zc(e,t),{commentString:i}=s.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=i(e.commentBefore);n.unshift(Lc(t,""))}let o=!1,a=null;if(e.contents){if(sc(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=i(e.contents.commentBefore);n.push(Lc(t,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=Jc(e.contents,s,()=>a=null,t);a&&(c+=Rc(c,"",i(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(Jc(e.contents,s));if(e.directives?.docEnd)if(e.comment){const t=i(e.comment);t.includes("\n")?(n.push("..."),n.push(Lc(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(Lc(i(t),"")))}return n.join("\n")+"\n"}(this,e)}}function lu(e){if(rc(e))return!0;throw new Error("Expected a YAML collection as document contents")}class uu extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class du extends uu{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class pu extends uu{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const fu=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let i=s-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){const e=Math.min(i-39,o.length-79);o="…"+o.substring(e),i-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,i))){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>s&&(e=Math.max(1,Math.min(t.col-s,80-i)));const a=" ".repeat(i)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function hu(e,{flow:t,indicator:n,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",p="",f=!1,h=!1,m=!1,g=null,y=null,w=null,v=null,b=null,I=null;for(const s of e)switch(m&&("space"!==s.type&&"newline"!==s.type&&"comma"!==s.type&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&"comment"!==s.type&&"newline"!==s.type&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),s.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!s.source.includes("\t")||(g=s),u=!0;break;case"comment":{u||i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=s.source.substring(1)||" ";d?d+=p+e:d=e,p="",l=!1;break}case"newline":l?d?d+=s.source:c=!0:p+=s.source,l=!0,f=!0,(y||w)&&(h=!0),u=!0;break;case"anchor":y&&i(s,"MULTIPLE_ANCHORS","A node can have at most one anchor"),s.source.endsWith(":")&&i(s.offset+s.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=s,null===I&&(I=s.offset),l=!1,u=!1,m=!0;break;case"tag":w&&i(s,"MULTIPLE_TAGS","A node can have at most one tag"),w=s,null===I&&(I=s.offset),l=!1,u=!1,m=!0;break;case n:(y||w)&&i(s,"BAD_PROP_ORDER",`Anchors and tags must be after the ${s.source} indicator`),b&&i(s,"UNEXPECTED_TOKEN",`Unexpected ${s.source} in ${t??"collection"}`),b=s,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){v&&i(s,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),v=s,l=!1,u=!1;break}default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${s.type} token`),l=!1,u=!1}const k=e[e.length-1],E=k?k.offset+k.source.length:s;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&i(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)&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:b,spaceBefore:c,comment:d,hasNewline:f,hasNewlineAfterProp:h,anchor:y,tag:w,end:E,start:I??E}}function mu(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(mu(t.key)||mu(t.value))return!0}return!1;default:return!0}}function gu(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&mu(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function yu(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const s="function"==typeof r?r:(t,n)=>t===n||tc(t)&&tc(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>s(e.key,n))}const wu="All mapping items must start at the same column";function vu(e,t,n,r){let s="";if(e){let i=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{n&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";s?s+=o+t:s=t,o="";break}case"newline":s&&(o+=e),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:s,offset:t}}const bu="Block collections are not allowed within flow collections",Iu=e=>e&&("block-map"===e.type||"block-seq"===e.type);function ku(e,t,n,r,s,i){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,s,i){const o=new(i?.nodeClass??al)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const i of r.items){const{start:l,key:u,sep:d,value:p}=i,f=hu(l,{indicator:"explicit-key-ind",next:u??d?.[0],offset:a,onError:s,parentIndent:r.indent,startOnNewline:!0}),h=!f.found;if(h){if(u&&("block-seq"===u.type?s(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&s(a,"BAD_INDENT",wu)),!f.anchor&&!f.tag&&!d){c=f.end,f.comment&&(o.comment?o.comment+="\n"+f.comment:o.comment=f.comment);continue}(f.hasNewlineAfterProp||mu(u))&&s(u??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==r.indent&&s(a,"BAD_INDENT",wu);const m=f.end,g=u?e(n,u,f,s):t(n,m,l,null,f,s);n.schema.compat&&gu(r.indent,u,s),yu(n,o.items,g)&&s(m,"DUPLICATE_KEY","Map keys must be unique");const y=hu(d??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:s,parentIndent:r.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){h&&("block-map"!==p?.type||y.hasNewline||s(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&f.start<y.found.offset-1024&&s(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,s):t(n,a,d,null,y,s);n.schema.compat&&gu(r.indent,p,s),a=c.range[2];const l=new tl(g,c);n.options.keepSourceTokens&&(l.srcToken=i),o.items.push(l)}else{h&&s(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 tl(g);n.options.keepSourceTokens&&(e.srcToken=i),o.items.push(e)}}return c&&c<a&&s(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[r.offset,a,c??a],o}(e,t,n,r,i):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,s,i){const o=new(i?.nodeClass??ll)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:i,value:l}of r.items){const u=hu(i,{indicator:"seq-item-ind",next:l,offset:a,onError:s,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?s(u.end,"BAD_INDENT","All sequence items must start at the same column"):s(a,"MISSING_CHAR","Sequence item without - indicator")}const d=l?e(n,l,u,s):t(n,u.end,i,null,u,s);n.schema.compat&&gu(r.indent,l,s),a=d.range[2],o.items.push(d)}return o.range=[r.offset,a,c??a],o}(e,t,n,r,i):function({composeNode:e,composeEmptyNode:t},n,r,s,i){const o="{"===r.start.source,a=o?"flow map":"flow sequence",c=new(i?.nodeClass??(o?al:ll))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1);let u=r.offset+r.start.source.length;for(let i=0;i<r.items.length;++i){const l=r.items[i],{start:d,key:p,sep:f,value:h}=l,m=hu(d,{flow:a,indicator:"explicit-key-ind",next:p??f?.[0],offset:u,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!m.found){if(!(m.anchor||m.tag||f||h)){0===i&&m.comma?s(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):i<r.items.length-1&&s(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&&mu(p)&&s(p,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===i)m.comma&&s(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||s(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];ec(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||f||m.found){const i=m.end,g=p?e(n,p,m,s):t(n,i,d,null,m,s);Iu(p)&&s(g.range,"BLOCK_IN_FLOW",bu);const y=hu(f??[],{flow:a,indicator:"map-value-ind",next:h,offset:g.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(y.found){if(!o&&!m.found&&n.options.strict){if(f)for(const e of f){if(e===y.found)break;if("newline"===e.type){s(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<y.found.offset-1024&&s(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else h&&("source"in h&&h.source&&":"===h.source[0]?s(h,"MISSING_CHAR",`Missing space after : in ${a}`):s(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const w=h?e(n,h,y,s):y.found?t(n,y.end,f,null,y,s):null;w?Iu(h)&&s(w.range,"BLOCK_IN_FLOW",bu):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const v=new tl(g,w);if(n.options.keepSourceTokens&&(v.srcToken=l),o){const e=c;yu(n,e.items,g)&&s(i,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(v)}else{const e=new al(n.schema);e.flow=!0,e.items.push(v),c.items.push(e)}u=w?w.range[2]:y.end}else{const r=h?e(n,h,m,s):t(n,m.end,f,null,m,s);c.items.push(r),u=r.range[2],Iu(h)&&s(r.range,"BLOCK_IN_FLOW",bu)}}const d=o?"}":"]",[p,...f]=r.end;let h=u;if(p&&p.source===d)h=p.offset+p.source.length;else{const e=a[0].toUpperCase()+a.substring(1);s(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&&f.unshift(p)}if(f.length>0){const e=vu(f,h,n.options.strict,s);e.comment&&(c.comment?c.comment+="\n"+e.comment:c.comment=e.comment),c.range=[r.offset,h,e.offset]}else c.range=[r.offset,h,h];return c}(e,t,n,r,i),a=o.constructor;return"!"===s||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function Eu(e,t,n){const r=t.offset,s=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:s}=t[0],i=s[0];let o=0,a="",c=-1;for(let t=1;t<s.length;++t){const n=s[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: ${s}`);let l=!1,u="",d=s.length;for(let e=1;e<t.length;++e){const s=t[e];switch(s.type){case"space":l=!0;case"newline":d+=s.source.length;break;case"comment":if(n&&!l){r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=s.source.length,u=s.source.substring(1);break;case"error":r(s,"UNEXPECTED_TOKEN",s.message),d+=s.source.length;break;default:{r(s,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${s.type}`);const e=s.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:i,indent:o,chomp:a,comment:u,length:d}}(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};const i=">"===s.mode?Cc.BLOCK_FOLDED:Cc.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let e=1;e<t.length;e+=2)s.push([t[e],t[e+1]]);return s}(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="+"===s.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=r+s.length;return t.source&&(n+=t.source.length),{value:e,type:i,comment:s.comment,range:[r,n,n]}}let c=t.indent+s.indent,l=t.offset+s.length,u=0;for(let t=0;t<a;++t){const[r,i]=o[t];if(""!==i&&"\r"!==i){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===s.indent&&(c=r.length),u=t,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===s.indent&&r.length>c&&(c=r.length),l+=r.length+i.length+1}for(let e=o.length-1;e>=a;--e)o[e][0].length>c&&(a=e+1);let d="",p="",f=!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 ${s.indent?"explicit indentation indicator":"first line"}`;n(l-r.length-(a?2:1),"BAD_INDENT",e),t=""}i===Cc.BLOCK_LITERAL?(d+=p+t.slice(c)+r,p="\n"):t.length>c||"\t"===r[0]?(" "===p?p="\n":f||"\n"!==p||(p="\n\n"),d+=p+t.slice(c)+r,p="\n",f=!0):""===r?"\n"===p?d+="\n":p="\n":(d+=p+r,p=" ",f=!1)}switch(s.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 h=r+s.length+t.source.length;return{value:d,type:i,comment:s.comment,range:[r,h,h]}}function Su(e,t,n){const{offset:r,type:s,source:i,end:o}=e;let a,c;const l=(e,t,s)=>n(r+e,t,s);switch(s){case"scalar":a=Cc.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 Au(e)}(i,l);break;case"single-quoted-scalar":a=Cc.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Au(e.slice(1,-1)).replace(/''/g,"'")}(i,l);break;case"double-quoted-scalar":a=Cc.QUOTE_DOUBLE,c=function(e,t){let n="";for(let r=1;r<e.length-1;++r){const s=e[r];if("\r"!==s||"\n"!==e[r+1])if("\n"===s){const{fold:t,offset:s}=xu(e,r);n+=t,r=s}else if("\\"===s){let s=e[++r];const i=Cu[s];if(i)n+=i;else if("\n"===s)for(s=e[r+1];" "===s||"\t"===s;)s=e[1+ ++r];else if("\r"===s&&"\n"===e[r+1])for(s=e[1+ ++r];" "===s||"\t"===s;)s=e[1+ ++r];else if("x"===s||"u"===s||"U"===s){const i={x:2,u:4,U:8}[s];n+=Tu(e,r+1,i,t),r+=i}else{const s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),n+=s}}else if(" "===s||"\t"===s){const t=r;let i=e[r+1];for(;" "===i||"\t"===i;)i=e[1+ ++r];"\n"===i||"\r"===i&&"\n"===e[r+2]||(n+=r>t?e.slice(t,r+1):s)}else n+=s}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(i,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}const u=r+i.length,d=vu(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Au(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 s=r[1],i=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)""===r[1]?"\n"===i?s+=i:i="\n":(s+=i+r[1],i=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,r=a.exec(e),s+i+(r?.[1]??"")}function xu(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 Cu={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function Tu(e,t,n,r){const s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(i)){const s=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}return String.fromCodePoint(i)}function Mu(e,t,n,r){const{value:s,type:i,comment:o,range:a}="block-scalar"===t.type?Eu(e,t,r):Su(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,s){if("!"===n)return e[za];const i=[];for(const t of e.tags)if(!t.collection&&t.tag===n){if(!t.default||!t.test)return t;i.push(t)}for(const e of i)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 s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[za]}(e.schema,s,c,n,r):"scalar"===t.type?function({directives:e,schema:t},n,r,s){const i=t.tags.find(e=>e.default&&e.test?.test(n))||t[za];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[za];if(i.tag!==o.tag){s(r,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${e.tagString(i.tag)} or ${e.tagString(o.tag)}`,!0)}}return i}(e,s,t,r):e.schema[za];let u;try{const i=l.resolve(s,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=tc(i)?i:new Cc(i)}catch(e){const i=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",i),u=new Cc(s)}return u.range=a,u.source=s,i&&(u.type=i),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Nu(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 Pu={composeNode:_u,composeEmptyNode:Lu};function _u(e,t,n,r){const{spaceBefore:s,comment:i,anchor:o,tag:a}=n;let c,l=!0;switch(t.type){case"alias":c=function({options:e},{offset:t,source:n,end:r},s){const i=new Sc(n.substring(1));""===i.source&&s(t,"BAD_ALIAS","Alias cannot be an empty string");i.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=vu(r,o,e.strict,s);i.range=[t,o,a.offset],a.comment&&(i.comment=a.comment);return i}(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=Mu(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,s){const i=r?t.directives.tagName(r.source,e=>s(r,"TAG_RESOLVE_FAILED",e)):null,o="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!i||"!"===i||i===al.tagName&&"map"===o||i===ll.tagName&&"seq"===o||!o)return ku(e,t,n,s,i);let a=t.schema.tags.find(e=>e.tag===i&&e.collection===o);if(!a){const c=t.schema.knownTags[i];if(!c||c.collection!==o)return c?.collection?s(r,"BAD_COLLECTION_TYPE",`${c.tag} used for ${o} collection, but expects ${c.collection}`,!0):s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),ku(e,t,n,s,i);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=ku(e,t,n,s,i,a),l=a.resolve?.(c,e=>s(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=sc(l)?l:new Cc(l);return u.range=c.range,u.tag=i,a?.format&&(u.format=a.format),u}(Pu,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=Lu(e,t.offset,void 0,null,n,r),l=!1}return o&&""===c.anchor&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),s&&(c.spaceBefore=!0),i&&("scalar"===t.type&&""===t.source?c.comment=i:c.commentBefore=i),e.options.keepSourceTokens&&l&&(c.srcToken=t),c}function Lu(e,t,n,r,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){const u=Mu(e,{type:"scalar",offset:Nu(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")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function Ru(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 $u(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){const i=e[s];switch(i[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(i.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[s+1]?.[0]&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}class Ou{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const s=Ru(e);r?this.warnings.push(new pu(s,t,n)):this.errors.push(new du(s,t,n))},this.directives=new yc({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=$u(this.prelude);if(n){const s=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!s)e.commentBefore=n;else if(rc(s)&&!s.flow&&s.items.length>0){let e=s.items[0];ec(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=s.commentBefore;s.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:$u(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 s=Ru(e);s[0]+=t,this.onError(s,"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:s,end:i},o){const a=Object.assign({_directives:t},e),c=new cu(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=hu(r,{indicator:"doc-start",next:s??i?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!s||"block-map"!==s.type&&"block-seq"!==s.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?_u(l,s,u,o):Lu(l,u.end,r,null,u,o);const d=c.contents.range[2],p=vu(i,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 du(Ru(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 du(Ru(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=vu(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 du(Ru(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 cu(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 Du(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 ju(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 s=t.length;"block-scalar-header"===e.props[0].type&&(s-=e.props[0].source.length);for(const e of r)e.offset+=s;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,s="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:s})}}}function Fu(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=Fu(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=qu(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=qu(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=qu(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 qu({start:e,key:t,sep:n,value:r}){let s="";for(const t of e)s+=t.source;if(t&&(s+=Fu(t)),n)for(const e of n)s+=e.source;return r&&(s+=Fu(r)),s}const Bu=Symbol("break visit"),Uu=Symbol("skip children"),Vu=Symbol("remove item");function Ku(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),Wu(Object.freeze([]),e,t)}function Wu(e,t,n){let r=n(t,e);if("symbol"==typeof r)return r;for(const s of["key","value"]){const i=t[s];if(i&&"items"in i){for(let t=0;t<i.items.length;++t){const r=Wu(Object.freeze(e.concat([[s,t]])),i.items[t],n);if("number"==typeof r)t=r-1;else{if(r===Bu)return Bu;r===Vu&&(i.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===s&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}Ku.BREAK=Bu,Ku.SKIP=Uu,Ku.REMOVE=Vu,Ku.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},Ku.parentCollection=(e,t)=>{const n=Ku.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};const Gu="\ufeff",Yu="",zu="",Ju="";function Hu(e){switch(e){case Gu:return"byte-order-mark";case Yu:return"doc-mode";case zu:return"flow-error-end";case Ju: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 Qu=Object.freeze({__proto__:null,BOM:Gu,DOCUMENT:Yu,FLOW_END:zu,SCALAR:Ju,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=t,a=Yc({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,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",s=[{type:"block-scalar-header",offset:i,indent:r,source:t}];return Du(s,c)||s.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:i,indent:r,props:s,source:n}}case'"':return{type:"double-quoted-scalar",offset:i,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:r,source:a,end:c};default:return{type:"scalar",offset:i,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 Gu:return"<BOM>";case Yu:return"<DOC>";case zu:return"<FLOW_END>";case Ju:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const r=(e,t,r)=>{const s="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new du([s,s+1],t,r);n(s,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Su(e,t,r);case"block-scalar":return Eu({options:{strict:t}},e,r)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:i=!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=Yc({type:o,value:t},{implicitKey:s||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),s=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=s}else{const{offset:t}=e,n="indent"in e?e.indent:-1,i=[{type:"block-scalar-header",offset:t,indent:n,source:r}];Du(i,"end"in e?e.end:void 0)||i.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:i,source:s})}}(e,c);break;case'"':ju(e,c,"double-quoted-scalar");break;case"'":ju(e,c,"single-quoted-scalar");break;default:ju(e,c,"scalar")}},stringify:e=>"type"in e?Fu(e):qu(e),tokenType:Hu,visit:Ku});function Zu(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const Xu=new Set("0123456789ABCDEFabcdef"),ed=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),td=new Set(",[]{}"),nd=new Set(" ,[]{}\n\r\t"),rd=e=>!e||nd.has(e);class sd{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)&&Zu(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]===Gu&&(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 Yu,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&&Zu(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&Zu(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Zu(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)&&Zu(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(rd),"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("..."))&&Zu(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield zu,yield*this.parseLineStart()}let s=0;for(;","===r[s];)s+=(yield*this.pushCount(1)),s+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(s+=(yield*this.pushIndicators()),r[s]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-s),"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(rd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Zu(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=>Zu(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 s=e;for(;" "===r;)r=this.buffer[--e];if(!("\n"===r&&e>=this.pos&&e+1+n>s))break;t=e}return yield Ju,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(Zu(t)||e&&td.has(t))break;n=r}else if(Zu(t)){let s=this.buffer[r+1];if("\r"===t&&("\n"===s?(r+=1,t="\n",s=this.buffer[r+1]):n=r),"#"===s||e&&td.has(s))break;if("\n"===t){const e=this.continueScalar(r+1);if(-1===e)break;r=Math.max(r,e-2)}}else{if(e&&td.has(t))break;n=r}return t||this.atEnd?(yield Ju,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(rd))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Zu(t)||e&&td.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(;!Zu(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(ed.has(t))t=this.buffer[++e];else{if("%"!==t||!Xu.has(this.buffer[e+1])||!Xu.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 id{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 od(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function ad(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 cd(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 ld(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 ud(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 dd(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||od(t.start,"explicit-key-ind")||od(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,cd(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 pd{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 sd,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=Hu(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&&dd(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===ad(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!==ad(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=ud(ld(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 s=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const s=t.sep[r];switch(s.type){case"newline":n.push(r);break;case"space":break;case"comment":s.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(s=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(s.push(this.sourceToken),e.items.push({start:s}),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?(s.push(this.sourceToken),e.items.push({start:s,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(od(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(cd(t.key)&&!od(t.sep,"newline")){const e=ud(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 s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(od(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=ud(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:s,key:null,sep:[this.sourceToken]}):od(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:s,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:s}),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||od(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=ud(ld(t));dd(e);const r=e.end.splice(1,e.end.length);r.push(this.sourceToken);const s={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]=s}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=ud(ld(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=ud(ld(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 fd(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new id||null,prettyErrors:t}}function hd(e,t={}){const{lineCounter:n,prettyErrors:r}=fd(t),s=new pd(n?.addNewLine),i=new Ou(t),o=Array.from(i.compose(s.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(fu(e,n)),t.warnings.forEach(fu(e,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function md(e,t={}){const{lineCounter:n,prettyErrors:r}=fd(t),s=new pd(n?.addNewLine),i=new Ou(t);let o=null;for(const t of i.compose(s.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new du(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(fu(e,n)),o.warnings.forEach(fu(e,n))),o}function gd(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const s=md(e,n);if(!s)return null;if(s.warnings.forEach(e=>Hc(s.options.logLevel,e)),s.errors.length>0){if("silent"!==s.options.logLevel)throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function yd(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 cu(e,r,n).toString(n)}var wd=Object.freeze({__proto__:null,Alias:Sc,CST:Qu,Composer:Ou,Document:cu,Lexer:sd,LineCounter:id,Pair:tl,Parser:pd,Scalar:Cc,Schema:au,YAMLError:uu,YAMLMap:al,YAMLParseError:du,YAMLSeq:ll,YAMLWarning:pu,isAlias:Qa,isCollection:rc,isDocument:Za,isMap:Xa,isNode:sc,isPair:ec,isScalar:tc,isSeq:nc,parse:gd,parseAllDocuments:hd,parseDocument:md,stringify:yd,visit:cc,visitAsync:uc}),vd=Object.freeze({__proto__:null,Alias:Sc,CST:Qu,Composer:Ou,Document:cu,Lexer:sd,LineCounter:id,Pair:tl,Parser:pd,Scalar:Cc,Schema:au,YAMLError:uu,YAMLMap:al,YAMLParseError:du,YAMLSeq:ll,YAMLWarning:pu,default:wd,isAlias:Qa,isCollection:rc,isDocument:Za,isMap:Xa,isNode:sc,isPair:ec,isScalar:tc,isSeq:nc,parse:gd,parseAllDocuments:hd,parseDocument:md,stringify:yd,visit:cc,visitAsync:uc});class bd{#ke;constructor(e){this.#ke=e}execute(){return new Promise((e,t)=>{const n=`${this.#ke}.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=wd.parse(t);if(n.moduleURL=this.#ke,n.hasCapabilities){const e=`${this.#ke}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=wd.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.#ke}.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 wd.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Id{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}}class kd{#n;#Ee;constructor(){this.#n=new Map,this.#Ee=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#Ee.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#Ee.has(t)||console.warn(`Unknown event type: ${t}`)}}class Ed{}class Sd extends Ed{#Se;constructor(e){super(),this.#Se=e}execute(){}}let Ad=class extends Id{#Ae;constructor(e){super(e),this.#Ae=new kd,this.#Ae.register("onExtension",Sd),this.#Ae.markKnown("onCommand"),this.#Ae.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Ae.handleEvent(e)),e}},xd=class extends Id{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,activationEvents:n}=e,r=e.capabilities,s=[];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;s.push({id:e,title:n,description:r})}return s.length&&s.forEach(({id:t,title:s,description:i})=>{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:s??t,description:i,execute:(...n)=>{const r=n.length?n[n.length-1]:void 0,s=r?.__punica?.correlationId;a.activate(e.name,{reason:"command",trigger:t}).then(()=>{u&&c.publishEvent({name:u,envelope:{id:c.createCorrelationId(),correlationId:s,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:s,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 Cd(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}function Td(e,t=Cd()){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 Md=class extends Id{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:[Td(n)],when:r})})}return e}},Nd=class extends Id{constructor(e){super(e)}async execute(){return await super.execute()}};class Pd extends Id{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=ja.fileOpeners;e.forEach((e,t)=>{if(!e.capability)return void console.warn(`[FileOpeners] Missing capability for file opener: ${e.id??t}`);const s=e.capability,i=e.id??`${n}:${s||"opener"}:${t.toString(10)}`;r.register({id:i,label:e.label,command:s,priority:e.priority,matches:e.matches})})}return e}}function _d(e){const{integrations:t}=e;if(!t)return;const{views:n}=t;if(!n)return;const{activityBar:r,statusBar:s,primarySidebar:i,secondarySidebar:o,contentSidebar:a,panel:c}=n;if(r){const e={...r};e.capability&&(e.command=e.capability),i&&!e.viewId&&(e.viewId=i.id),punica.shell.ActivityBar.manager.addItem(e)}if(s){const e={...s};e.capability&&(e.command=e.capability),punica.shell.Statusbar.manager.addItem(e)}!function(e,t){const n=punica.shell?.Views?.manager;if(!n?.registerPlacement)return;const{primarySidebar:r,secondarySidebar:s,contentSidebar:i,panel:o,activityBar:a}=t;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:"contentSidebar",extensionName:e.name,title:i.title??i.name,icon:i.icon,fallbackCommand:i.capability});if(o?.id){const t=Array.isArray(o.toolbar)?o.toolbar:void 0;Ld(e,o,"panel",{order:o.order,panelToolbar:t})}s?.id&&Ld(e,s,"secondarySidebar",{})}(e,{primarySidebar:i,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r})}function Ld(e,t,n,r){const s=punica.shell?.Views?.manager;if(!s?.registerPlacement)return;const i=punica.shell?.PanelLayout?.manager,o=punica.shell?.PanelContainers,a=Array.isArray(t.relocatableTo)?t.relocatableTo:[],c=Array.from(new Set([n,...a,...{panel:["secondarySidebar"],secondarySidebar:["panel"]}[n]??[]])),l=i?.getSlotOverride?.(t.id),u=l&&c.includes(l)?l:n,d=!1===t.showOnStartup;if(s.registerPlacement({viewId:t.id,slot:u,homeSlot:n,allowedSlots:c,extensionName:e.name,title:t.title??t.name,icon:t.icon,order:r.order,fallbackCommand:t.capability,onDemand:d,panelToolbar:r.panelToolbar}),!d){const e=o?.forSlot?.(u)??("panel"===u?punica.shell?.PanelTabs:null);e?.open?.({id:t.id,title:t.title??t.name??t.id,commandId:t.capability??"",iconClass:t.icon,order:r.order,autoActivate:!1,toolbar:r.panelToolbar})}}let Rd=0;function $d(){Rd++}function Od(){Rd>0&&Rd--}async function Dd(e){$d();try{return await e()}finally{Od()}}const jd=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#xe(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#xe(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}#xe(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 s;return"string"===n.type&&"enum"in n&&Array.isArray(n.enum)&&(s=Object.freeze([...n.enum])),[e,Object.freeze({...r,enum:s})]})))}: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 Fd=new class{#Ce=".punica/settings.json";#Te;#Me=null;#Ne=null;#Pe=new Map;#_e=null;#z=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Te=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Te="localStorage:punica.settings":this.#Te="settings.json"}async load(){this.#z||(await this.#Le(),await this.#Re(),this.#z=!0)}async#Le(){try{if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#Ne=await this.#$e(e)}else this.#Ne={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Te),t=JSON.parse(e);this.#Ne=await this.#$e(t)}catch{this.#Ne={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Ne={version:"1.0",extensions:{},system:{}}}}async#Re(){try{const e=await punica.runtime.fs.readFile(this.#Ce),t=JSON.parse(e);this.#Me=await this.#$e(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Me=null}}async save(e="project"){this.#_e&&clearTimeout(this.#_e),this.#_e=window.setTimeout(async()=>{"global"===e?await this.#Oe():await this.#De(),this.#_e=null},500)}async#Oe(){if(this.#Ne)if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#Ne,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Te,JSON.stringify(this.#Ne,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#De(){this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Ce,JSON.stringify(this.#Me,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#z)return void this.load();if("system"===e){const e=this.#Me?.system?.[t];if(void 0!==e)return e;const n=this.#Ne?.system?.[t];return void 0!==n?n:void 0}const n=this.#Me?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#Ne?.extensions?.[e]?.[t];if(void 0!==r)return r;const s=punica.extensions.metadata.manager.getExtension(e);return s?.configuration?.properties?.[t]?.default}async set(e,t,n,r="project"){if(this.#z||await this.load(),"system"===e){const s=this.get(e,t);return"global"===r?(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system||(this.#Ne.system={}),this.#Ne.system[t]=n,await this.save("global")):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system||(this.#Me.system={}),this.#Me.system[t]=n,await this.save("project")),void this.#je(e,t,n,s)}const s=this.validate(e,t,n);if(!s.ok)throw new Error(`Invalid setting value: ${s.errors?.join(", ")}`);const i=this.get(e,t);"global"===r?(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]||(this.#Ne.extensions[e]={}),this.#Ne.extensions[e][t]=n,await this.save("global")):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]||(this.#Me.extensions[e]={}),this.#Me.extensions[e][t]=n,await this.save("project")),this.#je(e,t,n,i)}getAll(e){if(!this.#z)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#Ne?.extensions?.[e]??{},s=this.#Me?.extensions?.[e]??{},i={};for(const[e,t]of Object.entries(n)){const n=t;i[e]=n.default}return{...i,...r,...s}}validate(e,t,n){const r=punica.extensions.metadata.manager.getExtension(e),s=r?.configuration?.properties?.[t];if(!s)return{ok:!1,errors:[`Setting "${t}" not found in extension "${e}"`]};const i=[];switch(s.type){case"boolean":"boolean"!=typeof n&&i.push(`Setting "${t}" must be a boolean`);break;case"string":"string"!=typeof n?i.push(`Setting "${t}" must be a string`):s.enum&&!s.enum.includes(n)&&i.push(`Setting "${t}" must be one of: ${s.enum.join(", ")}`);break;case"number":("number"!=typeof n||isNaN(n))&&i.push(`Setting "${t}" must be a number`)}return{ok:0===i.length,errors:i.length>0?i: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){if("system"===e){const n=this.get(e,t),r=void 0!==this.#Me?.system?.[t],s=void 0!==this.#Ne?.system?.[t];if(!r&&!s)return;return r&&delete this.#Me.system[t],s&&delete this.#Ne.system[t],r&&await this.#De(),s&&await this.#Oe(),void this.#je(e,t,void 0,n)}const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Me?.extensions?.[e]&&(delete this.#Me.extensions[e][t],await this.save("project")),this.#Ne?.extensions?.[e]&&(delete this.#Ne.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.#z?"system"===e?void 0!==this.#Me?.system?.[t]?"project":void 0!==this.#Ne?.system?.[t]?"global":"default":void 0!==this.#Me?.extensions?.[e]?.[t]?"project":void 0!==this.#Ne?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#Pe.has(e)||this.#Pe.set(e,new Set),this.#Pe.get(e).add(t),()=>{this.#Pe.get(e)?.delete(t)}}async export(e){this.#z||await this.load();const t=e?.scope??"merged",n={version:this.#Ne?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Me?.system:"global"===t?this.#Ne?.system:{...this.#Ne?.system,...this.#Me?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#Ne?.extensions??{}),...Object.keys(this.#Me?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Me?.extensions?.[e]??{}:"global"===t?this.#Ne?.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.#Me:this.#Ne)||("project"===r?this.#Me={version:"1.0",extensions:{},system:{}}:this.#Ne={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Me:this.#Ne;for(const[r,s]of Object.entries(n.extensions??{}))t.extensions&&!t.extensions.includes(r)||(e.extensions[r]={...e.extensions[r],...s});n.system&&(e.system={...e.system,...n.system})}else{if(t?.extensions)for(const e of t.extensions)n.extensions[e]&&("project"===r?(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]=n.extensions[e]):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]=n.extensions[e]));else"project"===r?this.#Me={...this.#Me,...n,version:this.#Me?.version??"1.0"}:this.#Ne={...this.#Ne,...n,version:this.#Ne?.version??"1.0"};n.system&&("project"===r?(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system=n.system):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system=n.system))}await this.save(r)}async#$e(e){return e.version,e}#je(e,t,n,r){const s=this.#Pe.get(e);s&&s.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}})}},qd="system",Bd="ui.language",Ud="en";const Vd=new class{#Fe=new Map;#Pe=new Set;#qe=null;#Be=new Set;#Ue=new Map;getLocale(){return this.#qe??=this.#Ve(),this.#qe}supportedLocales(){const e=this.#Ke()?.supported;return Array.isArray(e)&&e.length?e:[Ud]}async setLocale(e){const t=String(e||"").trim();if(t&&t!==this.getLocale()){try{await punica.extensions.settings.manager.set(qd,Bd,t,"global")}catch(e){throw e instanceof Error?e:new Error(String(e))}this.#qe=t,this.#We(t)}}onDidChange(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}#We(e){for(const t of[...this.#Pe])try{t(e)}catch{}}#Ke(){try{return punica.shell?.Profile?.manager?.registry?.getActive?.()?.localization}catch{return}}#Ve(){const e=this.supportedLocales();try{const t=punica.extensions?.settings?.manager?.get?.(qd,Bd);if("string"==typeof t&&e.includes(t))return t}catch{}try{const t=globalThis.navigator,n=t?.language?.toLowerCase().split("-")[0];if(n&&e.includes(n))return n}catch{}const t=this.#Ke()?.default;return t&&e.includes(t)?t:e.includes(Ud)?Ud:e[0]}refresh(){const e=this.#Ve();e!==this.#qe&&(this.#qe=e,this.#We(e))}register(e,t){e&&t&&this.#Fe.set(e,t)}t(e,t,n){const r=this.#Ge(e,t,n?.count);return void 0===r?(this.#Ye(`${e}:${t}`,e,t),t):n?r.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):r}#Ge(e,t,n){const r=this.#Fe.get(e);if(!r)return;const s=[],i=e=>{e&&!s.includes(e)&&s.push(e)};i(this.getLocale()),i(this.#Ke()?.default),i(Ud);const o=[];"number"==typeof n&&Number.isFinite(n)&&o.push(`${t}.${this.#ze(this.getLocale(),n)}`,`${t}.other`),o.push(t);for(const e of s){const t=r[e];if(t)for(const e of o){const n=t[e];if("string"==typeof n)return n}}}#ze(e,t){let n=this.#Ue.get(e);if(!n){try{n=new Intl.PluralRules(e)}catch{n=new Intl.PluralRules(Ud)}this.#Ue.set(e,n)}return n.select(t)}#Ye(e,t,n){this.#Be.has(e)||(this.#Be.add(e),console.warn(`[i18n] missing message "${n}" for ${t} (${this.getLocale()})`))}resetForTesting(){this.#Fe.clear(),this.#Pe.clear(),this.#qe=null,this.#Be.clear(),this.#Ue.clear()}};function Kd(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 Wd=new Map;function Gd(e){const t=Wd.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),Wd.delete(e)}const Yd={register(e,t,n){const r=n?.target??document.head,s=Wd.get(e)??document.getElementById(e);if(s)return n?.overwrite&&(s.textContent=t),Wd.set(e,s),{id:e,dispose(){Gd(e)}};const i=document.createElement("style");if(i.id=e,n?.attrs)for(const[e,t]of Object.entries(n.attrs))i.setAttribute(e,t);return i.textContent=t,r.appendChild(i),Wd.set(e,i),{id:e,dispose(){Gd(e)}}},unregister(e){Gd(e)},has:e=>!!Wd.has(e)||!!document.getElementById(e)};const zd={manager:new class{#Je;#He;#Qe;#Ze;#Xe;#et;#tt;#nt;#rt;constructor(){this.#Je=new Map,this.#He=new Map,this.#Qe=new Map,this.#Ze=new Map,this.#Xe=new Set,this.#et=new Set,this.#tt=new Map,this.#nt=new Map,this.#rt=new Map}getRuntimeState(e){return this.#He.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 s=this.#nt.get(t);if(s&&s.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${s.extensionName}" and "${n}".`);this.#nt.set(t,{id:t,extensionName:n,definition:r})}}#st(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 s={id:t,extensionName:e.name,definition:n},i=this.#nt.get(t);i&&i.extensionName!==e.name&&console.warn(`[Extensions] Capability id collision "${t}" between "${i.extensionName}" and "${e.name}". Keeping the last loaded.`),this.#nt.set(t,s)}this.#it(e,n)}}#it(e,t){const n=Eo.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`)}#ot(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 bd(e),n=new xd(t),r=new Md(n),s=new Nd(r),i=new Pd(s);return new Ad(i)})(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.#Je.set(r.name,r),this.#He.set(r.name,"loaded"),this.#st(r),this.#ot(r);try{_d(r)}catch(e){console.error(`[Extensions] view registration failed for ${r.name}:`,e)}const s=r.activationEvents??[];(s.includes("onStartup")||s.includes("onStartup:begin"))&&this.#Xe.add(r.name),s.includes("onStartup:finish")&&this.#et.add(r.name),s.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#tt.get(t);n||(n=new Set,this.#tt.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#He.get(e))return;const n=this.#Qe.get(e);if(n)return n;if(!this.#Je.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),s=this.#at(e,r);this.#Qe.set(e,s);try{await s}finally{this.#Qe.delete(e)}}async#at(e,t){this.#He.set(e,"activating"),Kd("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new Fa(e),n=new Ua(t),r=new Va(n);return new Ba(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.#ct(e,t);"headless"===t.presentation?await Dd(()=>r.module.activate(n)):await r.module.activate(n);const s=this.#Ze.get(e);s&&(s.module=r.module),this.#He.set(e,"active"),Kd("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#He.set(e,"failed"),Kd("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}}#ct(e,t){const n=[];this.#Ze.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.#rt.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const s=globalThis.punica?.shell?.Views?.manager;if(!s?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const i=s.registerProvider(t,r,e);return n.push(i),i},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,s=r.punica?.runtime?.capabilities?.gateway;if(s?.call){const i=r.punica?.kernel?.Events?.manager,o=i?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await s.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 i=r.punica?.shell?.Views?.manager;if(!i?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await i.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 s=n.punica?.kernel?.Events?.manager,i=s?.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:i},policy:{mode:"execute"}})}const s=n.punica?.shell?.Views?.manager;if(!s?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);s.hide(e,{kind:"extension",id:t})}(t,e)}}};return r}async startupBegin(){await this.#lt(this.#Xe,"startup:begin")}async startupFinish(){await this.#lt(this.#et,"startup:finish")}async#lt(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.#Je.get(e)}getAllExtensions(){return Array.from(this.#Je.values())}getCapability(e){return this.#nt.get(e)?.definition}listCapabilities(){return Array.from(this.#nt.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 s=Br().validate(r,t);return s.ok?{ok:!0}:{ok:!1,errors:s.errors}}registerCapabilityHandler(e,t){this.#rt.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#nt.get(e);if(!r)throw new fr(pr.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#He.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new fr(pr.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 s=this.#rt.get(e);if(!s)throw new fr(pr.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 s.fn(t,n)}async deactivate(e){if("active"!==this.#He.get(e))return;const t=this.#Je.get(e);this.#He.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.#Ze.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#Ze.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.#Ze.delete(e)}for(const[t,n]of this.#rt)n.extensionName===e&&this.#rt.delete(t)}finally{this.#He.set(e,"loaded"),Kd("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#He.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.#nt)n.extensionName===e&&this.#nt.delete(t);for(const[t,n]of this.#tt)n.delete(e)&&0===n.size&&this.#tt.delete(t);const n=this.#Je.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.#Xe.delete(e),this.#et.delete(e),this.#Qe.delete(e),this.#Ze.delete(e),this.#Je.delete(e),this.#He.delete(e),Kd("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.#He.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.#tt.get(e);return t?Array.from(t):[]}},Styles:Yd,metadata:{manager:jd},settings:{manager:Fd},i18n:{manager:Vd}};function Jd(e){if(null==e)return!1;if(Array.isArray(e))return e.some(Jd);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(Jd)}return!1}function Hd(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=Qd(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=Qd(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||""),s=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"}):s||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||""),s=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"}):s||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?Jd(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 Qd(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 Zd{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await Sn().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=Kr();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 Xd(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),s=Hd(r);if(!s.ok)return void console.warn(`[NodeRegistry] Invalid manifest at ${t}:`,s.issues);const i=r,o=i.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:i})}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():"",s=t&&"description"in t?String(t.description||"").toLowerCase():"",i=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||s.includes(n)||i.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 Xd(e,t){for(const n of e)n.isDirectory?n.children&&Xd(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let ep;function tp(){return ep||(ep=new Zd),ep}function np(e,t,n,r=!1){if("code"!==e.cell_type)throw new Error("Cell must be a code cell");let s=Array.isArray(e.source)?e.source.join(""):String(e.source||"");const i=JSON.stringify(t);return s=s.replace(/__ivy_node_id__/g,i),s}async function rp(e,t,n,r){let s={};for await(const i 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"===i.type&&"text"in i){const e=i.text;try{const t=JSON.parse(e.trim());t&&"object"==typeof t&&(s=t)}catch{}}return s}function sp(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 ip=/token|secret|key|password|passwd|api[_-]?key/i;function op(e){const t={};let n=0,r=!1;for(const s of Object.keys(e)){const i=ip.test(s)?"[REDACTED]":e[s],o=s.length+JSON.stringify(i??null).length;n+o>16e3?r=!0:(n+=o,t[s]=i)}return r&&(t.__truncated__=!0),t}async function ap(e,t){const n=Date.now(),r=tp().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const s=Hd(r.manifest);if(!s.ok)throw new Error(`Invalid manifest: ${s.issues.map(e=>e.message).join(", ")}`);const i=r.manifest;if(Jd(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=i.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(!i.program)throw new Error("Manifest missing program");const l=i.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 f=u.find(e=>e.id===d),h=u.find(e=>e.id===p);if(!f)throw new Error(`Input cell with id "${d}" not found in program.cells`);if(!h)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||(i.runtime,"python"),w=t.runId??`ivynode-${e}-${n}`,v=(e,t)=>{try{punica.kernel.Events.manager.publish(e,t)}catch{}},b=(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}`},I=e=>{const t=e;return"stdout"!==t.type&&"stderr"!==t.type||"string"!=typeof t.text?"":t.text},k=await m.session.open({language:y}),E=t.runId||`ivynode-${e}-${Date.now()}`;let S={};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 k.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 s=np(r,e),i=r.id||`cell-${n}`,o=b(r,n),a=Date.now();let c,l="";v("ivy.node.cell.started",{runId:w,nodeId:e,cellId:i,index:n,label:o,startedAtMs:a});try{let e=null;for await(const n of k.run({id:i,language:y,code:s,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:cell:${i}`})){g.push({type:n.type,data:n}),l+=I(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 v("ivy.node.cell.failed",{runId:w,nodeId:e,cellId:i,index:n,label:o,durationMs:Date.now()-a,error:t instanceof Error?t.message:String(t),logs:l}),t}try{const e=await rp(k,E,i,t.timeoutMs),n=op(sp(S,e));Object.keys(n).length&&(c=n),S=e}catch{}v("ivy.node.cell.finished",{runId:w,nodeId:e,cellId:i,index:n,label:o,durationMs:Date.now()-a,logs:l,...c?{variables:c}:{}})}const s=await async function(e,t,n,r){const s=JSON.stringify(t),i=`\nimport json\ntry:\n if '__ivy_ctx__' in globals() and isinstance(__ivy_ctx__, dict):\n if "nodes" in __ivy_ctx__ and ${s} in __ivy_ctx__["nodes"]:\n node_data = __ivy_ctx__["nodes"][${s}]\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:i,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")}(k,e,E,t.timeoutMs),i=o.outputs;if(!i?.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}}(s,i.schema);if(!a.valid)throw new Error(`Output validation failed: ${a.errors.join(", ")}`);return{output:s,events:g,durationMs:Date.now()-n}}finally{await k.close()}}function cp(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function lp(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function up(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function dp(e,t){const n=e.value;switch(e.type){case"isType":return{passed:lp(t)===String(n??""),expected:String(n??""),actual:lp(t)};case"equals":return{passed:up(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=>up(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:lp(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:lp(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):lp(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:lp(t)}}}function pp(e,t,n=""){const r=e.assertions||{},s={},i=[];if(void 0!==r.schema){const e=!0===r.schema;s.schema={passed:e},i.push(!e)}if(void 0!==r.expectsError){const e=!1===r.expectsError;s.error={passed:e},i.push(!e)}if(r.errorPattern&&r.expectsError){const e=new RegExp(r.errorPattern).test(n);s.error={passed:e,expected:r.errorPattern,actual:n||void 0},i.push(!e)}if(r.properties&&"object"==typeof r.properties){const e={};for(const[n,s]of Object.entries(r.properties)){if(!s||"object"!=typeof s)continue;const r=cp(t,n);let o;const a=s.matcher;if(a&&"object"==typeof a)o=dp(a,r);else if("string"==typeof a)o=dp({type:a,value:s.expected},r);else{if(void 0===s.expected)continue;o=dp({type:"equals",value:s.expected},r)}e[n]=o,i.push(!o.passed)}Object.keys(e).length&&(s.properties=e)}return{status:i.some(Boolean)?"fail":"pass",assertions:Object.keys(s).length>0?s:void 0}}function fp(e,t,n){const r=!0===e.assertions?.expectsError,s=e.assertions?.errorPattern;let i;return i=r?s?new RegExp(s).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:i,error:t,assertions:{error:{passed:r,expected:s,actual:t}}}}function hp(e){const{capabilityId:t,version:n,tier:r,results:s,startedAtMs:i}=e,o=s.filter(e=>"pass"===e.status).length,a=s.filter(e=>"fail"===e.status).length,c=s.filter(e=>"skip"===e.status).length,l=s.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:s.length,passedCases:o,failedCases:a,skippedCases:c,durationMs:Date.now()-i},cases:s}}function mp(){return Date.now()}function gp(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function yp(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function wp(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function vp(){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 bp(){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 Ip(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 kp(e){try{const t=vp();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 Ep(e,t){const r=vp();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 s=await n();await r.call("fs.writeFile",{path:e,content:t},{sessionId:"internal",workspaceId:s,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}function Sp(e,t,n,r,s){const i=s?.traceId??t;punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:t,traceId:i,spanId:s?.spanId,parentSpanId:s?.parentSpanId,timestampMs:mp(),source:s?.source??"flow:engine",kind:n},payload:r})}const Ap=new Set(["sensitive","secret"]);function xp(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Cp(e,t,n,r){if(!function(e,t,n){return!(!n||!Ap.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:xp(e)}}const Tp=new class{#ut=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#ut.set(e,(this.#ut.get(e)??0)+r),!0;const s=this.#ut.get(e)??0;return!(s+r>n)&&(this.#ut.set(e,s+r),!0)}used(e){return this.#ut.get(e)??0}release(e){this.#ut.delete(e)}reset(){this.#ut.clear()}};class Mp{async ensureBase(){await kp(".punica"),await kp(wp(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await kp(wp(".punica","workflow-runs",e)),await kp(wp(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),s=mp();await this.ensureRunDirs(e);const i=n.surface??"output",o=n.payload,a=n.text;let c,l=o,u=a;if(n.redactionPolicy||n.capabilityClassification){const e=Cp(o??a,n.redactionPolicy,i,n.capabilityClassification);e&&"object"==typeof e&&!0===e.redacted&&(c=e,l=c,u=void 0)}const d="string"==typeof u,p=wp(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let f;f=d?String(u??""):gp(l??{},2);const h=n.sizeBudget?.maxBytes;if(c||"number"!=typeof h)"number"==typeof h&&Tp.acquire(e,f.length,h);else{Tp.acquire(e,f.length,h)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(i,f.length),f=gp(c,2),Tp.acquire(e,f.length,h))}await Ep(p,f);const m=f.length,g=yp(d?String(u??""):gp(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs:s,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 Sp("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function Np(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 Pp(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function _p(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 Lp(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 Rp(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 $p(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Op(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 Dp(e,t,n){const r=Op(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 jp(e,t){const n=Op(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 Fp(e,t){const n=Op(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 qp(e,t=".punica"){const n=$p(t,"workflow-runs",e.runId),r=$p(n,"checkpoint.json"),s=$p(n,"checkpoint.json.tmp"),i=JSON.stringify(e,null,2);await jp("writeCheckpoint",n),await Dp("writeCheckpoint",s,i);try{await async function(e,t,n){const r=Op(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",s,r)}catch{try{await Fp("writeCheckpoint",r)}catch{}await Dp("writeCheckpoint",r,i);try{await Fp("writeCheckpoint",s)}catch{}}}async function Bp(e,t=".punica"){const n=$p(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=Op(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 Up(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 Vp{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,s=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 i=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)),s=new Map,i=new Map;t.forEach(e=>{s.set(e.id,0),i.set(e.id,[])}),r.forEach(e=>{i.get(e.fromId).push(e.toId),s.set(e.toId,(s.get(e.toId)??0)+1)});const o=[];for(const[e,t]of s.entries())0===t&&o.push(e);const a=[];for(;o.length;){const e=o.shift();a.push(e);for(const t of i.get(e)??[])s.set(t,(s.get(t)??0)-1),0===(s.get(t)??0)&&o.push(t)}if(a.length!==t.length)throw new Error("Workflow graph is not a DAG (cycle detected).");return a}(i),a=punica.kernel.Events.manager.createCorrelationId(),c=a,l=punica.kernel.Events.manager.createCorrelationId(),u={runId:a,specVersion:"0.1",status:"QUEUED",createdAtMs:mp(),startedAtMs:mp(),traceId:c,entryNodeId:i.graph.entryNodeId,metadata:{title:i.title,tags:i.tags},steps:[]};for(const e of o){const t=i.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=_p(i),p=i.graph.runBudget?.maxInFlight;return this.runs.set(a,{run:u,spec:i,order:o,cursor:0,paused:!1,cancelled:!1,rootSpanId:l,filePathOrUri:r,dependencyGraph:d,inFlightNodes:new Set,maxInFlight:p,nodeOutputs:new Map,input:s}),Sp("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),Up({name:"flow.run.started",correlationId:a,traceId:c,payload:{runId:a,flowId:i.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",Sp("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 Bp(e);if(!n)return!1;{const r=n.dependencyGraphState?_p(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"),Sp("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=mp();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 Sp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Sp("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=wp(".punica","workflow-runs",e,"run.json");await Ep(n,gp({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=wp(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Ep(e,gp({version:1,updatedAtMs:mp(),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 qp(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=wp(".punica","workflow-runs","index.json"),t=await async function(e){const t=vp();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);Sp("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class Kp{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,s,i){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=s,this.resumeRunLoop=i}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 s=t?.payload??{},i=s?.request??{},o=s?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(i?.kind??"capability"),id:String(i?.id??""),risk:String(i?.risk??"low"),approval:String(i?.approval??"once"),reason:"string"==typeof i?.reason?i.reason:void 0,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:mp()};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:mp(),resolved:!1},Sp("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",Sp("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}),Sp("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),Up({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 s=this.pendingToRunStep.get(r.attemptCorrelationId);if(!s)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id},n,{workspaceId:r.workspaceId})}catch{}Sp("workflow.pendingApprovalResolved",s.runId,"info",{runId:s.runId,stepId:s.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:mp()},{traceId:s.runId}),Up({name:"flow.approval.granted",correlationId:s.runId,traceId:s.runId,payload:{runId:s.runId,stepId:s.stepId,pendingId:t,scope:n,capability:{kind:r.kind,id:r.id}}}),this.pendingByCorrelation.delete(r.attemptCorrelationId);const i=this.runs.get(s.runId);if(i){const e=i.run.steps.find(e=>e.stepId===s.stepId);e?.approval&&(e.approval.resolved=!0,e.approval.decision="approved"),i.run.status="RUNNING",Sp("workflow.runUpdated",i.run.runId,"info",{runId:i.run.runId,patch:{status:"RUNNING"}},{traceId:i.run.traceId,spanId:i.rootSpanId}),this.persistRun(i.run.runId),this.resumeRunLoop(i.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;Sp("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:mp()},{traceId:r.runId}),Up({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 s=this.runs.get(r.runId);return s&&(s.run.status="FAILED",s.run.endedAtMs=mp(),Sp("workflow.runUpdated",s.run.runId,"error",{runId:s.run.runId,patch:{status:"FAILED",endedAtMs:s.run.endedAtMs,error:{message:"Approval rejected",nodeId:r.stepId}}},{traceId:s.run.traceId,spanId:s.rootSpanId}),Sp("workflow.runFinished",s.run.runId,"error",{runId:s.run.runId,status:"FAILED",endedAtMs:s.run.endedAtMs},{traceId:s.run.traceId,spanId:s.rootSpanId}),this.persistRun(s.run.runId),this.persistIndex()),!0}}const Wp=3e4,Gp={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const Yp=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.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.#le.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function zp(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function Jp(e,t){if(!t.retry)return 0;const n=t.retry.initialDelayMs??1e3,r=t.retry.maxDelayMs??3e4,s=t.retry.backoffMultiplier??2,i=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(s,e-1),r),i)}const Hp=new class{#dt=new Map;register(e,t){this.#dt.set(e,t)}get(e){return this.#dt.get(e)}resolveOrThrow(e){const t=this.#dt.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.#dt.clear()}};function Qp(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 Zp(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,...s]=n;if(!t.has(r))return{ok:!1,reason:"missing-node"};const i=t.get(r);if(0===s.length)return{ok:!0,value:i??null};const o=Qp(i,s);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function Xp(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 ef(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tf(e){return String(e??"").split(".").filter(e=>e.length>0)}function nf(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];ef(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function rf(e,t,n){const r=t.filter(t=>t.toId===e.id&&(void 0!==t.fromPath||void 0!==t.toPath)),s=e.data?.input;if(0===r.length)return void 0!==s?s:void 0!==e.defaults?e.defaults:void 0;const i={...ef(e.defaults)?e.defaults:{},...ef(s)?s:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?tf(e.fromPath):[],s=r.length?Qp(t,r):t;if(void 0===s)continue;const o=e.toPath?tf(e.toPath):[];o.length?nf(i,o,s):ef(s)?Object.assign(i,s):i[e.fromId]=s}return i}class sf 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 of(e,t){if(function(e){return!0===e.cancelled}(e))throw new sf(e.run?.runId,t)}class af{runs;pendingToRunStep;runIdToSession;artifactStore;persistRun;persistCheckpoint;persistIndex;notifyTerminal;constructor(e,t,n,r,s,i,o,a){this.runs=e,this.pendingToRunStep=t,this.runIdToSession=n,this.artifactStore=r,this.persistRun=s,this.persistCheckpoint=i,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=vp();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,s=n.rootSpanId;for(;n.cursor<n.order.length;){if(n.cancelled)return;if(n.paused)return;const i=n.order[n.cursor];n.run.currentNodeId=i;const o=n.spec.graph.nodes.find(e=>e.id===i),a=n.run.steps.find(e=>e.stepId===i);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",Sp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED",currentNodeId:i}},{traceId:r,spanId:s}),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,f=l.timeoutMs;let h=a.attempt??0;for(;h<=d;){h++,a.attempt=h,"PENDING"!==a.status&&"RETRYING"!==a.status&&"WAITING_APPROVAL"!==a.status&&(a.status="PENDING"),a.status="RUNNING",a.startedAtMs=mp(),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}),Sp("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:s}),Up({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 i=await this.executeNodeAttempt(o,a,l,{attemptCorrelationId:c,spanId:u,rootSpanId:s,traceId:r,workspaceId:t?.workspaceId,filePathOrUri:n.filePathOrUri,notebook:n.notebook,timeoutMs:f,nodeOutputs:n.nodeOutputs,runBudget:n.spec.graph.runBudget,runInput:n.input,resolvedInput:rf(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==i.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,i.output),Sp("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:s}),Up({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",Sp("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:s}),n.run.status="WAITING_APPROVAL",Sp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:i}},{traceId:r,spanId:s}),await this.persistRun(e),void await this.persistIndex();const f=o.includes("Timed out")||o.includes("timeout");if(!(h<=d&&(p||!f)&&!o.includes("Policy")&&!o.includes("Invalid input"))||h>d)return"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="FAILED",a.endedAtMs=mp(),a.error={message:o},Sp("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:s}),Up({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=mp(),n.run.error={message:o,nodeId:i,correlationId:c},Sp("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:s}),Sp("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:s}),Up({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=Jp(h,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Sp("workflow.stepRetry",e,"info",{runId:e,stepId:a.stepId,attempt:h,maxAttempts:d,delayMs:m,error:o},{traceId:r,spanId:u,parentSpanId:s}),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=mp(),Sp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:s}),Sp("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:s}),Up({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=$p(n,"workflow-runs",e.runId),s=$p(r,"run.json"),i=JSON.stringify({run:e,spec:t},null,2);await jp("writeRunHistory",r),await Dp("writeRunHistory",s,i)}(n.run,n.spec),await async function(e,t=".punica"){const n=$p(t,"workflow-runs",e,"checkpoint.json");try{await Fp("deleteCheckpoint",n)}catch{}}(e);const i=this.runIdToSession.get(e);if(i){try{await i.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 s=r.run.traceId,i=r.rootSpanId,o=r.maxInFlight??1/0,a=!!(c=r.spec.graph.runBudget)&&!0===c.failFast;for(var c;!Pp(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=Np(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=>{Rp(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 Lp(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Lp(o,!0,n);try{const a=this.prepareNodeExecutionConfig(c,r),u=a.retry,d=u?.maxAttempts??0,p=a.timeoutMs;let f=l.attempt??0,h=!1;for(;f<=d&&!h;){of(r),f++,l.attempt=f,l.status="RUNNING",l.startedAtMs=mp();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:i,traceId:s,workspaceId:t?.workspaceId,filePathOrUri:r.filePathOrUri,notebook:r.notebook,timeoutMs:p,nodeOutputs:r.nodeOutputs,runBudget:r.spec.graph.runBudget,runInput:r.input,resolvedInput:rf(c,r.spec.graph.edges,r.nodeOutputs??new Map)});void 0!==o.output&&r.nodeOutputs&&r.nodeOutputs.set(c.id,o.output),h=!0}catch(e){if(e instanceof sf)throw l.status="CANCELLED",l.endedAtMs=mp(),e;const t=String(e?.message??e);if(f<=d){const e=Jp(f,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=mp(),l.error={message:t},e}}h&&(Lp(o,!0,n),await this.persistRun(e))}catch(t){Lp(o,!1,n),t instanceof sf||(r.run.status="FAILED",r.run.endedAtMs=mp(),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=mp(),Sp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:s,spanId:i}),Sp("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:s,spanId:i}),Up({name:"flow.run.completed",correlationId:e,traceId:s,payload:{runId:e,endedAtMs:r.run.endedAtMs}}),await this.persistRun(e),await this.persistIndex(),this.notifyTerminal?.(e,"COMPLETED")):"FAILED"===r.run.status&&(Up({name:"flow.run.failed",kind:"error",correlationId:e,traceId:s,payload:{runId:e,endedAtMs:r.run.endedAtMs,error:r.run.error}}),this.notifyTerminal?.(e,"FAILED"))}prepareNodeExecutionConfig(e,t){const n=Hp.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:Wp,retry:{...Gp},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 s=Hp.get(e.ref.kind);let i;try{i=await(s?.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),s=r.timeoutMs?await async function(e,t){return Promise.race([e,zp(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=mp(),t.outputsPreview=s.outputsPreview,t.artifactIds=s.artifactIds??[],s}finally{i&&i()}}async executeNode(e,t){return Hp.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class cf 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 lf(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new cf(e??0,t);return n}const uf="__default__";class df{workspaceId;#pt=new Map;#ft=new Map;#ht=new Map;#mt=new Mp;#gt=!1;#yt=new Map;#wt;#vt;#bt;constructor(e=uf){this.workspaceId=e,this.#wt=new Vp(this.#pt,this.#yt,this.#mt),this.#vt=new Kp(this.#pt,this.#ft,this.#ht,e=>this.#wt.persistRun(e),()=>this.#wt.persistIndex(),e=>this.#It(e)),this.#bt=new af(this.#pt,this.#ht,this.#yt,this.#mt,e=>this.#wt.persistRun(e),e=>this.#wt.persistCheckpoint(e),()=>this.#wt.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#gt||(this.#gt=!0,this.#vt.setupApprovalSubscription(),this.#wt.loadIndex())}async startRun(e){const t=await this.#wt.startRun(e);return this.#It(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#wt.pauseRun(e)}async resumeRun(e){const t=await this.#wt.resumeRun(e);return t&&this.#It(e,{}),t}async cancelRun(e,t){return this.#wt.cancelRun(e,t)}getRun(e){return this.#wt.getRun(e)}listRuns(e){return this.#wt.listRuns(e)}approvePending(e){return this.#vt.approvePending(e)}rejectPending(e){return this.#vt.rejectPending(e)}hasRun(e){return this.#pt.has(e)}getNodeOutput(e,t){const n=this.#pt.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=lf(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#wt.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;Up({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.#kt.get(n);if(t)return this.#kt.delete(n),void e(t);this.#Et.set(n,e)});this.#It(n,{workspaceId:this.workspaceId});const s=await r,i=this.getRun(n),o=this.getNodeOutput(n,"flow-output");return{runId:n,parentRunId:e.parentRunId,depth:t,status:s,output:o,startedAtMs:i?.startedAtMs,endedAtMs:i?.endedAtMs,error:i?.error}}notifyTerminal(e,t){const n=this.#Et.get(e);if(n)return this.#Et.delete(e),void n(t);this.#kt.set(e,t)}#Et=new Map;#kt=new Map;hasPending(e){return this.#ht.has(e)}async#It(e,t){const n=this.#pt.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,s=n.dependencyGraph;r&&s?await this.#bt.executeParallel(e,t,s,n):await this.#bt.executeSequential(e,t)}}const pf=new Map,ff=new Map,hf=new Map;function mf(e){const t=e??uf;let n=pf.get(t);return n||(n=new df(t),pf.set(t,n)),n}let gf=!1;const yf=new class{initialize(){if(gf)return;gf=!0;const e=punica.kernel.Commands.manager;e.registerCommand(Ye.WORKFLOW.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(Ye.WORKFLOW.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(Ye.WORKFLOW.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(Ye.WORKFLOW.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(Ye.WORKFLOW.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(Ye.WORKFLOW.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(Ye.WORKFLOW.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(Ye.WORKFLOW.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(Ye.WORKFLOW.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:uf}(e),n=mf(t);n.initialize();const r=await n.startRun(e);return ff.set(r.runId,t),r}async pauseRun(e){const t=this.#St(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#St(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#St(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#St(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#St(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of pf.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.#At(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#At(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(lf(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=mf(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return ff.set(n.runId,t.workspaceId),n}#St(e){const t=ff.get(e);if(t)return pf.get(t);for(const[t,n]of pf.entries())if(n.hasRun(e))return ff.set(e,t),n}#At(e){const t=hf.get(e);if(t)return pf.get(t);for(const[t,n]of pf.entries())if(n.hasPending(e))return hf.set(e,t),n}};function wf(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 vf(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class bf{packages=new Map;async discover(){this.packages.clear();try{if(!await Sn().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=Kr();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 If(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(!vf(r))return void console.warn(`[AgentRegistry] Not an IvyAgent manifest: ${t}`);const s=r,i=s.capability;if(!i||"object"!=typeof i||!("id"in i))return void console.warn(`[AgentRegistry] Missing capability.id in ${t}`);const o=t.lastIndexOf("/"),a=o>=0?t.slice(0,o):"";this.packages.set(i.id,{packageRoot:a,manifestPath:t,manifest:s})}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():"",s=t&&"description"in t?String(t.description||"").toLowerCase():"",i=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||s.includes(n)||i.includes(n)})}return t}unregister(e){return this.packages.delete(e)}clear(){this.packages.clear()}}function If(e,t){for(const n of e)n.isDirectory?n.children&&If(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let kf;function Ef(){return kf||(kf=new bf),kf}const Sf=new Set(["COMPLETED","FAILED","CANCELLED"]);function Af(e){return new Promise(t=>setTimeout(t,e))}async function xf(e,t,n){const r=Date.now()+n;let s=e.getRun(t);for(;Date.now()<r;){s=e.getRun(t);const n=s?.status;if(n&&(Sf.has(n)||"WAITING_APPROVAL"===n))return{record:s,timedOut:!1};await Af(250)}return{record:s,timedOut:!0}}async function Cf(e,t,n,r,s){const i=Date.now(),o=(e,t)=>({caseId:n.id,status:e.status,durationMs:Date.now()-i,...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:s,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(fp(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await xf(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(fp(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(fp(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(pp(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(fp(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const Tf={validator:{validate:Hd},registry:{discover:()=>tp().discover(),get:e=>tp().get(e),list:()=>tp().list(),search:e=>tp().search(e),setTestReport:(e,t)=>tp().setTestReport(e,t),getLatestTestReport:e=>tp().getLatestTestReport(e)},runner:{run:ap},test:{run:async function(e,t){const n=tp(),r=n.get(e);if(!r){if(t?.manifest){if(vf(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 s=n?.tests;if(!s||!Array.isArray(s.cases)||!s.cases.length)throw new Error(`No test specification found for agent: ${r}`);const i=yf,o=wf(n),a=Date.now(),c=[];for(const e of s.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??s.timeoutMs??3e4;c.push(await Cf(i,o,e,n,t?.workspaceId))}const l=hp({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:s.tier,results:c,startedAtMs:a});try{tp().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 s=r.manifest,i=s.tests;if(!i)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of i.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 s=await ap(e,{input:t.input,runId:`test-${e}-${t.id}-${Date.now()}`,timeoutMs:i.timeoutMs||3e4}),o=s.events.filter(e=>"error"===e.type).map(e=>{const t=e.data;return t?.message||""}).join(" "),a=pp(t,s.output,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:s.output,assertions:a.assertions}}catch(e){const s=fp(t,e instanceof Error?e.message:String(e));r={caseId:t.id,status:"error"===s.status?"fail":s.status,durationMs:Date.now()-n,error:s.error,assertions:s.assertions}}a.push(r)}const c=s.capability,l=hp({capabilityId:e,version:c&&"object"==typeof c&&"version"in c?String(c.version||"0.0.0"):"0.0.0",tier:i.tier,results:a,startedAtMs:o});return n.setTestReport(e,l),l}}},Mf={discover:()=>Ef().discover(),get:e=>Ef().get(e),list:()=>Ef().list(),search:e=>Ef().search(e),unregister:e=>Ef().unregister(e),run:(e,t)=>async function(e,t){const n=Ef().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??yf,s=t?.timeoutMs??3e4,i=wf(n.manifest),o=Date.now(),a=await r.startRun({spec:i,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 xf(r,c,s);if(u){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} did not complete in ${s}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:wf,isAgentManifest:vf},Nf=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",[]]]),Pf=new Set(["COMPLETED","FAILED","CANCELLED"]);const _f=new class{canTransitionTo(e,t){if(e===t)return!1;const n=Nf.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 Nf.get(e)??[]}isTerminal(e){return Pf.has(e)}},Lf=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Rf={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const $f={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function Of(e){return{x:$f.marginX+e%6*240,y:$f.marginY+120*Math.floor(e/6)}}function Df(e){const t=Math.max(0,e.inputCount??0),n=Math.max(0,e.outputCount??0),r=22*(t+n),s=t>0&&n>0?9:0;return 60+Math.max(56,16+r+s)}function jf(e,t){const n={...$f,...t??{}},r=e.nodes??[],s={};if(!r.length)return s;const i=new Map;r.forEach((e,t)=>i.set(e.id,t));const o=(e.edges??[]).filter(e=>e.source!==e.target&&i.has(e.source)&&i.has(e.target));if(1===r.length)return s[r[0].id]={x:n.marginX,y:n.marginY},s;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)=>{s[e.id]=Of(t)}),s;const p=e=>a.get(e).length>0||c.get(e).length>0,f=r.filter(e=>!p(e.id)),h=r.filter(e=>p(e.id));if(!h.length)return r.forEach((e,t)=>{s[e.id]=Of(t)}),s;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 h)y[m.get(e.id)].push(e.id);const w=new Map,v=(e,t)=>{const n=e.map((e,n)=>{const r=t(e).filter(e=>w.has(e));return{id:e,i:n,score:r.length?r.reduce((e,t)=>e+w.get(t),0)/r.length:n}});return n.sort((e,t)=>e.score-t.score||e.i-t.i),n.map(e=>e.id)},b=e=>e.forEach((e,t)=>w.set(e,t));y.forEach(b);for(let e=1;e<y.length;e++)y[e]=v(y[e],e=>c.get(e)),b(y[e]);for(let e=y.length-2;e>=0;e--)y[e]=v(y[e],e=>a.get(e)),b(y[e]);const I=new Map;for(const e of r)I.set(e.id,Df(e));const k=e=>e.reduce((e,t)=>e+I.get(t),0)+Math.max(0,e.length-1)*n.verticalGap,E=Math.max(...y.map(k)),S=n.marginY+E/2;y.forEach((e,t)=>{const r=n.marginX+t*(n.cardWidth+n.horizontalGap);let i=S-k(e)/2;for(const t of e)s[t]={x:r,y:i},i+=I.get(t)+n.verticalGap});const A=n.marginY+E+2*n.verticalGap;return f.forEach((e,t)=>{s[e.id]={x:n.marginX+t*(n.cardWidth+n.horizontalGap/2),y:A}}),s}let Ff;function qf(e){if(!Ff)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 Ff}function Bf(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");Ff=e}function Uf(){Ff=void 0}function Vf(){return Ff}function Kf(e){return qf("createFlowRenderer").createRenderer(e)}function Wf(e){return qf("createViewportController").createViewportController(e)}function Gf(e,t){return qf("attachZoomControl").attachZoomControl(e,t)}function Yf(e,t){return qf("attachMinimap").attachMinimap(e,t)}function zf(e,t){const n={...e,metadata:{...e.metadata??{}}},r=n.metadata,s=r.ivy=r.ivy?{...r.ivy}:{},i=s.view??{},o={x:t.viewport?.x??i.viewport?.x??0,y:t.viewport?.y??i.viewport?.y??0,zoom:t.viewport?.zoom??i.viewport?.zoom??1},a={...i.nodes??{}};return t.nodes.forEach(e=>{e&&e.id&&(a[e.id]={x:e.x,y:e.y})}),s.view={...i,viewport:o,nodes:a},n}var Jf={setRendererProvider:Bf,resetRendererProvider:Uf,getRendererProvider:Vf,createFlowRenderer:Kf,createViewportController:Wf,attachZoomControl:Gf,attachMinimap:Yf,mergeViewSnapshotIntoNotebook:zf,computeFlowLayout:jf,gridFallbackPosition:Of,get rendererProvider(){return Ff}},Hf=Object.freeze({__proto__:null,attachMinimap:Yf,attachZoomControl:Gf,computeFlowLayout:jf,createFlowRenderer:Kf,createViewportController:Wf,default:Jf,getRendererProvider:Vf,gridFallbackPosition:Of,mergeViewSnapshotIntoNotebook:zf,resetRendererProvider:Uf,setRendererProvider:Bf});function Qf(e,t,n){return{path:e,message:t,severity:"error",code:n}}function Zf(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const Xf="WF_INVALID_VERSION",eh="WF_INVALID_EDGE_REF",th=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function nh(e){return"string"==typeof e&&th.test(e)}const rh=new class{#xt=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.#xt.set(e,t)}unregister(e){return this.#xt.delete(e)}get(e){return this.#xt.get(e)}list(){return Array.from(this.#xt.keys())}clear(){this.#xt.clear()}},sh={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 s=e.graph.nodes[t];if(s.disabled)continue;const i=s.ref;if("ivyNode"!==i.kind&&"workflow"!==i.kind)continue;const o=i.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:s.id,code:"WF_UNKNOWN_CAPABILITY"}))}return r}},ih={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)),s=e.graph.entryNodeId;if(!s||!r.has(s))return t;const i=new Map;for(const e of r)i.set(e,[]);for(const t of e.graph.edges)r.has(t.fromId)&&r.has(t.toId)&&i.get(t.fromId).push(t.toId);const o=new Set([s]),a=[s];for(;a.length>0;){const e=a.shift();for(const t of i.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 "${s}"`,path:`graph.nodes[${n}].id`,nodeId:r.id,code:"WF_UNREACHABLE_NODE"}))}return t}},oh={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,s=new Map;for(const e of t)r.set(e.id,0),s.set(e.id,[]);for(const t of e.graph.edges)n.has(t.fromId)&&n.has(t.toId)&&(s.get(t.fromId).push(t.toId),r.set(t.toId,(r.get(t.toId)??0)+1));const i=[];for(const[e,t]of r.entries())0===t&&i.push(e);let o=0;const a=new Set;for(;i.length>0;){const e=i.shift();a.add(e),o++;for(const t of s.get(e)??[])r.set(t,(r.get(t)??0)-1),0===(r.get(t)??0)&&i.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}},ah={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 s=e.graph.nodes[r];if(s.disabled)continue;if("ivyNode"!==s.ref.kind)continue;const i=s.ref.id;if("string"!=typeof i||0===i.length)continue;const o=t.getCapability(i);if(!o)continue;const a=o.defaults;if(!("required"===a?.execution?.idempotency))continue;const c=s.executionOverride;("none"===c?.idempotency||!0===s.data?.skipIdempotencyKey)&&n.push({ruleId:"idempotency-required-but-no-key",severity:"error",message:`Capability "${i}" declares idempotency: 'required' but node "${s.id}" opts out of key derivation — write/retry semantics will double-execute on a network retry`,path:`graph.nodes[${r}]`,nodeId:s.id,code:"WF_IDEMPOTENCY_REQUIRED"})}return n}};function ch(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function lh(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 uh={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 s=0;s<e.graph.edges.length;s++){const i=e.graph.edges[s],o=r.get(i.fromId),a=r.get(i.toId);if(!o||!a)continue;if(o.disabled||a.disabled)continue;const c=ch(o.ref),l=ch(a.ref);if(!c||!l)continue;const u=t.getCapability(c),d=t.getCapability(l);if(!u||!d)continue;const p=u.outputs?.schema,f=d.inputs?.schema;if(!p||!f)continue;const h=lh(p,i.fromPath),m=lh(f,i.toPath);h&&m&&(h.type&&m.type&&h.type!==m.type&&n.push({ruleId:"schema-mismatch",severity:"warning",message:`Edge ${i.fromId} → ${i.toId} type mismatch: upstream emits "${h.type}" but downstream expects "${m.type}"`,path:`graph.edges[${s}]`,code:"WF_SCHEMA_MISMATCH"}))}return n}},dh=["while","forEach"],ph={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 s=r.ref.primitive;if(!dh.includes(s))continue;const i=r.data,o=i?.maxIterations;"number"==typeof o?o<=0&&t.push({ruleId:"infinite-loop",severity:"error",message:`${s} 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:`${s} 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 fh(e,t,n){let r=0;for(const s of e.graph.nodes){if(s.disabled)continue;if("workflow"!==s.ref.kind)continue;const e=s.ref,i=e.id??"<unnamed>";if(n.has(i))return t+1;if(!e.inline)continue;const o=new Set(n);o.add(i);const a=1+fh(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const hh={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],s=e.id??"<root>",i=fh(e,n,new Set([s]));return i<=n||r.push({ruleId:"subflow-depth-exceeded",severity:"error",message:`Flow "${s}" has a statically-derivable inline subflow chain of depth ${i} — exceeds cap (${n}). Direct cycles count as depth > cap.`,path:"graph",code:"WF_SUBFLOW_DEPTH_EXCEEDED"}),r}},mh=[sh,ih,oh,ah,uh,ph,hh];const gh=new class{#fe=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#fe.values())try{const s=t.check(e,r);s&&s.length>0&&n.push(...s)}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.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of mh)this.#fe.set(e.id,e)}};function yh(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 s=new Set([t]),i=new Map,o=[t];for(;o.length>0;){const e=o.shift();if(e===n)break;for(const t of r.get(e)??[])if(!s.has(t.to)){if(s.add(t.to),i.set(t.to,t),t.to===n){o.length=0;break}o.push(t.to)}}if(!s.has(n))return;const a=[];let c=n;for(;c!==t;){const e=i.get(c);if(!e)return;a.unshift(e),c=e.from}return a}function wh(e){return e.map(e=>`${e.from}=>${e.to}`)}function vh(e,t){return`${e}=>${t}`}const bh=new class{#Ct=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.#Ct.set(vh(e.from,e.to),e)}unregister(e,t){return this.#Ct.delete(vh(e,t))}find(e,t){return this.#Ct.get(vh(e,t))}list(){return Array.from(this.#Ct.values())}clear(){this.#Ct.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,s=e.targetVersion;if(!nh(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(!nh(s))return{ok:!1,reason:"invalid-result",message:`targetVersion "${String(s)}" is not a valid semver — substrate refuses to migrate to an unrecognized version.`,appliedTransformers:[]};if(r===s)return{ok:!0,document:e.document,appliedTransformers:[],fromVersion:r,toVersion:s};if("reject"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${s} 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} → ${s} and policy is 'warn'. Substrate did not migrate; downstream consumers may see a stale IR.`,partialDocument:e.document,appliedTransformers:[]};const i=("function"==typeof t.__plan?t.__plan.bind(t):(e,n)=>yh(new Map(t.list().map(e=>[`${e.from}=>${e.to}`,e])),e,n))(r,s);if(!i||0===i.length)return{ok:!1,reason:"no-path",message:`No transformer chain from ${r} to ${s}. Register transformers via punica.flow.primitives.migrations.register(...).`,appliedTransformers:[]};let o=e.document;const a=[];for(const e of i)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:wh(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:wh(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:wh(a)}}return{ok:!0,document:o,appliedTransformers:wh(a),fromVersion:r,toVersion:s}}(e,this)}__plan(e,t){return yh(this.#Ct,e,t)}};function Ih(){return Date.now()}class kh{#he=new Map;#Pe=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.#he.set(e.id,n),this.#We({type:"registered",triggerId:e.id,kind:e.kind,ts:Ih()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#he.get(e.id)===n&&(this.#he.delete(e.id),this.#We({type:"unregistered",triggerId:e.id,ts:Ih()}))}}}unregister(e){const t=this.#he.get(e);return!!t&&(t.unsubscribed=!0,this.#he.delete(e),this.#We({type:"unregistered",triggerId:e,ts:Ih()}),!0)}list(){return Array.from(this.#he.values()).map(e=>e.trigger)}subscribe(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}async fire(e,t){const n=this.#he.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Ih()}-${Math.floor(1e6*Math.random())}`,s=Ih();this.#We({type:"fired",triggerId:e,ts:s,payload:t,correlationId:r}),Up({name:"flow.trigger.fired",source:"flow:triggers",correlationId:r,payload:{triggerId:e,kind:n.trigger.kind,flowId:n.trigger.flowId,firedAtMs:s,payload:t??null}});try{return await n.callback({triggerId:e,firedAtMs:s,payload:t,correlationId:r}),!0}catch(t){return this.#We({type:"error",triggerId:e,ts:Ih(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#he.values())e.unsubscribed=!0;this.#he.clear(),this.#Pe.clear()}#We(e){for(const t of this.#Pe)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const Eh=new kh;let Sh=Eh;const Ah={get manager(){return Sh},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()");Sh!==e&&Sh instanceof kh&&Sh.clear(),Sh=e},resetProvider(){Sh instanceof kh&&Sh.clear(),Sh=Eh}};function xh(e,t){return`${e}=>${t}`}const Ch={migrators:new class{#Tt=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.#Tt.set(xh(e.from,e.to),e)}unregister(e,t){return this.#Tt.delete(xh(e,t))}find(e,t){return this.#Tt.get(xh(e,t))}list(){return Array.from(this.#Tt.values())}clear(){this.#Tt.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}},Th={...Tf,agents:Mf,engine:{manager:yf,statusStateMachine:_f,subscribeNodeStatuses:function(e,t){const n=new Set(e.nodeIds);let r=null;const s=(e,s,i)=>{const o=String(e??"");if(!o||!n.has(o))return;const a=String(s??"").toUpperCase(),c=Rf[a];if(!c)return;const l=i?String(i):null,u=null!==l&&l!==r;u&&(r=l),t({nodeId:o,status:c,runId:l,isNewRun:u,stepStatus:a})},i=e=>{const t=e?.payload?.payload??e?.payload??{};switch(e?.name){case"workflow.stepStarted":return s(t?.step?.stepId,t?.step?.status??"RUNNING",t?.runId);case"workflow.stepUpdated":return s(t?.stepId,t?.patch?.status,t?.runId);case"workflow.stepFinished":return s(t?.step?.stepId,t?.step?.status,t?.runId);default:return}};let o=null;try{o=punica.kernel.Events.manager.subscribeMany(Lf,i)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:Hf,validateWorkflowDocument:function(e,t){const n=[],r=[],s=t?.mode??"best-effort",i=t?.hasCapability;if(!e||"ivy.workflow/v0.1"!==e.apiVersion)return n.push(Qf("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',Xf)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(Qf("kind",'kind must equal "Workflow"',Xf)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!nh(o)){const e=Qf("version","version must be a semver string (major.minor.patch[-prerelease][+build]); got "+("string"==typeof o?`"${o}"`:typeof o),"WF_INVALID_SEMVER");"strict"===s?n.push(e):r.push({...e,severity:"warning"})}if(!e.graph||"object"!=typeof e.graph)return n.push(Qf("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(Qf("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(Qf("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(Qf(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(Qf(`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(Qf(`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(Qf(`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"],s=r.primitive;"string"==typeof s&&e.includes(s)||n.push(Qf(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(Qf(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(Qf(`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),f=c.some(e=>"flow-output"===e.toId);return p&&!u&&n.push(Qf("graph.nodes","flow-input node is required when edges reference it")),f&&!d&&n.push(Qf("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(Qf("graph.entryNodeId",`entryNodeId "${e.graph.entryNodeId}" must reference an existing node`,"WF_INVALID_ENTRY")),c.forEach((e,t)=>{const r=String(e?.fromId??""),s=String(e?.toId??"");r||n.push(Qf(`graph.edges[${t}].fromId`,"fromId is required")),s||n.push(Qf(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(Qf(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,eh)),s&&!l.has(s)&&n.push(Qf(`graph.edges[${t}].toId`,`toId "${s}" must reference a node.id`,eh))}),"strict"===s&&function(e,t,n){const r=e.filter(e=>!e.disabled),s=new Set(r.map(e=>e.id)),i=t.filter(e=>s.has(e.fromId)&&s.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 i)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(Qf("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 s=e.filter(e=>!e.disabled),i=new Set(s.map(e=>e.id));if(!i.has(n))return;const o=t.filter(e=>i.has(e.fromId)&&i.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 s)if(!a.has(t.id)){const s=e.indexOf(t);r.push(Zf(`graph.nodes[${s}].id`,`Node "${t.id}" is unreachable from entry node "${n}"`,"WF_UNREACHABLE_NODE"))}}(a,c,e.graph.entryNodeId,r),i&&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(i(a))return;("strict"===s?n:r).push(("strict"===s?Qf:Zf)(`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:rh,linter:gh,migrations:bh,checkpoints:Ch},triggers:Ah},Mh=[];function Nh(e){Mh.push(e)}function Ph(){const e={};for(const t of Mh)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function _h(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Lh(e){return"string"==typeof e}function Rh(e){return"string"==typeof e&&e.trim().length>0}function $h(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const Oh=new Set(["shell.activityBar","shell.appBar","shell.statusbar","shell.view","shell.views","shell.keyboardShortcuts","shell.layout","shell.contentTabs","shell.panelTabs","shell.panelLayout","shell.viewDnd","flow.shell"]),Dh=new Set(["light","dark","auto"]),jh=new Set(["compact","comfortable"]),Fh=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const qh=new class{validate(e){const t=[];if(!_h(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)}`),_h(e.identity)?(Rh(e.identity.id)||t.push("identity.id must be a non-empty string"),Rh(e.identity.name)||t.push("identity.name must be a non-empty string"),Rh(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),_h(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys(Ph()),r=new Set([...Oh,...n]);e.shell.activeModules.forEach((e,n)=>{Lh(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&&(_h(e.shell.layout)?(Rh(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),_h(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(_h(e.theme)?(Dh.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||jh.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"),_h(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||$h(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||$h(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)=>{Lh(e)&&Fh.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}}};let Bh;function Uh(){return Bh??qh}function Vh(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}}class Kh{#Mt=new Map;#Nt;register(e){if(this.#Mt.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#Mt.set(e.identity.id,e),void 0===this.#Nt&&(this.#Nt=e.identity.id)}get(e){return this.#Mt.get(e)}getActive(){if(void 0===this.#Nt||!this.#Mt.has(this.#Nt))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#Mt.get(this.#Nt)}setActive(e){if(!this.#Mt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#Nt=e}switchProfile(e){if(!this.#Mt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#Nt=e,Vh({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Mt.has(e)}list(){return Array.from(this.#Mt.values())}}const Wh={manager:new class{registry=new Kh;get validator(){return Uh()}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.#Pt(t)}this.#Pt(e)}#Pt(e){const t=this.validator.validate(e);if(!t.valid)throw Vh({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),Vh({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}};class Gh{name=Ge.EXTENSIONS.MANAGER;version="1.0.0";dependencies=[Ge.KERNEL.COMMANDS,Ge.KERNEL.EVENTS,Ge.RUNTIME.WORKSPACE];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(Ge.KERNEL.COMMANDS),i=r.getState(Ge.KERNEL.EVENTS),o=r.getState(Ge.RUNTIME.WORKSPACE),a=r.getState(Ge.SHELL.LAYOUT);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(i!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(void 0!==a&&a!==e.ModuleLifecycleState.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 Yh{name=Ge.FLOW.VALIDATOR;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}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 zh(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 Jh{prepareExecutionConfig(e){const t=zh(e);if(!t)return{};const n=bp(),r=n?.getSpec?.(t);return{capabilityDefaults:Ip(r)}}async acquireResources(e,t,n){const r=zh(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 Yp.acquire(n,e.concurrency.max),()=>{Yp.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,s=zh(e),i=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!s)throw new Error("capabilityId missing for capability.call node");const o=vp();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(s,i,{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=bp(),u=l?.getSpec?.(s),d=u?.defaults?.dataClassification,p=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`${s}.result`,payload:c,meta:{source:"capability.call",capabilityId:s},redactionPolicy:e.redactionPolicy,surface:"output",capabilityClassification:d,sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:yp(gp(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Hh(e){return e.data??{}}function Qh(e){return e.nodeOutputs??new Map}async function Zh(e,t,n,r,s){const i=await e.artifactStore.writeArtifact(t.traceId,n.id,{type:"json",name:`primitive.${r}.decision`,payload:s,meta:{source:"primitive",primitive:r},redactionPolicy:n.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:yp(gp(s,0),320),artifactIds:[i.id]}}class Xh{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=Hh(e),s=Zp(r.predicate,Qh(t));if(!s.ok)throw new Error(`[primitive:if] predicate did not resolve (${s.reason}) on node "${e.id}"`);const i={taken:Xp(s.value)?"then":"else",predicate:s.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Zh(n,t,e,"if",i),output:i}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Zh(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Hh(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 s=Zp(r.collection,Qh(t));if(!s.ok&&"missing-node"!==s.reason)throw new Error(`[primitive:forEach] collection did not resolve (${s.reason}) on node "${e.id}"`);const i=s.ok?s.value:null,o=Array.isArray(i)?i:[],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 Zh(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Hh(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 s=Zp(r.predicate,Qh(t));if(!s.ok)throw new Error(`[primitive:while] predicate did not resolve (${s.reason}) on node "${e.id}"`);const i=Xp(s.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:i,initialPredicateValue:s.value};return{...await Zh(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Hh(e);if(!r.tryBodyFlowId)throw new Error(`[primitive:try] tryBodyFlowId is required on node "${e.id}"`);const s={tryBodyFlowId:r.tryBodyFlowId,catchBodyFlowId:r.catchBodyFlowId??null,finallyBodyFlowId:r.finallyBodyFlowId??null};return{...await Zh(n,t,e,"try",s),output:s}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Zh(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Zh(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Hh(e),s=r.lambdaId??"";if("string"!=typeof s||0===s.length)throw new Error(`[primitive:lambda] lambdaId is required on node "${e.id}"`);const i=rh.get(s);if(!i)throw new Error(`[primitive:lambda] lambdaId "${s}" is not registered (node "${e.id}")`);let o=null;if(void 0!==r.input){const n=Zp(r.input,Qh(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 i(o,{nodeId:e.id,attemptCorrelationId:t.attemptCorrelationId,traceId:t.traceId}),c=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`primitive.lambda.${s}.result`,payload:a,meta:{source:"primitive",primitive:"lambda",lambdaId:s},redactionPolicy:e.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:yp(gp(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 em{async execute(e,t){return{output:t.runInput??null}}}class tm{async execute(e,t){return{output:t.resolvedInput??null}}}let nm=!1;class rm{name=Ge.FLOW.ENGINE;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS,Ge.KERNEL.POLICY,Ge.KERNEL.COMMANDS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(Ge.KERNEL.EVENTS),i=r.getState(Ge.KERNEL.POLICY),o=r.getState(Ge.KERNEL.COMMANDS);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(i!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(nm||(Hp.register("ivyNode",new Jh),Hp.register("primitive",new Xh),Hp.register("flowInput",new em),Hp.register("flowOutput",new tm),nm=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class sm{name=Ge.FLOW.SHELL;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 im{name=Ge.KERNEL.EVENTS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;#l=null;get state(){return this.#we}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 om{name=Ge.KERNEL.COMMANDS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class am{name=Ge.KERNEL.POLICY;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 cm{name=Ge.KERNEL.HISTORY;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class lm{name=Ge.KERNEL.TIME_SERVER;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class um{name=Ge.KERNEL.TASKS;version="1.0.0";dependencies=[Ge.RUNTIME.TERMINALS,Ge.RUNTIME.WORKSPACE];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(Ge.RUNTIME.TERMINALS),i=r.getState(Ge.RUNTIME.WORKSPACE);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(i!==e.ModuleLifecycleState.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 dm{name=Ge.KERNEL.NOTIFICATIONS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class pm{name=Ge.KERNEL.AI;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS,Ge.KERNEL.POLICY,Ge.KERNEL.LLM];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(Ge.KERNEL.EVENTS),i=r.getState(Ge.KERNEL.POLICY),o=r.getState(Ge.KERNEL.LLM);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(i!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==e.ModuleLifecycleState.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 fm=class{name=Ge.KERNEL.LLM;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS,Ge.KERNEL.POLICY];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(Ge.KERNEL.EVENTS),i=r.getState(Ge.KERNEL.POLICY);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(i!==e.ModuleLifecycleState.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:rn,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class hm{name=Ge.RUNTIME.FS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class mm{name=Ge.RUNTIME.SEARCH;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 gm{name=Ge.RUNTIME.VCS;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 ym{name=Ge.RUNTIME.WORKSPACE;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 wm{name=Ge.RUNTIME.LLM;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 vm{name=Ge.RUNTIME.TASKS;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 bm{name=Ge.RUNTIME.SECRETS;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 Im{name=Ge.RUNTIME.TERMINALS;version="1.0.0";dependencies=[Ge.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Ge.KERNEL.EVENTS)!==e.ModuleLifecycleState.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){}}function km(){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 Em(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 Sm(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 Am(e,t,r){const s=punica.kernel.Events.manager,i=r?.__punica??{},o=i.correlationId??s.createCorrelationId(),a=i.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:i.parentSpanId},policy:{mode:"execute"}}}function xm(){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=km();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");Em("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Am("workspace.readFile","command",t))})}catch(e){Sm("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??""),s=km();if(!s)throw new Error("[CoreCapabilities] Capability gateway not available");await s.call("workspace.writeFile",{path:n,content:r},await Am("workspace.writeFile","command",t)),Em("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Sm("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();Em("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){Sm("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{Em("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Am("vcs.status","command",t))})}catch(e){Sm("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):[],s=null!=e?.cwd?String(e.cwd):void 0,i=e?.env&&"object"==typeof e.env?e.env:void 0;Em("capability.tasks.runCommand.result",t,{command:n,args:r,cwd:s,...await punica.runtime.capabilities.gateway.call("tasks.runCommand",{command:n,args:r,cwd:s,env:i},await Am("tasks.runCommand","command",t))})}catch(e){Sm("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?Em("capability.llm.invoke.result",t,r):Sm(n,t,r),r}catch(r){const s={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Sm(n,t,s),s}}}),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?Em("capability.llm.plan.result",t,r):Sm(n,t,r)}catch(e){Sm(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 s=await punica.kernel.llm.manager.api.generateCode(e);if(s.ok)if(s.structured&&"object"==typeof s.structured){const e=s.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 i=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)");Em(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 nn(e,i);if(t.errors.length>0)throw new Error(`Failed to apply some files:\n${t.errors.map(e=>`${e.path}: ${e.error}`).join("\n")}`)}})?{...s,metadata:{...s.metadata,applied:!0}}:{...s,metadata:{...s.metadata,applied:!1,cancelled:!0}})}else Em(n,t,s)}else Em(n,t,s);else Sm(r,t,s)}catch(e){Sm(r,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"code-generator",role:"code-generator"}})}}}),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?Em("capability.llm.edit-workflow.result",t,r):Sm(n,t,r)}catch(e){Sm(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"workflow-editor",role:"workflow-editor"}})}}});const t=e=>async(t,n)=>{try{await punica.runtime.capabilities.gateway.call("shell.toggleSlot",{slot:e},await Am("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(Ye.SHELL.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(Ye.SHELL.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(Ye.SHELL.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Cm="1.0.0",Tm=an,Mm={},Nm=ja,Pm=zd,_m=Th,Lm=new class{#_t=new Map;#Lt=new Map;#Rt=new Map;register(t){if(this.#_t.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#_t.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#_t.set(t.name,t),this.#Lt.set(t.name,e.ModuleLifecycleState.CREATED)}get(e){return this.#_t.get(e)}getAll(){return Array.from(this.#_t.values())}resolveBootstrapOrder(){return this.#$t()}resolveStartOrder(){return this.#$t()}#$t(){const e=new Set,t=new Set,n=[],r=s=>{if(t.has(s)){const e=Array.from(t).concat(s);throw new Error(`Circular dependency detected: ${e.join(" → ")}`)}if(e.has(s))return;t.add(s);const i=this.#_t.get(s);if(!i)throw new Error(`Module ${s} not found`);for(const e of i.dependencies)r(e);t.delete(s),e.add(s),n.push(s)};for(const t of this.#_t.keys())e.has(t)||r(t);return n}async bootstrapAll(){const t=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#Lt.set(n,e.ModuleLifecycleState.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#Lt.set(n,e.ModuleLifecycleState.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Lt.set(n,e.ModuleLifecycleState.BOOTSTRAP_FAILED),this.#Rt.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} bootstrap failed:`,r),new Error(`Critical module ${n} failed to bootstrap: ${r.message}`)}}console.log("[ModuleRegistry] All modules bootstrapped successfully")}async startAll(){const t=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#Lt.get(n);if(r!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#Lt.set(n,e.ModuleLifecycleState.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#Lt.set(n,e.ModuleLifecycleState.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Lt.set(n,e.ModuleLifecycleState.START_FAILED),this.#Rt.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} start failed:`,r),new Error(`Critical module ${n} failed to start: ${r.message}`)}}for(const n of t){this.#Lt.get(n)===e.ModuleLifecycleState.STARTED&&this.#Lt.set(n,e.ModuleLifecycleState.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#Lt.get(e)}areAllModulesReady(){for(const[t,n]of this.#_t){if(this.#Lt.get(t)!==e.ModuleLifecycleState.READY)return!1}return!0}getError(e){return this.#Rt.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#_t.keys())t.includes(n)&&e.push(n);return e}};Nh({moduleFactories:{"flow.shell":()=>new sm}});var Rm=Object.freeze({__proto__:null,StdioTransport:class{#Ot;#Dt;#jt;#Ft=null;#qt=null;#Bt=null;#Ut=null;#Vt=null;#Kt=new Map;#Wt=1;#Gt="";constructor(e,t=[],n={}){this.#Ot=e,this.#Dt=t,this.#jt=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#Yt(e):await this.#zt()}async#Yt(e){this.#Bt=e;const{sessionId:t}=await e.spawn({command:this.#Ot,args:this.#Dt,env:this.#jt});this.#qt=t,this.#Ut=e.onData(e=>{e.sessionId===t&&this.#Jt(e.chunk)}),this.#Vt=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.#Kt.values())e(n);this.#Kt.clear()})}async#zt(){const e=await import(
2
- /* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#Ft=e.spawn(this.#Ot,this.#Dt,{env:{...n,...this.#jt},stdio:["pipe","pipe","inherit"]}),this.#Ft.stdout.setEncoding("utf8"),this.#Ft.stdout.on("data",e=>{this.#Jt(e)}),this.#Ft.on("error",e=>{for(const{reject:t}of this.#Kt.values())t(e);this.#Kt.clear()})}#Jt(e){let t;for(this.#Gt+=e;-1!==(t=this.#Gt.indexOf("\n"));){const e=this.#Gt.slice(0,t).trim();this.#Gt=this.#Gt.slice(t+1),e&&this.#Ht(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#Qt(n)}async request(e,t={}){const n=this.#Wt++;return new Promise((r,s)=>{this.#Kt.set(n,{resolve:r,reject:s});const i=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#Qt(i)}catch(e){this.#Kt.delete(n),s(e instanceof Error?e:new Error(String(e)))}})}#Qt(e){if(this.#Bt&&this.#qt)this.#Bt.write(this.#qt,e);else{if(!this.#Ft?.stdin)throw new Error("MCP stdio transport is not connected");this.#Ft.stdin.write(e)}}close(){this.#Ut?.(),this.#Vt?.(),this.#Ut=null,this.#Vt=null,this.#Bt&&this.#qt&&this.#Bt.close(this.#qt),this.#Ft?.kill(),this.#Ft=null,this.#qt=null,this.#Bt=null;for(const{reject:e}of this.#Kt.values())e(new Error("MCP stdio transport closed"));this.#Kt.clear()}#Ht(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#Kt.get(t.id);n&&(this.#Kt.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var $m=Object.freeze({__proto__:null,StreamableHttpTransport:class{#Zt;#Xt;#Wt=1;#qt;constructor(e,t={}){this.#Zt=e.replace(/\/$/,""),this.#Xt=t}async connect(){const e=await fetch(`${this.#Zt}/sse`,{headers:{...this.#Xt,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#qt=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#en({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#Wt++,r=await this.#en({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#en(e){const t={...this.#Xt,"Content-Type":"application/json",Accept:"application/json"};this.#qt&&(t["mcp-session-id"]=this.#qt);const n=await fetch(`${this.#Zt}/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.#qt=void 0}}});var Om=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return ya(gd(e))}});e.COMMAND_IDS=Ye,e.MODULE_NAMES=Ge,e.Profile=Wh,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 Mh)t.facade&&Object.assign(e,t.facade);return e}()));const n=Wh.manager;for(const e of function(){const e=[];for(const t of Mh)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 Mh)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(Lm.register(new im),Lm.register(new om),Lm.register(new cm),Lm.register(new lm),Lm.register(new dm),Lm.register(new Yh),Lm.register(new am),Lm.register(new fm),Lm.register(new pm),Lm.register(new rm),Lm.register(new hm),Lm.register(new mm),Lm.register(new gm),Lm.register(new ym),Lm.register(new wm),Lm.register(new bm),Lm.register(new Im),Lm.register(new vm),Lm.register(new va),Lm.register(new um),r){const e=Ph(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(Lm.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}Lm.register(new Gh),console.log(`[Punica] Module registry initialized with ${Lm.getAll().length} modules`),await Lm.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}},e.emitShellEvent=Vh,e.enterHeadlessScope=$d,e.exitHeadlessScope=Od,e.extensions=Pm,e.flow=_m,e.getProfileValidator=Uh,e.initialize=function(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Cm,kernel:Tm,shell:Mm,runtime:Nm,extensions:Pm,flow:_m};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=Nh;const t=e.debug??{};t.logTrinityCatalog=Zo,t.logTrinityCatalogVerbose=Xo,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=Zo,n.logTrinityCatalogVerbose=Xo);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("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{xm(),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.isHeadlessScope=function(){return Rd>0},e.isMacPlatform=Cd,e.kernel=Tm,e.parseKeyChord=Td,e.registerShell=Nh,e.runInHeadlessScope=Dd,e.runtime=Nm,e.setProfileValidator=function(e){Bh=e},e.shell=Mm,e.start=async function(){try{console.log("[Punica] Starting system..."),await Lm.startAll(),Lm.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:Cm}}),console.log("[Punica] System started successfully"),Zo()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}},e.version=Cm});
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;e.ModuleLifecycleState=void 0,(t=e.ModuleLifecycleState||(e.ModuleLifecycleState={})).CREATED="created",t.BOOTSTRAPPING="bootstrapping",t.BOOTSTRAPPED="bootstrapped",t.BOOTSTRAP_FAILED="bootstrap_failed",t.STARTING="starting",t.STARTED="started",t.START_FAILED="start_failed",t.READY="ready";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?.workspace}function s(){return punica.runtime?.fs}function i(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 o(e){return i(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 a=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function c(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||a.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function l(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,s]of Object.entries(n))c(t)?r[t]=null==s?s:"[REDACTED]":r[t]=e(s);return r}(e)}function u(e,t=2){const n=l(e);return o(JSON.stringify(n,null,t))}function d(e){const t=[];return function e(n,r){if(!n||"object"!=typeof n)return;const s=n,i=s.properties;if(i&&"object"==typeof i)for(const[n,s]of Object.entries(i)){if(!s||"object"!=typeof s)continue;const i=s,o=[...r,n];!0===i.sensitive&&t.push(o),e(i,o)}const o=s.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=s[t];if(Array.isArray(n))for(const t of n)e(t,r)}}(e,[]),t}function p(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 s=!1;for(const e of n)"*"===e[0]&&(1===e.length?s=!0:r.push(e.slice(1)));return s&&0===r.length?t.map(e=>null==e?e:"[REDACTED]"):t.map(t=>e(t,r))}const r={};for(const[s,i]of Object.entries(t)){const t=[];let o=!1;for(const e of n)e[0]===s&&(1===e.length?o=!0:t.push(e.slice(1)));o?r[s]=null==i?i:"[REDACTED]":t.length>0?r[s]=e(i,t):r[s]=i}return r}(e,t)}const f=/^(?:secrets|secret-manager)\./,h=new Set(["value"]);const m={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 s=r[0];return n.activate(s,{reason:"command",trigger:e}).then(()=>{const n=this.#e.get(e);return n?(console.log("[Commands] execute after activate",e,"via extension",s),n.execute(...t)):void console.error(`Command ${e} not found after activating extension "${s}"`)}).catch(t=>{console.error(`Error activating extension "${s}" for command ${e}:`,t)})}console.log("[Commands] execute",e,"with args",function(e,t){const n=f.test(e);return t.map(e=>{if(n&&e&&"object"==typeof e&&!Array.isArray(e)){const t={};for(const[n,r]of Object.entries(e))t[n]=h.has(n)?"[REDACTED]":r;return l(t)}return l(e)})}(e,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 g=new class{async write(e){try{const t=s();if(!t)return;const n=".punica/audit";await t.createFolder(n).catch(()=>{});const r=new Date(e.timestamp).toISOString().split("T")[0],i=`${n}/${`${r}_${e.invocationId}.json`}`;await t.createFileWithContent(i,JSON.stringify(e,null,2))}catch(e){console.warn("[AuditWriter] Failed to write audit record:",e)}}async read(e){try{const t=s();if(!t)return[];const n=".punica/audit",r=await t.getFileTree(),i=(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(...i(r.children,t)));return n},o=i(r,n),a=[];for(const n of o)if(n.name.endsWith(".json"))try{const r=await t.readFile(n.path),s=JSON.parse(r);if(e?.since&&s.timestamp<e.since)continue;if(e?.until&&s.timestamp>e.until)continue;if(e?.capability&&s.capability!==e.capability)continue;if(e?.workspaceId&&s.workspace!==e.workspaceId)continue;a.push(s)}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 y={manager:new class{#n=new Map;#r=[];#s=[];registerCommand(e){this.#n.set(e.id,e)}executeCommand(e){const t=this.#n.get(e);t?(t.execute(),this.#r.push(t),this.#s=[]):console.error(`Command with ID ${e} not found.`)}undo(){const e=this.#r.pop();e?(e.undo(),this.#s.push(e)):console.error("No command to undo.")}redo(){const e=this.#s.pop();e?(e.execute(),this.#r.push(e)):console.error("No command to redo.")}},auditWriter:g};const w={manager:new class{#i=[];#o=null;#a(){null===this.#o&&(this.#o=window.setInterval(()=>{const e=new Date;this.#i.forEach(t=>t.update(e))},1e3))}#c(){null!==this.#o&&(window.clearInterval(this.#o),this.#o=null)}subscribe(e){this.#i.push(e),1==this.#i.length&&this.#a()}unsubscribe(e){this.#i=this.#i.filter(t=>t!==e),0==this.#i.length&&this.#c()}}};function v(){return(new Date).toISOString()}function b(e,t){const n=new Map,r=new Map,s=new Set;function i(e){for(const t of s)try{t(e)}catch{}try{const t=window,n=t.punica?.Commands?.manager,r=t.punica?.runtime,s="failed"===e.status?"error":"cancelled"===e.status?"warning":"info";let i=`[${e.label}] ${e.status}`;null!=e.exitCode&&(i+=` (exitCode=${e.exitCode})`),n&&n.executeCommand("output.append",{channel:"Tasks",text:i,level:s}),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:i,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(s,a){const c=n.get(s);if(!c)throw new Error(`[Runtime.tasks] Task definition not found: ${s}`);const l=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`task_${Date.now()}_${Math.floor(1e6*Math.random())}`}(),u=v(),{env:d,workspaceId:p,resolvedEnvironmentId:f}=await async function(e,n){if(!t)return{env:e};try{const r=await t.getCurrent();if(!r)return{env:e};const s=n??r.currentEnvironmentId,i=r.environments.find(e=>e.id===s),o={...i?.variables??{},...e??{}};return{env:Object.keys(o).length?o:void 0,workspaceId:r.id,resolvedEnvironmentId:i?.id}}catch{return{env:e}}}(c.env,a?.environmentId),h=await e.create({cwd:c.cwd,env:d,title:c.label}),m={runId:l,definitionId:c.id,label:c.label,status:"running",startedAt:u,terminalId:h.id,workspaceId:p,environmentId:f};r.set(l,m),i(m);const g=[c.command,...c.args??[]].join(" ").trim();try{const e=window,t=e.punica?.Commands?.manager;t&&"function"==typeof t.executeCommand&&(g?t.executeCommand("terminal.openForTaskSession",{sessionId:h.id,commandLine:g}):t.executeCommand("terminal.openForSession",h.id))}catch{}return e.onExit(h.id,e=>{const t=r.get(l);if(!t)return;const n={...t,status:0===e||null==e?"success":"failed",finishedAt:v(),exitCode:e??null};r.set(l,n),i(n),c.autoRerun&&setTimeout(()=>{o.run(c.id,{environmentId:f}).catch(()=>{})},300)}),m},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 s={...n,status:"cancelled",finishedAt:v()};r.set(t,s),i(s)},onDidChangeRun:e=>(s.add(e),()=>{s.delete(e)})};return o}const I=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=b(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 k={manager:I},E=Object.freeze({__proto__:null,createTasksApi:b,default:k,manager:I});const S=6048e5,A={rules:[],defaultTtlMs:S};function x(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 C(e,t,n){const r=function(e,t){let n=null,r=-1;for(const s of t)if(x(e,s.pattern)){const e=s.pattern.length;e>r&&(n=s,r=e)}return n}(e,t.rules??[]);return n-(r?.ttlMs??t.defaultTtlMs??S)}const T=".punica/.gitignore",M="# Punica editor — workspace internal state.\n# Auto-generated. Everything under .punica/ is ignored by default;\n# only the authored artifacts and user config below are tracked.\n/*\n\n!.gitignore\n\n# Authored artifacts (user's project content)\n!/ivy-nodes/\n!/ivy-agents/\n!/ivy-mcps/\n!/ivy-inputs/\n\n# Generated, and required by something outside this machine. The CI generator\n# writes the gate drivers here and the workflow it produces calls them by path,\n# so a runner that checks out the repository must find them.\n!/ci/\n\n# User configuration\n!/settings.json\n!/tasks.json\n!/launch.json\n!/database.yaml\n!/experiments.yaml\n!/mlops.yaml\n!/python.yaml\n!/vectors.yaml\n!/mcp.yaml\n!/mcp/\n";function N(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.startsWith("!"))}async function P(){const e=s();if(e&&(!r()||await n()))try{if(!!e.exists&&await e.exists(T)){const t=function(e){if(!e.includes("# Punica editor — workspace internal state."))return null;const t=new Set(N(e)),n=N(M).filter(e=>!t.has(e));return 0===n.length?null:`${e.endsWith("\n")?e:`${e}\n`}\n# Added by a later version of the editor.\n${n.join("\n")}\n`}(await e.readFile(T)??"");return void(t&&e.updateFileContent&&await e.updateFileContent(T,t))}try{await e.createFolder(".punica")}catch{}await e.createFileWithContent(T,M)}catch{}}const _=".punica/events";let L={};function R(e){const t=[],n=[...e];for(;n.length>0;){const e=n.pop();if(e){if(Array.isArray(e.children))for(const t of e.children)n.push(t);!0!==e.isDirectory&&"string"==typeof e.path&&e.path.startsWith(_)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function $(e,t){if(!t)return!0;const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId&&n?.id!==t.correlationId)return!1;if(void 0!==t.name){if(!(Array.isArray(t.name)?t.name:[t.name]).includes(e.name))return!1}return!(void 0!==t.since&&(n?.timestampMs??0)<t.since)&&!(void 0!==t.until&&(n?.timestampMs??0)>t.until)}const O=new class{#d;#p=!1;#f=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const t=s();if(!t)return;if(r()&&!await n())return;const i=Date.now();try{await t.createFolder(_)}catch{}if(!this.#p){this.#p=!0;try{await t.createFileWithContent(`${_}/.gitignore`,"*\n!.gitignore\n")}catch{}}this.#f||(this.#f=!0,await P());for(const n of e)try{const e=n.envelope?.timestampMs??Date.now(),r=new Date(e).toISOString().split("T")[0],s=n.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,i=`${_}/${r}_${s}.json`,o=u(n);await t.createFileWithContent(i,o)}catch{}try{L.onWrite?.(Date.now()-i,e.length)}catch{}}async query(e){const t=s();if(!t)return[];let n;try{n=await t.getFileTree()}catch{return[]}if(!Array.isArray(n))return[];const r=R(n),i=[];for(const n of r)try{const r=await t.readFile(n),s=JSON.parse(r);$(s,e)&&i.push(s)}catch{}return i.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),e?.limit&&e.limit>0?i.slice(-e.limit):i}async delete(e){const t=s();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const r=R(n);let i=0;const o=[];for(const n of r)try{const r=await t.readFile(n);if($(JSON.parse(r),e))await t.deleteFile(n),i++;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),i++}catch{}}return i}async applyRetention(e,t=Date.now()){const n=s();if(!n)return 0;let r;try{r=await n.getFileTree()}catch{return 0}if(!Array.isArray(r))return 0;const i=R(r);let o=0;for(const r of i)try{const s=await n.readFile(r),i=JSON.parse(s),a=i.envelope?.timestampMs??0;a<C(i.name,e,t)&&(await n.deleteFile(r),o++)}catch{}return o}};let D=O;function j(){return D}const F=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 q=F;function B(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=q.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function U(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(x(e.name,t)){r=!0;break}if(!r)return!1}return!0}class V extends Error{constructor(e){super(e),this.name="EventReplayError"}}let K={exportSpan:()=>{}};function W(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function G(){return Date.now()}function Y(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let s=[],i=null;function o(){try{L.onQueueDepthChange?.(s.length)}catch{}}async function a(){if(0===s.length)return;const e=[...s];s=[],o(),i&&(clearTimeout(i),i=null);try{await j().write(e),Z()}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function c(e){(function(e){if("audit"===e.envelope?.kind)return!0;const t=e.name;return r.some(e=>e.test(t))})(e)&&(s.push(e),o(),s.length>=10?a():i||(i=setTimeout(()=>{a()},5e3)))}function l(n,r){if("string"==typeof n){const t=n;let s=e.get(t);return s||(s=new Set,e.set(t,s)),s.add(r),()=>{s?.delete(r),s&&0===s.size&&e.delete(t)}}const s={filter:n,listener:r};return t.push(s),()=>{const e=t.indexOf(s);e>=0&&t.splice(e,1)}}function d(r,s){const i=s,o=i&&"object"==typeof i&&i.name===r?i:{name:r,envelope:{id:W(),timestampMs:G()},payload:s};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(s)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(U(o,t.filter))try{t.listener(o)}catch{}}}async function p(e){try{return await j().query(e)}catch{return[]}}function f(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}return{publish:d,subscribe:l,subscribeMany(e,t){const n=e.map(e=>l(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:W,publishEvent:function(e){const t=B({id:e.envelope?.id??W(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??G(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{K.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=u(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 d(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:f,getTrace:function(e){return f({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?f(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??"",u(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 u({exportedAt:G(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:p,replay:async function(e){"dispatch"===e.mode&&function(){throw new V('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 s=[];if(t)try{s=await p({name:e.name,since:e.since,until:e.until})}catch{s=[]}const i=function(e,t,n){const r=new Set,s=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}s.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}s.push(e)}const i={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=s.filter(e=>{if(!U(e,i))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,s,{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 i)console.log("[Punica Replay]",e.name,e);else for(const e of i)d(e.name,e);return{count:i.length,events:i}}}}const z=Y();var J={manager:z};let H=A;function Q(){return H}async function Z(){try{const e=j(),t=Q();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??S;return await e.delete({until:G()-n})??0}catch{return 0}}var X=Object.freeze({__proto__:null,createCorrelationId:W,createEventsApi:Y,default:J,getRetentionConfig:Q,manager:z,runEventRetentionCleanup:Z,setRetentionConfig:function(e){H=e??A}});function ee(){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)}`,s=t.timestamp||(new Date).toISOString(),i={...t,id:r,timestamp:s};e=[i,...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 te=ee();var ne={manager:te},re=Object.freeze({__proto__:null,createNotificationsApi:ee,default:ne,manager:te});const se="punica.kernel.policy.v2";function ie(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function oe(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class ae{#m=new Map;constructor(){this.#g()}set(e,t,n){let r=this.#m.get(e);r||(r=new Map,this.#m.set(e,r)),r.set(t,n),this.#y()}get(e,t){return this.#m.get(e)?.get(t)}has(e,t){return this.#m.get(e)?.has(t)??!1}delete(e,t){const n=this.#m.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#m.delete(e),r&&this.#y(),r}list(){const e=[];for(const t of this.#m.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#m.size&&(this.#m.clear(),this.#y())}restoreAll(e){this.#m.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=oe(n);if(!e)continue;let r=this.#m.get(n.key);r||(r=new Map,this.#m.set(n.key,r)),r.set(e,n),t++}return this.#y(),t}#g(){const e=ie();if(e)try{const t=e.getItem(se);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=oe(e);if(!t)continue;let n=this.#m.get(e.key);n||(n=new Map,this.#m.set(e.key,n)),n.set(t,e)}}catch{}}#y(){const e=ie();if(e)try{let t={};try{const n=e.getItem(se);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(se,JSON.stringify(n))}catch{}}}let ce=new ae;function le(){return Date.now()}function ue(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function de(e){return`${e.kind}:${e.id}`}function pe(e,t){return"workspace"===e?`workspace:${t??""}`:e}function fe(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const he="punica.kernel.policy.v1",me="punica.kernel.policy.v2";class ge{#w="execute";#v;#b=new Set;#I=new Map;#k=[];#E=1e3;constructor(e){this.#v=e??new ae,this.#S()}#S(){const e=fe();if(e)try{const t=e.getItem(me);if(t){const e=JSON.parse(t);if(e&&2===e.v)return void("suggest"!==e.mode&&"execute"!==e.mode||(this.#w=e.mode))}const n=e.getItem(he);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#w=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#v.restoreAll(n),this.#y();try{e.removeItem(he)}catch{}return}}}catch{}}#y(){const e=fe();if(e)try{let t={};try{const n=e.getItem(me);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#w,exportedAt:le()};e.setItem(me,JSON.stringify(n))}catch{}}setMode(e){this.#w=e,this.#y()}getMode(){return this.#w}clearApprovals(){this.#v.clear(),this.#b.clear()}#A(e,t,n="info"){try{z.publishEvent({name:e,envelope:{id:z.createCorrelationId(),timestampMs:le(),source:"kernel:policy",kind:n},payload:t})}catch{}}#x(e,t){return`${e}|${t}`}revokeApproval(e){const t=de({kind:e.kind,id:e.id}),n="workspace"===e.scope?pe("workspace",e.workspaceId):pe(e.scope),r=this.#v.delete(t,n);return r&&(this.#C("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.#b.delete(this.#x(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#v.list();if(t)return n;const r=le();return n.filter(e=>!ue(e,r))}hasApproval(e,t,n){const r=de(e),s="workspace"===t?n?.workspaceId?pe("workspace",n.workspaceId):null:pe(t);if(null===s)return!1;const i=this.#v.get(r,s);if(!i)return!1;if(ue(i,le())){const e=this.#x(r,s);return this.#b.has(e)||(this.#b.add(e),this.#A("approval.expired",{kind:i.kind,id:i.id,scope:i.scope,workspaceId:i.workspaceId,expiresAt:i.expiresAt,decidedBy:i.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=de(e),s="workspace"===t?pe("workspace",n?.workspaceId):pe(t),i={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:le(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,chainRef:n?.chainRef};return this.#v.set(r,s,i),this.#C("approval",e,void 0,t,n?.workspaceId),this.#b.delete(this.#x(r,s)),this.#A("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:n?.decidedBy,expiresAt:n?.expiresAt}),i}#C(e,t,n,r,s){this.#k.push({timestampMs:le(),type:e,request:t,decision:n,scope:r,workspaceId:s}),this.#k.length>this.#E&&this.#k.splice(0,this.#k.length-this.#E)}evaluate(e,t){const n=n=>{const r=t,s=r?.correlationId,i=r?.traceId??s;z.publishEvent({name:"policy.evaluated",envelope:{id:z.createCorrelationId(),correlationId:s,traceId:i,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})};if("suggest"===this.#w){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===e.approval){const r={allowed:!0,mode:"execute",requiresApproval:!1};return this.#C("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.#C("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.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}requestApproval(e,t){z.publishEvent({name:"policy.approvalRequested",envelope:{id:z.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:le(),mode:this.#w,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.#w=e.mode);let s=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 i="workspace"===n?pe("workspace",r):pe(n);"string"==typeof i&&i&&(this.#v.has(t,i)||(this.#v.set(t,i,e),s++))}else s=this.#v.restoreAll(r),this.#b.clear();return this.#y(),z.publishEvent({name:"policy.stateImported",envelope:{id:z.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:s,merged:n}}),s}saveTemplate(e,t,n){const r=n??"global";let s=this.#I.get(r);s||(s=new Map,this.#I.set(r,s));const i={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??le(),updatedAtMs:le()};s.set(e,i),this.#y()}getTemplate(e,t){const n=t??"global",r=this.#I.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#I.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#I.get(n);if(!r)return!1;const s=r.delete(e);return s&&this.#y(),s}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:le(),version:1,count:n.length,entries:n},null,2)}}const ye=new ge(ce);var we={manager:ye},ve=Object.freeze({__proto__:null,PolicyManager:ge,default:we,manager:ye});async function be(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(),s=t,i=await n(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:t,workspaceId:i,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:t},trace:{traceId:s,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 Ie(e,t,n,r){let s=e;if(s||(s=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,s=n?.payload??n?.event?.payload;if("ai.planGenerated"===r&&s?.plan?.planId)return s.plan}}catch{}return null}(),s&&r(s)),!s)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 be(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}(s,t,n)}const ke={estimate:e=>Math.ceil(e.length/4)};function Ee(){return ke}function Se(e){const t=Ee();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 Ae={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 xe="[elided tool result:";function Ce(e){const t=(e.content??"").length;return`${xe} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function Te(e,t){let n=0;for(let r=e.length-1;r>0;r--){const s=e[r].role;if(("assistant"===s||"user"===s)&&(n++,n>=t))return r}return 1}async function Me(e,t,n,r){const s=Se(e);if(s<=t.maxContextTokens)return{messages:[...e],compacted:!1,strategy:"none",preTokens:s,postTokens:s,estSavedTokens:0};const i=Math.floor(.6*t.maxContextTokens),o=Te(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(xe)?{...e,content:Ce(e)}:e);let c=Se(a);if(c<=i||!t.summarizeWhenOver||!n){const e=c<s;return{messages:a,compacted:e,strategy:e?"elide":"none",preTokens:s,postTokens:c,estSavedTokens:s-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??{}),i=(t?.text??"").trim();if(i){const e=[a[0],{role:"assistant",content:`[conversation summary]\n${i}`},...u];return c=Se(e),{messages:e,compacted:!0,strategy:"summarize",preTokens:s,postTokens:c,estSavedTokens:s-c}}}catch{}return{messages:a,compacted:c<s,strategy:"elide",preTokens:s,postTokens:c,estSavedTokens:s-c}}const Ne=Object.freeze({narrowThreshold:24,catalogTopN:100,topCategories:64,hotSetSize:40});function Pe(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.agent?.toolSelection}catch{return}}function _e(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function Le(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}async function Re(e,t,n,r){try{const s=await r(t,function(e,t){return"number"==typeof e.rankLimit&&e.rankLimit>0?Math.floor(e.rankLimit):Math.max(2*e.catalogTopN,t)}(n,e.length))??[],i=new Map;let o=!1,a=0;s.forEach((e,t)=>{null!=e?.id&&i.set(String(e.id),t),"number"==typeof e?.score&&(o=!0,e.score>a&&(a=e.score))});const c=function(e){const t=new Map;for(const n of e){const e=Le(String(n.id)),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}(e);if(0===i.size||o&&a<=1e-9)return function(e,t){const n=[],r=[...e.values()],s=new Array(r.length).fill(0);let i=!0;for(;i&&n.length<t;){i=!1;for(let e=0;e<r.length&&n.length<t;e++){const t=s[e];t<r[e].length&&(n.push(r[e][t]),s[e]=t+1,i=!0)}}return n}(c,n.catalogTopN);const l=e=>i.has(String(e.id))?i.get(String(e.id)):Number.POSITIVE_INFINITY,u=[...c.keys()],d=new Map(u.map(e=>[e,Math.min(...c.get(e).map(l))])),p=new Map(u.map((e,t)=>[e,t]));u.sort((e,t)=>{const n=d.get(e)-d.get(t);return 0!==n?n:p.get(e)-p.get(t)});const f=[];for(const e of u.slice(0,n.topCategories)){const t=c.get(e),n=t.filter(e=>i.has(String(e.id))).sort((e,t)=>l(e)-l(t)),r=t.filter(e=>!i.has(String(e.id)));f.push(...n,...r)}return f.slice(0,n.catalogTopN)}catch{return e}}async function $e(e){const{entries:t,intent:n,budget:r,rank:s}=e,i=new Set((e.pinnedIds??[]).map(String)),o=i.size?t.filter(e=>i.has(String(e.id))):[],a=function(e,t,n,r=[]){const s=[],i=new Set,o=new Map,a=(e,t)=>{const n=String(e.id);if(s.push(e),i.add(n),t){const e=Le(n);o.set(e,(o.get(e)??0)+1)}};for(const e of r){if(s.length>=t)break;null==e?.id||i.has(String(e.id))||a(e,!1)}for(const r of e){if(s.length>=t)break;const e=String(r?.id??"");e&&!i.has(e)&&((o.get(Le(e))??0)>=n||a(r,!0))}for(const n of e){if(s.length>=t)break;const e=String(n?.id??"");e&&!i.has(e)&&a(n,!0)}return s}(await Re(t,n,r,s),r.hotSetSize,function(e){return"number"==typeof e.perCategoryCap&&e.perCategoryCap>0?Math.floor(e.perCategoryCap):Math.max(2,Math.ceil(e.hotSetSize/10))}(r),o),c=new Set(a.map(e=>String(e.id)));return{hot:a,deferred:t.filter(e=>!c.has(String(e.id)))}}const Oe=["capability.search","capability.describe"];function De(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function je(e,t,n,r){const s=punica.kernel?.Events?.manager;s&&s.publishEvent({name:e,envelope:{id:s.createCorrelationId(),correlationId:t,timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}function Fe(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function qe(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function Be(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 Ue(e,t,n){const r=await e("capability.schemaExport",{filter:t.toolFilter,mode:"ai-tools"},n);let s=r?.capabilities??[];if(console.log("[AgentLoop] schemaExport raw catalog",{total:s.length,byCategory:s.reduce((e,t)=>{const n=Le(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:s.map(e=>String(e.id))}),t.toolFilter)return{hot:s.map(Fe).sort(qe),deferredIndex:[]};const i=s.filter(e=>Oe.includes(String(e.id)));s=s.filter(e=>!Oe.includes(String(e.id))&&(!function(e){const t=String(e?.id??"");return!("core"!==String(e?.origin??"core")||!t.startsWith("ai.")&&(t.startsWith("capability.")?Oe.includes(t):!t.startsWith("llm.")))}(e)&&(!(!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)))));const o=function(e){const t={...Ne};for(const n of[Pe(),e])if(n){for(const e of Object.keys(t))_e(n[e])&&(t[e]=Math.floor(n[e]));for(const e of["perCategoryCap","rankLimit"])_e(n[e])&&(t[e]=Math.floor(n[e]))}return t.catalogTopN=Math.max(t.catalogTopN,t.hotSetSize),t.topCategories=Math.max(t.topCategories,t.catalogTopN),t}("number"==typeof t.hotSetSize&&t.hotSetSize>0?{hotSetSize:Math.floor(t.hotSetSize)}:void 0);if(console.log("[AgentLoop] after default-exclude filter",{remaining:s.length,includeIvyNodes:!!t.includeIvyNodes,includeMcp:!!t.includeMcp,allowedMcpServers:t.allowedMcpServers??[],willTier:!1!==t.deferToolLoading&&s.length>o.narrowThreshold,narrowThreshold:o.narrowThreshold}),s.length<=o.narrowThreshold)return{hot:s.map(Fe).sort(qe),deferredIndex:[]};const a=async(t,r)=>{const s=await e("capability.recommend",{intent:t,limit:r},n);return s?.recommendations??[]};if(!1===t.deferToolLoading){return{hot:(await Re(s,t.query,o,a)).map(Fe).sort(qe),deferredIndex:[]}}const{hot:c,deferred:l}=await(u={entries:s,intent:t.query,budget:o,pinnedIds:t.pinnedTools,rank:a},$e(u));var u;const d=new Set(c.map(e=>String(e.id))),p=i.length===Oe.length?i.map(Fe):[{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}}}}],f=l.map(e=>({id:String(e.id),line:Be(e),category:Le(String(e.id))})).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0);return console.log("[AgentLoop] tiered catalog",{hot:c.length,deferred:f.length,hotSetSize:o.hotSetSize,pinned:t.pinnedTools??[],hotIds:[...d]}),{hot:[...p,...c.map(Fe)].sort(qe),deferredIndex:f}}async function Ve(e,t,n,r){const s={id:t.id,name:t.name,arguments:t.arguments,status:"success"};try{const r=await e(t.name,t.arguments,n);return{...s,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{...s,status:"failed",error:String(e?.message??e)}}const i=String(n.trace?.traceId??n.sessionId??""),o=await function(e,t,n){return new Promise(r=>{const s=punica.kernel.Events.manager;let i=!1;const o=e=>{if(!i){i=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=s.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed"],n=>{const r=n?.payload?.payload??n?.payload,s=r?.pending;s?.id===e&&(s?.traceId&&s.traceId!==t||o("ai.approvalRecorded"===n?.name?"approved":"dismissed"))})??void 0,c=setInterval(()=>{n()&&o("cancelled")},250),l=setTimeout(()=>o("timeout"),18e4)})}(t.name,i,r);if("approved"!==o)return{...s,status:"blocked",error:`tool "${t.name}" not approved (${o})`};try{const r=await e(t.name,t.arguments,n);return{...s,status:"success",resultPayload:r}}catch(e){return{...s,status:"failed",error:String(e?.message??e)}}}async function Ke(e,t,n,r,s,i){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Ye(n)}\nRejected arguments:\n${Ye(r)}\nValidation errors: ${s}\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:i.sessionId},i);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 We(e,t,n,r,s){let i=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Ve(e,{...t,arguments:i},r,s);if("failed"!==l.status||!De(l.error))return o?{...l,arguments:i,repaired:!0}:l;if(a=l.error??"",2===c||s())break;const u=await Ke(e,t.name,n,i,a,r);if(!u)break;i=u,o=!0}const c={id:t.id,name:t.name,arguments:i,status:"failed",error:a||"input validation failed"};return o&&(c.repaired=!0),c}function Ge(e){return Ee().estimate(e)}function Ye(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function ze(e,t,r,s){const i=punica.kernel.Events.manager,o=s??i.createCorrelationId(),a="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,c=(l=e.profile,Ae[l??"balanced"]);var l;const u=[],d=e.sessionId?punica.kernel?.AI?.sessions:void 0,p=[];let f=0;const h=[],m=Date.now();let g=0,y=0,w=0,v=0,b=!1,I=0,k=!1,E=0;const S=(t,n)=>{const r={inputTokens:g,outputTokens:y,totalTokens:w,latencyMs:Date.now()-m,steps:u.length,toolCalls:E};k&&(r.totalCost=I),b&&(r.cacheReadTokens=v);const s={runId:o,finishReason:t,steps:u,usage:r};if(void 0!==n&&(s.finalText=n),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:u.length}),(t=>{if(d&&e.sessionId&&0!==f)try{const n=[{role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}},...h];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&&f>0)try{d.recordUsage?.(e.sessionId,r)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return je("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),s};je("ai.agentStarted",o,"info",{runId:o,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{}});const A=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!A)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),S("error");const x=await n(),C=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,x,r);let T;e.sessionId&&(C.conversationId=e.sessionId);try{T=await Ue(A,e,C)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),S("error")}const M=[...T.hot];console.log("[AgentLoop] tool catalog built",{hot:M.length,deferred:T.deferredIndex.length,toolFilter:e.toolFilter??null,names:M.map(e=>e.name)});const N=new Map(M.map(e=>[e.name,e.parameters])),P=new Map(T.deferredIndex.map(e=>[e.id,e])),_=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!N.has(String(e.id))).map(Fe).sort(qe);for(const e of n)M.push(e),N.set(e.name,e.parameters),P.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:M.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."}),e.includeProjectContext)try{const e=function(e){const t=e;if(!t||"object"!=typeof t)return null;const n=[],r=t.workspace;r?.name&&n.push(`Project: ${r.name} (${r.kind}) at ${r.rootUri}`+(r.environment?` [env: ${r.environment}]`:"")),Array.isArray(t.stack)&&t.stack.length&&n.push(`Stack: ${t.stack.join(", ")}`);const s=t.dependencies?.python;s&&n.push(`Python deps (${s.source}, ${s.count}): ${(s.names??[]).join(", ")}`);const i=t.dependencies?.node;i&&n.push(`Node deps (${i.source}, ${i.count}`+(i.dev?` + ${i.dev} dev`:"")+`): ${(i.names??[]).join(", ")}`),t.scripts&&Object.keys(t.scripts).length&&n.push(`Scripts: ${Object.entries(t.scripts).map(([e,t])=>`${e}=${t}`).join(" · ")}`),Array.isArray(t.entrypoints)&&t.entrypoints.length&&n.push(`Entrypoints: ${t.entrypoints.join(", ")}`);const o=t.vcs;return o&&n.push(`VCS: ${o.branch??"(detached)"}`+(o.ahead?` ↑${o.ahead}`:"")+(o.behind?` ↓${o.behind}`:"")+` · ${o.dirtyFiles} dirty`),t.readme&&n.push(`README: ${t.readme}`),Array.isArray(t.layout)&&t.layout.length&&n.push(`Layout${t.truncated?" (truncated)":""}:\n${t.layout.join("\n")}`),n.length?"Workspace orientation (already loaded — do not re-derive; call tools only for detail beyond this):\n"+n.join("\n"):null}(await A("workspace.projectContext",{},C));e&&p.push({role:"system",content:e})}catch(e){console.warn("[AgentLoop] projectContext orientation unavailable:",e)}if(T.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."}}(T.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}:{}}),f=p.length;let L=0;for(let n=0;n<a;n++){if(t())return S("cancelled");let r,s=!1;if(Se(p)>c.maxContextTokens){const e=await Me(p,c,A,C);e.compacted&&(p.splice(0,p.length,...e.messages),L=0,s=!0,je("ai.agentContextCompacted",o,"info",{runId:o,step:n,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const i=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:n,messageCount:p.length,toolsSent:M.length,toolChoice:"auto",toolNames:M.map(e=>e.name)});const t={stableToolsAndSystem:!0,stableMessagePrefix:L,cacheKey:o};r=await A("llm.chatStream",{messages:p,tools:M,toolChoice:"auto",correlationId:o,cacheHints:t,...e.profile?{profile:e.profile}:{}},C),L=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),S("error")}if(t())return S("cancelled");const a=Date.now()-i,l=(r.text??"").trim(),d="string"==typeof r.thinking?r.thinking:void 0,f=r.toolCalls??[],m={index:n,assistantText:l||void 0,thinking:d,toolCalls:[],latencyMs:a},x=r.usage,T=r.meta;x?(m.usage=x,g+=x.inputTokens??0,y+=x.outputTokens??0,w+=x.totalTokens??(x.inputTokens??0)+(x.outputTokens??0),"number"==typeof x.cacheReadInputTokens&&(v+=x.cacheReadInputTokens,b=!0)):T&&(m.usage={inputTokens:T.promptTokens,outputTokens:T.completionTokens,totalTokens:T.promptTokens+T.completionTokens},g+=T.promptTokens,y+=T.completionTokens,w+=T.promptTokens+T.completionTokens),T&&"number"==typeof T.totalCost&&(I+=T.totalCost,k=!0);const R={runId:o,step:n,estToolDefTokens:Ge(JSON.stringify(M)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+Ge(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+Ge(t.content??""),0),toolCount:M.length,deferredToolCount:P.size,compactionApplied:s};if(m.usage&&(R.reportedInputTokens=m.usage.inputTokens,R.reportedOutputTokens=m.usage.outputTokens,"number"==typeof m.usage.cacheReadInputTokens&&(R.cacheReadTokens=m.usage.cacheReadInputTokens)),je("ai.agentTurnUsage",o,"info",{...R}),0===f.length)return u.push(m),je("ai.agentStep",o,"info",{runId:o,turn:m}),S("final",l);u.push(m),je("ai.agentStep",o,"info",{runId:o,turn:m});const $=f.map(e=>`${e.name}(${Ye(e.arguments)})`).join(", "),O={role:"assistant",content:l?`${l}\n[calling tools: ${$}]`:`[calling tools: ${$}]`,toolCalls:f.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};p.push(O),h.push(O);let D=!1;for(const e of f){if(t())return S("cancelled");if(je("ai.agentToolCall",o,"info",{runId:o,toolCall:{id:e.id,name:e.name,arguments:e.arguments},status:"running"}),!N.has(e.name)&&P.has(e.name))try{_(await A("capability.describe",{ids:[e.name]},C))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const r=await We(A,e,N.get(e.name),C,t);m.toolCalls.push(r),E++,"success"===r.status&&"capability.describe"===r.name&&_(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?Ye(r.resultPayload).slice(0,300):void 0}),je("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const s={role:"tool",content:"success"===r.status?Ye(r.resultPayload,c.toolResultMaxChars):`ERROR: ${r.error??"tool failed"}`,name:r.name,toolCallId:r.id};p.push(s),h.push(s),"blocked"===r.status&&(D=!0)}if(D)return S("blocked")}return S("maxSteps")}function Je(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 He={KERNEL:{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"},RUNTIME:{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"},SHELL:{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",PANEL_LAYOUT:"shell.panelLayout"},FLOW:{SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},EXTENSIONS:{MANAGER:"extensions.manager"}},Qe={SHELL:{TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},AI:{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"},POLICY:{EXPORT:"policy.export",IMPORT:"policy.import",LIST_APPROVALS:"policy.listApprovals",SET_MODE:"policy.setMode",SHOW_MODE:"policy.showMode"},MCP:{CONNECT:"mcp.connect",DISCONNECT:"mcp.disconnect",LIST_SERVERS:"mcp.listServers",LIST_TOOLS:"mcp.listTools"},WORKFLOW:{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 Ze(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 Xe(e,t,n,r,s,i,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:s,parentSpanId:i,timestampMs:Date.now(),source:o,kind:t},payload:a})}const et="punica.kernel.ai.sessions.index.v1";function tt(e){return`punica.kernel.ai.session.${e}.v1`}function nt(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const rt=new class{readIndex(){const e=nt();if(!e)return[];try{const t=e.getItem(et);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=nt();if(t)try{t.setItem(et,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=nt();if(t)try{const n=t.getItem(tt(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=nt();if(t)try{t.setItem(tt(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=nt();if(t)try{t.removeItem(tt(e))}catch{}}};let st=rt;function it(){return st}const ot="New chat";function at(){return Date.now()}function ct(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${at().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function lt(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:at(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function ut(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function dt(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 pt=new class{#T=null;#M=null;#N=new Map;#P=!1;#_=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 s=e?.envelope?.correlationId,i=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:s,...o?{traceId:o}:{},workspaceId:i,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#N)}),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#T=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(Qe.POLICY.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(Qe.POLICY.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(Qe.POLICY.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=Je(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),s=e.document.createElement("a");s.href=r,s.download=`punica-policy-export-${Date.now()}.json`,e.document.body.appendChild(s),s.click(),e.document.body.removeChild(s),URL.revokeObjectURL(r)}else console.log("[Policy] Export:\n"+n)}}),t.registerCommand(Qe.POLICY.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(Qe.POLICY.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`+Je(e,2))}}),t.registerCommand(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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 s="always"===r?"always":"workspace"===r?"workspace":"once";e.approvePending(n,s)||console.warn("[AI] Failed to approve pending",n)}}),t.registerCommand(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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(Qe.AI.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"+Je(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+Je(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Qe.AI.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(),s=t?.__punica?.traceId??r,i=t?.__punica?.spanId??punica.kernel.Events.manager.createCorrelationId(),o=t?.__punica?.source??"kernel:ai",a=e?.source;Xe("ai.request","info",r,s,i,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:Ze(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();Xe("ai.response","result",r,s,u,i,o,{kind:"summarize",output:{summaryPreview:Ze(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),Xe("ai.summaryGenerated","result",r,s,punica.kernel.Events.manager.createCorrelationId(),u,o,{summary:l,usage:c?.usage,modelId:c?.modelId,provider:c?.provider,source:a})}catch(e){Xe("ai.response","error",r,s,punica.kernel.Events.manager.createCorrelationId(),i,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.#M,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#_){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#P=e;for(const t of this.#_.values())t.cancelRequested=e,e&&t.controller.abort()}}})}getLastPlan(){return this.#T}getPendingApprovals(){return e=this.#N,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.#N)}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.#N)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#T=e);const t=await Ie(this.#T,this.#M,()=>this.#P,e=>{this.#T=e});return this.#M=t,this.#P=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#_.set(t,n);try{return await ze(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#_.delete(t)}}},ft=new class{#L;create(e){const t=it(),n={sessionId:ct("sess"),title:e?.title?.trim()||ot,createdAtMs:at(),updatedAtMs:at(),messageCount:0,tokenEstimate:0};e?.workspaceId&&(n.workspaceId=e.workspaceId);const r={version:1,meta:n,transcript:[]};t.writeSession(r);const s=t.readIndex();return s.push(n),this.#R(s,n),t.writeIndex(s),lt("ai.sessionCreated",n),{...n}}list(e){const t=it().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return it().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#$(e,e=>{e.title=n});return!!r&&(lt("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#$(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(lt("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=it(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[s]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),lt("ai.sessionDeleted",s),!0}appendMessages(e,t,n){if(0===t.length)return;const r=it(),s=r.readSession(e);if(!s)return;const i=t.map(e=>{const t={...e,id:e.id||ct("msg"),createdAtMs:e.createdAtMs||at(),content:e.content.length>16e3?e.content.slice(0,16e3)+"…":e.content};return n?.runId&&!t.runId&&(t.runId=n.runId),t});s.transcript.push(...i),s.transcript.length>200&&s.transcript.splice(0,s.transcript.length-200);const o=s.meta;if(o.messageCount=s.transcript.length,o.updatedAtMs=at(),n?.runId&&(o.lastRunId=n.runId),o.tokenEstimate=s.transcript.reduce((e,t)=>{return e+(n=t.content,Math.ceil(n.length/4));var n},0),o.title===ot){const e=s.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:ot}(e.content))}r.writeSession(s),this.#O(o),lt("ai.sessionUpdated",o,{appendedCount:i.length,runId:n?.runId});const a=this.#L;a?.shouldCompact(s)&&Promise.resolve().then(()=>a.compact(s)).then(t=>{const n=it().readSession(e);n&&(n.contextView=t,it().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=it().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(...ut(n.messages).map(dt)),e}return ut(t.transcript.slice(-40)).map(dt)}setCompactor(e){this.#L=e}recordUsage(e,t){const n=this.#$(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=at(),e.usage=n});return!!n&&(lt("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#$(e,t){const n=it(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=at(),n.writeSession(r),this.#O(r.meta),{...r.meta}}#O(e){const t=it(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#R(e,t){const n=it(),r=e=>e.workspaceId===t.workspaceId;let s=e.filter(r);for(;s.length>50;){const i=s.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(!i)break;const o=e.findIndex(e=>e.sessionId===i.sessionId);o>=0&&e.splice(o,1),n.deleteSession(i.sessionId),lt("ai.sessionDeleted",i,{evicted:!0}),s=e.filter(r)}}};ft.setCompactor(function(){const e=Ae.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=Te([{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(xe)?{...e,content:Ce(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());var ht={manager:pt,sessions:ft},mt=Object.freeze({__proto__:null,default:ht,manager:pt,sessions:ft});const gt=new class{#D=new Map;#j=new Map;#F=new Map;#q;registerProductOriginResolver(e){this.#q=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.#D.has(e.id)){const n=this.#D.get(e.id),r=n?.originExtension||this.#F.get(e.id),s=t||e.originExtension;if(!r||!s||r!==s)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.#q&&(t=this.#q(e.productId)),t&&(e.originExtension=t,this.#F.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.#D.set(e.id,e),this.#j.set(e.id,e.capability)}unregister(e){this.#D.delete(e),this.#j.delete(e),this.#F.delete(e)}unregisterByOrigin(e){const t=[];this.#F.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>this.unregister(e))}get(e){return this.#D.get(e)}list(e=!1){const t=Array.from(this.#D.values());return e?t.filter(e=>{const t=e.originExtension||this.#F.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.#F.get(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0}))}has(e){return this.#D.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#F.get(e);return!n||this.#B(n)}getCapability(e){return this.#j.get(e)}listCapabilities(){return Array.from(this.#j.values())}};async function yt(e){const{primaryModelId:t,count:n,exclude:r}=e,s=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(!s||!Array.isArray(s.installed)||0===s.installed.length)return t?[t]:[];const i=new Set(s.installed.map(e=>e.id)),o=[],a=e=>{e&&i.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 s.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function wt(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=gt.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,s=[];s.push("Assess the risk level for this task:"),s.push(""),s.push(`Instruction Class: ${e.id}`),s.push(`Role: ${e.role}`),s.push(""),s.push("User Prompt:"),s.push(t.userPrompt),s.push(""),s.push("Context:"),s.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),s.push(`- File Path: ${r?.filePath??"N/A"}`),s.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),s.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),s.push(""),s.push("Consider:"),s.push("- Is this production code?"),s.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),s.push("- Is it a critical business function?"),s.push("- Does it handle sensitive data?"),s.push("- Is it a simple utility or a complex system?"),s.push(""),s.push('Respond with ONLY one word: "low", "medium", or "high".');const i=s.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:i}],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:i}],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 s=[];return s=r&&r.length>0?r.slice():await yt({primaryModelId:t,count:3}),{strategy:s.length>1?"multi":"single",modelIds:s.length?s:[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 vt(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 bt(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function It(){const e=globalThis;return e.punica?.runtime?.fs}function kt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Et={type:"ai",id:"llm:context"},St={kind:"ai",id:"context-builder"};async function At(e){if(e.filePath)try{const t=bt(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:Et,origin:St,trace:{traceId:kt()},policy:{mode:"execute"}}):await(It()?.readFile?.(e.filePath));if(!n)return;const r=5e3,s=n.length>r?n.slice(0,r)+"\n... (truncated)":n;return`File content (${e.filePath}):\n\`\`\`\n${s}\n\`\`\``}catch{return}}async function xt(e){try{const t=bt(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Et,origin:St,trace:{traceId:kt()},policy:{mode:"execute"}}):await(It()?.getFileTree?.());if(!n||!Array.isArray(n)||0===n.length)return;const r=n.filter(e=>!e.isDirectory).length,s=n.filter(e=>e.isDirectory).length;return`Workspace structure: ${r} files, ${s} 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 Ct(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Tt(){return"undefined"==typeof document?void 0:document}function Mt(){const e=Tt();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 Nt(e){try{const t=Ct();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Mt();if(!n)return;const r=n.getSelection?.(),s=n.getModel?.();if(!r||!s||r.isEmpty())return;const i=s.getValueInRange(r),o=String(i??"").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 Pt(){try{const e=Ct();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=Mt();if(e){const n=e.getPosition?.(),r=e.getModel?.();if(n&&r){const e=n.lineNumber,s=n.column,i=r.getOffsetAt(n);t.push(`Cursor position: Line ${e}, Column ${s} (offset: ${i})`)}}}catch{}try{const e=Tt();if(e){const n=e.querySelector('[id*="content-tabs"]');if(n){const e=n.querySelectorAll('[role="tab"]');e.length>1&&t.push(`Open files: ${e.length} tabs`)}}}catch{}return t.length>0?`Editor State:\n${t.join("\n")}`:void 0}catch{return}}function _t(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Lt={type:"ai",id:"llm:context"},Rt={kind:"ai",id:"context-builder"};async function $t(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}(),s=r?await r.call("vcs.status",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Lt,origin:Rt,trace:{traceId:_t()},policy:{mode:"execute"}}):await t.status();if(s){const e=[];s.current&&(e.push(`Branch: ${s.current}`),s.tracking&&e.push(`Tracking: ${s.tracking}`),s.ahead&&s.ahead>0&&e.push(`Ahead: ${s.ahead}`),s.behind&&s.behind>0&&e.push(`Behind: ${s.behind}`));const t=s.modified??[],r=s.staged??[],i=s.created??[],o=s.deleted??[],a=s.renamed??[],c=(t,n,r)=>{if(0===n.length)return;const s=n.slice(0,r).join(", "),i=n.length>r?"...":"";e.push(`${t} (${n.length}): ${s}${i}`)};c("Staged",r,5),c("Modified",t,5),c("Created",i,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??"",s=(e.message??"").split("\n")[0].substring(0,60);return` ${t} ${n} ${r?`(${r})`:""}: ${s}${s.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),s=[];t?.name&&s.push(`Current: ${t.name}`),r.length>0&&s.push(`Other branches: ${r.map(e=>e.name).filter(Boolean).join(", ")}`),s.length>0&&n.push(`Branches:\n${s.join("\n")}`)}}catch{}return n.length>0?n.join("\n\n"):void 0}async function Ot(){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})`:"",s=e.startedAt?new Date(e.startedAt).toLocaleDateString():"";return` ${n}: ${t}${r}${s?` (${s})`:""}`}).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 jt="problems.getDiagnostics";function Ft(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===jt))return;let r;try{r=t.executeCommand?.(jt)}catch{return}if(!r||!Array.isArray(r)||0===r.length)return;const s=e.filePath?r.filter(t=>t.file===e.filePath):r;if(0===s.length)return;const i=s.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=s.length;return`Diagnostics (${o} ${1===o?"issue":"issues"}):\n${i}${o>10?`\n ... and ${o-10} more`:""}`}catch{return}}function qt(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 Bt=new class{#U;#V=[];constructor(e){this.#U=Math.max(1,e?.maxRecords??1e4)}record(e){this.#V.push(e),this.#V.length>this.#U&&this.#V.splice(0,this.#V.length-this.#U)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,s=new Map;let i=0,o=0,a=0,c=0,l=0;for(const e of this.#V){if(e.timestamp<n||e.timestamp>r)continue;const u=qt(t,e),d=s.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,s.set(u,d),i+=e.totalCost,o+=1,a+=e.promptTokens,c+=e.completionTokens,l+=e.cachedPromptTokens??0}const u=Array.from(s.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:i,totalCalls:o,totalPromptTokens:a,totalCompletionTokens:c,totalCachedPromptTokens:l,byKey:u}}clear(){this.#V.length=0}};function Ut(e){return e.remaining[0]}function Vt(e,t,n,r){if(e.terminal)return e;const s=function(e,t){return"error"===e?t.onError??"fail":"timeout"===e?t.onTimeout??"fail":t.onRateLimit??"next"}(t,n),i=e.remaining[0];if(!i)return{...e,terminal:!0,lastError:r??e.lastError};if("fail"===s)return{...e,attempted:[...e.attempted,i],position:e.position+1,remaining:[],terminal:!0,pendingQueue:!1,lastError:r??e.lastError};if("queue"===s)return{...e,pendingQueue:!0,lastError:r??e.lastError};const o=e.remaining.slice(1);return{...e,position:e.position+1,attempted:[...e.attempted,i],remaining:o,terminal:0===o.length,pendingQueue:!1,lastError:r??e.lastError}}function Kt(e){return{...e,terminal:!0,pendingQueue:!1}}let Wt;function Gt(e){Wt=e}function Yt(e){return!!e&&"string"==typeof e.providerId&&""!==e.providerId.trim()}const zt={onError:"next",onTimeout:"next",onRateLimit:"next"};function Jt(e){const t=e?.status??e?.statusCode;return"number"==typeof t&&(408!==t&&429!==t&&(401!==t&&403!==t&&(t>=400&&t<500)))}function Ht(e){const t=e?.status??e?.statusCode;if(429===t)return"rateLimit";if(408===t||504===t)return"timeout";const n=String(e?.name??"").toLowerCase();if("aborterror"===n||"timeouterror"===n)return"timeout";const r=String(e?.message??e??"").toLowerCase();return r.includes("rate limit")||r.includes("rate_limit")||r.includes("too many requests")||r.includes("429")?"rateLimit":r.includes("timed out")||r.includes("timeout")||r.includes("etimedout")?"timeout":"error"}function Qt(e){const t=e.providerId.trim(),n=t.toLowerCase(),r=n.startsWith("local:")?"local":n.startsWith("remote:")?"remote":void 0;return{providerId:t,...r?{route:r}:{},...e.modelId?{modelId:e.modelId}:{}}}async function Zt(e,t){const r=gt;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 s=r.get(e.instructionClass);if(!s)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(vt(e)),At(e),Promise.resolve(Nt(e)),xt(e),$t(e),Ot(),Promise.resolve(Pt()),Dt(e),Promise.resolve(Ft(e))])).filter(e=>void 0!==e&&e.length>0).join("\n\n"):""}(e.context),i=r?`${r}\n\n${e.userPrompt}`:e.userPrompt,o=await wt(s,e),a={messages:[{role:"system",content:s.systemPrompt},{role:"user",content:i,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??s.temperature??.2,maxTokens:e.options?.maxTokens??s.maxTokens??2e3,responseFormat:s.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(),f=async(t,n)=>{const r=punica.kernel.Events.manager;return await punica.runtime.capabilities.gateway.call(t,{...a,...n},{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"}})},h=(e,t,n)=>{try{const r=punica.kernel.Events.manager;r.publishEvent({name:"llm.fallback",envelope:{id:r.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:s.id,fromProviderId:e,toProviderId:t,reason:n}})}catch{}},m=function(e){const t=e.providerChain;if(Array.isArray(t)&&t.length>0)return t.filter(Yt);if(!Wt)return[];try{const e=Wt();return Array.isArray(e)?e.filter(Yt):[]}catch{return[]}}(s);let g,y;if(m.length>0){let e,t=function(e){return{position:0,attempted:[],remaining:e.slice(),terminal:0===e.length,pendingQueue:!1}}(m);const n=Date.now();for(;!t.terminal;){const n=Ut(t);if(!n)break;const r=Date.now();try{l=await f(c,Qt(n)),d=Date.now()-r,g=t.position,t=Kt(t);break}catch(r){if(e=r,Jt(r))break;const i=Vt(t,Ht(r),s.fallbackPolicy??zt,r);if(i.pendingQueue){t={...i,terminal:!0};break}const o=Ut(i);o&&h(n.providerId,o.providerId,r?.message??"unknown"),t=i}}if(!l)throw e??new Error(`No provider in the chain for "${s.id}" produced a response.`);0===d&&(d=Date.now()-n)}else 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(),i=punica.kernel.Events.manager;try{i.publishEvent({name:"llm.fallback",envelope:{id:i.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:s.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??i.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??i.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(),i=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(s.outputSchema&&"json_object"===s.responseFormat)try{c=JSON.parse(i.text)}catch{}return{res:i,expert:{modelId:i.modelId??t,text:i.text,structured:c,usage:i.usage,latencyMs:o}}}),i=await Promise.all(r);u=i.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,s);l={text:c.text,modelId:c.modelId,provider:i.find(e=>e.expert.modelId===c.modelId)?.res.provider,usage:c.usage},d=Date.now()-t}if(s.outputSchema&&"json_object"===s.responseFormat)try{y=JSON.parse(l.text)}catch(e){return{ok:!1,error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}`,metadata:{instructionClass:s.id,role:s.role,originExtension:s.originExtension,productId:s.productId}}}const w={ok:!0,text:l.text,structured:y,metadata:{instructionClass:s.id,role:s.role,originExtension:s.originExtension,productId:s.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"),i=String(l.modelId??"unknown"),o=0,c={provider:r,model:i,promptTokens:e,completionTokens:t,totalCost:o,latencyMs:d,...void 0!==g?{fallbackChainPosition:g}:{}};Bt.record({capabilityId:s.id,provider:r,model:i,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:s.id,workspaceId:p,meta:c}})}catch{}return w}catch(e){return{ok:!1,error:`LLM invocation failed: ${e?.message??String(e)}`,metadata:{instructionClass:s.id,role:s.role,originExtension:s.originExtension,productId:s.productId}}}}async function Xt(e){return Zt({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 en(e){return Zt({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function tn(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 Zt({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function nn(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function rn(e,t){const n=nn(e).split("/").filter(Boolean),r=nn(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function sn(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function on(e,t){const n=nn(e).split("/").filter(Boolean),r=nn(t).split("/").filter(Boolean);let s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;const i=n.length-s,o=r.slice(s);return[...Array(i).fill(".."),...o].join("/")}async function an(e,t){const n=[];let r=0;const s=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 i=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}i+=r.content.length}const e=on(t,rn(t,nn(r.path)));(e.startsWith("..")||sn(e))&&n.push({path:r.path,error:"Path traversal detected"})}if(i>s)throw new Error(`CodegenBundle exceeds max total size: ${i} > 1048576 bytes`);for(const t of e.files)if(!n.some(e=>e.path===t.path))try{const e=nn(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 s=punica.runtime.capabilities?.gateway;s?await s.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 s=punica.runtime.capabilities?.gateway;s?await s.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 cn={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 ln=new class{api;constructor(){this.api={instructionClassRegistry:gt,invoke:Zt,plan:Xt,generateCode:en,editWorkflow:tn,listInstructionClasses:e=>gt.listSummaries(e),setDefaultProviderChainResolver:Gt}}};var un={manager:ln};const dn={Commands:m,History:y,TimeServer:w,Tasks:E,Events:X,Notifications:re,Policy:ve,AI:mt,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:cn,applyCodegenBundle:an,default:un,manager:ln})};function pn(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__",s=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(`^${s}$`,"i").test(t.path)}(e.pattern,t);default:return!1}}const fn=new class{#K=[];register(e){this.#K=this.#K.filter(t=>t.id!==e.id),this.#K.push({priority:0,...e}),this.#K.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#K=this.#K.filter(t=>t.id!==e)}clear(){this.#K=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#K){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>pn(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.#K.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>pn(t,e))}).map(e=>({opener:e,command:e.command}))}};let hn,mn,gn,yn,wn,vn;function bn(){if(hn)return hn;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return hn=punica.runtime.resources,hn}function In(){if(mn)return mn;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return mn=e,mn}function kn(){if(yn)return yn;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return yn=e,yn}function En(){if(wn)return wn;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function Sn(){if(vn)return vn;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return vn=e,vn}function An(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 xn(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 Cn=An({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 Tn(){return Cn.get()}function Mn(e){Cn.set(e),e&&xn({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Nn(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 Pn=Symbol("punica.llm.gatewayGovernedAi");let _n,Ln,Rn;function $n(){if(_n)return _n;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return _n=punica.runtime.llm,_n}function On(e){if(_n=e,Ln=void 0,Rn=void 0,!e)return;const t=e;Nn("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class Dn{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 jn=null;function Fn(){return jn||(jn=new Dn),jn}class qn{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 Bn{providerSession;id;providerId;language;kernelspec;languageRuntime;constructor(e,t,n,r,s,i){this.providerSession=e,this.id=t,this.providerId=n,this.language=r,this.kernelspec=s,this.languageRuntime=i}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},s=this.languageRuntime.prepare(e,r);return this.providerSession.run(s,n,t)}async interrupt(){return this.providerSession.interrupt()}async restart(){return this.providerSession.restart()}async close(){return this.providerSession.close()}}const Un={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}}},Vn={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}}},Kn={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},Wn={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},Gn={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 Yn(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 zn{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),s=await t.openSession({...e,kernelspec:r}),i=Yn("session");return new Bn(s,i,t.id,e.language,r,n)}}class Jn{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 Hn=null;function Qn(){return Hn||(Hn=new Jn),Hn}class Zn{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 Xn{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 er=null;function tr(){return er||(er=new Xn),er}class nr{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 rr{#W=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#W.set(e.id,e)}get(e){return this.#W.get(e)}list(){return Array.from(this.#W.values())}select(e){return this.list().find(t=>t.canRun(e))}}let sr=null;function ir(){return sr||(sr=new rr),sr}function or(e,t){const n=Math.min(e.length,t.length);let r=0,s=0,i=0;for(let o=0;o<n;o++)r+=e[o]*t[o],s+=e[o]*e[o],i+=t[o]*t[o];return 0===s||0===i?0:r/(Math.sqrt(s)*Math.sqrt(i))}const ar="default";class cr{#G=new Map;#Y(e){const t=e||ar;let n=this.#G.get(t);return n||(n=new Map,this.#G.set(t,n)),n}upsert(e,t=ar){const n=this.#Y(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=ar){const r=this.#Y(n),s=[];for(const t of r.values())s.push({id:t.id,score:or(e,t.vector),text:t.text,metadata:t.metadata});return s.sort((e,t)=>t.score-e.score),s.slice(0,Math.max(0,t))}delete(e,t=ar){const n=this.#Y(t);for(const t of e)n.delete(t)}clear(e=ar){this.#G.delete(e||ar)}count(e=ar){return this.#Y(e).size}export(e=ar){return Array.from(this.#Y(e).values())}import(e,t=ar){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#G.set(t||ar,n)}}const lr=".punica/vectors";class ur{#v=new cr;#z=new Set;#J(){try{return punica.runtime?.fs}catch{return}}#H(e){return`${lr}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#Q(e){const t=e||"default";if(this.#z.has(t))return;this.#z.add(t);const n=this.#J();if(n?.readFile)try{const e=await n.readFile(this.#H(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#v.import(r.records,t)}catch{}}async#Z(e){const t=this.#J();if(t)try{if(t.mkdir)try{await t.mkdir(lr)}catch{}const n={version:1,records:this.#v.export(e)},r=this.#H(e),s=JSON.stringify(n);try{await t.updateFileContent(r,s)}catch{await t.createFileWithContent(r,s)}}catch(e){console.warn("[Runtime.vectors] Failed to persist collection:",e)}}async upsert(e,t){const n=t?.collection??"default";await this.#Q(n),this.#v.upsert(e,n),await this.#Z(n)}async query(e){const t=e.collection??"default";return await this.#Q(t),this.#v.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#Q(n),this.#v.delete(e,n),await this.#Z(n)}async clear(e){const t=e?.collection??"default";await this.#Q(t),this.#v.clear(t),await this.#Z(t)}async count(e){const t=e?.collection??"default";return await this.#Q(t),this.#v.count(t)}}let dr,pr,fr;function hr(){return dr||(pr||(pr=new ur),pr)}function mr(){if(!fr)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 fr}var gr;!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"}(gr||(gr={}));class yr extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const wr=new class{#X=new Map;#ee=new Map;registerCapability(e){if(!e.name)throw new yr(gr.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new yr(gr.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 yr(gr.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.#X.has(e.name))throw new yr(gr.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 yr(gr.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 yr(gr.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.#te(t,e.name);if(n)throw new yr(gr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#X.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{}}#te(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#X.get(e);if(!r?.requires)return null;for(const s of r.requires){const r=this.#te(s,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#X.has(e.name))throw new yr(gr.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ee.set(e.name,e)}getSpec(e){return this.#X.get(e)}getProvider(e){return this.#ee.get(e)}hasCapability(e){return this.#X.has(e)}hasProvider(e){return this.#ee.has(e)}listCapabilities(){return Array.from(this.#X.keys())}getAllSpecs(){return Array.from(this.#X.values())}clear(){this.#X.clear(),this.#ee.clear()}};function vr(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 br(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:Sr(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}const Ir=["write","delete","remove","modify","destroy","create","update","install","publish","process","spawn","exec","run"],kr=["network","http","fetch","request","upload","download"],Er=["read","list","get","query","inspect","search"];function Sr(e){if(!e||0===e.length)return"none";let t="none";for(const n of e){if("string"!=typeof n)continue;const e=n.toLowerCase(),r="none"===e?"none":Ir.some(t=>e.includes(t))?"write":kr.some(t=>e.includes(t))?"network":Er.some(t=>e.includes(t))?"read":"write";if("write"===r)return"write";"network"===r?t="network":"read"===r&&"none"===t&&(t="read")}return t}const Ar=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function xr(){const e=globalThis;return e.punica?.extensions?.manager}function Cr(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function Tr(){const e=globalThis;return e.punica?.flow?.registry}function Mr(){const e=globalThis;return e.punica?.flow?.agents}function Nr(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const Pr={core:function(e){const t=wr.getSpec(e);if(t)return{origin:"core",definition:vr(t)}},extension:function(e){const t=xr();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=Cr();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=Tr();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=Mr();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=Nr();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},_r={core:function(){return wr.getAllSpecs().map(e=>({origin:"core",definition:vr(e)}))},extension:function(){const e=xr();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=Cr();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=Tr();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=Mr();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=Nr();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Lr={getCapability(e){for(const t of Ar){const n=Pr[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,s=[];for(const e of Ar)if(!t||t.has(e))for(const t of _r[e]()){const e=t.definition.id;r.has(e)||(r.add(e),s.push(t))}return s},hasCapability(e){return void 0!==this.getCapability(e)}};function Rr(e,t,n){switch(e){case"mcp":return function(e,t){const{mcpServerId:n,mcpToolName:r}=t;return{name:e.id,async execute(t,s){const i=globalThis.punica?.runtime?.mcp;if(!i?.callTool)throw new yr(gr.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 yr(gr.CAPABILITY_PROVIDER_MISSING,`MCP capability "${e.id}" is missing serverId or toolName metadata`,{capability:e.id,origin:"mcp"});return await i.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 yr(gr.CAPABILITY_PROVIDER_MISSING,`LLM kernel API is not initialized — cannot invoke instruction-class capability "${e.id}".`,{capability:e.id,origin:"instruction-class"});const s=null!==t&&"object"==typeof t?t:{},i="string"==typeof s.instructionClass?s.instructionClass:e.id,o="string"==typeof s.userPrompt?s.userPrompt:"string"==typeof s.prompt?s.prompt:JSON.stringify(t);return await r.invokeLlmCapability({instructionClass:i,userPrompt:o,context:s.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 yr(gr.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 s="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,i=await r.run(e.id,{input:t??{},timeoutMs:s});return i?.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 yr(gr.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 s="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,i=await r.run(e.id,{input:t??{},timeoutMs:s});return i?.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 yr(gr.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 yr(gr.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let $r={recordSpan:()=>{}};function Or(e){try{$r.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function Dr(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=n,o={capability:s,"actor.type":i.actor.type,"origin.kind":i.origin.kind};i.actor.extensionName&&(o["actor.extension"]=i.actor.extensionName),i.origin.extension&&(o["origin.extension"]=i.origin.extension),i.workspaceId&&(o["workspace.id"]=i.workspaceId),r.tags={...r.tags,...o};try{const e=await t();return r.durationMs=Date.now()-r.startTimeMs,Or({invocationId:n.invocationId,capability:s,traceId:i.trace.traceId,spanId:n.invocationId,parentSpanId:i.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:i.trace.traceId,spanId:i.trace.parentSpanId??n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"error"},payload:{invocationId:n.invocationId,capability:s,error:r.error.message,durationMs:r.durationMs}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.failed event:",e)}throw Or({invocationId:n.invocationId,capability:s,traceId:i.trace.traceId,spanId:n.invocationId,parentSpanId:i.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"error",errorCode:e instanceof yr?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function jr(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(jr);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=jr(r);return t}return e}const Fr=new WeakMap;function qr(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,input:i}=n;if(!0===r.spec.secretBearing||s.startsWith("secrets."))r.redactedInput=jr(i);else{const e=function(e){const t=Fr.get(e);if(t)return t;const n=d(e.inputSchema);return Fr.set(e,n),n}(r.spec);r.redactedInput=e.length>0?p(i,e):i}return await t()}}function Br(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function Ur(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Br(t))}const Vr=new class{validate(e,t){const n=[];if(!e||"object"!=typeof e)return{ok:!0,errors:n};const r=e,s=r.type;if(s&&(Ur(s,t)||n.push(`Expected type "${s}", got "${Br(t)}"`)),"object"===s&&t&&"object"==typeof t&&!Array.isArray(t)){const e=t,s=r.required,i=r.properties;if(Array.isArray(s))for(const t of s)t in e&&void 0!==e[t]||n.push(`Missing required field: "${t}"`);if(i)for(const[t,r]of Object.entries(e)){if(void 0===r)continue;const e=i[t];if(!e)continue;const s=e.type;s&&(Ur(s,r)||n.push(`Field "${t}": expected type "${s}", got "${Br(r)}"`))}}return{ok:0===n.length,errors:n}}};let Kr=Vr;function Wr(){return Kr}function Gr(){return async(e,t)=>{const{req:n,state:r}=e,{input:s}=n,{inputSchema:i}=r.spec,o=Wr().validate(i,s);if(!o.ok)throw new yr(gr.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const Yr=An({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function zr(){return Yr.get()}const Jr=["path","oldPath","newPath","src","dst","target","linkPath"];function Hr(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("/"),s=n.split("/").filter(e=>""!==e&&"."!==e),i=[];for(const e of s)if(".."===e){if(0===i.length)return{ok:!1,reason:"traversal above root"};i.pop()}else i.push(e);let o=(r?"/":"")+i.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 Qr(){try{return zr().cwd}catch{return}}function Zr(){return async(e,t)=>{const{input:n}=e.req;if("object"!=typeof n||null===n)return await t();const r=n;let s,i=!1;for(const e of Jr){const t=r[e];if("string"!=typeof t)continue;i||(s=Qr(),i=!0);const n=Hr(t,s);if(!n.ok)throw new yr(gr.CAPABILITY_PATH_TRAVERSAL_DENIED,`Path traversal denied on field "${e}": ${n.reason}`,{field:e,reason:n.reason,value:t,...void 0!==s?{cwd:s}:{}})}return await t()}}const Xr="encrypted-at-rest";function es(){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 s=function(){try{return zr()}catch{return}}();if(!s)throw new yr(gr.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:Xr,reason:"provider not registered"});if(!s.capabilities?.has(Xr))throw new yr(gr.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${Xr}" capability flag`,{capability:n.name,required:Xr,reason:"capability not advertised"});return xn({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:Xr}}),t()}}function ts(e,t,n,r,s){try{const i=globalThis.punica?.kernel?.Events?.manager;if(!i||"function"!=typeof i.publishEvent)return;i.publishEvent({name:"capability.denied_by_profile",source:"runtime:capabilities:middleware:profileBudget",kind:"warn",correlationId:s,payload:{invocationId:s,capability:e,profile:t,reason:n,origin:r??"unknown"}})}catch{}}function ns(){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:s,allowedOrigins:i}=n.capabilities;if("*"===r&&!s?.length&&!i?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(i&&i.length>0){const e=Lr.getCapability(o),t=e?.origin;if(!t||!i.includes(t))throw ts(o,c,"origin-not-allowed",t,a),new yr(gr.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(s&&s.includes(o))throw ts(o,c,"in-denylist",void 0,a),new yr(gr.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 ts(o,c,"not-in-allowlist",void 0,a),new yr(gr.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const rs={alg:"HS256",typ:"PUNICA-APPROVAL"};class ss extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function is(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 os(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 as(e){return(new TextEncoder).encode(e)}function cs(e){return is(as(JSON.stringify(e)))}function ls(e){return JSON.parse((t=os(e),(new TextDecoder).decode(t)));var t}function us(){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 ds(){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 ps{#ne;#re;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?as(e.secret):ds()}async sign(e){const t=await this.#se(),n=cs(rs),r=cs(e),s=as(`${n}.${r}`),i=await us().sign("HMAC",t,s);return`${n}.${r}.${is(new Uint8Array(i))}`}getSecret(){return this.#ne}async#se(){return this.#re||(this.#re=await us().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#re}}class fs{#ne;#re;#ie=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?as(e.secret):ds()}async verify(e){const t=e.split(".");if(3!==t.length)throw new ss("MALFORMED","Token must have 3 dot-separated segments");const[n,r,s]=t;let i,o;try{i=ls(n)}catch{throw new ss("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==i.alg||"PUNICA-APPROVAL"!==i.typ)throw new ss("BAD_HEADER",`Unexpected token header: alg=${i.alg??"(missing)"} typ=${i.typ??"(missing)"}`);try{o=ls(r)}catch{throw new ss("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#se(),c=as(`${n}.${r}`);let l;try{l=os(s)}catch{throw new ss("MALFORMED","Token signature is not valid base64url")}const u=us();if(!await u.verify("HMAC",a,l,c))throw new ss("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new ss("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new ss("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#ie.add(e)}isRevoked(e){return this.#ie.has(e)}async#se(){return this.#re||(this.#re=await us().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#re}}let hs;function ms(){return hs||(hs=function(){const e=new ps,t=new fs({secret:e.getSecret()});return{signer:e,verifier:t}}()),hs}const gs=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function ys(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=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:i.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:d?"error":"warning"},payload:{capability:s,risk:a,approval:c,actor:i.actor,decision:d?"deny":"allow",failClosed:u}})}catch{}if(console.warn(`[CapabilityGateway] Policy manager not available for "${s}" (risk=${a}, approval=${c}); `+(d?"DENYING (fail-closed)":"allowing (fail-open)")+"."),d)throw new yr(gr.CAPABILITY_DENIED,`Policy manager unavailable and capability "${s}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:s,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"===i.actor.type){"approval"===gs({capabilityId:s,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 f={kind:"capability",id:s,risk:l,approval:u,reason:o.description??o.title??`Capability: ${s}`},h=a.evaluate(f,{workspaceId:i.workspaceId,correlationId:n.invocationId,traceId:i.trace.traceId});if(r.policyDecision={allowed:h.allowed,requiresApproval:h.requiresApproval||d,approvalToken:i.policy.approvalToken,reason:h.reason||p},d||h.requiresApproval)if(i.policy.approvalToken)try{await ms().verifier.verify(i.policy.approvalToken)}catch(e){if(e instanceof ss){try{const t=globalThis.punica?.kernel?.Events?.manager;t&&t.publishEvent({name:"token.invalid",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:i.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:"error"},payload:{capability:s,tokenError:e.code,actor:i.actor}})}catch{}throw new yr(gr.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:s,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!(a.hasApproval(f,"always",{workspaceId:i.workspaceId})||a.hasApproval(f,"workspace",{workspaceId:i.workspaceId})||a.hasApproval(f,"once",{workspaceId:i.workspaceId}))){a.requestApproval(f,{workspaceId:i.workspaceId,correlationId:n.invocationId,traceId:i.trace.traceId});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:i.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:s,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}throw new yr(gr.CAPABILITY_APPROVAL_REQUIRED,`Approval required: ${p}`,{capability:s,reason:p})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:i.workspaceId};if(!(a.hasApproval(f,"always",e)||a.hasApproval(f,"workspace",e))&&"function"==typeof a.revokeApproval)try{a.revokeApproval({kind:f.kind,id:f.id,scope:"once"})}catch{}}}if(!h.allowed&&!d&&"suggest"!==h.mode)throw new yr(gr.CAPABILITY_DENIED,h.reason??"Policy denied execution",{capability:s,decision:h});return await t()}}const ws=new class{#m=new Map;#oe;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#oe=t<=0?1:t}get(e,t){const n=this.#ae(e,t),r=this.#m.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#m.delete(n),this.#m.set(n,r),r;this.#m.delete(n)}}set(e){const t=this.#ae(e.capabilityId,e.key);for(this.#m.delete(t),this.#m.set(t,e);this.#m.size>this.#oe;){const e=this.#m.keys().next().value;if(void 0===e)break;this.#m.delete(e)}}delete(e,t){return this.#m.delete(this.#ae(e,t))}clear(){this.#m.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#m)r.expiresAtMs<=e&&(this.#m.delete(n),t++);return t}size(){return this.#m.size}#ae(e,t){return`${e}|${t}`}};let vs=ws;function bs(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,input:i,idempotencyKey:o}=n,a=r.spec.defaults?.idempotency??"none";if("none"===a)return t();if("required"===a&&!o)throw new yr(gr.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${s}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:s});if(!o)return t();const c=vs,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")}(i),u=c.get(s,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:s,idempotencyKey:o,cachedAtMs:u.createdAtMs,actor:n.ctx.actor}}),new yr(gr.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED,`Capability "${s}" idempotencyKey "${o}" was previously used with a different input`,{capability:s,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:s,inputHash:l,response:d,createdAtMs:p,expiresAtMs:p+864e5}),r.tags["idempotency.cached"]="true",d}}const Is=new class{#ce=new Map;getBucket(e,t){let n=this.#ce.get(e);return n||(n={tokens:t,lastRefillMs:Date.now(),perSecond:t,maxTokens:t},this.#ce.set(e,n)),n}consumeToken(e,t){const n=this.getBucket(e,t),r=Date.now(),s=(r-n.lastRefillMs)/1e3*t;return n.tokens=Math.min(n.maxTokens,n.tokens+s),n.lastRefillMs=r,n.tokens>=1&&(n.tokens-=1,!0)}};function ks(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=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(":")}(s,i.actor.type,i.actor.extensionName??i.origin.extension);if(!Is.consumeToken(c,a.perSecond))throw new yr(gr.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${s}" (${a.perSecond}/s)`,{capability:s,perSecond:a.perSecond,key:c});return await t()}}const Es=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.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.#le.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function Ss(){return async(e,t)=>{const{req:n,state:r}=e,{ctx:s}=n,{spec:i}=r,o=i.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:s.workspaceId,tenantId:s.tenantId,extension:s.actor.extensionName??s.origin.extension,actorType:s.actor.type});try{await Es.acquire(a,o.max)}catch(e){throw new yr(gr.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{Es.release(a)}}}const As=new class{#ue=new Map;getBreaker(e){let t=this.#ue.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#ue.set(e,t)),t}};function xs(){return async(e,t)=>{const{req:n,state:r}=e,{name:s}=n,i=r.spec.defaults?.circuitBreaker;if(!i)return await t();const o=i.failureThreshold??3,a=i.cooldownMs??6e4,c=As.getBreaker(s),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new yr(gr.CAPABILITY_CIRCUIT_OPEN,`Circuit breaker open for "${s}"`,{capability:s,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 Cs(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 Ts(e,t,n,r){let s;const i=new Promise((e,t)=>{s=setTimeout(()=>{t(new yr(gr.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),i])}finally{void 0!==s&&clearTimeout(s)}}function Ms(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 Ns(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:Ms(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(Ms(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=zr()}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(Ms(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 Ps=new WeakMap;function _s(e,t){if(!0===t.secretBearing)return Ls(e);const n=function(e){const t=Ps.get(e);if(t)return t;const n=d(e.outputSchema);return Ps.set(e,n),n}(t);return n.length>0?p(e,n):e}function Ls(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ls);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ls(r);return t}return e}function Rs(){return async(e,t)=>{const{req:n,state:r}=e,{name:s,ctx:i}=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=_s(r.output,o);await Ns({invocationId:n.invocationId,capability:s,actor:i.actor,origin:i.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:i.workspaceId,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const $s=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Os(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const Ds=new class{async call(e,t,n,r){const s=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let i=wr.getSpec(e),o=i?wr.getProvider(e):void 0,a="core";if(!i){const t=Lr.getCapability(e);if(!t)throw Os({name:"capability.unknown_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:n.actor}}),new yr(gr.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,i=br(t.definition),o=Rr(t.origin,t.definition,t.metadata)}if(!o)throw new yr(gr.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(i.requires)for(const t of i.requires)if(!wr.hasCapability(t))throw new yr(gr.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});i.deprecated&&Os({name:"capability.deprecated_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:a,since:i.deprecated.since,reason:i.deprecated.reason,replacement:i.deprecated.replacement,actor:n.actor}});const c={req:{invocationId:s,name:e,input:t,ctx:n,idempotencyKey:r},state:{spec:i,capabilityOrigin:a,startTimeMs:Date.now(),tags:{}}},l=this.#de(o);try{return await this.#pe(l,c)}catch(e){if(e instanceof yr)throw e;throw new yr(gr.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#de(e){const t={auditTrail:Rs,traceMetrics:Dr,redaction:qr,validateInput:Gr,pathTraversalGuard:Zr,encryptionRouting:es,profileBudget:ns,policyGate:ys,idempotency:bs,rateLimit:ks,concurrency:Ss,circuitBreaker:xs,timeoutRetry:()=>function(e){return async(t,n)=>{const{req:r,state:s}=t,{input:i,idempotencyKey:o}=r,{spec:a}=s,c=a.defaults?.timeoutMs??3e4,l=a.defaults?.retries??0,u=a.defaults?.retryBackoffMs??1e3,d="write"!==a.sideEffect||Boolean(o);let p=null,f=0;for(;f<=l;){f++;try{const n=await Ts(e,i,t,c);return s.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),f<=l&&d&&Cs(p)){const e=u*Math.pow(2,f-1);await new Promise(t=>setTimeout(t,e));continue}throw s.error=p,p}}throw s.error=p??new Error("Execution failed"),s.error}}(e)};return $s.map(e=>t[e]())}#pe(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const s=e[n];return n++,await s(t,r)};return r()}};function js(e,t){const n=zr(),r=n[t];if("function"!=typeof r)throw new yr(gr.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 Fs(e,t,n){const r=zr();if(!r.capabilities?.has(n))throw new yr(gr.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 s=r[t];if("function"!=typeof s)throw new yr(gr.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 s.bind(r)}class qs{name="fs.readFile";async execute(e,t){const n=zr();return await n.readFile(e.path)}}class Bs{name="fs.writeFile";async execute(e,t){const n=zr();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class Us{name="fs.listFiles";async execute(e,t){const n=zr();return await n.getFileTree()}}class Vs{name="fs.stat";async execute(e,t){return await js("fs.stat","stat")(e.path)}}class Ks{name="fs.exists";async execute(e,t){return await js("fs.exists","exists")(e.path)}}class Ws{name="fs.copy";async execute(e,t){await js("fs.copy","copy")(e.src,e.dst)}}class Gs{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await js("fs.mkdir","mkdir")(e.path,n)}}class Ys{name="fs.history";async execute(e,t){return await Fs("fs.history","history","versioning")(e.path)}}class zs{name="fs.readAtVersion";async execute(e,t){return await Fs("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class Js{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await js("fs.list","list")(e.path,n)}}const Hs=An({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 s=String(n??"").trim();if(!s)throw new Error("[Runtime.secrets] Secret name is required");const i=Date.now();if(t.has(s)){const e=t.get(s);t.set(s,{...e,updatedAtMs:i})}else t.set(s,{createdAtMs:i,updatedAtMs:i});e.set(s,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 Qs(){return Hs.get()}function Zs(e){Hs.set(e),e&&xn({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class Xs{name="secrets.get";async execute(e,t){return Qs().get(e.name)}}class ei{name="secrets.set";async execute(e,t){Qs().set(e.name,e.value)}}function ti(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Pn]=!0,n}class ni{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=ti(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class ri{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,s=t.sessionId??t.trace?.traceId,i=e=>{if(r)try{r.publishEvent({name:"llm.chunk",envelope:{id:r.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"progress"},payload:{capabilityId:this.name,chunk:e}})}catch{}},o=ti(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);if("function"!=typeof n.chatStream){const e=await n.chat(o);return i({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(i(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 si{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 ii{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 oi{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 ai{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 ci{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 li{name="workspace.readFile";async execute(e,t){const n=zr();return await n.readFile(e.path)}}class ui{name="workspace.writeFile";async execute(e,t){const n=zr();await n.createFileWithContent(e.path,e.content)}}class di{name="workspace.listFiles";async execute(e,t){const n=zr(),r=await n.getFileTree(),s=[],i=e=>{for(const t of e??[])s.push({path:t.path,name:t.name,isDirectory:t.isDirectory}),t.isDirectory&&Array.isArray(t.children)&&t.children.length&&i(t.children)};return i(r??[]),{entries:s}}}const pi=[".git",".hg",".svn",".punica","node_modules","bower_components",".pnpm-store","dist","build","out",".next",".nuxt",".svelte-kit",".turbo",".parcel-cache",".cache","coverage","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".venv","venv",".eggs","target",".gradle",".idea",".vscode","vendor"],fi=["png","jpg","jpeg","gif","webp","bmp","ico","tiff","psd","woff","woff2","ttf","otf","eot","zip","tar","gz","tgz","bz2","xz","7z","rar","jar","mp3","mp4","mov","avi","mkv","webm","wav","flac","ogg","pdf","doc","docx","xls","xlsx","ppt","pptx","parquet","feather","arrow","orc","avro","db","sqlite","sqlite3","mdb","h5","hdf5","npy","npz","pkl","pickle","pt","pth","ckpt","safetensors","onnx","gguf","ggml","bin","model","pyc","pyo","class","o","obj","so","dylib","dll","exe","wasm","map"];function hi(e){let t=e.trim();if(!t||t.startsWith("#")||t.startsWith("!"))return null;t.endsWith("/")&&(t=t.slice(0,-1));const n=t.startsWith("/");if(n&&(t=t.replace(/^\/+/,"")),!t)return null;const r=t.includes("/"),s=function(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];"*"===r?"*"===e[n+1]?(n++,"/"===e[n+1]?(n++,t+="(?:.*/)?"):t+=".*"):t+="[^/]*":"?"===r?t+="[^/]":".+^${}()|[]\\".includes(r)?t+="\\"+r:t+=r}return t}(t),i=new RegExp(`^${r||n?"":"(?:.*/)?"}${s}(?:/.*)?$`);return e=>i.test(e)}const mi={py:"python",ipynb:"python",ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",rs:"rust",go:"go",java:"java",kt:"kotlin",rb:"ruby",php:"php",c:"c",h:"c",cpp:"c++",cc:"c++",hpp:"c++",cs:"c#",swift:"swift",scala:"scala",r:"r",jl:"julia",sh:"shell",sql:"sql"},gi=new Set(["main.py","app.py","manage.py","wsgi.py","asgi.py","__main__.py","cli.py","run.py","train.py","index.ts","index.js","main.ts","main.js","server.ts","server.js"]);function yi(e){const t=e.trim();if(!t||t.startsWith("#")||t.startsWith("-"))return null;const n=t.split(" #")[0].trim().match(/^[A-Za-z0-9._-]+/);return n?n[0]:null}function wi(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function vi(e,t,n){const r=new Map;for(const t of e){if(t.endsWith("/"))continue;const e=mi[wi(t)];e&&r.set(e,(r.get(e)??0)+1)}return n&&r.set("python",(r.get("python")??0)+1),t&&r.set("node",(r.get("node")??0)+1),[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,6).map(([e])=>e)}function bi(e,t){const n=new Set;t&&n.add(t.replace(/^\.\//,""));for(const t of e){if(t.endsWith("/"))continue;const e=t.slice(t.lastIndexOf("/")+1);if(gi.has(e)&&n.add(t),n.size>=8)break}return[...n].slice(0,8)}function Ii(e){const t={};let n,r;if(e.packageJson)try{const s=JSON.parse(e.packageJson),i=Object.keys(s.dependencies??{}),o=Object.keys(s.devDependencies??{});if(t.node={source:"package.json",count:i.length,dev:o.length,names:[...i,...o].slice(0,60)},s.scripts&&Object.keys(s.scripts).length){n={};for(const[e,t]of Object.entries(s.scripts).slice(0,30))n[e]=t}"string"==typeof s.main&&(r=s.main)}catch{t.node={source:"package.json",count:0,dev:0,names:[]}}const s=e.requirementsTxt?function(e){const t=[];for(const n of e.split(/\r?\n/)){const e=yi(n);e&&t.push(e)}return t}(e.requirementsTxt):e.pyproject?function(e){const t=e.search(/dependencies\s*=\s*\[/);if(t<0)return[];const n=e.indexOf("[",t);let r=0,s=-1;for(let t=n;t<e.length;t++)if("["===e[t])r++;else if("]"===e[t]&&0===--r){s=t;break}if(s<0)return[];const i=[];for(const t of e.slice(n+1,s).match(/["']([^"']+)["']/g)??[]){const e=yi(t.replace(/["']/g,""));e&&i.push(e)}return i}(e.pyproject):null;s&&(t.python={source:e.requirementsTxt?"requirements.txt":"pyproject.toml",count:s.length,names:s.slice(0,60)});const i={workspace:e.workspace,stack:vi(e.layout,!!t.node,!!t.python),dependencies:t,entrypoints:bi(e.layout,r),layout:e.layout.slice(0,250),truncated:e.layoutTruncated||e.layout.length>250};if(n&&(i.scripts=n),e.readme&&(i.readme=function(e){const t=e.replace(/\r\n/g,"\n").trim();return t.length<=800?t:t.slice(0,800).replace(/\s+\S*$/,"")+" …"}(e.readme)),e.vcs){const t=e.vcs,n=(t.staged?.length??0)+(t.modified?.length??0)+(t.created?.length??0)+(t.deleted?.length??0)+(t.renamed?.length??0)+(t.not_added?.length??0);i.vcs={branch:t.current??null,...null!=t.ahead?{ahead:t.ahead}:{},...null!=t.behind?{behind:t.behind}:{},dirtyFiles:n}}return i}const ki=["readme.md","readme.rst","readme.txt","readme"];async function Ei(e,t){try{return await e.readFile(t)}catch{return}}async function Si(){const e=zr(),t=await e.getFileTree()??[],n=function(e){const t=new Map;for(const n of e??[])n.isDirectory||t.set(n.name.toLowerCase(),n.path);return t}(t),r=function(e={}){const t=new Set(pi),n=new Set(fi),r=(e.gitignore??"").split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")&&!e.startsWith("!")),s=r.map(hi).filter(e=>null!=e),i=[],o=new Set,a=e=>{o.has(e)||(o.add(e),i.push(e))};for(const e of pi)a(`${e}/`);for(const e of fi)a(`*.${e}`);for(const e of r)a(e);return{patterns:i,isNoise:e=>{const r=String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"");if(!r)return!1;const i=r.split("/");for(const e of i)if(t.has(e))return!0;const o=i[i.length-1],a=o.lastIndexOf(".");if(a>0){const e=o.slice(a+1).toLowerCase();if(n.has(e))return!0}for(const e of s)if(e(r))return!0;return!1}}}({gitignore:n.has(".gitignore")?await Ei(e,n.get(".gitignore")):void 0}),{layout:s,truncated:i}=function(e,t){const n=[];let r=!1;const s=(e,i)=>{for(const o of e??[]){const e=o.path.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"");if(!t(e)){if(n.length>=250)return void(r=!0);n.push(o.isDirectory?`${e}/`:e),o.isDirectory&&o.children?.length&&i<2&&s(o.children,i+1)}}};return s(e??[],0),{layout:n,truncated:r}}(t,r.isNoise),o=t=>n.has(t)?Ei(e,n.get(t)):Promise.resolve(void 0),[a,c,l]=await Promise.all([o("package.json"),o("requirements.txt"),o("pyproject.toml")]);let u;for(const t of ki)if(n.has(t)&&(u=await Ei(e,n.get(t)),u))break;let d=null;try{const e=await(punica.runtime.workspace?.getCurrent?.());if(e){const t=e.environments?.find(t=>t.id===e.currentEnvironmentId);d={name:e.name,kind:e.kind,rootUri:e.rootUri,...t?{environment:t.name}:{}}}}catch{}let p=null;try{const e=globalThis.punica?.runtime?.vcs;e?.status&&(p=await e.status())}catch{}return{context:Ii({workspace:d,layout:s,layoutTruncated:i,packageJson:a,requirementsTxt:c,pyproject:l,readme:u,vcs:p}),noisePatterns:r.patterns}}class Ai{name="workspace.projectContext";async execute(e,t){const{context:n}=await Si();return n}}async function xi(e,t,n){try{await e.updateFileContent(t,n)}catch{await e.createFileWithContent(t,n)}}class Ci{name="workspace.writeOrientation";async execute(e,t){const n=!1!==e?.claudeMd,r=!1!==e?.claudeignore,s=zr(),{context:i,noisePatterns:o}=await Si(),a=[];if(n&&(await xi(s,"CLAUDE.md",function(e){const t=[],n=e.workspace;t.push(`# ${n?.name??"Workspace"}`,""),t.push("> Orientation generated by Punica. A snapshot to start from — verify against the code before relying on any single line.",""),n&&(t.push(`- **Kind:** ${n.kind}`),t.push(`- **Root:** ${n.rootUri}`),n.environment&&t.push(`- **Environment:** ${n.environment}`)),e.stack.length&&t.push(`- **Stack:** ${e.stack.join(", ")}`),e.vcs&&t.push(`- **VCS:** ${e.vcs.branch??"(detached)"}`+(e.vcs.ahead?` ↑${e.vcs.ahead}`:"")+(e.vcs.behind?` ↓${e.vcs.behind}`:"")+` · ${e.vcs.dirtyFiles} uncommitted`),t.push("");const r=e.dependencies.python,s=e.dependencies.node;if((r||s)&&(t.push("## Dependencies",""),r&&t.push(`**Python** (\`${r.source}\`, ${r.count}): ${r.names.join(", ")}`,""),s&&t.push(`**Node** (\`${s.source}\`, ${s.count} + ${s.dev} dev): ${s.names.join(", ")}`,"")),e.scripts&&Object.keys(e.scripts).length){t.push("## Scripts","");for(const[n,r]of Object.entries(e.scripts))t.push(`- \`${n}\`: ${r}`);t.push("")}if(e.entrypoints.length){t.push("## Entry points","");for(const n of e.entrypoints)t.push(`- \`${n}\``);t.push("")}return e.readme&&t.push("## README (digest)","",e.readme,""),e.layout.length&&(t.push("## Layout"+(e.truncated?" (truncated)":""),"","```"),t.push(...e.layout),t.push("```","")),t.join("\n")}(i)),a.push("CLAUDE.md")),r){const e="# Generated by Punica (workspace.writeOrientation).\n# Paths an assistant should skip: dependencies, build output, caches, binary/data blobs, plus your .gitignore.\n"+o.join("\n")+"\n";await xi(s,".claudeignore",e),a.push(".claudeignore")}return{written:a}}}const Ti=".punica/facts",Mi=`${Ti}/facts.json`;async function Ni(e){let t;try{t=await e.readFile(Mi)}catch{return{}}try{const e=JSON.parse(t);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}class Pi{name="context.remember";async execute(e,t){const n=String(e?.key??"").trim();if(!n)throw new Error("context.remember requires input { key: string }.");const r=zr(),s=await Ni(r);return s[n]=e.value??null,await async function(e,t){const n=`${JSON.stringify(t,null,2)}\n`;try{await e.updateFileContent(Mi,n)}catch{try{await e.createFolder(".punica")}catch{}try{await e.createFolder(Ti)}catch{}await e.createFileWithContent(Mi,n)}}(r,s),{key:n,count:Object.keys(s).length}}}class _i{name="context.recall";async execute(e,t){const n=zr(),r=await Ni(n),s=e?.key?String(e.key).trim():"";if(s){const e=Object.prototype.hasOwnProperty.call(r,s);return{key:s,value:e?r[s]:null,found:e}}const i=Object.keys(r),o={};for(const e of i.slice(0,200))o[e]=r[e];return{facts:o,count:i.length,truncated:i.length>200}}}class Li{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 Ri{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 $i{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 Oi{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 Di{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 s={...e,workspaceId:e.workspaceId??t.workspaceId,parentTraceId:e.parentTraceId??t.trace?.traceId};return r.runSubflow(s)}}const ji="capability.catalog";class Fi{name=ji;async execute(e,t){const n=e??{},r=Lr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>qi(e,n));return{capabilities:r,count:r.length}}}function qi(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=Bi(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=Bi(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=Bi(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 Bi(e){return Array.isArray(e)?e:[e]}const Ui=["examples","$comment","default","title"];function Vi(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 Ki=["properties","patternProperties","definitions","$defs"];function Wi(e){if(Array.isArray(e))return e.map(e=>Wi(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!Ui.includes(n))if("description"!==n||"string"!=typeof r){if(Ki.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=Wi(n);t[n]=e;continue}t[n]=Wi(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const Gi="capability.schemaExport";class Yi{name=Gi;async execute(e,t){const n=e??{},r=n.filter??{},s=Lr.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>qi(e,r)),i=n.mode??"full",o=s.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"===i?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=Vi(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=Wi(e.inputSchema));e.policy&&(t.policy={...e.policy});return t}(t):"summary"===i?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=Vi(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 zi(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return[];const s=Lr.listCapabilities();if(0===s.length)return[];const i=function(e,t){const n=Qi(Hi(e));return t.map(e=>({...e,score:Zi(n,Qi(Hi(e.text)))}))}(r,s.map(e=>({id:e.definition.id,description:e.definition.description,text:Ji(e.definition)}))),o=i.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 Nn("llm.recommendIntent",{intent:r,limit:n,path:"text-similarity",topIds:o.map(e=>e.id),topScore:o[0]?.score??0}),o}function Ji(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 Hi(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(e=>e.length>0)}function Qi(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function Zi(e,t){if(0===e.size||0===t.size)return 0;let n=0,r=0,s=0;for(const[,t]of e)r+=t*t;for(const[,e]of t)s+=e*e;for(const[r,s]of e){const e=t.get(r);void 0!==e&&(n+=s*e)}const i=Math.sqrt(r)*Math.sqrt(s);return 0===i?0:n/i}const Xi="capability.recommend";class eo{name=Xi;async execute(e,t){const n=e??{},r=String(n.intent??""),s=await zi(r,"number"==typeof n.limit?{limit:n.limit}:void 0);return{recommendations:s.map(e=>({id:e.id,score:e.score,description:e.description})),path:"text-similarity",count:s.length}}}const to="capability.describe",no="capability.search";function ro(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class so{name=to;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),s=(await(new Yi).execute({mode:"ai-tools"},t)).capabilities.filter(e=>r.has(String(e.id))),i=new Set(s.map(e=>String(e.id)));return{tools:s,missing:n.filter(e=>!i.has(e))}}}class io{name=no;async execute(e,t){const n=e??{},r=String(n.query??"").trim(),s=Math.min(Math.max(1,Math.floor(n.limit??16)),50);if(!r)return{results:[],count:0};const i=Lr.listCapabilities(),o=new Map(i.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await zi(r,{limit:s});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=i.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,s).map(e=>{const t=o.get(e);return{id:e,description:Vi(t?.description??t?.title??e,100),category:ro(e)}});return{results:c,count:c.length}}}function oo(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function ao(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 co{name="ai.session.create";async execute(e,t){const n=e??{};return{session:oo().create(n)}}}class lo{name="ai.session.list";async execute(e,t){const n=oo().list(e?.workspaceId);return{sessions:n,count:n.length}}}class uo{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:oo().get(n)}}}class po{name="ai.session.rename";async execute(e,t){const n=e;return{ok:oo().rename(String(n?.sessionId??""),String(n?.title??""))}}}class fo{name="ai.session.archive";async execute(e,t){const n=e;return{ok:oo().archive(String(n?.sessionId??""),n?.archived)}}}class ho{name="ai.session.delete";async execute(e,t){return{ok:oo().delete(String(e?.sessionId??""))}}}const mo={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"}]}},go={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"}]}},yo=new Set(["low","medium","high"]),wo={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&yo.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"}]:[]}},vo=new Set(["none","plan","step"]),bo={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&vo.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 Io={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"}]:[]}},ko=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Eo={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&ko.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"}]}},So=new Set(["low","medium","high"]),Ao=["write","delete","remove","modify","destroy"],xo=[mo,go,wo,bo,Io,Eo,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!So.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&&Ao.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 Co=new class{#fe=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#fe.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.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of xo)this.#fe.set(e.id,e)}},To="capability.lint";class Mo{name=To;async execute(e,t){const n=e??{},r=Lr.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),s=Co.lintAll(r).map(e=>({id:e.id,ok:e.ok,issues:e.issues}));return{results:s,ok:s.every(e=>e.ok),count:s.length}}}const No={type:"object"};function Po(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function _o(e){let t;return t=function(e){if(e instanceof yr)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:Po(e),{content:[{type:"text",text:t}],isError:!0}}const Lo="capability.serveList",Ro="capability.serveCall",$o=new Set([Lo,Ro]);class Oo{name=Lo;async execute(e,t){const n=(e??{}).filter??{},r=Lr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!$o.has(e.definition.id)).filter(e=>qi(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??No,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class Do{name=Ro;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||$o.has(r)||!Lr.getCapability(r))return _o(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:Po(e)}],isError:!1}}(await Ds.call(r,n.arguments??{},t))}catch(e){return _o(e)}}}const jo="shell.revealView",Fo="shell.hideView",qo="shell.listViews",Bo="shell.toggleView",Uo="shell.toggleSlot",Vo="shell.moveView";function Ko(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new yr(gr.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:jo});return e}function Wo(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 Go{name=jo;async execute(e,t){const{viewId:n,focus:r}=e??{},s=Ko();if(!s.getPlacement(n))throw new yr(gr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:jo,viewId:n});return await s.reveal(n,Wo(t),{focus:r}),{viewId:n,revealed:!0}}}class Yo{name=Fo;async execute(e,t){const{viewId:n}=e??{};return Ko().hide(n,Wo(t)),{viewId:n,hidden:!0}}}class zo{name=qo;async execute(e,t){return{views:Ko().listViews()}}}class Jo{name=Bo;async execute(e,t){const{viewId:n,focus:r}=e??{},s=Ko();if(!s.getPlacement(n))throw new yr(gr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:Bo,viewId:n});return"visible"===s.getState(n)?(s.hide(n,Wo(t)),{viewId:n,visible:!1}):(await s.reveal(n,Wo(t),{focus:r}),{viewId:n,visible:!0})}}const Ho=new Map;class Qo{name=Uo;async execute(e,t){const{slot:n,focus:r}=e??{},s=Ko(),i=s.getVisibleView(n);if(i)return Ho.set(n,i),s.hide(i,Wo(t)),{slot:n,visible:!1,viewId:i};const o=Ho.get(n);let a=o&&s.getPlacement(o)?o:void 0;return a||(a=s.listViews().find(e=>e.slot===n)?.viewId),a?(await s.reveal(a,Wo(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}class Zo{name=Vo;async execute(e,t){const{viewId:n,slot:r}=e??{},s=Ko(),i=s.getPlacement(n);if(!i)throw new yr(gr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover movable views.`,{capability:Vo,viewId:n});const o=i.allowedSlots??[];if(!o.includes(r))throw new yr(gr.CAPABILITY_INPUT_INVALID,`View "${n}" cannot be moved to slot "${r}". Allowed slots: ${o.length?o.join(", "):"(none)"}.`,{capability:Vo,viewId:n,slot:r});return await s.moveView(n,r,Wo(t)),{viewId:n,slot:r,moved:!0}}}function Xo(e){try{wr.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function ea(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 ta(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 na(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=Lr.getCapability(e.id);return t?void ta(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Lr.listCapabilities(n),s=r.map(ea);if(console.log("[Punica] Trinity capability catalog",{count:s.length}),s.length>0){if(console.table(s),e?.verbose){console.log("[Punica] Full definitions (same fields as .punica/capabilities.yaml):");for(const e of r)ta(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function ra(e){return na({...e,verbose:!0})}function sa(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 ia(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,s=t.policy?.risk??"—",i=function(e){const t=e.indexOf("\n");return(-1===t?e:e.slice(0,t)).trim()}(t.description??t.title??"")||"—";return`| ${n} | ${r} | ${s} | ${o=i,o.replace(/\|/g,"\\|")} |`;var o}function oa(e){return JSON.stringify(e,null,2)}const aa=new class{#he=new Map;get(e){return this.#he.get(e)}list(){return[...this.#he.values()]}register(e,t){for(const e of t)this.#he.set(e.definition.id,e),this.#me(e.definition.id)}unregister(e){for(const[t,n]of this.#he)n.serverId===e&&(this.#he.delete(t),this.#ge(t))}hasServer(e){for(const t of this.#he.values())if(t.serverId===e)return!0;return!1}#me(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{}}#ge(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{}}},ca=16384,la="runtime:mcp:client";function ua(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function da(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 da(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=>da(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,s]of Object.entries(e))n[r]=da(s,t+1);return n}return e}function pa(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=ca)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(da(e,0),null,2)??"null";if(r.length<=ca)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,ca)+"\n… [truncated]",bytes:n,truncated:!0}}function fa(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const ha=new class{#ye=new Map;async connect(e){if(this.#ye.has(e.id))return this.#ye.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return ka}),r=e.toolOverrides??await t(e.id),s="stdio"===e.kind?await n(e.env):e.env,i="streamable-http"===e.kind||"sse"===e.kind?await n(e.headers):e.headers,o={...e,env:s,headers:i,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:fa(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const s=ua(),i=pa(r??{});xn({name:"mcp.request",source:la,correlationId:s,payload:{...n(s,e,r),kind:"notification",requestJson:i.json,requestBytes:i.bytes,requestTokens:Ee().estimate(i.json),truncated:i.truncated}}),t.notify(e,r)},async request(e,r){const s=ua(),i=Date.now(),o=pa(r??{});xn({name:"mcp.request",source:la,correlationId:s,payload:{...n(s,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:Ee().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=pa(o??null);return xn({name:"mcp.response",source:la,correlationId:s,payload:{...n(s,e,r),kind:"request",isError:!1,durationMs:Date.now()-i,responseJson:a.json,responseBytes:a.bytes,responseTokens:Ee().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw xn({name:"mcp.response",source:la,correlationId:s,kind:"error",payload:{...n(s,e,r),kind:"request",isError:!0,durationMs:Date.now()-i,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 jm});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 Fm});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??{},s={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},i={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:s,sideEffects:u,executionDefaults:i,tags:l}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});aa.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(),aa.unregister(e.id),this.#ye.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#ye.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#ye.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#ye.values()].map(e=>e.handle)}listTools(e){return e?this.#ye.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#ye.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},ma=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/,ga=/^\$\{secret\.([A-Za-z0-9_.-]+)\}$/;async function ya(e){try{const t=globalThis.punica?.runtime?.secrets,n=await(t?.resolve?.(e));return"string"==typeof n&&""!==n?n:void 0}catch{return}}async function wa(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[s,i]of Object.entries(e)){if("string"!=typeof i){t[s]=i;continue}const e=i.match(ga);if(e){const n=e[1],r=await ya(n);void 0!==r?t[s]=r:console.warn(`[Punica] MCP secret placeholder \${secret.${n}} — not found in Secret Manager`);continue}const o=i.match(ma);if(o){const e=o[1];if(!r){console.warn(`[Punica] MCP env placeholder \${env.${e}} skipped — not in Node/Electron`);continue}const i=n[e];void 0!==i?t[s]=i:console.warn(`[Punica] MCP env placeholder \${env.${e}} — variable unset`)}else t[s]=i}return t}async function va(e){try{const t=globalThis,n=t.punica?.runtime?.fs,r=n?.readFile,s=n?.exists;if(!r)return{};if(s){const t=`.punica/mcp/${e}.yaml`;if(!await s(t))return{}}let i;try{i=await r(`.punica/mcp/${e}.yaml`,{encoding:"utf8"})}catch{return{}}if("string"!=typeof i||""===i.trim())return{};const{parse:o}=await Promise.resolve().then(function(){return Ed}),a=o(i);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 ba(){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 s;try{s=await n(".punica/mcp.yaml",{encoding:"utf8"})}catch{return[]}const{parseYamlMcpConfig:i}=await Promise.resolve().then(function(){return qm}),o=i(s);return Promise.all(o.map(e=>async function(e){const t=await va(e.id),n="stdio"===e.kind?await wa(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?await wa(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 Ia(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?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?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 ka=Object.freeze({__proto__:null,loadMcpConfig:ba,loadServerOverrides:va,parseStaticConfig:Ia,resolveEnvPlaceholders:wa});class Ea{name=He.RUNTIME.MCP;version="1.0.0";dependencies=[He.KERNEL.EVENTS,He.RUNTIME.FS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){this.#we=e.ModuleLifecycleState.BOOTSTRAPPING;const n=await ba();this.#ve(n),this.#we=e.ModuleLifecycleState.BOOTSTRAPPED}async#ve(e){for(const t of e)try{await ha.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#we=e.ModuleLifecycleState.STARTING,this.#we=e.ModuleLifecycleState.STARTED,console.log(`[Punica] MCP module started — ${aa.list().length} capability(ies) active`)}}const Sa=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const Aa={get capabilities(){return Yr.hasProvider()?Yr.get().capabilities:void 0},get cwd(){return Yr.hasProvider()?Yr.get().cwd:void 0},hasProvider:()=>Yr.hasProvider(),getFileTree:()=>Yr.get().getFileTree(),readFile:e=>Yr.get().readFile(e),readBytes:(e,t,n)=>{const r=Yr.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)=>Yr.get().updateFileContent(e,t),createFolder:e=>Yr.get().createFolder(e),deleteFolder:e=>Yr.get().deleteFolder(e),deleteFile:(e,t)=>Yr.get().deleteFile(e,t),renameFile:(e,t)=>Yr.get().renameFile(e,t),renameFolder:(e,t)=>Yr.get().renameFolder(e,t),revealInOS:e=>{const t=Yr.get();if("function"!=typeof t.revealInOS)throw new Error("[Runtime.fs] Provider does not implement revealInOS()");return t.revealInOS(e)},createFileWithContent:(e,t)=>Yr.get().createFileWithContent(e,t),list:(e,t)=>{const n=Yr.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=Yr.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=Yr.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},xa=function(e){return e||{query:e=>In().query(e),startIndex:e=>{const t=In();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(Sa?.search),Ca=function(e){return e||{status:()=>Sn().status(),branches:()=>Sn().branches(),logs:e=>Sn().logs(e),init:e=>Sn().init(e),clone:e=>Sn().clone(e),commit:e=>Sn().commit(e),stage:e=>Sn().stage(e),unstage:e=>Sn().unstage(e),discard:e=>Sn().discard(e),reset:e=>Sn().reset(e),switchBranch:e=>Sn().switchBranch(e),createBranch:(e,t)=>Sn().createBranch(e,t),fetch:e=>Sn().fetch(e),pull:e=>Sn().pull(e),push:e=>Sn().push(e)}}(Sa?.vcs),Ta=function(e){return e||{create:e=>kn().create(e),write:(e,t)=>kn().write(e,t),resize:(e,t,n)=>kn().resize(e,t,n),close:e=>kn().close(e),onData:(e,t)=>kn().onData(e,t),onExit:(e,t)=>kn().onExit(e,t),list:()=>kn().list()}}(Sa?.terminals),Ma=function(e){return e||{start:e=>En().start(e),send:(e,t)=>En().send(e,t),onMessage:(e,t)=>En().onMessage(e,t),onStderr:(e,t)=>En().onStderr(e,t),onExit:(e,t)=>En().onExit(e,t),stop:e=>En().stop(e),list:()=>En().list()}}(Sa?.debug),Na=function(e){return e||{run:e=>function(){if(gn)return gn;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return gn=e,gn}().run(e)}}(Sa?.tasks),Pa=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&Mn(e),{getCurrent:()=>Cn.get().getCurrent(),list:()=>Cn.get().list(),open:e=>Cn.get().open(e),setEnvironment:(e,t)=>Cn.get().setEnvironment(e,t),onDidChange:e=>Cn.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(Sa?.workspace),_a=function(e){return e||{list:async e=>bn().list(e),get:e=>bn().get(e),register:e=>bn().register(e),unregister:e=>bn().unregister(e),onDidChange:e=>bn().onDidChange(e)}}(Sa?.resources),La=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&On(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){(Ln&&Ln!==e||Rn&&t&&Rn!==t)&&z.publishEvent({name:"llm.providerChanged",envelope:{id:z.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:Ln,newProviderId:e,previousEndpoint:Rn,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),Ln=e,t&&(Rn=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)}})(),s=e?.correlationId??z.createCorrelationId(),i=ye.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!i.allowed)throw i.requiresApproval&&ye.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:s}),z.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:z.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(i.reason??"[Policy] Remote LLM request denied");return z.publishEvent({name:"llm.remoteRequestSent",envelope:{id:z.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),function(e){return"remote"===e?.route||String(e?.providerId??"").toLowerCase().startsWith("remote:")}(e)?{...e,correlationId:s,route:"remote",providerId:t}:{...e,correlationId:s}}const s={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",s=e?.providerId??"remote",i=$n(),o=!0===e?.[Pn];if(!o&&("remote"===t||n(e))){const t=e?.endpoint,n=await r(e,s,t);return await i.chat(n)}const a=await i.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:s,r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch{return}})(),i=e?.correlationId??z.createCorrelationId(),o=ye.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw z.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:z.createCorrelationId(),correlationId:i,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&&ye.requestApproval({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r,correlationId:i}),new Error(o.reason??"[Policy] Remote LLM request denied (auto route bypass detected)");z.publishEvent({name:"llm.remoteRequestSent",envelope:{id:z.createCorrelationId(),correlationId:i,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",s=e?.providerId??"remote",i=$n();let o=e;if(!(!0===e?.[Pn])&&("remote"===t||n(e))){const t=e?.endpoint;o=await r(e,s,t)}if("function"!=typeof i.chatStream){const e=await i.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 i.chatStream(o)){if(o?.signal?.aborted)return;yield e}},__punicaWrappedLlmFacade:!0};return s.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))},..."function"==typeof e.registerModelFile?{registerModelFile:async t=>{await e.registerModelFile(t)}}:{},localServerStatus:async()=>await(e.localServerStatus?.()),startLocalServer:async t=>await(e.startLocalServer?.(t)),stopLocalServer:async()=>{await(e.stopLocalServer?.())}}}(),s}(Sa?.llm),Ra=function(e){if(e)return e;const t=Fn(),n=new qn(t),r=new zn(t,n);t.registerLanguageRuntime(Un),t.registerLanguageRuntime(Vn),t.registerLanguageRuntime(Kn),t.registerLanguageRuntime(Wn),t.registerLanguageRuntime(Gn);const s=new Map;return{async*run(e,t){const n=t?.runId??Yn("run"),i=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});s.set(n,i);try{for await(const n of i.run(e,t))yield n}finally{s.delete(n),await i.close()}},async cancel(e){const t=s.get(e);t&&(await t.interrupt(),s.delete(e))},session:r,registry:t}}(Sa?.compute),$a=function(e){if(e)return e;const t=Qn(),n=new Zn(t);return{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],s=t.getProvider(r);if(!s)throw new Error(`Dataset provider not found: ${r}`);return s.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}}(Sa?.datasets),Oa=function(e){if(e)return e;const t=tr(),n=new nr(t);return{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],s=t.getProvider(r);if(!s)throw new Error(`Model provider not found: ${r}`);return s.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}}(Sa?.models),Da=function(e){if(e)return e;const t=ir();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,s=t.select(r);if(!s){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 s.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)}}}(Sa?.modelRuntimes),ja=function(e){if(e)return e;const t=ir();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)}}}(Sa?.inference),Fa=function(e){return e||{upsert:(e,t)=>hr().upsert(e,t),query:e=>hr().query(e),delete:(e,t)=>hr().delete(e,t),clear:e=>hr().clear(e),count:e=>hr().count(e)}}(Sa?.vectors),qa=function(e){if(e)return e;function t(){const e=mr().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=mr().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}function r(){const e=mr().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 s={start:e=>r().start(e),stop:()=>r().stop(),status:()=>r().status(),onRequest:e=>r().onRequest(e),reply:(e,t)=>r().reply(e,t)},i={info:e=>{const t=mr().system;return t?t.info(e):Promise.reject(new Error("[Runtime.host] No machine-facts (system) surface is registered. This is only available on hosts that can measure the machine (e.g. Electron); a browser host does not provide it."))}};return{dataDir:()=>mr().dataDir(),dataFs:{list:(e,t)=>mr().dataFs.list(e,t),readFile:e=>mr().dataFs.readFile(e),stat:e=>mr().dataFs.stat(e),mkdir:(e,t)=>mr().dataFs.mkdir(e,t),deleteFile:e=>mr().dataFs.deleteFile(e),deleteFolder:e=>mr().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=mr().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=mr().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=>n().requestJson(e),get download(){const e=fr?.http?.download;if(e)return e=>n().download(e)},get onDownloadProgress(){const e=fr?.http?.onDownloadProgress;if(e)return e=>n().onDownloadProgress(e)}},get mcpServer(){return fr?.mcpServer?s:void 0},get system(){return fr?.system?i:void 0}}}(Sa?.host),Ba=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&Zs(e);return{set:(e,t)=>Hs.get().set(e,t),get:e=>Hs.get().get(e),delete:e=>Hs.get().delete(e),list:()=>Hs.get().list(),resolve:async e=>{const t=await async function(e){try{const t=punica.kernel?.Commands?.manager?.executeCommand("secrets.get",{name:e}),n=await Promise.resolve(t);if(void 0===n)return;const r=n.value;return"string"==typeof r&&""!==r?r:null}catch{return}}(e);return void 0!==t?t:Hs.get().get(`secret-manager.${e}`)},__punicaWrappedSecretsFacade:!0}}(Sa?.secrets);console.log("[Runtime] Facades created"),function(){Xo({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}}),wr.registerProvider(new qs),Xo({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"}}),wr.registerProvider(new Bs),Xo({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}}),wr.registerProvider(new Us),Xo({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}}),wr.registerProvider(new Vs),Xo({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}}),wr.registerProvider(new Ks),Xo({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"}}),wr.registerProvider(new Ws),Xo({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"}}),wr.registerProvider(new Gs),Xo({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}}),wr.registerProvider(new Js),Xo({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}}),wr.registerProvider(new Ys),Xo({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}}),wr.registerProvider(new zs),Xo({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}}),wr.registerProvider(new Xs),Xo({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"}}),wr.registerProvider(new ei),Xo({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}}}),wr.registerProvider(new ni),Xo({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}}}),wr.registerProvider(new ri),Xo({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}}}),wr.registerProvider(new ii),Xo({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}}}),wr.registerProvider(new si),Xo({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}}),wr.registerProvider(new oi),Xo({name:"vcs.status",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),wr.registerProvider(new ai),Xo({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"}}),wr.registerProvider(new ci),Xo({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}}),wr.registerProvider(new li),Xo({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"}}),wr.registerProvider(new ui),Xo({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}}),wr.registerProvider(new di),Xo({name:"workspace.projectContext",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),wr.registerProvider(new Ai),Xo({name:"workspace.writeOrientation",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",properties:{claudeMd:{type:"boolean"},claudeignore:{type:"boolean"}}},outputSchema:{type:"object",properties:{written:{type:"array",items:{type:"string"}}}},defaults:{timeoutMs:3e4,idempotency:"optional"}}),wr.registerProvider(new Ci),Xo({name:"context.remember",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["key"],properties:{key:{type:"string"},value:{}}},outputSchema:{type:"object",properties:{key:{type:"string"},count:{type:"number"}}},defaults:{timeoutMs:1e4,idempotency:"optional"}}),wr.registerProvider(new Pi),Xo({name:"context.recall",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{key:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),wr.registerProvider(new _i),Xo({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"}}),wr.registerProvider(new Li),Xo({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"}}),wr.registerProvider(new Ri),Xo({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"}}),wr.registerProvider(new $i),Xo({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}}),wr.registerProvider(new Oi),Xo({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"}}),wr.registerProvider(new Di),Xo({name:ji,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}}),wr.registerProvider(new Fi),Xo({name:Gi,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}}),wr.registerProvider(new Yi),Xo({name:Xi,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}}),wr.registerProvider(new eo),Xo({name:no,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}}),wr.registerProvider(new io),Xo({name:to,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}}),wr.registerProvider(new so);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[ao("ai.session.create",{properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),ao("ai.session.list",{properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),ao("ai.session.get",{required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),ao("ai.session.rename",{required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),ao("ai.session.archive",{required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),ao("ai.session.delete",{risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())Xo(e);for(const e of[new co,new lo,new uo,new po,new fo,new ho])wr.registerProvider(e);Xo({name:To,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}}),wr.registerProvider(new Mo),Xo({name:Lo,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}}),wr.registerProvider(new Oo),Xo({name:Ro,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}}),wr.registerProvider(new Do),Xo({name:jo,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}}),wr.registerProvider(new Go),Xo({name:Fo,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}}),wr.registerProvider(new Yo),Xo({name:qo,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}}),wr.registerProvider(new zo),Xo({name:Bo,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}}),wr.registerProvider(new Jo),Xo({name:Uo,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}}),wr.registerProvider(new Qo),Xo({name:Vo,version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId","slot"],properties:{viewId:{type:"string"},slot:{type:"string"}}},outputSchema:{type:"object",required:["viewId","slot","moved"],properties:{viewId:{type:"string"},slot:{type:"string"},moved:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),wr.registerProvider(new Zo)}(),console.log("[Runtime] Capabilities registered");const Ua={lifecyclePhase:Sa?.lifecyclePhase??"bootstrapping",fs:Aa,fileOpeners:Sa?.fileOpeners??fn,search:xa,vcs:Ca,terminals:Ta,debug:Ma,tasks:Na,workspace:Pa,resources:_a,secrets:Ba,llm:La,compute:Ra,datasets:$a,models:Oa,modelRuntimes:Da,inference:ja,vectors:Fa,host:qa,capabilities:{gateway:Ds,unifiedRegistry:Lr,logTrinityCatalog:na,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??"—",s=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${s}`);const i=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";return n.push(`**Side effects:** ${i}`),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(oa(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(oa(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 s=t.requires;if(s&&s.length>0){n.push("## Requires"),n.push("");for(const e of s)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 i=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(i&&(n.push("## Source"),n.push(""),n.push(i),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(`## ${sa(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(ia(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:aa,connect:e=>ha.connect(e),disconnect:e=>ha.disconnect(e),listServers:()=>ha.listServers(),listTools:e=>ha.listTools(e),callTool:(e,t,n)=>ha.callTool(e,t,n)},setFsProvider:function(e){Yr.set(e),e&&xn({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:On,setComputeProvider:function(e){Fn().registerProvider(e)},setComputeRuntime:function(e){Fn().registerLanguageRuntime(e)},setDatasetProvider:function(e){Qn().registerProvider(e)},setModelProvider:function(e){tr().registerProvider(e)},setModelRuntime:function(e){ir().register(e)},setHostProvider:function(e){fr=e},setVectorsProvider:function(e){dr=e},setSearchProvider:function(e){mn=e},setWorkspaceProvider:Mn,setTerminalProvider:function(e){yn=e},setDebugProvider:function(e){wn=e},setVcsProvider:function(e){vn=e},setResourcesProvider:function(e){hn=e},setTasksProvider:function(e){gn=e},setSecretsProvider:Zs};class Va{#be;constructor(e){this.#be=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#be);n?e(n):t(new Error("Extension not found"))})}}let Ka=class{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}},Wa=class extends Ka{constructor(e){super(e)}async execute(){return await super.execute()}},Ga=class extends Ka{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))}}},Ya=class extends Ka{constructor(e){super(e)}async execute(){return await super.execute()}};const za=Symbol.for("yaml.alias"),Ja=Symbol.for("yaml.document"),Ha=Symbol.for("yaml.map"),Qa=Symbol.for("yaml.pair"),Za=Symbol.for("yaml.scalar"),Xa=Symbol.for("yaml.seq"),ec=Symbol.for("yaml.node.type"),tc=e=>!!e&&"object"==typeof e&&e[ec]===za,nc=e=>!!e&&"object"==typeof e&&e[ec]===Ja,rc=e=>!!e&&"object"==typeof e&&e[ec]===Ha,sc=e=>!!e&&"object"==typeof e&&e[ec]===Qa,ic=e=>!!e&&"object"==typeof e&&e[ec]===Za,oc=e=>!!e&&"object"==typeof e&&e[ec]===Xa;function ac(e){if(e&&"object"==typeof e)switch(e[ec]){case Ha:case Xa:return!0}return!1}function cc(e){if(e&&"object"==typeof e)switch(e[ec]){case za:case Ha:case Za:case Xa:return!0}return!1}const lc=Symbol("break visit"),uc=Symbol("skip children"),dc=Symbol("remove node");function pc(e,t){const n=gc(t);if(nc(e)){fc(null,e.contents,n,Object.freeze([e]))===dc&&(e.contents=null)}else fc(null,e,n,Object.freeze([]))}function fc(e,t,n,r){const s=yc(e,t,n,r);if(cc(s)||sc(s))return wc(e,r,s),fc(e,s,n,r);if("symbol"!=typeof s)if(ac(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=fc(e,t.items[e],n,r);if("number"==typeof s)e=s-1;else{if(s===lc)return lc;s===dc&&(t.items.splice(e,1),e-=1)}}}else if(sc(t)){r=Object.freeze(r.concat(t));const e=fc("key",t.key,n,r);if(e===lc)return lc;e===dc&&(t.key=null);const s=fc("value",t.value,n,r);if(s===lc)return lc;s===dc&&(t.value=null)}return s}async function hc(e,t){const n=gc(t);if(nc(e)){await mc(null,e.contents,n,Object.freeze([e]))===dc&&(e.contents=null)}else await mc(null,e,n,Object.freeze([]))}async function mc(e,t,n,r){const s=await yc(e,t,n,r);if(cc(s)||sc(s))return wc(e,r,s),mc(e,s,n,r);if("symbol"!=typeof s)if(ac(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=await mc(e,t.items[e],n,r);if("number"==typeof s)e=s-1;else{if(s===lc)return lc;s===dc&&(t.items.splice(e,1),e-=1)}}}else if(sc(t)){r=Object.freeze(r.concat(t));const e=await mc("key",t.key,n,r);if(e===lc)return lc;e===dc&&(t.key=null);const s=await mc("value",t.value,n,r);if(s===lc)return lc;s===dc&&(t.value=null)}return s}function gc(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 yc(e,t,n,r){return"function"==typeof n?n(e,t,r):rc(t)?n.Map?.(e,t,r):oc(t)?n.Seq?.(e,t,r):sc(t)?n.Pair?.(e,t,r):ic(t)?n.Scalar?.(e,t,r):tc(t)?n.Alias?.(e,t,r):void 0}function wc(e,t,n){const r=t[t.length-1];if(ac(r))r.items[e]=n;else if(sc(r))"key"===e?r.key=n:r.value=n;else{if(!nc(r)){const e=tc(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}pc.BREAK=lc,pc.SKIP=uc,pc.REMOVE=dc,hc.BREAK=lc,hc.SKIP=uc,hc.REMOVE=dc;const vc={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},bc=e=>e.replace(/[!,[\]{}]/g,e=>vc[e]);class Ic{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Ic.defaultYaml,e),this.tags=Object.assign({},Ic.defaultTags,t)}clone(){const e=new Ic(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Ic(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Ic.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Ic.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Ic.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Ic.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 s=this.tags[n];if(s)try{return s+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+bc(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&&cc(e.contents)){const t={};pc(e.contents,(e,n)=>{cc(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(const[s,i]of n)"!!"===s&&"tag:yaml.org,2002:"===i||e&&!r.some(e=>e.startsWith(i))||t.push(`%TAG ${s} ${i}`);return t.join("\n")}}function kc(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 Ec(e){const t=new Set;return pc(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Sc(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function Ac(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],s=Ac(e,r,String(t),n);void 0===s?delete r[t]:s!==n&&(r[t]=s)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),s=Ac(e,r,t,n);void 0===s?r.delete(t):s!==n&&r.set(t,s)}else if(r instanceof Set)for(const t of Array.from(r)){const n=Ac(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 s=Ac(e,r,t,n);void 0===s?delete r[t]:s!==n&&(r[t]=s)}return e.call(t,n,r)}function xc(e,t,n){if(Array.isArray(e))return e.map((e,t)=>xc(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!ic(r=e)&&!ac(r)||!r.anchor))return e.toJSON(t,n);const s={aliasCount:0,count:1,res:void 0};n.anchors.set(e,s),n.onCreate=e=>{s.res=e,delete n.onCreate};const i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}var r;return"bigint"!=typeof e||n?.keep?e:Number(e)}Ic.defaultYaml={explicit:!1,version:"1.2"},Ic.defaultTags={"!!":"tag:yaml.org,2002:"};class Cc{constructor(e){Object.defineProperty(this,ec,{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:s}={}){if(!nc(e))throw new TypeError("A document argument is required");const i={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=xc(this,"",i);if("function"==typeof r)for(const{count:e,res:t}of i.anchors.values())r(t,e);return"function"==typeof s?Ac(s,{"":o},"",o):o}}class Tc extends Cc{constructor(e){super(za),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return pc(e,{Node:(e,n)=>{if(n===this)return pc.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:s}=t,i=this.resolve(r);if(!i){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(i);if(o||(xc(i,null,t),o=n.get(i)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(s>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=Mc(r,i,n)),o.count*o.aliasCount>s)){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(kc(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 Mc(e,t,n){if(tc(t)){const r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}if(ac(t)){let r=0;for(const s of t.items){const t=Mc(e,s,n);t>r&&(r=t)}return r}if(sc(t)){const r=Mc(e,t.key,n),s=Mc(e,t.value,n);return Math.max(r,s)}return 1}const Nc=e=>!e||"function"!=typeof e&&"object"!=typeof e;class Pc extends Cc{constructor(e){super(Za),this.value=e}toJSON(e,t){return t?.keep?this.value:xc(this.value,e,t)}toString(){return String(this.value)}}Pc.BLOCK_FOLDED="BLOCK_FOLDED",Pc.BLOCK_LITERAL="BLOCK_LITERAL",Pc.PLAIN="PLAIN",Pc.QUOTE_DOUBLE="QUOTE_DOUBLE",Pc.QUOTE_SINGLE="QUOTE_SINGLE";function _c(e,t,n){if(nc(e)&&(e=e.contents),cc(e))return e;if(sc(e)){const t=n.schema[Ha].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:s,onTagObj:i,schema:o,sourceObjects:a}=n;let c;if(r&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=s(e)),new Tc(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 Pc(e);return c&&(c.node=t),t}l=e instanceof Map?o[Ha]:Symbol.iterator in Object(e)?o[Xa]:o[Ha]}i&&(i(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 Pc(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Lc(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 _c(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 Rc=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class $c extends Cc{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=>cc(t)||sc(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Rc(e))this.add(t);else{const[n,...r]=e,s=this.get(n,!0);if(ac(s))s.addIn(r,t);else{if(void 0!==s||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,Lc(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(ac(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,s=this.get(n,!0);return 0===r.length?!t&&ic(s)?s.value:s:ac(s)?s.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!sc(t))return!1;const n=t.value;return null==n||e&&ic(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!!ac(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(ac(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,Lc(this.schema,r,t))}}}}$c.maxFlowStringSingleLineLength=60;const Oc=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Dc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const jc=(e,t,n)=>e.endsWith("\n")?Dc(n,t):n.includes("\n")?"\n"+Dc(n,t):(e.endsWith(" ")?"":" ")+n,Fc="flow",qc="block",Bc="quoted";function Uc(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return e;const c=Math.max(1+i,1+s-t.length);if(e.length<=c)return e;const l=[],u={};let d,p,f=s-t.length;"number"==typeof r&&(r>s-Math.max(2,i)?l.push(0):f=s-r);let h=!1,m=-1,g=-1,y=-1;n===qc&&(m=Vc(e,m,t.length),-1!==m&&(f=m+c));for(let r;r=e[m+=1];){if(n===Bc&&"\\"===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===qc&&(m=Vc(e,m,t.length)),f=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>=f)if(d)l.push(d),f=d+c,d=void 0;else if(n===Bc){for(;" "===p||"\t"===p;)p=r,r=e[m+=1],h=!0;const t=m>y+1?m-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,f=t+c,d=void 0}else h=!0}p=r}if(h&&a&&a(),0===l.length)return e;o&&o();let w=e.slice(0,l[0]);for(let r=0;r<l.length;++r){const s=l[r],i=l[r+1]||e.length;0===s?w=`\n${t}${e.slice(0,i)}`:(n===Bc&&u[s]&&(w+=`${e[s]}\\`),w+=`\n${t}${e.slice(s+1,i)}`)}return w}function Vc(e,t,n){let r=t,s=t+1,i=e[s];for(;" "===i||"\t"===i;)if(t<s+n)i=e[++t];else{do{i=e[++t]}while(i&&"\n"!==i);r=t,s=t+1,i=e[s]}return r}const Kc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Wc=e=>/^(%|---|\.\.\.)/m.test(e);function Gc(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(Wc(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<s)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+=i," "===n[e+2]&&(o+="\\"),e+=1,a=e+1}break;default:e+=1}return o=a?o+n.slice(a):n,r?o:Uc(o,i,Bc,Kc(t,!1))}function Yc(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return Gc(e,t);const n=t.indent||(Wc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:Uc(r,n,Fc,Kc(t,!1))}function zc(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=Gc;else{const t=e.includes('"'),s=e.includes("'");r=t&&!s?Yc:s&&!t?Gc:n?Yc:Gc}return r(e,t)}let Jc;try{Jc=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{Jc=/\n+(?!\n|$)/g}function Hc({comment:e,type:t,value:n},r,s,i){const{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return zc(n,r);const l=r.indent||(r.forceBlockIndent||Wc(n)?" ":""),u="literal"===o||"folded"!==o&&t!==Pc.BLOCK_FOLDED&&(t===Pc.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const r=t-n,s=e.length;if(s<=r)return!1;for(let t=0,n=0;t<s;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,s-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 f=n.substring(p);const h=f.indexOf("\n");-1===h?d="-":n===f||h!==f.length-1?(d="+",i&&i()):d="",f&&(n=n.slice(0,-f.length),"\n"===f[f.length-1]&&(f=f.slice(0,-1)),f=f.replace(Jc,`$&${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 w=n.substring(0,y<m?y+1:m);w&&(n=n.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let v=(u?"|":">")+(g?l?"2":"1":"")+d;if(e&&(v+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),u)return`${v}\n${l}${w}${n=n.replace(/\n+/g,`$&${l}`)}${f}`;return`${v}\n${l}${Uc(`${w}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${f}`,l,qc,Kc(r,!0))}`}function Qc(e,t,n,r){const{implicitKey:s,inFlow:i}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Pc.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Pc.QUOTE_DOUBLE);const c=e=>{switch(e){case Pc.BLOCK_FOLDED:case Pc.BLOCK_LITERAL:return s||i?zc(o.value,t):Hc(o,t,n,r);case Pc.QUOTE_DOUBLE:return Gc(o.value,t);case Pc.QUOTE_SINGLE:return Yc(o.value,t);case Pc.PLAIN:return function(e,t,n,r){const{type:s,value:i}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&i.includes("\n")||u&&/[[\]{},]/.test(i))return zc(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes("\n")?zc(i,t):Hc(e,t,n,r);if(!a&&!u&&s!==Pc.PLAIN&&i.includes("\n"))return Hc(e,t,n,r);if(Wc(i)){if(""===c)return t.forceBlockIndent=!0,Hc(e,t,n,r);if(a&&c===l)return zc(i,t)}const d=i.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 zc(i,t)}return a?d:Uc(d,c,Fc,Kc(t,!1))}(o,t,n,r);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=s&&e||n;if(l=c(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}function Zc(e,t){const n=Object.assign({blockQuote:!0,commentString:Oc,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 Xc(e,t,n,r){if(sc(e))return e.toString(t,n,r);if(tc(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 s;const i=cc(e)?e:t.doc.createNode(e,{onTagObj:e=>s=e});s||(s=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(ic(t)){r=t.value;const s=e.filter(e=>e.identify?.(r));n=s.find(e=>e.format===t.format)??s.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,i));const o=function(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const s=[],i=(ic(e)||ac(e))&&e.anchor;i&&kc(i)&&(n.add(i),s.push(`&${i}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&s.push(r.directives.tagString(o)),s.join(" ")}(i,s,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof s.stringify?s.stringify(i,t,n,r):ic(i)?Qc(i,t,n,r):i.toString(t,n,r);return o?ic(i)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function el(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function tl(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&nl(n))if(r=tc(r)?r.resolve(e.doc):r,oc(r))for(const n of r.items)rl(e,t,n);else if(Array.isArray(r))for(const n of r)rl(e,t,n);else rl(e,t,r);else{const s=xc(n,"",e);if(t instanceof Map)t.set(s,xc(r,s,e));else if(t instanceof Set)t.add(s);else{const i=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(cc(e)&&n?.doc){const t=Zc(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)+'..."'),el(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,s,e),o=xc(r,i,e);i in t?Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[i]=o}}return t}const nl=e=>"<<"===e||ic(e)&&"<<"===e.value&&(!e.type||e.type===Pc.PLAIN);function rl(e,t,n){const r=e&&tc(n)?n.resolve(e.doc):n;if(!rc(r))throw new Error("Merge sources must be maps or map aliases");const s=r.toJSON(null,e,Map);for(const[e,n]of s)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 sl(e,t,n){const r=_c(e,void 0,n),s=_c(t,void 0,n);return new il(r,s)}class il{constructor(e,t=null){Object.defineProperty(this,ec,{value:Qa}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return cc(t)&&(t=t.clone(e)),cc(n)&&(n=n.clone(e)),new il(t,n)}toJSON(e,t){return tl(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,r,s){const{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n;let p=cc(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(ac(e)||!cc(e)&&"object"==typeof e)throw new Error("With simple keys, collection cannot be used as a key value")}let f=!d&&(!e||p&&null==t&&!n.inFlow||ac(e)||(ic(e)?e.type===Pc.BLOCK_FOLDED||e.type===Pc.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!f&&(d||!i),indent:a+c});let h,m,g,y=!1,w=!1,v=Xc(e,n,()=>y=!0,()=>w=!0);if(!f&&!n.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(n.inFlow){if(i||null==t)return y&&r&&r(),""===v?"?":f?`? ${v}`:v}else if(i&&!d||null==t&&f)return v=`? ${v}`,p&&!y?v+=jc(v,n.indent,l(p)):w&&s&&s(),v;y&&(p=null),f?(p&&(v+=jc(v,n.indent,l(p))),v=`? ${v}\n${a}:`):(v=`${v}:`,p&&(v+=jc(v,n.indent,l(p)))),cc(t)?(h=!!t.spaceBefore,m=t.commentBefore,g=t.comment):(h=!1,m=null,g=null,t&&"object"==typeof t&&(t=o.createNode(t))),n.implicitKey=!1,f||p||!ic(t)||(n.indentAtStart=v.length+1),w=!1,u||!(c.length>=2)||n.inFlow||f||!oc(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let b=!1;const I=Xc(t,n,()=>b=!0,()=>w=!0);let k=" ";if(p||h||m)k=h?"\n":"",m&&(k+=`\n${Dc(l(m),n.indent)}`),""!==I||n.inFlow?k+=`\n${n.indent}`:"\n"===k&&(k="\n\n");else if(!f&&ac(t)){const e=I[0],r=I.indexOf("\n"),s=-1!==r,i=n.inFlow??t.flow??0===t.items.length;if(s||!i){let t=!1;if(s&&("&"===e||"!"===e)){let n=I.indexOf(" ");"&"===e&&-1!==n&&n<r&&"!"===I[n+1]&&(n=I.indexOf(" ",n+1)),(-1===n||r<n)&&(t=!0)}t||(k=`\n${n.indent}`)}}else""!==I&&"\n"!==I[0]||(k="");return v+=k+I,n.inFlow?b&&r&&r():g&&!b?v+=jc(v,n.indent,l(g)):w&&s&&s(),v}(this,e,t,n):JSON.stringify(this)}}function ol(e,t,n){return(t.inFlow??e.flow?cl:al)(e,t,n)}function al({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:i,type:null});let d=!1;const p=[];for(let e=0;e<t.length;++e){const s=t[e];let o=null;if(cc(s))!d&&s.spaceBefore&&p.push(""),ll(n,p,s.commentBefore,d),s.comment&&(o=s.comment);else if(sc(s)){const e=cc(s.key)?s.key:null;e&&(!d&&e.spaceBefore&&p.push(""),ll(n,p,e.commentBefore,d))}d=!1;let a=Xc(s,u,()=>o=null,()=>d=!0);o&&(a+=jc(a,i,l(o))),d&&o&&(d=!1),p.push(r+a)}let f;if(0===p.length)f=s.start+s.end;else{f=p[0];for(let e=1;e<p.length;++e){const t=p[e];f+=t?`\n${c}${t}`:"\n"}}return e?(f+="\n"+Dc(l(e),c),a&&a()):d&&o&&o(),f}function cl({items:e},t,{flowChars:n,itemIndent:r}){const{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=t;r+=i;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 s=e[n];let i=null;if(cc(s))s.spaceBefore&&d.push(""),ll(t,d,s.commentBefore,!1),s.comment&&(i=s.comment);else if(sc(s)){const e=cc(s.key)?s.key:null;e&&(e.spaceBefore&&d.push(""),ll(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=cc(s.value)?s.value:null;n?(n.comment&&(i=n.comment),n.commentBefore&&(l=!0)):null==s.value&&e?.comment&&(i=e.comment)}i&&(l=!0);let o=Xc(s,c,()=>i=null);n<e.length-1&&(o+=","),i&&(o+=jc(o,r,a(i))),!l&&(d.length>u||o.includes("\n"))&&(l=!0),d.push(o),u=d.length}const{start:p,end:f}=n;if(0===d.length)return p+f;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${i}${s}${t}`:"\n";return`${e}\n${s}${f}`}return`${p}${o}${d.join(" ")}${o}${f}`}function ll({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){const s=Dc(t(r),e);n.push(s.trimStart())}}function ul(e,t){const n=ic(t)?t.value:t;for(const r of e)if(sc(r)){if(r.key===t||r.key===n)return r;if(ic(r.key)&&r.key.value===n)return r}}class dl extends $c{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ha,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:s}=n,i=new this(e),o=(e,o)=>{if("function"==typeof s)o=s.call(t,e,o);else if(Array.isArray(s)&&!s.includes(e))return;(void 0!==o||r)&&i.items.push(sl(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&&i.items.sort(e.sortMapEntries),i}add(e,t){let n;n=sc(e)?e:e&&"object"==typeof e&&"key"in e?new il(e.key,e.value):new il(e,e?.value);const r=ul(this.items,n.key),s=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);ic(r.value)&&Nc(n.value)?r.value.value=n.value:r.value=n.value}else if(s){const e=this.items.findIndex(e=>s(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=ul(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=ul(this.items,e),r=n?.value;return(!t&&ic(r)?r.value:r)??void 0}has(e){return!!ul(this.items,e)}set(e,t){this.add(new il(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)tl(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!sc(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})),ol(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const pl={collection:"map",default:!0,nodeClass:dl,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(rc(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>dl.from(e,t,n)};class fl extends $c{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Xa,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=hl(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=hl(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&ic(r)?r.value:r}has(e){const t=hl(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=hl(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];ic(r)&&Nc(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(xc(e,String(r++),t));return n}toString(e,t,n){return e?ol(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,s=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let i of t){if("function"==typeof r){const n=t instanceof Set?i:String(e++);i=r.call(t,n,i)}s.items.push(_c(i,void 0,n))}}return s}}function hl(e){let t=ic(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const ml={collection:"seq",default:!0,nodeClass:fl,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(oc(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>fl.from(e,t,n)},gl={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>Qc(e,t=Object.assign({actualString:!0},t),n,r)},yl={identify:e=>null==e,createNode:()=>new Pc(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Pc(null),stringify:({source:e},t)=>"string"==typeof e&&yl.test.test(e)?e:t.options.nullStr},wl={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Pc("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&wl.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function vl({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const s="number"==typeof r?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(i)){let e=i.indexOf(".");e<0&&(e=i.length,i+=".");let n=t-(i.length-e-1);for(;n-- >0;)i+="0"}return i}const bl={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:vl},Il={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():vl(e)}},kl={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 Pc(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:vl},El=e=>"bigint"==typeof e||Number.isInteger(e),Sl=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Al(e,t,n){const{value:r}=e;return El(r)&&r>=0?n+r.toString(t):vl(e)}const xl={identify:e=>El(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Sl(e,2,8,n),stringify:e=>Al(e,8,"0o")},Cl={identify:El,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Sl(e,0,10,n),stringify:vl},Tl={identify:e=>El(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Sl(e,2,16,n),stringify:e=>Al(e,16,"0x")},Ml=[pl,ml,gl,yl,wl,xl,Cl,Tl,bl,Il,kl];function Nl(e){return"bigint"==typeof e||Number.isInteger(e)}const Pl=({value:e})=>JSON.stringify(e),_l=[pl,ml].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Pl},{identify:e=>null==e,createNode:()=>new Pc(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Pl},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:Pl},{identify:Nl,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})=>Nl(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:Pl}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),Ll={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,s,i){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=Pc.BLOCK_LITERAL),t!==Pc.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(a.length/e),s=new Array(n);for(let t=0,r=0;t<n;++t,r+=e)s[t]=a.substr(r,e);a=s.join(t===Pc.BLOCK_LITERAL?"\n":" ")}return Qc({comment:e,type:t,value:a},r,s,i)}};function Rl(e,t){if(oc(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!sc(r)){if(rc(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new il(new Pc(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]=sc(r)?r:new il(r)}}else t("Expected a sequence for this tag");return e}function $l(e,t,n){const{replacer:r}=n,s=new fl(e);s.tag="tag:yaml.org,2002:pairs";let i=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(i++),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;s.items.push(sl(o,a,n))}return s}const Ol={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Rl,createNode:$l};class Dl extends fl{constructor(){super(),this.add=dl.prototype.add.bind(this),this.delete=dl.prototype.delete.bind(this),this.get=dl.prototype.get.bind(this),this.has=dl.prototype.has.bind(this),this.set=dl.prototype.set.bind(this),this.tag=Dl.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,s;if(sc(e)?(r=xc(e.key,"",t),s=xc(e.value,r,t)):r=xc(e,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,s)}return n}static from(e,t,n){const r=$l(e,t,n),s=new this;return s.items=r.items,s}}Dl.tag="tag:yaml.org,2002:omap";const jl={collection:"seq",identify:e=>e instanceof Map,nodeClass:Dl,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=Rl(e,t),r=[];for(const{key:e}of n.items)ic(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new Dl,n)},createNode:(e,t,n)=>Dl.from(e,t,n)};function Fl({value:e,source:t},n){return t&&(e?ql:Bl).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const ql={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 Pc(!0),stringify:Fl},Bl={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 Pc(!1),stringify:Fl},Ul={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:vl},Vl={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():vl(e)}},Kl={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 Pc(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:vl},Wl=e=>"bigint"==typeof e||Number.isInteger(e);function Gl(e,t,n,{intAsBigInt:r}){const s=e[0];if("-"!==s&&"+"!==s||(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"-"===s?BigInt(-1)*t:t}const i=parseInt(e,n);return"-"===s?-1*i:i}function Yl(e,t,n){const{value:r}=e;if(Wl(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return vl(e)}const zl={identify:Wl,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Gl(e,2,2,n),stringify:e=>Yl(e,2,"0b")},Jl={identify:Wl,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Gl(e,1,8,n),stringify:e=>Yl(e,8,"0")},Hl={identify:Wl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Gl(e,0,10,n),stringify:vl},Ql={identify:Wl,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Gl(e,2,16,n),stringify:e=>Yl(e,16,"0x")};class Zl extends dl{constructor(e){super(e),this.tag=Zl.tag}add(e){let t;t=sc(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new il(e.key,null):new il(e,null);ul(this.items,t.key)||this.items.push(t)}get(e,t){const n=ul(this.items,e);return!t&&sc(n)?ic(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=ul(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new il(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,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof r&&(e=r.call(t,e,e)),s.items.push(sl(e,null,n));return s}}Zl.tag="tag:yaml.org,2002:set";const Xl={collection:"map",identify:e=>e instanceof Set,nodeClass:Zl,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Zl.from(e,t,n),resolve(e,t){if(rc(e)){if(e.hasAllNullValues(!0))return Object.assign(new Zl,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function eu(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,s=e=>t?BigInt(e):Number(e),i=r.replace(/_/g,"").split(":").reduce((e,t)=>e*s(60)+s(t),s(0));return"-"===n?s(-1)*i:i}function tu(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return vl(e);let r="";t<0&&(r="-",t*=n(-1));const s=n(60),i=[t%s];return t<60?i.unshift(0):(t=(t-i[0])/s,i.unshift(t%s),t>=60&&(t=(t-i[0])/s,i.unshift(t))),r+i.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const nu={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})=>eu(e,n),stringify:tu},ru={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=>eu(e,!1),stringify:tu},su={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(su.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,s,i,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,r-1,s,i||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=eu(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$/,"")},iu=[pl,ml,gl,yl,ql,Bl,zl,Jl,Hl,Ql,Ul,Vl,Kl,Ll,jl,Ol,Xl,nu,ru,su],ou=new Map([["core",Ml],["failsafe",[pl,ml,gl]],["json",_l],["yaml11",iu],["yaml-1.1",iu]]),au={binary:Ll,bool:wl,float:kl,floatExp:Il,floatNaN:bl,floatTime:ru,int:Cl,intHex:Tl,intOct:xl,intTime:nu,map:pl,null:yl,omap:jl,pairs:Ol,seq:ml,set:Xl,timestamp:su},cu={"tag:yaml.org,2002:binary":Ll,"tag:yaml.org,2002:omap":jl,"tag:yaml.org,2002:pairs":Ol,"tag:yaml.org,2002:set":Xl,"tag:yaml.org,2002:timestamp":su};function lu(e,t){let n=ou.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(ou.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=au[e];if(t)return t;const n=Object.keys(au).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const uu=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class du{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:s,sortMapEntries:i,toStringDefaults:o}){this.compat=Array.isArray(e)?lu(e,"compat"):e?lu(null,e):null,this.merge=!!n,this.name="string"==typeof s&&s||"core",this.knownTags=r?cu:{},this.tags=lu(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,Ha,{value:pl}),Object.defineProperty(this,Za,{value:gl}),Object.defineProperty(this,Xa,{value:ml}),this.sortMapEntries="function"==typeof i?i:!0===i?uu:null}clone(){const e=Object.create(du.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class pu{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ec,{value:Ja});let r=null;"function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t,t=void 0);const s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:i}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Ic({version:i}),this.setSchema(i,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(pu.prototype,{[ec]:{value:Ja}});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=cc(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){fu(this.contents)&&this.contents.add(e)}addIn(e,t){fu(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Ec(this);e.anchor=!t||n.has(t)?Sc(t||"a",n):t}return new Tc(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:s,anchorPrefix:i,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=function(e,t){const n=[],r=new Map;let s=null;return{onAnchor:r=>{n.push(r),s||(s=Ec(e));const i=Sc(t,s);return s.add(i),i},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!ic(t.node)&&!ac(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,i||"a"),f=_c(e,l,{aliasDuplicateObjects:s??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&ac(f)&&(f.flow=!0),d(),f}createPair(e,t,n={}){const r=this.createNode(e,null,n),s=this.createNode(t,null,n);return new il(r,s)}delete(e){return!!fu(this.contents)&&this.contents.delete(e)}deleteIn(e){return Rc(e)?null!=this.contents&&(this.contents=null,!0):!!fu(this.contents)&&this.contents.deleteIn(e)}get(e,t){return ac(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Rc(e)?!t&&ic(this.contents)?this.contents.value:this.contents:ac(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!ac(this.contents)&&this.contents.has(e)}hasIn(e){return Rc(e)?void 0!==this.contents:!!ac(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=Lc(this.schema,[e],t):fu(this.contents)&&this.contents.set(e,t)}setIn(e,t){Rc(e)?this.contents=t:null==this.contents?this.contents=Lc(this.schema,Array.from(e),t):fu(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 Ic({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 Ic({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 du(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:i}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},a=xc(this.contents,t??"",o);if("function"==typeof s)for(const{count:e,res:t}of o.anchors.values())s(t,e);return"function"==typeof i?Ac(i,{"":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 s=Zc(e,t),{commentString:i}=s.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=i(e.commentBefore);n.unshift(Dc(t,""))}let o=!1,a=null;if(e.contents){if(cc(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=i(e.contents.commentBefore);n.push(Dc(t,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=Xc(e.contents,s,()=>a=null,t);a&&(c+=jc(c,"",i(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(Xc(e.contents,s));if(e.directives?.docEnd)if(e.comment){const t=i(e.comment);t.includes("\n")?(n.push("..."),n.push(Dc(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(Dc(i(t),"")))}return n.join("\n")+"\n"}(this,e)}}function fu(e){if(ac(e))return!0;throw new Error("Expected a YAML collection as document contents")}class hu extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class mu extends hu{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class gu extends hu{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const yu=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let i=s-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){const e=Math.min(i-39,o.length-79);o="…"+o.substring(e),i-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,i))){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>s&&(e=Math.max(1,Math.min(t.col-s,80-i)));const a=" ".repeat(i)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function wu(e,{flow:t,indicator:n,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",p="",f=!1,h=!1,m=!1,g=null,y=null,w=null,v=null,b=null,I=null;for(const s of e)switch(m&&("space"!==s.type&&"newline"!==s.type&&"comma"!==s.type&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&"comment"!==s.type&&"newline"!==s.type&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),s.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!s.source.includes("\t")||(g=s),u=!0;break;case"comment":{u||i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=s.source.substring(1)||" ";d?d+=p+e:d=e,p="",l=!1;break}case"newline":l?d?d+=s.source:c=!0:p+=s.source,l=!0,f=!0,(y||w)&&(h=!0),u=!0;break;case"anchor":y&&i(s,"MULTIPLE_ANCHORS","A node can have at most one anchor"),s.source.endsWith(":")&&i(s.offset+s.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=s,null===I&&(I=s.offset),l=!1,u=!1,m=!0;break;case"tag":w&&i(s,"MULTIPLE_TAGS","A node can have at most one tag"),w=s,null===I&&(I=s.offset),l=!1,u=!1,m=!0;break;case n:(y||w)&&i(s,"BAD_PROP_ORDER",`Anchors and tags must be after the ${s.source} indicator`),b&&i(s,"UNEXPECTED_TOKEN",`Unexpected ${s.source} in ${t??"collection"}`),b=s,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){v&&i(s,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),v=s,l=!1,u=!1;break}default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${s.type} token`),l=!1,u=!1}const k=e[e.length-1],E=k?k.offset+k.source.length:s;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&i(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)&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:b,spaceBefore:c,comment:d,hasNewline:f,hasNewlineAfterProp:h,anchor:y,tag:w,end:E,start:I??E}}function vu(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(vu(t.key)||vu(t.value))return!0}return!1;default:return!0}}function bu(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&vu(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function Iu(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const s="function"==typeof r?r:(t,n)=>t===n||ic(t)&&ic(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>s(e.key,n))}const ku="All mapping items must start at the same column";function Eu(e,t,n,r){let s="";if(e){let i=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{n&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";s?s+=o+t:s=t,o="";break}case"newline":s&&(o+=e),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:s,offset:t}}const Su="Block collections are not allowed within flow collections",Au=e=>e&&("block-map"===e.type||"block-seq"===e.type);function xu(e,t,n,r,s,i){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,s,i){const o=new(i?.nodeClass??dl)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const i of r.items){const{start:l,key:u,sep:d,value:p}=i,f=wu(l,{indicator:"explicit-key-ind",next:u??d?.[0],offset:a,onError:s,parentIndent:r.indent,startOnNewline:!0}),h=!f.found;if(h){if(u&&("block-seq"===u.type?s(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&s(a,"BAD_INDENT",ku)),!f.anchor&&!f.tag&&!d){c=f.end,f.comment&&(o.comment?o.comment+="\n"+f.comment:o.comment=f.comment);continue}(f.hasNewlineAfterProp||vu(u))&&s(u??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==r.indent&&s(a,"BAD_INDENT",ku);const m=f.end,g=u?e(n,u,f,s):t(n,m,l,null,f,s);n.schema.compat&&bu(r.indent,u,s),Iu(n,o.items,g)&&s(m,"DUPLICATE_KEY","Map keys must be unique");const y=wu(d??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:s,parentIndent:r.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){h&&("block-map"!==p?.type||y.hasNewline||s(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&f.start<y.found.offset-1024&&s(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,s):t(n,a,d,null,y,s);n.schema.compat&&bu(r.indent,p,s),a=c.range[2];const l=new il(g,c);n.options.keepSourceTokens&&(l.srcToken=i),o.items.push(l)}else{h&&s(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 il(g);n.options.keepSourceTokens&&(e.srcToken=i),o.items.push(e)}}return c&&c<a&&s(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[r.offset,a,c??a],o}(e,t,n,r,i):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,s,i){const o=new(i?.nodeClass??fl)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:i,value:l}of r.items){const u=wu(i,{indicator:"seq-item-ind",next:l,offset:a,onError:s,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?s(u.end,"BAD_INDENT","All sequence items must start at the same column"):s(a,"MISSING_CHAR","Sequence item without - indicator")}const d=l?e(n,l,u,s):t(n,u.end,i,null,u,s);n.schema.compat&&bu(r.indent,l,s),a=d.range[2],o.items.push(d)}return o.range=[r.offset,a,c??a],o}(e,t,n,r,i):function({composeNode:e,composeEmptyNode:t},n,r,s,i){const o="{"===r.start.source,a=o?"flow map":"flow sequence",c=new(i?.nodeClass??(o?dl:fl))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1);let u=r.offset+r.start.source.length;for(let i=0;i<r.items.length;++i){const l=r.items[i],{start:d,key:p,sep:f,value:h}=l,m=wu(d,{flow:a,indicator:"explicit-key-ind",next:p??f?.[0],offset:u,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!m.found){if(!(m.anchor||m.tag||f||h)){0===i&&m.comma?s(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):i<r.items.length-1&&s(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&&vu(p)&&s(p,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===i)m.comma&&s(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||s(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];sc(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||f||m.found){const i=m.end,g=p?e(n,p,m,s):t(n,i,d,null,m,s);Au(p)&&s(g.range,"BLOCK_IN_FLOW",Su);const y=wu(f??[],{flow:a,indicator:"map-value-ind",next:h,offset:g.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(y.found){if(!o&&!m.found&&n.options.strict){if(f)for(const e of f){if(e===y.found)break;if("newline"===e.type){s(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<y.found.offset-1024&&s(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else h&&("source"in h&&h.source&&":"===h.source[0]?s(h,"MISSING_CHAR",`Missing space after : in ${a}`):s(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const w=h?e(n,h,y,s):y.found?t(n,y.end,f,null,y,s):null;w?Au(h)&&s(w.range,"BLOCK_IN_FLOW",Su):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const v=new il(g,w);if(n.options.keepSourceTokens&&(v.srcToken=l),o){const e=c;Iu(n,e.items,g)&&s(i,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(v)}else{const e=new dl(n.schema);e.flow=!0,e.items.push(v),c.items.push(e)}u=w?w.range[2]:y.end}else{const r=h?e(n,h,m,s):t(n,m.end,f,null,m,s);c.items.push(r),u=r.range[2],Au(h)&&s(r.range,"BLOCK_IN_FLOW",Su)}}const d=o?"}":"]",[p,...f]=r.end;let h=u;if(p&&p.source===d)h=p.offset+p.source.length;else{const e=a[0].toUpperCase()+a.substring(1);s(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&&f.unshift(p)}if(f.length>0){const e=Eu(f,h,n.options.strict,s);e.comment&&(c.comment?c.comment+="\n"+e.comment:c.comment=e.comment),c.range=[r.offset,h,e.offset]}else c.range=[r.offset,h,h];return c}(e,t,n,r,i),a=o.constructor;return"!"===s||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function Cu(e,t,n){const r=t.offset,s=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:s}=t[0],i=s[0];let o=0,a="",c=-1;for(let t=1;t<s.length;++t){const n=s[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: ${s}`);let l=!1,u="",d=s.length;for(let e=1;e<t.length;++e){const s=t[e];switch(s.type){case"space":l=!0;case"newline":d+=s.source.length;break;case"comment":if(n&&!l){r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=s.source.length,u=s.source.substring(1);break;case"error":r(s,"UNEXPECTED_TOKEN",s.message),d+=s.source.length;break;default:{r(s,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${s.type}`);const e=s.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:i,indent:o,chomp:a,comment:u,length:d}}(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};const i=">"===s.mode?Pc.BLOCK_FOLDED:Pc.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let e=1;e<t.length;e+=2)s.push([t[e],t[e+1]]);return s}(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="+"===s.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=r+s.length;return t.source&&(n+=t.source.length),{value:e,type:i,comment:s.comment,range:[r,n,n]}}let c=t.indent+s.indent,l=t.offset+s.length,u=0;for(let t=0;t<a;++t){const[r,i]=o[t];if(""!==i&&"\r"!==i){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===s.indent&&(c=r.length),u=t,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===s.indent&&r.length>c&&(c=r.length),l+=r.length+i.length+1}for(let e=o.length-1;e>=a;--e)o[e][0].length>c&&(a=e+1);let d="",p="",f=!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 ${s.indent?"explicit indentation indicator":"first line"}`;n(l-r.length-(a?2:1),"BAD_INDENT",e),t=""}i===Pc.BLOCK_LITERAL?(d+=p+t.slice(c)+r,p="\n"):t.length>c||"\t"===r[0]?(" "===p?p="\n":f||"\n"!==p||(p="\n\n"),d+=p+t.slice(c)+r,p="\n",f=!0):""===r?"\n"===p?d+="\n":p="\n":(d+=p+r,p=" ",f=!1)}switch(s.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 h=r+s.length+t.source.length;return{value:d,type:i,comment:s.comment,range:[r,h,h]}}function Tu(e,t,n){const{offset:r,type:s,source:i,end:o}=e;let a,c;const l=(e,t,s)=>n(r+e,t,s);switch(s){case"scalar":a=Pc.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 Mu(e)}(i,l);break;case"single-quoted-scalar":a=Pc.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Mu(e.slice(1,-1)).replace(/''/g,"'")}(i,l);break;case"double-quoted-scalar":a=Pc.QUOTE_DOUBLE,c=function(e,t){let n="";for(let r=1;r<e.length-1;++r){const s=e[r];if("\r"!==s||"\n"!==e[r+1])if("\n"===s){const{fold:t,offset:s}=Nu(e,r);n+=t,r=s}else if("\\"===s){let s=e[++r];const i=Pu[s];if(i)n+=i;else if("\n"===s)for(s=e[r+1];" "===s||"\t"===s;)s=e[1+ ++r];else if("\r"===s&&"\n"===e[r+1])for(s=e[1+ ++r];" "===s||"\t"===s;)s=e[1+ ++r];else if("x"===s||"u"===s||"U"===s){const i={x:2,u:4,U:8}[s];n+=_u(e,r+1,i,t),r+=i}else{const s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),n+=s}}else if(" "===s||"\t"===s){const t=r;let i=e[r+1];for(;" "===i||"\t"===i;)i=e[1+ ++r];"\n"===i||"\r"===i&&"\n"===e[r+2]||(n+=r>t?e.slice(t,r+1):s)}else n+=s}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(i,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}const u=r+i.length,d=Eu(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Mu(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 s=r[1],i=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)""===r[1]?"\n"===i?s+=i:i="\n":(s+=i+r[1],i=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,r=a.exec(e),s+i+(r?.[1]??"")}function Nu(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 Pu={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function _u(e,t,n,r){const s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(i)){const s=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}return String.fromCodePoint(i)}function Lu(e,t,n,r){const{value:s,type:i,comment:o,range:a}="block-scalar"===t.type?Cu(e,t,r):Tu(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,s){if("!"===n)return e[Za];const i=[];for(const t of e.tags)if(!t.collection&&t.tag===n){if(!t.default||!t.test)return t;i.push(t)}for(const e of i)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 s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[Za]}(e.schema,s,c,n,r):"scalar"===t.type?function({directives:e,schema:t},n,r,s){const i=t.tags.find(e=>e.default&&e.test?.test(n))||t[Za];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[Za];if(i.tag!==o.tag){s(r,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${e.tagString(i.tag)} or ${e.tagString(o.tag)}`,!0)}}return i}(e,s,t,r):e.schema[Za];let u;try{const i=l.resolve(s,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=ic(i)?i:new Pc(i)}catch(e){const i=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",i),u=new Pc(s)}return u.range=a,u.source=s,i&&(u.type=i),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Ru(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 $u={composeNode:Ou,composeEmptyNode:Du};function Ou(e,t,n,r){const{spaceBefore:s,comment:i,anchor:o,tag:a}=n;let c,l=!0;switch(t.type){case"alias":c=function({options:e},{offset:t,source:n,end:r},s){const i=new Tc(n.substring(1));""===i.source&&s(t,"BAD_ALIAS","Alias cannot be an empty string");i.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=Eu(r,o,e.strict,s);i.range=[t,o,a.offset],a.comment&&(i.comment=a.comment);return i}(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=Lu(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,s){const i=r?t.directives.tagName(r.source,e=>s(r,"TAG_RESOLVE_FAILED",e)):null,o="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!i||"!"===i||i===dl.tagName&&"map"===o||i===fl.tagName&&"seq"===o||!o)return xu(e,t,n,s,i);let a=t.schema.tags.find(e=>e.tag===i&&e.collection===o);if(!a){const c=t.schema.knownTags[i];if(!c||c.collection!==o)return c?.collection?s(r,"BAD_COLLECTION_TYPE",`${c.tag} used for ${o} collection, but expects ${c.collection}`,!0):s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),xu(e,t,n,s,i);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=xu(e,t,n,s,i,a),l=a.resolve?.(c,e=>s(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=cc(l)?l:new Pc(l);return u.range=c.range,u.tag=i,a?.format&&(u.format=a.format),u}($u,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=Du(e,t.offset,void 0,null,n,r),l=!1}return o&&""===c.anchor&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),s&&(c.spaceBefore=!0),i&&("scalar"===t.type&&""===t.source?c.comment=i:c.commentBefore=i),e.options.keepSourceTokens&&l&&(c.srcToken=t),c}function Du(e,t,n,r,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){const u=Lu(e,{type:"scalar",offset:Ru(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")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function ju(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 Fu(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){const i=e[s];switch(i[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(i.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[s+1]?.[0]&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}class qu{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const s=ju(e);r?this.warnings.push(new gu(s,t,n)):this.errors.push(new mu(s,t,n))},this.directives=new Ic({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Fu(this.prelude);if(n){const s=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!s)e.commentBefore=n;else if(ac(s)&&!s.flow&&s.items.length>0){let e=s.items[0];sc(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=s.commentBefore;s.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:Fu(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 s=ju(e);s[0]+=t,this.onError(s,"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:s,end:i},o){const a=Object.assign({_directives:t},e),c=new pu(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=wu(r,{indicator:"doc-start",next:s??i?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!s||"block-map"!==s.type&&"block-seq"!==s.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Ou(l,s,u,o):Du(l,u.end,r,null,u,o);const d=c.contents.range[2],p=Eu(i,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 mu(ju(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 mu(ju(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=Eu(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 mu(ju(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 pu(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 Bu(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 Uu(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 s=t.length;"block-scalar-header"===e.props[0].type&&(s-=e.props[0].source.length);for(const e of r)e.offset+=s;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,s="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:s})}}}function Vu(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=Vu(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=Ku(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=Ku(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=Ku(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 Ku({start:e,key:t,sep:n,value:r}){let s="";for(const t of e)s+=t.source;if(t&&(s+=Vu(t)),n)for(const e of n)s+=e.source;return r&&(s+=Vu(r)),s}const Wu=Symbol("break visit"),Gu=Symbol("skip children"),Yu=Symbol("remove item");function zu(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),Ju(Object.freeze([]),e,t)}function Ju(e,t,n){let r=n(t,e);if("symbol"==typeof r)return r;for(const s of["key","value"]){const i=t[s];if(i&&"items"in i){for(let t=0;t<i.items.length;++t){const r=Ju(Object.freeze(e.concat([[s,t]])),i.items[t],n);if("number"==typeof r)t=r-1;else{if(r===Wu)return Wu;r===Yu&&(i.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===s&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}zu.BREAK=Wu,zu.SKIP=Gu,zu.REMOVE=Yu,zu.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},zu.parentCollection=(e,t)=>{const n=zu.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};const Hu="\ufeff",Qu="",Zu="",Xu="";function ed(e){switch(e){case Hu:return"byte-order-mark";case Qu:return"doc-mode";case Zu:return"flow-error-end";case Xu: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 td=Object.freeze({__proto__:null,BOM:Hu,DOCUMENT:Qu,FLOW_END:Zu,SCALAR:Xu,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=t,a=Qc({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,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",s=[{type:"block-scalar-header",offset:i,indent:r,source:t}];return Bu(s,c)||s.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:i,indent:r,props:s,source:n}}case'"':return{type:"double-quoted-scalar",offset:i,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:r,source:a,end:c};default:return{type:"scalar",offset:i,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 Hu:return"<BOM>";case Qu:return"<DOC>";case Zu:return"<FLOW_END>";case Xu:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const r=(e,t,r)=>{const s="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new mu([s,s+1],t,r);n(s,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Tu(e,t,r);case"block-scalar":return Cu({options:{strict:t}},e,r)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:i=!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=Qc({type:o,value:t},{implicitKey:s||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),s=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=s}else{const{offset:t}=e,n="indent"in e?e.indent:-1,i=[{type:"block-scalar-header",offset:t,indent:n,source:r}];Bu(i,"end"in e?e.end:void 0)||i.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:i,source:s})}}(e,c);break;case'"':Uu(e,c,"double-quoted-scalar");break;case"'":Uu(e,c,"single-quoted-scalar");break;default:Uu(e,c,"scalar")}},stringify:e=>"type"in e?Vu(e):Ku(e),tokenType:ed,visit:zu});function nd(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const rd=new Set("0123456789ABCDEFabcdef"),sd=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),id=new Set(",[]{}"),od=new Set(" ,[]{}\n\r\t"),ad=e=>!e||od.has(e);class cd{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)&&nd(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]===Hu&&(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 Qu,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&&nd(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&nd(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!nd(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)&&nd(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(ad),"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("..."))&&nd(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield Zu,yield*this.parseLineStart()}let s=0;for(;","===r[s];)s+=(yield*this.pushCount(1)),s+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(s+=(yield*this.pushIndicators()),r[s]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-s),"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(ad),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||nd(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=>nd(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 s=e;for(;" "===r;)r=this.buffer[--e];if(!("\n"===r&&e>=this.pos&&e+1+n>s))break;t=e}return yield Xu,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(nd(t)||e&&id.has(t))break;n=r}else if(nd(t)){let s=this.buffer[r+1];if("\r"===t&&("\n"===s?(r+=1,t="\n",s=this.buffer[r+1]):n=r),"#"===s||e&&id.has(s))break;if("\n"===t){const e=this.continueScalar(r+1);if(-1===e)break;r=Math.max(r,e-2)}}else{if(e&&id.has(t))break;n=r}return t||this.atEnd?(yield Xu,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(ad))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(nd(t)||e&&id.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(;!nd(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(sd.has(t))t=this.buffer[++e];else{if("%"!==t||!rd.has(this.buffer[e+1])||!rd.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 ld{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 ud(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function dd(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 pd(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 fd(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 hd(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 md(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||ud(t.start,"explicit-key-ind")||ud(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,pd(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 gd{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 cd,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=ed(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&&md(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===dd(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!==dd(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=hd(fd(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 s=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const s=t.sep[r];switch(s.type){case"newline":n.push(r);break;case"space":break;case"comment":s.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(s=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(s.push(this.sourceToken),e.items.push({start:s}),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?(s.push(this.sourceToken),e.items.push({start:s,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(ud(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(pd(t.key)&&!ud(t.sep,"newline")){const e=hd(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 s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(ud(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=hd(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:s,key:null,sep:[this.sourceToken]}):ud(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:s,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:s}),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||ud(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=hd(fd(t));md(e);const r=e.end.splice(1,e.end.length);r.push(this.sourceToken);const s={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]=s}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=hd(fd(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=hd(fd(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 yd(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new ld||null,prettyErrors:t}}function wd(e,t={}){const{lineCounter:n,prettyErrors:r}=yd(t),s=new gd(n?.addNewLine),i=new qu(t),o=Array.from(i.compose(s.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(yu(e,n)),t.warnings.forEach(yu(e,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function vd(e,t={}){const{lineCounter:n,prettyErrors:r}=yd(t),s=new gd(n?.addNewLine),i=new qu(t);let o=null;for(const t of i.compose(s.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new mu(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(yu(e,n)),o.warnings.forEach(yu(e,n))),o}function bd(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const s=vd(e,n);if(!s)return null;if(s.warnings.forEach(e=>el(s.options.logLevel,e)),s.errors.length>0){if("silent"!==s.options.logLevel)throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function Id(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 pu(e,r,n).toString(n)}var kd=Object.freeze({__proto__:null,Alias:Tc,CST:td,Composer:qu,Document:pu,Lexer:cd,LineCounter:ld,Pair:il,Parser:gd,Scalar:Pc,Schema:du,YAMLError:hu,YAMLMap:dl,YAMLParseError:mu,YAMLSeq:fl,YAMLWarning:gu,isAlias:tc,isCollection:ac,isDocument:nc,isMap:rc,isNode:cc,isPair:sc,isScalar:ic,isSeq:oc,parse:bd,parseAllDocuments:wd,parseDocument:vd,stringify:Id,visit:pc,visitAsync:hc}),Ed=Object.freeze({__proto__:null,Alias:Tc,CST:td,Composer:qu,Document:pu,Lexer:cd,LineCounter:ld,Pair:il,Parser:gd,Scalar:Pc,Schema:du,YAMLError:hu,YAMLMap:dl,YAMLParseError:mu,YAMLSeq:fl,YAMLWarning:gu,default:kd,isAlias:tc,isCollection:ac,isDocument:nc,isMap:rc,isNode:cc,isPair:sc,isScalar:ic,isSeq:oc,parse:bd,parseAllDocuments:wd,parseDocument:vd,stringify:Id,visit:pc,visitAsync:hc});class Sd{#ke;constructor(e){this.#ke=e}execute(){return new Promise((e,t)=>{const n=`${this.#ke}.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=kd.parse(t);if(n.moduleURL=this.#ke,n.hasCapabilities){const e=`${this.#ke}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=kd.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.#ke}.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 kd.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Ad{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}}class xd{#n;#Ee;constructor(){this.#n=new Map,this.#Ee=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#Ee.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#Ee.has(t)||console.warn(`Unknown event type: ${t}`)}}class Cd{}class Td extends Cd{#Se;constructor(e){super(),this.#Se=e}execute(){}}let Md=class extends Ad{#Ae;constructor(e){super(e),this.#Ae=new xd,this.#Ae.register("onExtension",Td),this.#Ae.markKnown("onCommand"),this.#Ae.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Ae.handleEvent(e)),e}},Nd=class extends Ad{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,activationEvents:n}=e,r=e.capabilities,s=[];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;s.push({id:e,title:n,description:r})}return s.length&&s.forEach(({id:t,title:s,description:i})=>{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:s??t,description:i,execute:(...n)=>{const r=n.length?n[n.length-1]:void 0,s=r?.__punica?.correlationId;a.activate(e.name,{reason:"command",trigger:t}).then(()=>{u&&c.publishEvent({name:u,envelope:{id:c.createCorrelationId(),correlationId:s,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:s,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 Pd(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}function _d(e,t=Pd()){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 Ld=class extends Ad{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:[_d(n)],when:r})})}return e}},Rd=class extends Ad{constructor(e){super(e)}async execute(){return await super.execute()}};class $d extends Ad{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=Ua.fileOpeners;e.forEach((e,t)=>{if(!e.capability)return void console.warn(`[FileOpeners] Missing capability for file opener: ${e.id??t}`);const s=e.capability,i=e.id??`${n}:${s||"opener"}:${t.toString(10)}`;r.register({id:i,label:e.label,command:s,priority:e.priority,matches:e.matches})})}return e}}function Od(e){const{integrations:t}=e;if(!t)return;const{views:n}=t;if(!n)return;const{activityBar:r,statusBar:s,primarySidebar:i,secondarySidebar:o,contentSidebar:a,panel:c}=n;if(r){const e={...r};e.capability&&(e.command=e.capability),i&&!e.viewId&&(e.viewId=i.id),punica.shell.ActivityBar.manager.addItem(e)}if(s){const e={...s};e.capability&&(e.command=e.capability),punica.shell.Statusbar.manager.addItem(e)}!function(e,t){const n=punica.shell?.Views?.manager;if(!n?.registerPlacement)return;const{primarySidebar:r,secondarySidebar:s,contentSidebar:i,panel:o,activityBar:a}=t;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:"contentSidebar",extensionName:e.name,title:i.title??i.name,icon:i.icon,fallbackCommand:i.capability});if(o?.id){const t=Array.isArray(o.toolbar)?o.toolbar:void 0;Dd(e,o,"panel",{order:o.order,panelToolbar:t})}s?.id&&Dd(e,s,"secondarySidebar",{})}(e,{primarySidebar:i,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r})}function Dd(e,t,n,r){const s=punica.shell?.Views?.manager;if(!s?.registerPlacement)return;const i=punica.shell?.PanelLayout?.manager,o=punica.shell?.PanelContainers,a=Array.isArray(t.relocatableTo)?t.relocatableTo:[],c=Array.from(new Set([n,...a,...{panel:["secondarySidebar"],secondarySidebar:["panel"]}[n]??[]])),l=i?.getSlotOverride?.(t.id),u=l&&c.includes(l)?l:n,d=!1===t.showOnStartup;if(s.registerPlacement({viewId:t.id,slot:u,homeSlot:n,allowedSlots:c,extensionName:e.name,title:t.title??t.name,icon:t.icon,order:r.order,fallbackCommand:t.capability,onDemand:d,panelToolbar:r.panelToolbar}),!d){const e=o?.forSlot?.(u)??("panel"===u?punica.shell?.PanelTabs:null);e?.open?.({id:t.id,title:t.title??t.name??t.id,commandId:t.capability??"",iconClass:t.icon,order:r.order,autoActivate:!1,toolbar:r.panelToolbar})}}let jd=0;function Fd(){jd++}function qd(){jd>0&&jd--}async function Bd(e){Fd();try{return await e()}finally{qd()}}const Ud=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#xe(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#xe(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}#xe(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 s;return"string"===n.type&&"enum"in n&&Array.isArray(n.enum)&&(s=Object.freeze([...n.enum])),[e,Object.freeze({...r,enum:s})]})))}: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 Vd=new class{#Ce=".punica/settings.json";#Te;#Me=null;#Ne=null;#Pe=new Map;#_e=null;#z=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Te=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Te="localStorage:punica.settings":this.#Te="settings.json"}async load(){this.#z||(await this.#Le(),await this.#Re(),this.#z=!0)}async#Le(){try{if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#Ne=await this.#$e(e)}else this.#Ne={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Te),t=JSON.parse(e);this.#Ne=await this.#$e(t)}catch{this.#Ne={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Ne={version:"1.0",extensions:{},system:{}}}}async#Re(){try{const e=await punica.runtime.fs.readFile(this.#Ce),t=JSON.parse(e);this.#Me=await this.#$e(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Me=null}}async save(e="project"){this.#_e&&clearTimeout(this.#_e),this.#_e=window.setTimeout(async()=>{"global"===e?await this.#Oe():await this.#De(),this.#_e=null},500)}async#Oe(){if(this.#Ne)if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#Ne,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Te,JSON.stringify(this.#Ne,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#De(){this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Ce,JSON.stringify(this.#Me,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#z)return void this.load();if("system"===e){const e=this.#Me?.system?.[t];if(void 0!==e)return e;const n=this.#Ne?.system?.[t];return void 0!==n?n:void 0}const n=this.#Me?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#Ne?.extensions?.[e]?.[t];if(void 0!==r)return r;const s=punica.extensions.metadata.manager.getExtension(e);return s?.configuration?.properties?.[t]?.default}async set(e,t,n,r="project"){if(this.#z||await this.load(),"system"===e){const s=this.get(e,t);return"global"===r?(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system||(this.#Ne.system={}),this.#Ne.system[t]=n,await this.save("global")):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system||(this.#Me.system={}),this.#Me.system[t]=n,await this.save("project")),void this.#je(e,t,n,s)}const s=this.validate(e,t,n);if(!s.ok)throw new Error(`Invalid setting value: ${s.errors?.join(", ")}`);const i=this.get(e,t);"global"===r?(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]||(this.#Ne.extensions[e]={}),this.#Ne.extensions[e][t]=n,await this.save("global")):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]||(this.#Me.extensions[e]={}),this.#Me.extensions[e][t]=n,await this.save("project")),this.#je(e,t,n,i)}getAll(e){if(!this.#z)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#Ne?.extensions?.[e]??{},s=this.#Me?.extensions?.[e]??{},i={};for(const[e,t]of Object.entries(n)){const n=t;i[e]=n.default}return{...i,...r,...s}}validate(e,t,n){const r=punica.extensions.metadata.manager.getExtension(e),s=r?.configuration?.properties?.[t];if(!s)return{ok:!1,errors:[`Setting "${t}" not found in extension "${e}"`]};const i=[];switch(s.type){case"boolean":"boolean"!=typeof n&&i.push(`Setting "${t}" must be a boolean`);break;case"string":"string"!=typeof n?i.push(`Setting "${t}" must be a string`):s.enum&&!s.enum.includes(n)&&i.push(`Setting "${t}" must be one of: ${s.enum.join(", ")}`);break;case"number":("number"!=typeof n||isNaN(n))&&i.push(`Setting "${t}" must be a number`)}return{ok:0===i.length,errors:i.length>0?i: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){if("system"===e){const n=this.get(e,t),r=void 0!==this.#Me?.system?.[t],s=void 0!==this.#Ne?.system?.[t];if(!r&&!s)return;return r&&delete this.#Me.system[t],s&&delete this.#Ne.system[t],r&&await this.#De(),s&&await this.#Oe(),void this.#je(e,t,void 0,n)}const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Me?.extensions?.[e]&&(delete this.#Me.extensions[e][t],await this.save("project")),this.#Ne?.extensions?.[e]&&(delete this.#Ne.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.#z?"system"===e?void 0!==this.#Me?.system?.[t]?"project":void 0!==this.#Ne?.system?.[t]?"global":"default":void 0!==this.#Me?.extensions?.[e]?.[t]?"project":void 0!==this.#Ne?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#Pe.has(e)||this.#Pe.set(e,new Set),this.#Pe.get(e).add(t),()=>{this.#Pe.get(e)?.delete(t)}}async export(e){this.#z||await this.load();const t=e?.scope??"merged",n={version:this.#Ne?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Me?.system:"global"===t?this.#Ne?.system:{...this.#Ne?.system,...this.#Me?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#Ne?.extensions??{}),...Object.keys(this.#Me?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Me?.extensions?.[e]??{}:"global"===t?this.#Ne?.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.#Me:this.#Ne)||("project"===r?this.#Me={version:"1.0",extensions:{},system:{}}:this.#Ne={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Me:this.#Ne;for(const[r,s]of Object.entries(n.extensions??{}))t.extensions&&!t.extensions.includes(r)||(e.extensions[r]={...e.extensions[r],...s});n.system&&(e.system={...e.system,...n.system})}else{if(t?.extensions)for(const e of t.extensions)n.extensions[e]&&("project"===r?(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]=n.extensions[e]):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]=n.extensions[e]));else"project"===r?this.#Me={...this.#Me,...n,version:this.#Me?.version??"1.0"}:this.#Ne={...this.#Ne,...n,version:this.#Ne?.version??"1.0"};n.system&&("project"===r?(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system=n.system):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system=n.system))}await this.save(r)}async#$e(e){return e.version,e}#je(e,t,n,r){const s=this.#Pe.get(e);s&&s.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}})}},Kd="system",Wd="ui.language",Gd="en";const Yd=new class{#Fe=new Map;#Pe=new Set;#qe=null;#Be=new Set;#Ue=new Map;getLocale(){return this.#qe??=this.#Ve(),this.#qe}supportedLocales(){const e=this.#Ke()?.supported;return Array.isArray(e)&&e.length?e:[Gd]}async setLocale(e){const t=String(e||"").trim();if(t&&t!==this.getLocale()){try{await punica.extensions.settings.manager.set(Kd,Wd,t,"global")}catch(e){throw e instanceof Error?e:new Error(String(e))}this.#qe=t,this.#We(t)}}onDidChange(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}#We(e){for(const t of[...this.#Pe])try{t(e)}catch{}}#Ke(){try{return punica.shell?.Profile?.manager?.registry?.getActive?.()?.localization}catch{return}}#Ve(){const e=this.supportedLocales();try{const t=punica.extensions?.settings?.manager?.get?.(Kd,Wd);if("string"==typeof t&&e.includes(t))return t}catch{}try{const t=globalThis.navigator,n=t?.language?.toLowerCase().split("-")[0];if(n&&e.includes(n))return n}catch{}const t=this.#Ke()?.default;return t&&e.includes(t)?t:e.includes(Gd)?Gd:e[0]}refresh(){const e=this.#Ve();e!==this.#qe&&(this.#qe=e,this.#We(e))}register(e,t){e&&t&&this.#Fe.set(e,t)}t(e,t,n){const r=this.#Ge(e,t,n?.count);return void 0===r?(this.#Ye(`${e}:${t}`,e,t),t):n?r.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):r}#Ge(e,t,n){const r=this.#Fe.get(e);if(!r)return;const s=[],i=e=>{e&&!s.includes(e)&&s.push(e)};i(this.getLocale()),i(this.#Ke()?.default),i(Gd);const o=[];"number"==typeof n&&Number.isFinite(n)&&o.push(`${t}.${this.#ze(this.getLocale(),n)}`,`${t}.other`),o.push(t);for(const e of s){const t=r[e];if(t)for(const e of o){const n=t[e];if("string"==typeof n)return n}}}#ze(e,t){let n=this.#Ue.get(e);if(!n){try{n=new Intl.PluralRules(e)}catch{n=new Intl.PluralRules(Gd)}this.#Ue.set(e,n)}return n.select(t)}#Ye(e,t,n){this.#Be.has(e)||(this.#Be.add(e),console.warn(`[i18n] missing message "${n}" for ${t} (${this.getLocale()})`))}resetForTesting(){this.#Fe.clear(),this.#Pe.clear(),this.#qe=null,this.#Be.clear(),this.#Ue.clear()}};function zd(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 Jd=new Map;function Hd(e){const t=Jd.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),Jd.delete(e)}const Qd={register(e,t,n){const r=n?.target??document.head,s=Jd.get(e)??document.getElementById(e);if(s)return n?.overwrite&&(s.textContent=t),Jd.set(e,s),{id:e,dispose(){Hd(e)}};const i=document.createElement("style");if(i.id=e,n?.attrs)for(const[e,t]of Object.entries(n.attrs))i.setAttribute(e,t);return i.textContent=t,r.appendChild(i),Jd.set(e,i),{id:e,dispose(){Hd(e)}}},unregister(e){Hd(e)},has:e=>!!Jd.has(e)||!!document.getElementById(e)};const Zd={manager:new class{#Je;#He;#Qe;#Ze;#Xe;#et;#tt;#nt;#rt;constructor(){this.#Je=new Map,this.#He=new Map,this.#Qe=new Map,this.#Ze=new Map,this.#Xe=new Set,this.#et=new Set,this.#tt=new Map,this.#nt=new Map,this.#rt=new Map}getRuntimeState(e){return this.#He.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 s=this.#nt.get(t);if(s&&s.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${s.extensionName}" and "${n}".`);this.#nt.set(t,{id:t,extensionName:n,definition:r})}}#st(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 s={id:t,extensionName:e.name,definition:n},i=this.#nt.get(t);i&&i.extensionName!==e.name&&console.warn(`[Extensions] Capability id collision "${t}" between "${i.extensionName}" and "${e.name}". Keeping the last loaded.`),this.#nt.set(t,s)}this.#it(e,n)}}#it(e,t){const n=Co.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`)}#ot(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 Sd(e),n=new Nd(t),r=new Ld(n),s=new Rd(r),i=new $d(s);return new Md(i)})(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.#Je.set(r.name,r),this.#He.set(r.name,"loaded"),this.#st(r),this.#ot(r);try{Od(r)}catch(e){console.error(`[Extensions] view registration failed for ${r.name}:`,e)}const s=r.activationEvents??[];(s.includes("onStartup")||s.includes("onStartup:begin"))&&this.#Xe.add(r.name),s.includes("onStartup:finish")&&this.#et.add(r.name),s.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#tt.get(t);n||(n=new Set,this.#tt.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#He.get(e))return;const n=this.#Qe.get(e);if(n)return n;if(!this.#Je.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),s=this.#at(e,r);this.#Qe.set(e,s);try{await s}finally{this.#Qe.delete(e)}}async#at(e,t){this.#He.set(e,"activating"),zd("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new Va(e),n=new Ga(t),r=new Ya(n);return new Wa(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.#ct(e,t);"headless"===t.presentation?await Bd(()=>r.module.activate(n)):await r.module.activate(n);const s=this.#Ze.get(e);s&&(s.module=r.module),this.#He.set(e,"active"),zd("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#He.set(e,"failed"),zd("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}}#ct(e,t){const n=[];this.#Ze.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.#rt.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const s=globalThis.punica?.shell?.Views?.manager;if(!s?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const i=s.registerProvider(t,r,e);return n.push(i),i},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,s=r.punica?.runtime?.capabilities?.gateway;if(s?.call){const i=r.punica?.kernel?.Events?.manager,o=i?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await s.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 i=r.punica?.shell?.Views?.manager;if(!i?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await i.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 s=n.punica?.kernel?.Events?.manager,i=s?.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:i},policy:{mode:"execute"}})}const s=n.punica?.shell?.Views?.manager;if(!s?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);s.hide(e,{kind:"extension",id:t})}(t,e)}}};return r}async startupBegin(){await this.#lt(this.#Xe,"startup:begin")}async startupFinish(){await this.#lt(this.#et,"startup:finish")}async#lt(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.#Je.get(e)}getAllExtensions(){return Array.from(this.#Je.values())}getCapability(e){return this.#nt.get(e)?.definition}listCapabilities(){return Array.from(this.#nt.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 s=Wr().validate(r,t);return s.ok?{ok:!0}:{ok:!1,errors:s.errors}}registerCapabilityHandler(e,t){this.#rt.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#nt.get(e);if(!r)throw new yr(gr.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#He.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new yr(gr.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 s=this.#rt.get(e);if(!s)throw new yr(gr.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 s.fn(t,n)}async deactivate(e){if("active"!==this.#He.get(e))return;const t=this.#Je.get(e);this.#He.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.#Ze.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#Ze.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.#Ze.delete(e)}for(const[t,n]of this.#rt)n.extensionName===e&&this.#rt.delete(t)}finally{this.#He.set(e,"loaded"),zd("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#He.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.#nt)n.extensionName===e&&this.#nt.delete(t);for(const[t,n]of this.#tt)n.delete(e)&&0===n.size&&this.#tt.delete(t);const n=this.#Je.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.#Xe.delete(e),this.#et.delete(e),this.#Qe.delete(e),this.#Ze.delete(e),this.#Je.delete(e),this.#He.delete(e),zd("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.#He.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.#tt.get(e);return t?Array.from(t):[]}},Styles:Qd,metadata:{manager:Ud},settings:{manager:Vd},i18n:{manager:Yd}};function Xd(e){if(null==e)return!1;if(Array.isArray(e))return e.some(Xd);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(Xd)}return!1}function ep(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=tp(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=tp(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||""),s=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"}):s||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||""),s=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"}):s||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?Xd(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 tp(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 np{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await Tn().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=zr();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 rp(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),s=ep(r);if(!s.ok)return void console.warn(`[NodeRegistry] Invalid manifest at ${t}:`,s.issues);const i=r,o=i.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:i})}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():"",s=t&&"description"in t?String(t.description||"").toLowerCase():"",i=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||s.includes(n)||i.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 rp(e,t){for(const n of e)n.isDirectory?n.children&&rp(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let sp;function ip(){return sp||(sp=new np),sp}function op(e,t,n,r=!1){if("code"!==e.cell_type)throw new Error("Cell must be a code cell");let s=Array.isArray(e.source)?e.source.join(""):String(e.source||"");const i=JSON.stringify(t);return s=s.replace(/__ivy_node_id__/g,i),s}async function ap(e,t,n,r){let s={};for await(const i 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"===i.type&&"text"in i){const e=i.text;try{const t=JSON.parse(e.trim());t&&"object"==typeof t&&(s=t)}catch{}}return s}function cp(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 lp=/token|secret|key|password|passwd|api[_-]?key/i;function up(e){const t={};let n=0,r=!1;for(const s of Object.keys(e)){const i=lp.test(s)?"[REDACTED]":e[s],o=s.length+JSON.stringify(i??null).length;n+o>16e3?r=!0:(n+=o,t[s]=i)}return r&&(t.__truncated__=!0),t}async function dp(e,t){const n=Date.now(),r=ip().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const s=ep(r.manifest);if(!s.ok)throw new Error(`Invalid manifest: ${s.issues.map(e=>e.message).join(", ")}`);const i=r.manifest;if(Xd(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=i.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(!i.program)throw new Error("Manifest missing program");const l=i.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 f=u.find(e=>e.id===d),h=u.find(e=>e.id===p);if(!f)throw new Error(`Input cell with id "${d}" not found in program.cells`);if(!h)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||(i.runtime,"python"),w=t.runId??`ivynode-${e}-${n}`,v=(e,t)=>{try{punica.kernel.Events.manager.publish(e,t)}catch{}},b=(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}`},I=e=>{const t=e;return"stdout"!==t.type&&"stderr"!==t.type||"string"!=typeof t.text?"":t.text},k=await m.session.open({language:y}),E=t.runId||`ivynode-${e}-${Date.now()}`;let S={};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 k.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 s=op(r,e),i=r.id||`cell-${n}`,o=b(r,n),a=Date.now();let c,l="";v("ivy.node.cell.started",{runId:w,nodeId:e,cellId:i,index:n,label:o,startedAtMs:a});try{let e=null;for await(const n of k.run({id:i,language:y,code:s,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:cell:${i}`})){g.push({type:n.type,data:n}),l+=I(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 v("ivy.node.cell.failed",{runId:w,nodeId:e,cellId:i,index:n,label:o,durationMs:Date.now()-a,error:t instanceof Error?t.message:String(t),logs:l}),t}try{const e=await ap(k,E,i,t.timeoutMs),n=up(cp(S,e));Object.keys(n).length&&(c=n),S=e}catch{}v("ivy.node.cell.finished",{runId:w,nodeId:e,cellId:i,index:n,label:o,durationMs:Date.now()-a,logs:l,...c?{variables:c}:{}})}const s=await async function(e,t,n,r){const s=JSON.stringify(t),i=`\nimport json\ntry:\n if '__ivy_ctx__' in globals() and isinstance(__ivy_ctx__, dict):\n if "nodes" in __ivy_ctx__ and ${s} in __ivy_ctx__["nodes"]:\n node_data = __ivy_ctx__["nodes"][${s}]\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:i,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")}(k,e,E,t.timeoutMs),i=o.outputs;if(!i?.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}}(s,i.schema);if(!a.valid)throw new Error(`Output validation failed: ${a.errors.join(", ")}`);return{output:s,events:g,durationMs:Date.now()-n}}finally{await k.close()}}function pp(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function fp(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function hp(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function mp(e,t){const n=e.value;switch(e.type){case"isType":return{passed:fp(t)===String(n??""),expected:String(n??""),actual:fp(t)};case"equals":return{passed:hp(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=>hp(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:fp(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:fp(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):fp(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:fp(t)}}}function gp(e,t,n=""){const r=e.assertions||{},s={},i=[];if(void 0!==r.schema){const e=!0===r.schema;s.schema={passed:e},i.push(!e)}if(void 0!==r.expectsError){const e=!1===r.expectsError;s.error={passed:e},i.push(!e)}if(r.errorPattern&&r.expectsError){const e=new RegExp(r.errorPattern).test(n);s.error={passed:e,expected:r.errorPattern,actual:n||void 0},i.push(!e)}if(r.properties&&"object"==typeof r.properties){const e={};for(const[n,s]of Object.entries(r.properties)){if(!s||"object"!=typeof s)continue;const r=pp(t,n);let o;const a=s.matcher;if(a&&"object"==typeof a)o=mp(a,r);else if("string"==typeof a)o=mp({type:a,value:s.expected},r);else{if(void 0===s.expected)continue;o=mp({type:"equals",value:s.expected},r)}e[n]=o,i.push(!o.passed)}Object.keys(e).length&&(s.properties=e)}return{status:i.some(Boolean)?"fail":"pass",assertions:Object.keys(s).length>0?s:void 0}}function yp(e,t,n){const r=!0===e.assertions?.expectsError,s=e.assertions?.errorPattern;let i;return i=r?s?new RegExp(s).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:i,error:t,assertions:{error:{passed:r,expected:s,actual:t}}}}function wp(e){const{capabilityId:t,version:n,tier:r,results:s,startedAtMs:i}=e,o=s.filter(e=>"pass"===e.status).length,a=s.filter(e=>"fail"===e.status).length,c=s.filter(e=>"skip"===e.status).length,l=s.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:s.length,passedCases:o,failedCases:a,skippedCases:c,durationMs:Date.now()-i},cases:s}}function vp(){return Date.now()}function bp(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Ip(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function kp(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Ep(){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 Sp(){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 Ap(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 xp(e){try{const t=Ep();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 Cp(e,t){const r=Ep();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 s=await n();await r.call("fs.writeFile",{path:e,content:t},{sessionId:"internal",workspaceId:s,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}function Tp(e,t,n,r,s){const i=s?.traceId??t;punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:t,traceId:i,spanId:s?.spanId,parentSpanId:s?.parentSpanId,timestampMs:vp(),source:s?.source??"flow:engine",kind:n},payload:r})}const Mp=new Set(["sensitive","secret"]);function Np(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Pp(e,t,n,r){if(!function(e,t,n){return!(!n||!Mp.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:Np(e)}}const _p=new class{#ut=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#ut.set(e,(this.#ut.get(e)??0)+r),!0;const s=this.#ut.get(e)??0;return!(s+r>n)&&(this.#ut.set(e,s+r),!0)}used(e){return this.#ut.get(e)??0}release(e){this.#ut.delete(e)}reset(){this.#ut.clear()}};class Lp{async ensureBase(){await xp(".punica"),await xp(kp(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await xp(kp(".punica","workflow-runs",e)),await xp(kp(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),s=vp();await this.ensureRunDirs(e);const i=n.surface??"output",o=n.payload,a=n.text;let c,l=o,u=a;if(n.redactionPolicy||n.capabilityClassification){const e=Pp(o??a,n.redactionPolicy,i,n.capabilityClassification);e&&"object"==typeof e&&!0===e.redacted&&(c=e,l=c,u=void 0)}const d="string"==typeof u,p=kp(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let f;f=d?String(u??""):bp(l??{},2);const h=n.sizeBudget?.maxBytes;if(c||"number"!=typeof h)"number"==typeof h&&_p.acquire(e,f.length,h);else{_p.acquire(e,f.length,h)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(i,f.length),f=bp(c,2),_p.acquire(e,f.length,h))}await Cp(p,f);const m=f.length,g=Ip(d?String(u??""):bp(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs:s,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 Tp("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function Rp(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 $p(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Op(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 Dp(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 jp(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 Fp(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function qp(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 Bp(e,t,n){const r=qp(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 Up(e,t){const n=qp(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 Vp(e,t){const n=qp(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 Kp(e,t=".punica"){const n=Fp(t,"workflow-runs",e.runId),r=Fp(n,"checkpoint.json"),s=Fp(n,"checkpoint.json.tmp"),i=JSON.stringify(e,null,2);await Up("writeCheckpoint",n),await Bp("writeCheckpoint",s,i);try{await async function(e,t,n){const r=qp(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",s,r)}catch{try{await Vp("writeCheckpoint",r)}catch{}await Bp("writeCheckpoint",r,i);try{await Vp("writeCheckpoint",s)}catch{}}}async function Wp(e,t=".punica"){const n=Fp(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=qp(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 Gp(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 Yp{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,s=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 i=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)),s=new Map,i=new Map;t.forEach(e=>{s.set(e.id,0),i.set(e.id,[])}),r.forEach(e=>{i.get(e.fromId).push(e.toId),s.set(e.toId,(s.get(e.toId)??0)+1)});const o=[];for(const[e,t]of s.entries())0===t&&o.push(e);const a=[];for(;o.length;){const e=o.shift();a.push(e);for(const t of i.get(e)??[])s.set(t,(s.get(t)??0)-1),0===(s.get(t)??0)&&o.push(t)}if(a.length!==t.length)throw new Error("Workflow graph is not a DAG (cycle detected).");return a}(i),a=punica.kernel.Events.manager.createCorrelationId(),c=a,l=punica.kernel.Events.manager.createCorrelationId(),u={runId:a,specVersion:"0.1",status:"QUEUED",createdAtMs:vp(),startedAtMs:vp(),traceId:c,entryNodeId:i.graph.entryNodeId,metadata:{title:i.title,tags:i.tags},steps:[]};for(const e of o){const t=i.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=Op(i),p=i.graph.runBudget?.maxInFlight;return this.runs.set(a,{run:u,spec:i,order:o,cursor:0,paused:!1,cancelled:!1,rootSpanId:l,filePathOrUri:r,dependencyGraph:d,inFlightNodes:new Set,maxInFlight:p,nodeOutputs:new Map,input:s}),Tp("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),Gp({name:"flow.run.started",correlationId:a,traceId:c,payload:{runId:a,flowId:i.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",Tp("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 Wp(e);if(!n)return!1;{const r=n.dependencyGraphState?Op(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"),Tp("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=vp();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 Tp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Tp("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=kp(".punica","workflow-runs",e,"run.json");await Cp(n,bp({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=kp(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Cp(e,bp({version:1,updatedAtMs:vp(),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 Kp(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=kp(".punica","workflow-runs","index.json"),t=await async function(e){const t=Ep();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);Tp("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class zp{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,s,i){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=s,this.resumeRunLoop=i}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 s=t?.payload??{},i=s?.request??{},o=s?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(i?.kind??"capability"),id:String(i?.id??""),risk:String(i?.risk??"low"),approval:String(i?.approval??"once"),reason:"string"==typeof i?.reason?i.reason:void 0,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:vp()};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:vp(),resolved:!1},Tp("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",Tp("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}),Tp("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),Gp({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 s=this.pendingToRunStep.get(r.attemptCorrelationId);if(!s)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id},n,{workspaceId:r.workspaceId})}catch{}Tp("workflow.pendingApprovalResolved",s.runId,"info",{runId:s.runId,stepId:s.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:vp()},{traceId:s.runId}),Gp({name:"flow.approval.granted",correlationId:s.runId,traceId:s.runId,payload:{runId:s.runId,stepId:s.stepId,pendingId:t,scope:n,capability:{kind:r.kind,id:r.id}}}),this.pendingByCorrelation.delete(r.attemptCorrelationId);const i=this.runs.get(s.runId);if(i){const e=i.run.steps.find(e=>e.stepId===s.stepId);e?.approval&&(e.approval.resolved=!0,e.approval.decision="approved"),i.run.status="RUNNING",Tp("workflow.runUpdated",i.run.runId,"info",{runId:i.run.runId,patch:{status:"RUNNING"}},{traceId:i.run.traceId,spanId:i.rootSpanId}),this.persistRun(i.run.runId),this.resumeRunLoop(i.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;Tp("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:vp()},{traceId:r.runId}),Gp({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 s=this.runs.get(r.runId);return s&&(s.run.status="FAILED",s.run.endedAtMs=vp(),Tp("workflow.runUpdated",s.run.runId,"error",{runId:s.run.runId,patch:{status:"FAILED",endedAtMs:s.run.endedAtMs,error:{message:"Approval rejected",nodeId:r.stepId}}},{traceId:s.run.traceId,spanId:s.rootSpanId}),Tp("workflow.runFinished",s.run.runId,"error",{runId:s.run.runId,status:"FAILED",endedAtMs:s.run.endedAtMs},{traceId:s.run.traceId,spanId:s.rootSpanId}),this.persistRun(s.run.runId),this.persistIndex()),!0}}const Jp=3e4,Hp={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const Qp=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.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.#le.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function Zp(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function Xp(e,t){if(!t.retry)return 0;const n=t.retry.initialDelayMs??1e3,r=t.retry.maxDelayMs??3e4,s=t.retry.backoffMultiplier??2,i=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(s,e-1),r),i)}const ef=new class{#dt=new Map;register(e,t){this.#dt.set(e,t)}get(e){return this.#dt.get(e)}resolveOrThrow(e){const t=this.#dt.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.#dt.clear()}};function tf(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 nf(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,...s]=n;if(!t.has(r))return{ok:!1,reason:"missing-node"};const i=t.get(r);if(0===s.length)return{ok:!0,value:i??null};const o=tf(i,s);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function rf(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 sf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function of(e){return String(e??"").split(".").filter(e=>e.length>0)}function af(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];sf(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function cf(e,t,n){const r=t.filter(t=>t.toId===e.id&&(void 0!==t.fromPath||void 0!==t.toPath)),s=e.data?.input;if(0===r.length)return void 0!==s?s:void 0!==e.defaults?e.defaults:void 0;const i={...sf(e.defaults)?e.defaults:{},...sf(s)?s:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?of(e.fromPath):[],s=r.length?tf(t,r):t;if(void 0===s)continue;const o=e.toPath?of(e.toPath):[];o.length?af(i,o,s):sf(s)?Object.assign(i,s):i[e.fromId]=s}return i}class lf 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 uf(e,t){if(function(e){return!0===e.cancelled}(e))throw new lf(e.run?.runId,t)}class df{runs;pendingToRunStep;runIdToSession;artifactStore;persistRun;persistCheckpoint;persistIndex;notifyTerminal;constructor(e,t,n,r,s,i,o,a){this.runs=e,this.pendingToRunStep=t,this.runIdToSession=n,this.artifactStore=r,this.persistRun=s,this.persistCheckpoint=i,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=Ep();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,s=n.rootSpanId;for(;n.cursor<n.order.length;){if(n.cancelled)return;if(n.paused)return;const i=n.order[n.cursor];n.run.currentNodeId=i;const o=n.spec.graph.nodes.find(e=>e.id===i),a=n.run.steps.find(e=>e.stepId===i);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",Tp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED",currentNodeId:i}},{traceId:r,spanId:s}),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,f=l.timeoutMs;let h=a.attempt??0;for(;h<=d;){h++,a.attempt=h,"PENDING"!==a.status&&"RETRYING"!==a.status&&"WAITING_APPROVAL"!==a.status&&(a.status="PENDING"),a.status="RUNNING",a.startedAtMs=vp(),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}),Tp("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:s}),Gp({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 i=await this.executeNodeAttempt(o,a,l,{attemptCorrelationId:c,spanId:u,rootSpanId:s,traceId:r,workspaceId:t?.workspaceId,filePathOrUri:n.filePathOrUri,notebook:n.notebook,timeoutMs:f,nodeOutputs:n.nodeOutputs,runBudget:n.spec.graph.runBudget,runInput:n.input,resolvedInput:cf(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==i.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,i.output),Tp("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:s}),Gp({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",Tp("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:s}),n.run.status="WAITING_APPROVAL",Tp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:i}},{traceId:r,spanId:s}),await this.persistRun(e),void await this.persistIndex();const f=o.includes("Timed out")||o.includes("timeout");if(!(h<=d&&(p||!f)&&!o.includes("Policy")&&!o.includes("Invalid input"))||h>d)return"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="FAILED",a.endedAtMs=vp(),a.error={message:o},Tp("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:s}),Gp({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=vp(),n.run.error={message:o,nodeId:i,correlationId:c},Tp("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:s}),Tp("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:s}),Gp({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=Xp(h,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Tp("workflow.stepRetry",e,"info",{runId:e,stepId:a.stepId,attempt:h,maxAttempts:d,delayMs:m,error:o},{traceId:r,spanId:u,parentSpanId:s}),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=vp(),Tp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:s}),Tp("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:s}),Gp({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=Fp(n,"workflow-runs",e.runId),s=Fp(r,"run.json"),i=JSON.stringify({run:e,spec:t},null,2);await Up("writeRunHistory",r),await Bp("writeRunHistory",s,i)}(n.run,n.spec),await async function(e,t=".punica"){const n=Fp(t,"workflow-runs",e,"checkpoint.json");try{await Vp("deleteCheckpoint",n)}catch{}}(e);const i=this.runIdToSession.get(e);if(i){try{await i.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 s=r.run.traceId,i=r.rootSpanId,o=r.maxInFlight??1/0,a=!!(c=r.spec.graph.runBudget)&&!0===c.failFast;for(var c;!$p(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=Rp(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=>{jp(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 Dp(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Dp(o,!0,n);try{const a=this.prepareNodeExecutionConfig(c,r),u=a.retry,d=u?.maxAttempts??0,p=a.timeoutMs;let f=l.attempt??0,h=!1;for(;f<=d&&!h;){uf(r),f++,l.attempt=f,l.status="RUNNING",l.startedAtMs=vp();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:i,traceId:s,workspaceId:t?.workspaceId,filePathOrUri:r.filePathOrUri,notebook:r.notebook,timeoutMs:p,nodeOutputs:r.nodeOutputs,runBudget:r.spec.graph.runBudget,runInput:r.input,resolvedInput:cf(c,r.spec.graph.edges,r.nodeOutputs??new Map)});void 0!==o.output&&r.nodeOutputs&&r.nodeOutputs.set(c.id,o.output),h=!0}catch(e){if(e instanceof lf)throw l.status="CANCELLED",l.endedAtMs=vp(),e;const t=String(e?.message??e);if(f<=d){const e=Xp(f,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=vp(),l.error={message:t},e}}h&&(Dp(o,!0,n),await this.persistRun(e))}catch(t){Dp(o,!1,n),t instanceof lf||(r.run.status="FAILED",r.run.endedAtMs=vp(),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=vp(),Tp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:s,spanId:i}),Tp("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:s,spanId:i}),Gp({name:"flow.run.completed",correlationId:e,traceId:s,payload:{runId:e,endedAtMs:r.run.endedAtMs}}),await this.persistRun(e),await this.persistIndex(),this.notifyTerminal?.(e,"COMPLETED")):"FAILED"===r.run.status&&(Gp({name:"flow.run.failed",kind:"error",correlationId:e,traceId:s,payload:{runId:e,endedAtMs:r.run.endedAtMs,error:r.run.error}}),this.notifyTerminal?.(e,"FAILED"))}prepareNodeExecutionConfig(e,t){const n=ef.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:Jp,retry:{...Hp},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 s=ef.get(e.ref.kind);let i;try{i=await(s?.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),s=r.timeoutMs?await async function(e,t){return Promise.race([e,Zp(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=vp(),t.outputsPreview=s.outputsPreview,t.artifactIds=s.artifactIds??[],s}finally{i&&i()}}async executeNode(e,t){return ef.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class pf 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 ff(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new pf(e??0,t);return n}const hf="__default__";class mf{workspaceId;#pt=new Map;#ft=new Map;#ht=new Map;#mt=new Lp;#gt=!1;#yt=new Map;#wt;#vt;#bt;constructor(e=hf){this.workspaceId=e,this.#wt=new Yp(this.#pt,this.#yt,this.#mt),this.#vt=new zp(this.#pt,this.#ft,this.#ht,e=>this.#wt.persistRun(e),()=>this.#wt.persistIndex(),e=>this.#It(e)),this.#bt=new df(this.#pt,this.#ht,this.#yt,this.#mt,e=>this.#wt.persistRun(e),e=>this.#wt.persistCheckpoint(e),()=>this.#wt.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#gt||(this.#gt=!0,this.#vt.setupApprovalSubscription(),this.#wt.loadIndex())}async startRun(e){const t=await this.#wt.startRun(e);return this.#It(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#wt.pauseRun(e)}async resumeRun(e){const t=await this.#wt.resumeRun(e);return t&&this.#It(e,{}),t}async cancelRun(e,t){return this.#wt.cancelRun(e,t)}getRun(e){return this.#wt.getRun(e)}listRuns(e){return this.#wt.listRuns(e)}approvePending(e){return this.#vt.approvePending(e)}rejectPending(e){return this.#vt.rejectPending(e)}hasRun(e){return this.#pt.has(e)}getNodeOutput(e,t){const n=this.#pt.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=ff(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#wt.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;Gp({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.#kt.get(n);if(t)return this.#kt.delete(n),void e(t);this.#Et.set(n,e)});this.#It(n,{workspaceId:this.workspaceId});const s=await r,i=this.getRun(n),o=this.getNodeOutput(n,"flow-output");return{runId:n,parentRunId:e.parentRunId,depth:t,status:s,output:o,startedAtMs:i?.startedAtMs,endedAtMs:i?.endedAtMs,error:i?.error}}notifyTerminal(e,t){const n=this.#Et.get(e);if(n)return this.#Et.delete(e),void n(t);this.#kt.set(e,t)}#Et=new Map;#kt=new Map;hasPending(e){return this.#ht.has(e)}async#It(e,t){const n=this.#pt.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,s=n.dependencyGraph;r&&s?await this.#bt.executeParallel(e,t,s,n):await this.#bt.executeSequential(e,t)}}const gf=new Map,yf=new Map,wf=new Map;function vf(e){const t=e??hf;let n=gf.get(t);return n||(n=new mf(t),gf.set(t,n)),n}let bf=!1;const If=new class{initialize(){if(bf)return;bf=!0;const e=punica.kernel.Commands.manager;e.registerCommand(Qe.WORKFLOW.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(Qe.WORKFLOW.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(Qe.WORKFLOW.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(Qe.WORKFLOW.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(Qe.WORKFLOW.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(Qe.WORKFLOW.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(Qe.WORKFLOW.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(Qe.WORKFLOW.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(Qe.WORKFLOW.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:hf}(e),n=vf(t);n.initialize();const r=await n.startRun(e);return yf.set(r.runId,t),r}async pauseRun(e){const t=this.#St(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#St(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#St(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#St(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#St(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of gf.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.#At(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#At(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(ff(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=vf(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return yf.set(n.runId,t.workspaceId),n}#St(e){const t=yf.get(e);if(t)return gf.get(t);for(const[t,n]of gf.entries())if(n.hasRun(e))return yf.set(e,t),n}#At(e){const t=wf.get(e);if(t)return gf.get(t);for(const[t,n]of gf.entries())if(n.hasPending(e))return wf.set(e,t),n}};function kf(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 Ef(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class Sf{packages=new Map;async discover(){this.packages.clear();try{if(!await Tn().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=zr();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 Af(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(!Ef(r))return void console.warn(`[AgentRegistry] Not an IvyAgent manifest: ${t}`);const s=r,i=s.capability;if(!i||"object"!=typeof i||!("id"in i))return void console.warn(`[AgentRegistry] Missing capability.id in ${t}`);const o=t.lastIndexOf("/"),a=o>=0?t.slice(0,o):"";this.packages.set(i.id,{packageRoot:a,manifestPath:t,manifest:s})}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():"",s=t&&"description"in t?String(t.description||"").toLowerCase():"",i=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||s.includes(n)||i.includes(n)})}return t}unregister(e){return this.packages.delete(e)}clear(){this.packages.clear()}}function Af(e,t){for(const n of e)n.isDirectory?n.children&&Af(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let xf;function Cf(){return xf||(xf=new Sf),xf}const Tf=new Set(["COMPLETED","FAILED","CANCELLED"]);function Mf(e){return new Promise(t=>setTimeout(t,e))}async function Nf(e,t,n){const r=Date.now()+n;let s=e.getRun(t);for(;Date.now()<r;){s=e.getRun(t);const n=s?.status;if(n&&(Tf.has(n)||"WAITING_APPROVAL"===n))return{record:s,timedOut:!1};await Mf(250)}return{record:s,timedOut:!0}}async function Pf(e,t,n,r,s){const i=Date.now(),o=(e,t)=>({caseId:n.id,status:e.status,durationMs:Date.now()-i,...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:s,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(yp(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await Nf(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(yp(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(yp(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(gp(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(yp(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const _f={validator:{validate:ep},registry:{discover:()=>ip().discover(),get:e=>ip().get(e),list:()=>ip().list(),search:e=>ip().search(e),setTestReport:(e,t)=>ip().setTestReport(e,t),getLatestTestReport:e=>ip().getLatestTestReport(e)},runner:{run:dp},test:{run:async function(e,t){const n=ip(),r=n.get(e);if(!r){if(t?.manifest){if(Ef(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 s=n?.tests;if(!s||!Array.isArray(s.cases)||!s.cases.length)throw new Error(`No test specification found for agent: ${r}`);const i=If,o=kf(n),a=Date.now(),c=[];for(const e of s.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??s.timeoutMs??3e4;c.push(await Pf(i,o,e,n,t?.workspaceId))}const l=wp({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:s.tier,results:c,startedAtMs:a});try{ip().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 s=r.manifest,i=s.tests;if(!i)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of i.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 s=await dp(e,{input:t.input,runId:`test-${e}-${t.id}-${Date.now()}`,timeoutMs:i.timeoutMs||3e4}),o=s.events.filter(e=>"error"===e.type).map(e=>{const t=e.data;return t?.message||""}).join(" "),a=gp(t,s.output,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:s.output,assertions:a.assertions}}catch(e){const s=yp(t,e instanceof Error?e.message:String(e));r={caseId:t.id,status:"error"===s.status?"fail":s.status,durationMs:Date.now()-n,error:s.error,assertions:s.assertions}}a.push(r)}const c=s.capability,l=wp({capabilityId:e,version:c&&"object"==typeof c&&"version"in c?String(c.version||"0.0.0"):"0.0.0",tier:i.tier,results:a,startedAtMs:o});return n.setTestReport(e,l),l}}},Lf={discover:()=>Cf().discover(),get:e=>Cf().get(e),list:()=>Cf().list(),search:e=>Cf().search(e),unregister:e=>Cf().unregister(e),run:(e,t)=>async function(e,t){const n=Cf().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??If,s=t?.timeoutMs??3e4,i=kf(n.manifest),o=Date.now(),a=await r.startRun({spec:i,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 Nf(r,c,s);if(u){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} did not complete in ${s}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:kf,isAgentManifest:Ef},Rf=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",[]]]),$f=new Set(["COMPLETED","FAILED","CANCELLED"]);const Of=new class{canTransitionTo(e,t){if(e===t)return!1;const n=Rf.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 Rf.get(e)??[]}isTerminal(e){return $f.has(e)}},Df=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],jf={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Ff={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function qf(e){return{x:Ff.marginX+e%6*240,y:Ff.marginY+120*Math.floor(e/6)}}function Bf(e){const t=Math.max(0,e.inputCount??0),n=Math.max(0,e.outputCount??0),r=22*(t+n),s=t>0&&n>0?9:0;return 60+Math.max(56,16+r+s)}function Uf(e,t){const n={...Ff,...t??{}},r=e.nodes??[],s={};if(!r.length)return s;const i=new Map;r.forEach((e,t)=>i.set(e.id,t));const o=(e.edges??[]).filter(e=>e.source!==e.target&&i.has(e.source)&&i.has(e.target));if(1===r.length)return s[r[0].id]={x:n.marginX,y:n.marginY},s;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)=>{s[e.id]=qf(t)}),s;const p=e=>a.get(e).length>0||c.get(e).length>0,f=r.filter(e=>!p(e.id)),h=r.filter(e=>p(e.id));if(!h.length)return r.forEach((e,t)=>{s[e.id]=qf(t)}),s;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 h)y[m.get(e.id)].push(e.id);const w=new Map,v=(e,t)=>{const n=e.map((e,n)=>{const r=t(e).filter(e=>w.has(e));return{id:e,i:n,score:r.length?r.reduce((e,t)=>e+w.get(t),0)/r.length:n}});return n.sort((e,t)=>e.score-t.score||e.i-t.i),n.map(e=>e.id)},b=e=>e.forEach((e,t)=>w.set(e,t));y.forEach(b);for(let e=1;e<y.length;e++)y[e]=v(y[e],e=>c.get(e)),b(y[e]);for(let e=y.length-2;e>=0;e--)y[e]=v(y[e],e=>a.get(e)),b(y[e]);const I=new Map;for(const e of r)I.set(e.id,Bf(e));const k=e=>e.reduce((e,t)=>e+I.get(t),0)+Math.max(0,e.length-1)*n.verticalGap,E=Math.max(...y.map(k)),S=n.marginY+E/2;y.forEach((e,t)=>{const r=n.marginX+t*(n.cardWidth+n.horizontalGap);let i=S-k(e)/2;for(const t of e)s[t]={x:r,y:i},i+=I.get(t)+n.verticalGap});const A=n.marginY+E+2*n.verticalGap;return f.forEach((e,t)=>{s[e.id]={x:n.marginX+t*(n.cardWidth+n.horizontalGap/2),y:A}}),s}let Vf;function Kf(e){if(!Vf)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 Vf}function Wf(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");Vf=e}function Gf(){Vf=void 0}function Yf(){return Vf}function zf(e){return Kf("createFlowRenderer").createRenderer(e)}function Jf(e){return Kf("createViewportController").createViewportController(e)}function Hf(e,t){return Kf("attachZoomControl").attachZoomControl(e,t)}function Qf(e,t){return Kf("attachMinimap").attachMinimap(e,t)}function Zf(e,t){const n={...e,metadata:{...e.metadata??{}}},r=n.metadata,s=r.ivy=r.ivy?{...r.ivy}:{},i=s.view??{},o={x:t.viewport?.x??i.viewport?.x??0,y:t.viewport?.y??i.viewport?.y??0,zoom:t.viewport?.zoom??i.viewport?.zoom??1},a={...i.nodes??{}};return t.nodes.forEach(e=>{e&&e.id&&(a[e.id]={x:e.x,y:e.y})}),s.view={...i,viewport:o,nodes:a},n}var Xf={setRendererProvider:Wf,resetRendererProvider:Gf,getRendererProvider:Yf,createFlowRenderer:zf,createViewportController:Jf,attachZoomControl:Hf,attachMinimap:Qf,mergeViewSnapshotIntoNotebook:Zf,computeFlowLayout:Uf,gridFallbackPosition:qf,get rendererProvider(){return Vf}},eh=Object.freeze({__proto__:null,attachMinimap:Qf,attachZoomControl:Hf,computeFlowLayout:Uf,createFlowRenderer:zf,createViewportController:Jf,default:Xf,getRendererProvider:Yf,gridFallbackPosition:qf,mergeViewSnapshotIntoNotebook:Zf,resetRendererProvider:Gf,setRendererProvider:Wf});function th(e,t,n){return{path:e,message:t,severity:"error",code:n}}function nh(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const rh="WF_INVALID_VERSION",sh="WF_INVALID_EDGE_REF",ih=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function oh(e){return"string"==typeof e&&ih.test(e)}const ah=new class{#xt=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.#xt.set(e,t)}unregister(e){return this.#xt.delete(e)}get(e){return this.#xt.get(e)}list(){return Array.from(this.#xt.keys())}clear(){this.#xt.clear()}},ch={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 s=e.graph.nodes[t];if(s.disabled)continue;const i=s.ref;if("ivyNode"!==i.kind&&"workflow"!==i.kind)continue;const o=i.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:s.id,code:"WF_UNKNOWN_CAPABILITY"}))}return r}},lh={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)),s=e.graph.entryNodeId;if(!s||!r.has(s))return t;const i=new Map;for(const e of r)i.set(e,[]);for(const t of e.graph.edges)r.has(t.fromId)&&r.has(t.toId)&&i.get(t.fromId).push(t.toId);const o=new Set([s]),a=[s];for(;a.length>0;){const e=a.shift();for(const t of i.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 "${s}"`,path:`graph.nodes[${n}].id`,nodeId:r.id,code:"WF_UNREACHABLE_NODE"}))}return t}},uh={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,s=new Map;for(const e of t)r.set(e.id,0),s.set(e.id,[]);for(const t of e.graph.edges)n.has(t.fromId)&&n.has(t.toId)&&(s.get(t.fromId).push(t.toId),r.set(t.toId,(r.get(t.toId)??0)+1));const i=[];for(const[e,t]of r.entries())0===t&&i.push(e);let o=0;const a=new Set;for(;i.length>0;){const e=i.shift();a.add(e),o++;for(const t of s.get(e)??[])r.set(t,(r.get(t)??0)-1),0===(r.get(t)??0)&&i.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}},dh={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 s=e.graph.nodes[r];if(s.disabled)continue;if("ivyNode"!==s.ref.kind)continue;const i=s.ref.id;if("string"!=typeof i||0===i.length)continue;const o=t.getCapability(i);if(!o)continue;const a=o.defaults;if(!("required"===a?.execution?.idempotency))continue;const c=s.executionOverride;("none"===c?.idempotency||!0===s.data?.skipIdempotencyKey)&&n.push({ruleId:"idempotency-required-but-no-key",severity:"error",message:`Capability "${i}" declares idempotency: 'required' but node "${s.id}" opts out of key derivation — write/retry semantics will double-execute on a network retry`,path:`graph.nodes[${r}]`,nodeId:s.id,code:"WF_IDEMPOTENCY_REQUIRED"})}return n}};function ph(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function fh(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 hh={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 s=0;s<e.graph.edges.length;s++){const i=e.graph.edges[s],o=r.get(i.fromId),a=r.get(i.toId);if(!o||!a)continue;if(o.disabled||a.disabled)continue;const c=ph(o.ref),l=ph(a.ref);if(!c||!l)continue;const u=t.getCapability(c),d=t.getCapability(l);if(!u||!d)continue;const p=u.outputs?.schema,f=d.inputs?.schema;if(!p||!f)continue;const h=fh(p,i.fromPath),m=fh(f,i.toPath);h&&m&&(h.type&&m.type&&h.type!==m.type&&n.push({ruleId:"schema-mismatch",severity:"warning",message:`Edge ${i.fromId} → ${i.toId} type mismatch: upstream emits "${h.type}" but downstream expects "${m.type}"`,path:`graph.edges[${s}]`,code:"WF_SCHEMA_MISMATCH"}))}return n}},mh=["while","forEach"],gh={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 s=r.ref.primitive;if(!mh.includes(s))continue;const i=r.data,o=i?.maxIterations;"number"==typeof o?o<=0&&t.push({ruleId:"infinite-loop",severity:"error",message:`${s} 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:`${s} 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 yh(e,t,n){let r=0;for(const s of e.graph.nodes){if(s.disabled)continue;if("workflow"!==s.ref.kind)continue;const e=s.ref,i=e.id??"<unnamed>";if(n.has(i))return t+1;if(!e.inline)continue;const o=new Set(n);o.add(i);const a=1+yh(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const wh={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],s=e.id??"<root>",i=yh(e,n,new Set([s]));return i<=n||r.push({ruleId:"subflow-depth-exceeded",severity:"error",message:`Flow "${s}" has a statically-derivable inline subflow chain of depth ${i} — exceeds cap (${n}). Direct cycles count as depth > cap.`,path:"graph",code:"WF_SUBFLOW_DEPTH_EXCEEDED"}),r}},vh=[ch,lh,uh,dh,hh,gh,wh];const bh=new class{#fe=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#fe.values())try{const s=t.check(e,r);s&&s.length>0&&n.push(...s)}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.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of vh)this.#fe.set(e.id,e)}};function Ih(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 s=new Set([t]),i=new Map,o=[t];for(;o.length>0;){const e=o.shift();if(e===n)break;for(const t of r.get(e)??[])if(!s.has(t.to)){if(s.add(t.to),i.set(t.to,t),t.to===n){o.length=0;break}o.push(t.to)}}if(!s.has(n))return;const a=[];let c=n;for(;c!==t;){const e=i.get(c);if(!e)return;a.unshift(e),c=e.from}return a}function kh(e){return e.map(e=>`${e.from}=>${e.to}`)}function Eh(e,t){return`${e}=>${t}`}const Sh=new class{#Ct=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.#Ct.set(Eh(e.from,e.to),e)}unregister(e,t){return this.#Ct.delete(Eh(e,t))}find(e,t){return this.#Ct.get(Eh(e,t))}list(){return Array.from(this.#Ct.values())}clear(){this.#Ct.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,s=e.targetVersion;if(!oh(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(!oh(s))return{ok:!1,reason:"invalid-result",message:`targetVersion "${String(s)}" is not a valid semver — substrate refuses to migrate to an unrecognized version.`,appliedTransformers:[]};if(r===s)return{ok:!0,document:e.document,appliedTransformers:[],fromVersion:r,toVersion:s};if("reject"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${s} 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} → ${s} and policy is 'warn'. Substrate did not migrate; downstream consumers may see a stale IR.`,partialDocument:e.document,appliedTransformers:[]};const i=("function"==typeof t.__plan?t.__plan.bind(t):(e,n)=>Ih(new Map(t.list().map(e=>[`${e.from}=>${e.to}`,e])),e,n))(r,s);if(!i||0===i.length)return{ok:!1,reason:"no-path",message:`No transformer chain from ${r} to ${s}. Register transformers via punica.flow.primitives.migrations.register(...).`,appliedTransformers:[]};let o=e.document;const a=[];for(const e of i)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:kh(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:kh(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:kh(a)}}return{ok:!0,document:o,appliedTransformers:kh(a),fromVersion:r,toVersion:s}}(e,this)}__plan(e,t){return Ih(this.#Ct,e,t)}};function Ah(){return Date.now()}class xh{#he=new Map;#Pe=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.#he.set(e.id,n),this.#We({type:"registered",triggerId:e.id,kind:e.kind,ts:Ah()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#he.get(e.id)===n&&(this.#he.delete(e.id),this.#We({type:"unregistered",triggerId:e.id,ts:Ah()}))}}}unregister(e){const t=this.#he.get(e);return!!t&&(t.unsubscribed=!0,this.#he.delete(e),this.#We({type:"unregistered",triggerId:e,ts:Ah()}),!0)}list(){return Array.from(this.#he.values()).map(e=>e.trigger)}subscribe(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}async fire(e,t){const n=this.#he.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Ah()}-${Math.floor(1e6*Math.random())}`,s=Ah();this.#We({type:"fired",triggerId:e,ts:s,payload:t,correlationId:r}),Gp({name:"flow.trigger.fired",source:"flow:triggers",correlationId:r,payload:{triggerId:e,kind:n.trigger.kind,flowId:n.trigger.flowId,firedAtMs:s,payload:t??null}});try{return await n.callback({triggerId:e,firedAtMs:s,payload:t,correlationId:r}),!0}catch(t){return this.#We({type:"error",triggerId:e,ts:Ah(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#he.values())e.unsubscribed=!0;this.#he.clear(),this.#Pe.clear()}#We(e){for(const t of this.#Pe)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const Ch=new xh;let Th=Ch;const Mh={get manager(){return Th},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()");Th!==e&&Th instanceof xh&&Th.clear(),Th=e},resetProvider(){Th instanceof xh&&Th.clear(),Th=Ch}};function Nh(e,t){return`${e}=>${t}`}const Ph={migrators:new class{#Tt=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.#Tt.set(Nh(e.from,e.to),e)}unregister(e,t){return this.#Tt.delete(Nh(e,t))}find(e,t){return this.#Tt.get(Nh(e,t))}list(){return Array.from(this.#Tt.values())}clear(){this.#Tt.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}},_h={..._f,agents:Lf,engine:{manager:If,statusStateMachine:Of,subscribeNodeStatuses:function(e,t){const n=new Set(e.nodeIds);let r=null;const s=(e,s,i)=>{const o=String(e??"");if(!o||!n.has(o))return;const a=String(s??"").toUpperCase(),c=jf[a];if(!c)return;const l=i?String(i):null,u=null!==l&&l!==r;u&&(r=l),t({nodeId:o,status:c,runId:l,isNewRun:u,stepStatus:a})},i=e=>{const t=e?.payload?.payload??e?.payload??{};switch(e?.name){case"workflow.stepStarted":return s(t?.step?.stepId,t?.step?.status??"RUNNING",t?.runId);case"workflow.stepUpdated":return s(t?.stepId,t?.patch?.status,t?.runId);case"workflow.stepFinished":return s(t?.step?.stepId,t?.step?.status,t?.runId);default:return}};let o=null;try{o=punica.kernel.Events.manager.subscribeMany(Df,i)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:eh,validateWorkflowDocument:function(e,t){const n=[],r=[],s=t?.mode??"best-effort",i=t?.hasCapability;if(!e||"ivy.workflow/v0.1"!==e.apiVersion)return n.push(th("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',rh)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(th("kind",'kind must equal "Workflow"',rh)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!oh(o)){const e=th("version","version must be a semver string (major.minor.patch[-prerelease][+build]); got "+("string"==typeof o?`"${o}"`:typeof o),"WF_INVALID_SEMVER");"strict"===s?n.push(e):r.push({...e,severity:"warning"})}if(!e.graph||"object"!=typeof e.graph)return n.push(th("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(th("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(th("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(th(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(th(`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(th(`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(th(`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"],s=r.primitive;"string"==typeof s&&e.includes(s)||n.push(th(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(th(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(th(`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),f=c.some(e=>"flow-output"===e.toId);return p&&!u&&n.push(th("graph.nodes","flow-input node is required when edges reference it")),f&&!d&&n.push(th("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(th("graph.entryNodeId",`entryNodeId "${e.graph.entryNodeId}" must reference an existing node`,"WF_INVALID_ENTRY")),c.forEach((e,t)=>{const r=String(e?.fromId??""),s=String(e?.toId??"");r||n.push(th(`graph.edges[${t}].fromId`,"fromId is required")),s||n.push(th(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(th(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,sh)),s&&!l.has(s)&&n.push(th(`graph.edges[${t}].toId`,`toId "${s}" must reference a node.id`,sh))}),"strict"===s&&function(e,t,n){const r=e.filter(e=>!e.disabled),s=new Set(r.map(e=>e.id)),i=t.filter(e=>s.has(e.fromId)&&s.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 i)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(th("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 s=e.filter(e=>!e.disabled),i=new Set(s.map(e=>e.id));if(!i.has(n))return;const o=t.filter(e=>i.has(e.fromId)&&i.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 s)if(!a.has(t.id)){const s=e.indexOf(t);r.push(nh(`graph.nodes[${s}].id`,`Node "${t.id}" is unreachable from entry node "${n}"`,"WF_UNREACHABLE_NODE"))}}(a,c,e.graph.entryNodeId,r),i&&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(i(a))return;("strict"===s?n:r).push(("strict"===s?th:nh)(`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:ah,linter:bh,migrations:Sh,checkpoints:Ph},triggers:Mh},Lh=[];function Rh(e){Lh.push(e)}function $h(){const e={};for(const t of Lh)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function Oh(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Dh(e){return"string"==typeof e}function jh(e){return"string"==typeof e&&e.trim().length>0}function Fh(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const qh=new Set(["shell.activityBar","shell.appBar","shell.statusbar","shell.view","shell.views","shell.keyboardShortcuts","shell.layout","shell.contentTabs","shell.panelTabs","shell.panelLayout","shell.viewDnd","flow.shell"]),Bh=new Set(["light","dark","auto"]),Uh=new Set(["compact","comfortable"]),Vh=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const Kh=new class{validate(e){const t=[];if(!Oh(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)}`),Oh(e.identity)?(jh(e.identity.id)||t.push("identity.id must be a non-empty string"),jh(e.identity.name)||t.push("identity.name must be a non-empty string"),jh(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),Oh(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys($h()),r=new Set([...qh,...n]);e.shell.activeModules.forEach((e,n)=>{Dh(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&&(Oh(e.shell.layout)?(jh(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),Oh(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(Oh(e.theme)?(Bh.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||Uh.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"),Oh(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||Fh(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||Fh(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)=>{Dh(e)&&Vh.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}}};let Wh;function Gh(){return Wh??Kh}function Yh(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}}class zh{#Mt=new Map;#Nt;register(e){if(this.#Mt.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#Mt.set(e.identity.id,e),void 0===this.#Nt&&(this.#Nt=e.identity.id)}get(e){return this.#Mt.get(e)}getActive(){if(void 0===this.#Nt||!this.#Mt.has(this.#Nt))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#Mt.get(this.#Nt)}setActive(e){if(!this.#Mt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#Nt=e}switchProfile(e){if(!this.#Mt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#Nt=e,Yh({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Mt.has(e)}list(){return Array.from(this.#Mt.values())}}const Jh={manager:new class{registry=new zh;get validator(){return Gh()}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.#Pt(t)}this.#Pt(e)}#Pt(e){const t=this.validator.validate(e);if(!t.valid)throw Yh({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),Yh({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}};class Hh{name=He.EXTENSIONS.MANAGER;version="1.0.0";dependencies=[He.KERNEL.COMMANDS,He.KERNEL.EVENTS,He.RUNTIME.WORKSPACE];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(He.KERNEL.COMMANDS),i=r.getState(He.KERNEL.EVENTS),o=r.getState(He.RUNTIME.WORKSPACE),a=r.getState(He.SHELL.LAYOUT);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(i!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(void 0!==a&&a!==e.ModuleLifecycleState.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 Qh{name=He.FLOW.VALIDATOR;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}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 Zh(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 Xh{prepareExecutionConfig(e){const t=Zh(e);if(!t)return{};const n=Sp(),r=n?.getSpec?.(t);return{capabilityDefaults:Ap(r)}}async acquireResources(e,t,n){const r=Zh(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 Qp.acquire(n,e.concurrency.max),()=>{Qp.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,s=Zh(e),i=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!s)throw new Error("capabilityId missing for capability.call node");const o=Ep();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(s,i,{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=Sp(),u=l?.getSpec?.(s),d=u?.defaults?.dataClassification,p=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`${s}.result`,payload:c,meta:{source:"capability.call",capabilityId:s},redactionPolicy:e.redactionPolicy,surface:"output",capabilityClassification:d,sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Ip(bp(c??{},0),320),artifactIds:[p.id],output:c??null}}}function em(e){return e.data??{}}function tm(e){return e.nodeOutputs??new Map}async function nm(e,t,n,r,s){const i=await e.artifactStore.writeArtifact(t.traceId,n.id,{type:"json",name:`primitive.${r}.decision`,payload:s,meta:{source:"primitive",primitive:r},redactionPolicy:n.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Ip(bp(s,0),320),artifactIds:[i.id]}}class rm{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=em(e),s=nf(r.predicate,tm(t));if(!s.ok)throw new Error(`[primitive:if] predicate did not resolve (${s.reason}) on node "${e.id}"`);const i={taken:rf(s.value)?"then":"else",predicate:s.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await nm(n,t,e,"if",i),output:i}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await nm(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=em(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 s=nf(r.collection,tm(t));if(!s.ok&&"missing-node"!==s.reason)throw new Error(`[primitive:forEach] collection did not resolve (${s.reason}) on node "${e.id}"`);const i=s.ok?s.value:null,o=Array.isArray(i)?i:[],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 nm(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=em(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 s=nf(r.predicate,tm(t));if(!s.ok)throw new Error(`[primitive:while] predicate did not resolve (${s.reason}) on node "${e.id}"`);const i=rf(s.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:i,initialPredicateValue:s.value};return{...await nm(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=em(e);if(!r.tryBodyFlowId)throw new Error(`[primitive:try] tryBodyFlowId is required on node "${e.id}"`);const s={tryBodyFlowId:r.tryBodyFlowId,catchBodyFlowId:r.catchBodyFlowId??null,finallyBodyFlowId:r.finallyBodyFlowId??null};return{...await nm(n,t,e,"try",s),output:s}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await nm(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await nm(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=em(e),s=r.lambdaId??"";if("string"!=typeof s||0===s.length)throw new Error(`[primitive:lambda] lambdaId is required on node "${e.id}"`);const i=ah.get(s);if(!i)throw new Error(`[primitive:lambda] lambdaId "${s}" is not registered (node "${e.id}")`);let o=null;if(void 0!==r.input){const n=nf(r.input,tm(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 i(o,{nodeId:e.id,attemptCorrelationId:t.attemptCorrelationId,traceId:t.traceId}),c=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`primitive.lambda.${s}.result`,payload:a,meta:{source:"primitive",primitive:"lambda",lambdaId:s},redactionPolicy:e.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:Ip(bp(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 sm{async execute(e,t){return{output:t.runInput??null}}}class im{async execute(e,t){return{output:t.resolvedInput??null}}}let om=!1;class am{name=He.FLOW.ENGINE;version="1.0.0";dependencies=[He.KERNEL.EVENTS,He.KERNEL.POLICY,He.KERNEL.COMMANDS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(He.KERNEL.EVENTS),i=r.getState(He.KERNEL.POLICY),o=r.getState(He.KERNEL.COMMANDS);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(i!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(om||(ef.register("ivyNode",new Xh),ef.register("primitive",new rm),ef.register("flowInput",new sm),ef.register("flowOutput",new im),om=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class cm{name=He.FLOW.SHELL;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 lm{name=He.KERNEL.EVENTS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;#l=null;get state(){return this.#we}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 um{name=He.KERNEL.COMMANDS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class dm{name=He.KERNEL.POLICY;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 pm{name=He.KERNEL.HISTORY;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class fm{name=He.KERNEL.TIME_SERVER;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class hm{name=He.KERNEL.TASKS;version="1.0.0";dependencies=[He.RUNTIME.TERMINALS,He.RUNTIME.WORKSPACE];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(He.RUNTIME.TERMINALS),i=r.getState(He.RUNTIME.WORKSPACE);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(i!==e.ModuleLifecycleState.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 mm{name=He.KERNEL.NOTIFICATIONS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class gm{name=He.KERNEL.AI;version="1.0.0";dependencies=[He.KERNEL.EVENTS,He.KERNEL.POLICY,He.KERNEL.LLM];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(He.KERNEL.EVENTS),i=r.getState(He.KERNEL.POLICY),o=r.getState(He.KERNEL.LLM);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(i!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==e.ModuleLifecycleState.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 ym=class{name=He.KERNEL.LLM;version="1.0.0";dependencies=[He.KERNEL.EVENTS,He.KERNEL.POLICY];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,s=r.getState(He.KERNEL.EVENTS),i=r.getState(He.KERNEL.POLICY);if(s!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(i!==e.ModuleLifecycleState.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:cn,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class wm{name=He.RUNTIME.FS;version="1.0.0";dependencies=[];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class vm{name=He.RUNTIME.SEARCH;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 bm{name=He.RUNTIME.VCS;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 Im{name=He.RUNTIME.WORKSPACE;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 km{name=He.RUNTIME.LLM;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 Em{name=He.RUNTIME.TASKS;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 Sm{name=He.RUNTIME.SECRETS;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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 Am{name=He.RUNTIME.TERMINALS;version="1.0.0";dependencies=[He.KERNEL.EVENTS];#we=e.ModuleLifecycleState.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(He.KERNEL.EVENTS)!==e.ModuleLifecycleState.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){}}function xm(){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 Cm(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 Tm(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 Mm(e,t,r){const s=punica.kernel.Events.manager,i=r?.__punica??{},o=i.correlationId??s.createCorrelationId(),a=i.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:i.parentSpanId},policy:{mode:"execute"}}}function Nm(){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=xm();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");Cm("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Mm("workspace.readFile","command",t))})}catch(e){Tm("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??""),s=xm();if(!s)throw new Error("[CoreCapabilities] Capability gateway not available");await s.call("workspace.writeFile",{path:n,content:r},await Mm("workspace.writeFile","command",t)),Cm("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Tm("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();Cm("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){Tm("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{Cm("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Mm("vcs.status","command",t))})}catch(e){Tm("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):[],s=null!=e?.cwd?String(e.cwd):void 0,i=e?.env&&"object"==typeof e.env?e.env:void 0;Cm("capability.tasks.runCommand.result",t,{command:n,args:r,cwd:s,...await punica.runtime.capabilities.gateway.call("tasks.runCommand",{command:n,args:r,cwd:s,env:i},await Mm("tasks.runCommand","command",t))})}catch(e){Tm("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?Cm("capability.llm.invoke.result",t,r):Tm(n,t,r),r}catch(r){const s={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Tm(n,t,s),s}}}),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?Cm("capability.llm.plan.result",t,r):Tm(n,t,r)}catch(e){Tm(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 s=await punica.kernel.llm.manager.api.generateCode(e);if(s.ok)if(s.structured&&"object"==typeof s.structured){const e=s.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 i=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)");Cm(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 an(e,i);if(t.errors.length>0)throw new Error(`Failed to apply some files:\n${t.errors.map(e=>`${e.path}: ${e.error}`).join("\n")}`)}})?{...s,metadata:{...s.metadata,applied:!0}}:{...s,metadata:{...s.metadata,applied:!1,cancelled:!0}})}else Cm(n,t,s)}else Cm(n,t,s);else Tm(r,t,s)}catch(e){Tm(r,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"code-generator",role:"code-generator"}})}}}),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?Cm("capability.llm.edit-workflow.result",t,r):Tm(n,t,r)}catch(e){Tm(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"workflow-editor",role:"workflow-editor"}})}}});const t=e=>async(t,n)=>{try{await punica.runtime.capabilities.gateway.call("shell.toggleSlot",{slot:e},await Mm("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(Qe.SHELL.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(Qe.SHELL.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(Qe.SHELL.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Pm="1.0.0",_m=dn,Lm={},Rm=Ua,$m=Zd,Om=_h,Dm=new class{#_t=new Map;#Lt=new Map;#Rt=new Map;register(t){if(this.#_t.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#_t.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#_t.set(t.name,t),this.#Lt.set(t.name,e.ModuleLifecycleState.CREATED)}get(e){return this.#_t.get(e)}getAll(){return Array.from(this.#_t.values())}resolveBootstrapOrder(){return this.#$t()}resolveStartOrder(){return this.#$t()}#$t(){const e=new Set,t=new Set,n=[],r=s=>{if(t.has(s)){const e=Array.from(t).concat(s);throw new Error(`Circular dependency detected: ${e.join(" → ")}`)}if(e.has(s))return;t.add(s);const i=this.#_t.get(s);if(!i)throw new Error(`Module ${s} not found`);for(const e of i.dependencies)r(e);t.delete(s),e.add(s),n.push(s)};for(const t of this.#_t.keys())e.has(t)||r(t);return n}async bootstrapAll(){const t=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#Lt.set(n,e.ModuleLifecycleState.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#Lt.set(n,e.ModuleLifecycleState.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Lt.set(n,e.ModuleLifecycleState.BOOTSTRAP_FAILED),this.#Rt.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} bootstrap failed:`,r),new Error(`Critical module ${n} failed to bootstrap: ${r.message}`)}}console.log("[ModuleRegistry] All modules bootstrapped successfully")}async startAll(){const t=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#Lt.get(n);if(r!==e.ModuleLifecycleState.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#Lt.set(n,e.ModuleLifecycleState.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#Lt.set(n,e.ModuleLifecycleState.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Lt.set(n,e.ModuleLifecycleState.START_FAILED),this.#Rt.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} start failed:`,r),new Error(`Critical module ${n} failed to start: ${r.message}`)}}for(const n of t){this.#Lt.get(n)===e.ModuleLifecycleState.STARTED&&this.#Lt.set(n,e.ModuleLifecycleState.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#Lt.get(e)}areAllModulesReady(){for(const[t,n]of this.#_t){if(this.#Lt.get(t)!==e.ModuleLifecycleState.READY)return!1}return!0}getError(e){return this.#Rt.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#_t.keys())t.includes(n)&&e.push(n);return e}};Rh({moduleFactories:{"flow.shell":()=>new cm}});var jm=Object.freeze({__proto__:null,StdioTransport:class{#Ot;#Dt;#jt;#Ft=null;#qt=null;#Bt=null;#Ut=null;#Vt=null;#Kt=new Map;#Wt=1;#Gt="";constructor(e,t=[],n={}){this.#Ot=e,this.#Dt=t,this.#jt=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#Yt(e):await this.#zt()}async#Yt(e){this.#Bt=e;const{sessionId:t}=await e.spawn({command:this.#Ot,args:this.#Dt,env:this.#jt});this.#qt=t,this.#Ut=e.onData(e=>{e.sessionId===t&&this.#Jt(e.chunk)}),this.#Vt=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.#Kt.values())e(n);this.#Kt.clear()})}async#zt(){const e=await import(
2
+ /* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#Ft=e.spawn(this.#Ot,this.#Dt,{env:{...n,...this.#jt},stdio:["pipe","pipe","inherit"]}),this.#Ft.stdout.setEncoding("utf8"),this.#Ft.stdout.on("data",e=>{this.#Jt(e)}),this.#Ft.on("error",e=>{for(const{reject:t}of this.#Kt.values())t(e);this.#Kt.clear()})}#Jt(e){let t;for(this.#Gt+=e;-1!==(t=this.#Gt.indexOf("\n"));){const e=this.#Gt.slice(0,t).trim();this.#Gt=this.#Gt.slice(t+1),e&&this.#Ht(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#Qt(n)}async request(e,t={}){const n=this.#Wt++;return new Promise((r,s)=>{this.#Kt.set(n,{resolve:r,reject:s});const i=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#Qt(i)}catch(e){this.#Kt.delete(n),s(e instanceof Error?e:new Error(String(e)))}})}#Qt(e){if(this.#Bt&&this.#qt)this.#Bt.write(this.#qt,e);else{if(!this.#Ft?.stdin)throw new Error("MCP stdio transport is not connected");this.#Ft.stdin.write(e)}}close(){this.#Ut?.(),this.#Vt?.(),this.#Ut=null,this.#Vt=null,this.#Bt&&this.#qt&&this.#Bt.close(this.#qt),this.#Ft?.kill(),this.#Ft=null,this.#qt=null,this.#Bt=null;for(const{reject:e}of this.#Kt.values())e(new Error("MCP stdio transport closed"));this.#Kt.clear()}#Ht(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#Kt.get(t.id);n&&(this.#Kt.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var Fm=Object.freeze({__proto__:null,StreamableHttpTransport:class{#Zt;#Xt;#Wt=1;#qt;constructor(e,t={}){this.#Zt=e.replace(/\/$/,""),this.#Xt=t}async connect(){const e=await fetch(`${this.#Zt}/sse`,{headers:{...this.#Xt,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#qt=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#en({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#Wt++,r=await this.#en({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#en(e){const t={...this.#Xt,"Content-Type":"application/json",Accept:"application/json"};this.#qt&&(t["mcp-session-id"]=this.#qt);const n=await fetch(`${this.#Zt}/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.#qt=void 0}}});var qm=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return Ia(bd(e))}});e.COMMAND_IDS=Qe,e.MODULE_NAMES=He,e.Profile=Jh,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 Lh)t.facade&&Object.assign(e,t.facade);return e}()));const n=Jh.manager;for(const e of function(){const e=[];for(const t of Lh)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 Lh)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(Dm.register(new lm),Dm.register(new um),Dm.register(new pm),Dm.register(new fm),Dm.register(new mm),Dm.register(new Qh),Dm.register(new dm),Dm.register(new ym),Dm.register(new gm),Dm.register(new am),Dm.register(new wm),Dm.register(new vm),Dm.register(new bm),Dm.register(new Im),Dm.register(new km),Dm.register(new Sm),Dm.register(new Am),Dm.register(new Em),Dm.register(new Ea),Dm.register(new hm),r){const e=$h(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(Dm.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}Dm.register(new Hh),console.log(`[Punica] Module registry initialized with ${Dm.getAll().length} modules`),await Dm.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}},e.emitShellEvent=Yh,e.enterHeadlessScope=Fd,e.exitHeadlessScope=qd,e.extensions=$m,e.flow=Om,e.getProfileValidator=Gh,e.initialize=function(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Pm,kernel:_m,shell:Lm,runtime:Rm,extensions:$m,flow:Om};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=Rh;const t=e.debug??{};t.logTrinityCatalog=na,t.logTrinityCatalogVerbose=ra,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=na,n.logTrinityCatalogVerbose=ra);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("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{Nm(),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.isHeadlessScope=function(){return jd>0},e.isMacPlatform=Pd,e.kernel=_m,e.parseKeyChord=_d,e.registerShell=Rh,e.runInHeadlessScope=Bd,e.runtime=Rm,e.setProfileValidator=function(e){Wh=e},e.shell=Lm,e.start=async function(){try{console.log("[Punica] Starting system..."),await Dm.startAll(),Dm.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:Pm}}),console.log("[Punica] System started successfully"),na()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}},e.version=Pm});
3
3
  //# sourceMappingURL=index.bundle.umd.js.map